问:
How do I fix an undefined reference to `nettle_sha256_digest`?
TL;DR

I'm attempting to build a go project that uses this dependency: https://github.com/mqu/openldap, which in turn externally links lldap and llber libraries, which in turn uses lgnutls, which uses lnettle, which is where I'm stuck.

The go build produces a long list of undefined references and the build fails. Here's a sample:

```<code>/usr/lib/x86_64-linux-gnu/libgnutls.a(sha-x86-ssse3.o): In function `_ctx_init':
(.text+0x468): undefined reference to `nettle_sha256_digest'
/usr/lib/x86_64-linux-gnu/libgnutls.a(sha-x86-ssse3.o): In function `_ctx_init':
(.text+0x476): undefined reference to `nettle_sha224_init'
/usr/lib/x86_64-linux-gnu/libgnutls.a(sha-x86-ssse3.o): In function `_ctx_init':
(.text+0x494): undefined reference to `nettle_sha256_init'
/usr/lib/x86_64-linux-gnu/libgnutls.a(sha-x86-ssse3.o): In function `_ctx_init':
(.text+0x4b8): undefined reference to `nettle_sha256_digest'
/usr/lib/x86_64-linux-gnu/libgnutls.a(sha-x86-ssse3.o): In function `_ctx_init':
(.text+0x4c6): undefined reference to `nettle_sha256_init'
/usr/lib/x86_64-linux-gnu/libgnutls.a(sha-x86-ssse3.o):(.data.rel.ro+0x18): undefined reference to `nettle_sha256_init'
/usr/lib/x86_64-linux-gnu/libgnutls.a(sha-x86-ssse3.o):(.data.rel.ro+0x28): undefined reference to `nettle_sha256_digest'
/usr/lib/x86_64-linux-gnu/libgnutls.a(sha-x86-ssse3.o):(.data.rel.ro+0x58): undefined reference to `nettle_sha224_init'
/usr/lib/x86_64-linux-gnu/libgnutls.a(sha-x86-ssse3.o):(.data.rel.ro+0x68): undefined reference to `nettle_sha224_digest'
/usr/lib/x86_64-linux-gnu/libgnutls.a(sha-x86-ssse3.o):(.data.rel.ro+0x98): undefined reference to `nettle_sha1_init'
/usr/lib/x86_64-linux-gnu/libgnutls.a(sha-x86-ssse3.o):(.data.rel.ro+0xa8): undefined reference to `nettle_sha1_digest'
</code>```

And my go build command:

```<code>CC=/usr/local/musl/bin/musl-gcc \
    GOOS=linux go build \
    -o /bin/activedirectory \
    -ldflags '-linkmode external -extldflags "-static -L/usr/lib/x86_64-linux-gnu -lnettle -lp11 -lsasl2 -lgnutls -ltasn1"'
</code>```

I have tried resolving this by installing libnettle4, nettle-dev, libghc-nettle-dev, nettle-bin. I have made sure to include -lnettle in the ldflags. No luck.

More context

The openldap library is linking the ldap and lber libs in the code:

```<code>package openldap

/*

#define LDAP_DEPRECATED 1
#include <stdlib.h>
#include <ldap.h>

static inline char* to_charptr(const void* s) { return (char*)s; }
static inline LDAPControl** to_ldapctrlptr(const void* s) {
    return (LDAPControl**) s;
}
*/
// #cgo CFLAGS: -DLDAP_DEPRECATED=1
// #cgo linux CFLAGS: -DLINUX=1
// #cgo LDFLAGS: -lldap -llber
</code>```

This has required me to install and include in the ldflags all the libraries you see in my build command.

So the dependency chain, in short, goes like this:

lldap -> lgnutls -> lnettle.

I added lgnutls and that resolved my gnutls dependency issues, but I'm unable to resolve my nettle depencency issues.

My question

What am I doing wrong in my attempts to fix these nettle dependency issues?

Bonus question

Is there a best practice for resolving these ld linker dependencies? Right now my flow looks like this:

Run the build

Watch for "undefined reference" errors

Figure out which package is missing by googling the error or looking at the name referenced (e.g. nettle_sha1_digest = nettle package)

Install that package

Repeat

I guess I'm wondering if there's a magic bullet that can install all dependencies for me? :)

答:
From the looks of it you're linking your dependent libraries in the wrong order (see Why does the order in which libraries are linked sometimes cause errors in GCC? for more context).

With statically linked libraries the linker attempts to resolve symbols in the order that the libraries were specified in. If a relied-upon symbol comes up as undefined then the linker looks to see if it's defined in the subsequent libraries specified. Since in your build invocation -lnettle is specified before -lgnutls the gnutls library can't resolve the symbols it needs from nettle.

What this means is that (at minimum) you'll have to move your reference to -lnettle to after -lgnutls. Not sure this will solve all of your problems since I'm not familiar with all of the linking dependencies you have listed, but it should at least solve your current errors running go build.

Body:
TL;DR

I'm attempting to build a go project that uses this dependency: https://github.com/mqu/openldap, which in turn externally links lldap and llber libraries, which in turn uses lgnutls, which uses lnettle, which is where I'm stuck.

The go build produces a long list of undefined references and the build fails. Here's a sample:

/usr/lib/x86_64-linux-gnu/libgnutls.a(sha-x86-ssse3.o): In function `_ctx_init':
(.text+0x468): undefined reference to `nettle_sha256_digest'
/usr/lib/x86_64-linux-gnu/libgnutls.a(sha-x86-ssse3.o): In function `_ctx_init':
(.text+0x476): undefined reference to `nettle_sha224_init'
/usr/lib/x86_64-linux-gnu/libgnutls.a(sha-x86-ssse3.o): In function `_ctx_init':
(.text+0x494): undefined reference to `nettle_sha256_init'
/usr/lib/x86_64-linux-gnu/libgnutls.a(sha-x86-ssse3.o): In function `_ctx_init':
(.text+0x4b8): undefined reference to `nettle_sha256_digest'
/usr/lib/x86_64-linux-gnu/libgnutls.a(sha-x86-ssse3.o): In function `_ctx_init':
(.text+0x4c6): undefined reference to `nettle_sha256_init'
/usr/lib/x86_64-linux-gnu/libgnutls.a(sha-x86-ssse3.o):(.data.rel.ro+0x18): undefined reference to `nettle_sha256_init'
/usr/lib/x86_64-linux-gnu/libgnutls.a(sha-x86-ssse3.o):(.data.rel.ro+0x28): undefined reference to `nettle_sha256_digest'
/usr/lib/x86_64-linux-gnu/libgnutls.a(sha-x86-ssse3.o):(.data.rel.ro+0x58): undefined reference to `nettle_sha224_init'
/usr/lib/x86_64-linux-gnu/libgnutls.a(sha-x86-ssse3.o):(.data.rel.ro+0x68): undefined reference to `nettle_sha224_digest'
/usr/lib/x86_64-linux-gnu/libgnutls.a(sha-x86-ssse3.o):(.data.rel.ro+0x98): undefined reference to `nettle_sha1_init'
/usr/lib/x86_64-linux-gnu/libgnutls.a(sha-x86-ssse3.o):(.data.rel.ro+0xa8): undefined reference to `nettle_sha1_digest'

And my go build command:

CC=/usr/local/musl/bin/musl-gcc \
    GOOS=linux go build \
    -o /bin/activedirectory \
    -ldflags '-linkmode external -extldflags "-static -L/usr/lib/x86_64-linux-gnu -lnettle -lp11 -lsasl2 -lgnutls -ltasn1"'

I have tried resolving this by installing libnettle4, nettle-dev, libghc-nettle-dev, nettle-bin. I have made sure to include -lnettle in the ldflags. No luck.

More context

The openldap library is linking the ldap and lber libs in the code:

package openldap

/*

#define LDAP_DEPRECATED 1
#include <stdlib.h>
#include <ldap.h>

static inline char* to_charptr(const void* s) { return (char*)s; }
static inline LDAPControl** to_ldapctrlptr(const void* s) {
    return (LDAPControl**) s;
}
*/
// #cgo CFLAGS: -DLDAP_DEPRECATED=1
// #cgo linux CFLAGS: -DLINUX=1
// #cgo LDFLAGS: -lldap -llber

This has required me to install and include in the ldflags all the libraries you see in my build command.

So the dependency chain, in short, goes like this:

lldap -> lgnutls -> lnettle.

I added lgnutls and that resolved my gnutls dependency issues, but I'm unable to resolve my nettle depencency issues.

My question

What am I doing wrong in my attempts to fix these nettle dependency issues?

Bonus question

Is there a best practice for resolving these ld linker dependencies? Right now my flow looks like this:

Run the build

Watch for "undefined reference" errors

Figure out which package is missing by googling the error or looking at the name referenced (e.g. nettle_sha1_digest = nettle package)

Install that package

Repeat

I guess I'm wondering if there's a magic bullet that can install all dependencies for me? :)


来源: stackexchange

问:
How to properly shutdown a java command line program
I have an interactive java program that allow user to send messages to a server, which behaves kind of like a shell, accepting user's keyboard input and perform various action.

For example

```<code>myProgram> send "Login as James" to server
</code>```

My program will parse the user input and perform the action, in this case, it will send the message "Login as James" to the server.

One of the command that I support its "quit", which will close all the server connection, clean up resources and shutdown the app. and the code for handling this quit command is

```<code>private void shutdown()
{
  closeAllConnection();
  cleanup();
  System.out.println("Thank you for using the tool, have a nice day!");
  System.exit(0);
}
</code>```

When I run findbug against my code, a DM_EXIT bug is raised

```<code>Bug: new myProgram.messagingTools.main(String[]) invokes System.exit(...), which shuts down the entire virtual machine
Pattern id: DM_EXIT, type: Dm, category: BAD_PRACTICE

Invoking System.exit shuts down the entire Java virtual machine. This should only been done when it is appropriate. Such calls make it hard or impossible for your code to be invoked by other code. Consider throwing a RuntimeException instead.
</code>```

and it complains that System.exit should not be used to shutdown the program.

Anyone have suggestion on how should I "Shutdown the application when my program receive the 'quit' command" ?

答: Use Runtime.getRuntime().exit(0) instead. This worked for me. Anyway eventually System.exit(0) is going to call this.

ContentLicense: CC BY-SA 3.0

Body:
I have an interactive java program that allow user to send messages to a server, which behaves kind of like a shell, accepting user's keyboard input and perform various action.

For example

myProgram> send "Login as James" to server

My program will parse the user input and perform the action, in this case, it will send the message "Login as James" to the server.

One of the command that I support its "quit", which will close all the server connection, clean up resources and shutdown the app. and the code for handling this quit command is

private void shutdown()
{
  closeAllConnection();
  cleanup();
  System.out.println("Thank you for using the tool, have a nice day!");
  System.exit(0);
}

When I run findbug against my code, a DM_EXIT bug is raised

Bug: new myProgram.messagingTools.main(String[]) invokes System.exit(...), which shuts down the entire virtual machine
Pattern id: DM_EXIT, type: Dm, category: BAD_PRACTICE

Invoking System.exit shuts down the entire Java virtual machine. This should only been done when it is appropriate. Such calls make it hard or impossible for your code to be invoked by other code. Consider throwing a RuntimeException instead.

and it complains that System.exit should not be used to shutdown the program.

Anyone have suggestion on how should I "Shutdown the application when my program receive the 'quit' command" ?


问:
Pandas: Convert a DataFrame into a Series when index is Year-Month and columns are Day
I have a dataframe that looks similar to the following:

```<code>df = pd.DataFrame({'Y_M':['201710','201711','201712'],'1':[1,5,9],'2':[2,6,10],'3':[3,7,11],'4':[4,8,12]})
df = df.set_index('Y_M')
</code>```

Which creates a dataframe looking like this:

```<code>        1  2  3   4
Y_M
201711  1  2  3  4
201712  5  6  7  8
201713  9  10 11 12
</code>```

The columns are the day of the month. They stretch on to the right, going all the way up to 31.  (February will have columns 29, 30, and 31 filled with NaN).
The index contains the year and the month (e.g. 201711 referring to Nov 2017)

My question is: How can I make this a single series, with the year/month/day combined? My output would be the following:

```<code>Y_M
20171001    1
20171002    2
20171003    3
20171004    4
20171101    5
20171102    6
20171103    7
20171104    8
20171201    9
20171202   10
20171203   11
20171204   12
</code>```

The index can be converted to a datetime. In fact I think it would make it easier.

Body:
I have a dataframe that looks similar to the following:

df = pd.DataFrame({'Y_M':['201710','201711','201712'],'1':[1,5,9],'2':[2,6,10],'3':[3,7,11],'4':[4,8,12]})
df = df.set_index('Y_M')

Which creates a dataframe looking like this:

        1  2  3   4
Y_M
201711  1  2  3  4
201712  5  6  7  8
201713  9  10 11 12

The columns are the day of the month. They stretch on to the right, going all the way up to 31.  (February will have columns 29, 30, and 31 filled with NaN).
The index contains the year and the month (e.g. 201711 referring to Nov 2017)

My question is: How can I make this a single series, with the year/month/day combined? My output would be the following:

Y_M
20171001    1
20171002    2
20171003    3
20171004    4
20171101    5
20171102    6
20171103    7
20171104    8
20171201    9
20171202   10
20171203   11
20171204   12

The index can be converted to a datetime. In fact I think it would make it easier.

Body:
Without bringing date into it.

s = df.stack()
s.index = s.index.map('{0[0]}{0[1]:>02s}'.format)
s

20171001     1
20171002     2
20171003     3
20171004     4
20171101     5
20171102     6
20171103     7
20171104     8
20171201     9
20171202    10
20171203    11
20171204    12
dtype: int64


问:
url pattern matching php
I have a url of the format /?var1 = val1&var2 = val2;

I want to check for the presence of just var2 = val2 in the url using php. How can that be done?

答:
If this is not the QUERY_STRING for the request (in which case you should just use $_GET as @Spechal said), you can use parse_str(). It "uses the same mechanism that PHP uses to populate the $_GET, $_POST, etc. variables."

See also parse_url().

ContentLicense: CC BY-SA 2.5

Title: url pattern matching php


问:
App's hierarchy within bottom navigation bar
I want to implement bottomNavigationBar. in that when i click on any item within fragment, it should open new view with bottomNavigationBar at bottom and back button on top like below screen.

there is also other example from below link:
View

in that, you can see you-tube did same thing with searchView. help me how can i do that.

答:
Try this

```<code>     @Override
  .  public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState)
    {
        View v = inflater.inflate(R.layout.fragmet_search, parent, false);
        return v;
    }

        @Override
        public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
           inflater.inflate(R.menu.your_search_menu_xml, menu);
           super.onCreateOptionsMenu(menu, inflater);
        }
</code>```

@FAT Suggestions Refer here

This may help you.

Body:
Try this

     @Override
  .  public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState)
    {
        View v = inflater.inflate(R.layout.fragmet_search, parent, false);
        return v;
    }

        @Override
        public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
           inflater.inflate(R.menu.your_search_menu_xml, menu);
           super.onCreateOptionsMenu(menu, inflater);
        }

@FAT Suggestions Refer here

This may help you.


问:
Azure - run a WCF service as a WebJob
I have a Web API which sends requests to a WCF server. The WCF project is being started using TopShelf.

My plan is to publish both API and WCF into Azure.
For that I created an App Service in the cloud and published the Web API in the app service.

The WCF was publised as a WebJob because I need it to run continuously however I get this error:

Topshelf.Hosts.ConsoleRunHost Error: 0 : An exception occurred, System.ServiceModel.AddressAlreadyInUseException

Is this because the Web API and WCF are sharing the same app service?

I don't know if this is the right approach or do I really need a VM for that?

Any help is really appreciated.

答:
You can't expose the WCF projects TCP-ports to outside, as App Service only supports 80 and 443 for Internet facing connections. But inside the App Service you should be able to open a custom socket and to use that to communicate between the services.

The best place for the documentation is available from here:

https://github.com/projectkudu/kudu/wiki/Azure-Web-App-sandbox#network-endpoint-listening

Couple things you could check:

Make sure that the WCF project is using a custom TCP port (not 80, 443)

Are you running in a shared plan?

If you can't get this to work and if you don't want to use Azure's IaaS solution (virtual machines) and prefer PaaS, you could check Azure Service Fabric. You should be quite easily to create a Service Fabric application using your two services.

Title: Azure - run a WCF service as a WebJob


问:
TFRecords and record shuffling
My understanding is that it is good practice to shuffle training samples for each epoch so that each mini-batch contains a nice random sample of the entire dataset. If I convert my entire data-set into a single file containing TFRecords then how is this shuffling to be achieved short of loading the entire data-set? My understanding is that there is no efficient random access to TFRecord files. So, to be specific, I am looking for guidance as to how TFRecord files are used in this scenario.</p>

答: Actually now you don't have to worry about shuffling before saving to TFRecords. It's because (currently) recommended method to read TFRecords uses tf.data.TFRecordDataset which implements .shuffle() method.

Title: TFRecords and record shuffling


问:
Swift: Display Image from URL
In Swift 3, I am trying to capture an image from the internet, and have these lines of code:

```<code>var catPictureURL = NSURL(fileURLWithPath: "http://i.imgur.com/w5rkSIj.jpg")
var catPictureData = NSData(contentsOf: catPictureURL as URL) // nil
var catPicture = UIImage(data: catPictureData as! Data)
</code>```

What am I doing wrong here?

答:
```<code>let url = ("https://firebasestorage.googleapis.com/v0/b/qualityaudit-678a4.appspot.com/o/profile_images%2FBFA28EDD-9E15-4CC3-9AF8-496B91E74A11.png?alt=media&token=b4518b07-2147-48e5-93fb-3de2b768412d")

self.myactivityindecator.startAnimating()

let urlString = url
    guard let url = URL(string: urlString) else { return }
    URLSession.shared.dataTask(with: url)

{
(data, response, error) in
        if error != nil {
            print("Failed fetching image:", error!)
            return
        }

        guard let response = response as? HTTPURLResponse, response.statusCode == 200 else {
            print("error")
            return
        }

        DispatchQueue.main.async {
            let image = UIImage(data: data!)
        let myimageview = UIImageView(image: image)
            print(myimageview)
            self.imgdata.image = myimageview.image
self.myactivityindecator.stopanimating()

     }
  }.resume()
</code>```

ContentLicense: CC BY-SA 4.0

Title: Swift: Display Image from URL

Body:
In Swift 3, I am trying to capture an image from the internet, and have these lines of code:

var catPictureURL = NSURL(fileURLWithPath: "http://i.imgur.com/w5rkSIj.jpg")
var catPictureData = NSData(contentsOf: catPictureURL as URL) // nil
var catPicture = UIImage(data: catPictureData as! Data)

What am I doing wrong here?


问:
Select statement only searches by check boxes when kept in the where statement
I have 21 textboxes and 25 checkboxes in a winform and I want to be able to type in these textboxes and check checkboxes and have the corresponding records returned when the statement is executed. At this point whenever I have a select statement with no checkboxes referenced in the where clause I can search by any textbox and have my records returned normally, however when I add in a search by checkbox , no records are returned except ones with  the certain checkboxes checked. So if I typed anything in the textboxes and didn't check a checkbox , I would still get the no record found message.

```<code>{

        con.Open();
        string str = "select * from engineering where (JobNumber like '%' + @search + '%' AND DateOrdered
        like '%' + @search1 + '%' AND Title like '%' + @search2 + '%' AND PhysicalAddressComplete like
        '%' + @search3 + '%' AND County like '%' + @search4 + '%' AND Client like '%' + @search5 + '%'
        AND Contact like '%' + @search6 + '%' AND ContactTitle like '%' + @search7 + '%' AND
        MailingAddressComplete like '%' + @search8 + '%' AND BusinessPhone like '%' + @search9 + '%'
        AND CellPhone like '%' + @search10 + '%' AND Email like '%' + @search11 + '%' AND OpenStatus
        like '%' + @search12 + '%' AND CloseStatus like '%' + @search13 + '%' AND Cabinet
        like '%' + @search14 + '%' AND Roll like '%' + @search15 + '%' AND Drawer like '%' + @search16 + '%'
        AND ConstructionDrawings like '%' + @search17 + '%' AND Fee like '%' + @search18 + '%' AND
        ConstructionCost like '%' + @search19 + '%' AND ProjectDescription like '%' + @search20 + '%'
        AND DesignBuild like " + DesignBuild + " )";
        SqlCommand xp = new SqlCommand(str, con);
        xp.Parameters.Add("@search", SqlDbType.NVarChar).Value = txtProjectNumber.Text;
        xp.Parameters.Add("@search1", SqlDbType.NVarChar).Value = txtDateOrdered.Text;
        xp.Parameters.Add("@search2", SqlDbType.NVarChar).Value = txtProjectName.Text;
        xp.Parameters.Add("@search3", SqlDbType.NVarChar).Value = txtProjectAddress.Text;
        xp.Parameters.Add("@search4", SqlDbType.NVarChar).Value = txtCounty.Text;
        xp.Parameters.Add("@search5", SqlDbType.NVarChar).Value = txtClient.Text;
        xp.Parameters.Add("@search6", SqlDbType.NVarChar).Value = txtClientContact.Text;
        xp.Parameters.Add("@search7", SqlDbType.NVarChar).Value = txtContactTitle.Text;
        xp.Parameters.Add("@search8", SqlDbType.NVarChar).Value = txtBillingAddress.Text;
        xp.Parameters.Add("@search9", SqlDbType.NVarChar).Value = txtBusinessPhone.Text;
        xp.Parameters.Add("@search10", SqlDbType.NVarChar).Value = txtCellPhone.Text;
        xp.Parameters.Add("@search11", SqlDbType.NVarChar).Value = txtEmail.Text;
        xp.Parameters.Add("@search12", SqlDbType.NVarChar).Value = txtOpenStatus.Text;
        xp.Parameters.Add("@search13", SqlDbType.NVarChar).Value = txtCloseStatus.Text;
        xp.Parameters.Add("@search14", SqlDbType.NVarChar).Value = txtCabinet.Text;
        xp.Parameters.Add("@search15", SqlDbType.NVarChar).Value = txtRoll.Text;
        xp.Parameters.Add("@search16", SqlDbType.NVarChar).Value = txtDrawer.Text;
        xp.Parameters.Add("@search17", SqlDbType.NVarChar).Value = txtDrawings.Text;
        xp.Parameters.Add("@search18", SqlDbType.NVarChar).Value = txtFee.Text;
        xp.Parameters.Add("@search19", SqlDbType.NVarChar).Value = txtCost.Text;
        xp.Parameters.Add("@search20", SqlDbType.NVarChar).Value = txtProjectDescription.Text;

        try
        {

            da = new SqlDataAdapter();
            da.SelectCommand = xp;
            da.Fill(ss);

            Showdata(pos);
          if (ss.Rows.Count >0)
            {

                this.chkEducational.Checked = ((int)ss.AsEnumerable().FirstOrDefault()["Education"] == 1);
                this.chkDesign.Checked = ((int)ss.AsEnumerable().FirstOrDefault()["DesignBuild"] == 1);
                this.chkMedical.Checked = ((int)ss.AsEnumerable().FirstOrDefault()["Medical"] == 1);
                this.chkReligious.Checked = ((int)ss.AsEnumerable().FirstOrDefault()["Religious"] == 1);
                this.chkMulti.Checked = ((int)ss.AsEnumerable().FirstOrDefault()["MultiFamily"] == 1);
                this.chkStudent.Checked = ((int)ss.AsEnumerable().FirstOrDefault()["Student"] == 1);
                this.chkAssisted.Checked = ((int)ss.AsEnumerable().FirstOrDefault()["Assisted"] == 1);
                this.chkSingleFamily.Checked = ((int)ss.AsEnumerable().FirstOrDefault()["Single"] == 1);
                this.chkBridge.Checked = ((int)ss.AsEnumerable().FirstOrDefault()["Bridge"] == 1);
                this.chkIntersection.Checked = ((int)ss.AsEnumerable().FirstOrDefault()["Intersection"] == 1);
                this.chkRoadway.Checked = ((int)ss.AsEnumerable().FirstOrDefault()["Roadway"] == 1);
                this.chkTransOther.Checked = ((int)ss.AsEnumerable().FirstOrDefault()["TransportationOther"] == 1);
                this.chkRetailSmall.Checked = ((int)ss.AsEnumerable().FirstOrDefault()["SmallRetail"] == 1);
                this.chkRetailLarge.Checked = ((int)ss.AsEnumerable().FirstOrDefault()["LargeRetail"] == 1);
                this.chkParks.Checked = ((int)ss.AsEnumerable().FirstOrDefault()["Parks"] == 1);
                this.chkIndustrial.Checked = ((int)ss.AsEnumerable().FirstOrDefault()["Industrial"] == 1);
                this.chkUtility.Checked = ((int)ss.AsEnumerable().FirstOrDefault()["Utility"] == 1);
                this.chkGCSmall.Checked = ((int)ss.AsEnumerable().FirstOrDefault()["GCSmall"] == 1);
                this.chkGCLarge.Checked = ((int)ss.AsEnumerable().FirstOrDefault()["GCLarge"] == 1);
                this.chkOffice.Checked = ((int)ss.AsEnumerable().FirstOrDefault()["Office"] == 1);
                this.chkOther.Checked = ((int)ss.AsEnumerable().FirstOrDefault()["Other"] == 1);
                this.chkMunicipal.Checked = ((int)ss.AsEnumerable().FirstOrDefault()["Municipal"] == 1);
                this.chkPrivate.Checked = ((int)ss.AsEnumerable().FirstOrDefault()["Privates"] == 1);
                this.chkInstitutional.Checked = ((int)ss.AsEnumerable().FirstOrDefault()["Institutional"] == 1);
                this.chkMilitary.Checked = ((int)ss.AsEnumerable().FirstOrDefault()["Military"] == 1);

            }

        }
        catch
        {
            MessageBox.Show("No Record Found");

        }

        con.Close();

    }
</code>```

However even still when I do not include the checkbox in the where clause I still get the "no record found message" , then once I click out of that message box my results are shown. Any help with either of these two issues would be great.

答:
Did you tried debugging your code where you are checking if (ss.Rows.Count >0)

```<code>this.chkEducational.Checked = ((int)ss.AsEnumerable().FirstOrDefault()["Education"] == 1);
                this.chkDesign.Checked = ((int)ss.AsEnumerable().FirstOrDefault()["DesignBuild"] == 1);
                this.chkMedical.Checked = ((int)ss.AsEnumerable().FirstOrDefault()["Medical"] == 1);
                this.chkReligious.Checked = ((int)ss.AsEnumerable().FirstOrDefault()["Religious"] == 1);
                this.chkMulti.Checked = ((int)ss.AsEnumerable().FirstOrDefault()["MultiFamily"] == 1);
                this.chkStudent.Checked = ((int)ss.AsEnumerable().FirstOrDefault()["Student"] == 1);
                this.chkAssisted.Checked = ((int)ss.AsEnumerable().FirstOrDefault()["Assisted"] == 1);
                this.chkSingleFamily.Checked = ((int)ss.AsEnumerable().FirstOrDefault()["Single"] == 1);
                this.chkBridge.Checked = ((int)ss.AsEnumerable().FirstOrDefault()["Bridge"] == 1);
                this.chkIntersection.Checked = ((int)ss.AsEnumerable().FirstOrDefault()["Intersection"] == 1);
                this.chkRoadway.Checked = ((int)ss.AsEnumerable().FirstOrDefault()["Roadway"] == 1);
                this.chkTransOther.Checked = ((int)ss.AsEnumerable().FirstOrDefault()["TransportationOther"] == 1);
                this.chkRetailSmall.Checked = ((int)ss.AsEnumerable().FirstOrDefault()["SmallRetail"] == 1);
                this.chkRetailLarge.Checked = ((int)ss.AsEnumerable().FirstOrDefault()["LargeRetail"] == 1);
                this.chkParks.Checked = ((int)ss.AsEnumerable().FirstOrDefault()["Parks"] == 1);
                this.chkIndustrial.Checked = ((int)ss.AsEnumerable().FirstOrDefault()["Industrial"] == 1);
                this.chkUtility.Checked = ((int)ss.AsEnumerable().FirstOrDefault()["Utility"] == 1);
                this.chkGCSmall.Checked = ((int)ss.AsEnumerable().FirstOrDefault()["GCSmall"] == 1);
                this.chkGCLarge.Checked = ((int)ss.AsEnumerable().FirstOrDefault()["GCLarge"] == 1);
                this.chkOffice.Checked = ((int)ss.AsEnumerable().FirstOrDefault()["Office"] == 1);
                this.chkOther.Checked = ((int)ss.AsEnumerable().FirstOrDefault()["Other"] == 1);
                this.chkMunicipal.Checked = ((int)ss.AsEnumerable().FirstOrDefault()["Municipal"] == 1);
                this.chkPrivate.Checked = ((int)ss.AsEnumerable().FirstOrDefault()["Privates"] == 1);
                this.chkInstitutional.Checked = ((int)ss.AsEnumerable().FirstOrDefault()["Institutional"] == 1);
                this.chkMilitary.Checked = ((int)ss.AsEnumerable().FirstOrDefault()["Military"] == 1);
</code>```

You code is breaking somewhere and that's why it is showing error.

Can you please share screen shot and the data coming in your dataset which is ss

Body:
I have 21 textboxes and 25 checkboxes in a winform and I want to be able to type in these textboxes and check checkboxes and have the corresponding records returned when the statement is executed. At this point whenever I have a select statement with no checkboxes referenced in the where clause I can search by any textbox and have my records returned normally, however when I add in a search by checkbox , no records are returned except ones with  the certain checkboxes checked. So if I typed anything in the textboxes and didn't check a checkbox , I would still get the no record found message.

{

        con.Open();
        string str = "select * from engineering where (JobNumber like '%' + @search + '%' AND DateOrdered
        like '%' + @search1 + '%' AND Title like '%' + @search2 + '%' AND PhysicalAddressComplete like
        '%' + @search3 + '%' AND County like '%' + @search4 + '%' AND Client like '%' + @search5 + '%'
        AND Contact like '%' + @search6 + '%' AND ContactTitle like '%' + @search7 + '%' AND
        MailingAddressComplete like '%' + @search8 + '%' AND BusinessPhone like '%' + @search9 + '%'
        AND CellPhone like '%' + @search10 + '%' AND Email like '%' + @search11 + '%' AND OpenStatus
        like '%' + @search12 + '%' AND CloseStatus like '%' + @search13 + '%' AND Cabinet
        like '%' + @search14 + '%' AND Roll like '%' + @search15 + '%' AND Drawer like '%' + @search16 + '%'
        AND ConstructionDrawings like '%' + @search17 + '%' AND Fee like '%' + @search18 + '%' AND
        ConstructionCost like '%' + @search19 + '%' AND ProjectDescription like '%' + @search20 + '%'
        AND DesignBuild like " + DesignBuild + " )";
        SqlCommand xp = new SqlCommand(str, con);
        xp.Parameters.Add("@search", SqlDbType.NVarChar).Value = txtProjectNumber.Text;
        xp.Parameters.Add("@search1", SqlDbType.NVarChar).Value = txtDateOrdered.Text;
        xp.Parameters.Add("@search2", SqlDbType.NVarChar).Value = txtProjectName.Text;
        xp.Parameters.Add("@search3", SqlDbType.NVarChar).Value = txtProjectAddress.Text;
        xp.Parameters.Add("@search4", SqlDbType.NVarChar).Value = txtCounty.Text;
        xp.Parameters.Add("@search5", SqlDbType.NVarChar).Value = txtClient.Text;
        xp.Parameters.Add("@search6", SqlDbType.NVarChar).Value = txtClientContact.Text;
        xp.Parameters.Add("@search7", SqlDbType.NVarChar).Value = txtContactTitle.Text;
        xp.Parameters.Add("@search8", SqlDbType.NVarChar).Value = txtBillingAddress.Text;
        xp.Parameters.Add("@search9", SqlDbType.NVarChar).Value = txtBusinessPhone.Text;
        xp.Parameters.Add("@search10", SqlDbType.NVarChar).Value = txtCellPhone.Text;
        xp.Parameters.Add("@search11", SqlDbType.NVarChar).Value = txtEmail.Text;
        xp.Parameters.Add("@search12", SqlDbType.NVarChar).Value = txtOpenStatus.Text;
        xp.Parameters.Add("@search13", SqlDbType.NVarChar).Value = txtCloseStatus.Text;
        xp.Parameters.Add("@search14", SqlDbType.NVarChar).Value = txtCabinet.Text;
        xp.Parameters.Add("@search15", SqlDbType.NVarChar).Value = txtRoll.Text;
        xp.Parameters.Add("@search16", SqlDbType.NVarChar).Value = txtDrawer.Text;
        xp.Parameters.Add("@search17", SqlDbType.NVarChar).Value = txtDrawings.Text;
        xp.Parameters.Add("@search18", SqlDbType.NVarChar).Value = txtFee.Text;
        xp.Parameters.Add("@search19", SqlDbType.NVarChar).Value = txtCost.Text;
        xp.Parameters.Add("@search20", SqlDbType.NVarChar).Value = txtProjectDescription.Text;

        try
        {

            da = new SqlDataAdapter();
            da.SelectCommand = xp;
            da.Fill(ss);

            Showdata(pos);
          if (ss.Rows.Count >0)
            {

                this.chkEducational.Checked = ((int)ss.AsEnumerable().FirstOrDefault()["Education"] == 1);
                this.chkDesign.Checked = ((int)ss.AsEnumerable().FirstOrDefault()["DesignBuild"] == 1);
                this.chkMedical.Checked = ((int)ss.AsEnumerable().FirstOrDefault()["Medical"] == 1);
                this.chkReligious.Checked = ((int)ss.AsEnumerable().FirstOrDefault()["Religious"] == 1);
                this.chkMulti.Checked = ((int)ss.AsEnumerable().FirstOrDefault()["MultiFamily"] == 1);
                this.chkStudent.Checked = ((int)ss.AsEnumerable().FirstOrDefault()["Student"] == 1);
                this.chkAssisted.Checked = ((int)ss.AsEnumerable().FirstOrDefault()["Assisted"] == 1);
                this.chkSingleFamily.Checked = ((int)ss.AsEnumerable().FirstOrDefault()["Single"] == 1);
                this.chkBridge.Checked = ((int)ss.AsEnumerable().FirstOrDefault()["Bridge"] == 1);
                this.chkIntersection.Checked = ((int)ss.AsEnumerable().FirstOrDefault()["Intersection"] == 1);
                this.chkRoadway.Checked = ((int)ss.AsEnumerable().FirstOrDefault()["Roadway"] == 1);
                this.chkTransOther.Checked = ((int)ss.AsEnumerable().FirstOrDefault()["TransportationOther"] == 1);
                this.chkRetailSmall.Checked = ((int)ss.AsEnumerable().FirstOrDefault()["SmallRetail"] == 1);
                this.chkRetailLarge.Checked = ((int)ss.AsEnumerable().FirstOrDefault()["LargeRetail"] == 1);
                this.chkParks.Checked = ((int)ss.AsEnumerable().FirstOrDefault()["Parks"] == 1);
                this.chkIndustrial.Checked = ((int)ss.AsEnumerable().FirstOrDefault()["Industrial"] == 1);
                this.chkUtility.Checked = ((int)ss.AsEnumerable().FirstOrDefault()["Utility"] == 1);
                this.chkGCSmall.Checked = ((int)ss.AsEnumerable().FirstOrDefault()["GCSmall"] == 1);
                this.chkGCLarge.Checked = ((int)ss.AsEnumerable().FirstOrDefault()["GCLarge"] == 1);
                this.chkOffice.Checked = ((int)ss.AsEnumerable().FirstOrDefault()["Office"] == 1);
                this.chkOther.Checked = ((int)ss.AsEnumerable().FirstOrDefault()["Other"] == 1);
                this.chkMunicipal.Checked = ((int)ss.AsEnumerable().FirstOrDefault()["Municipal"] == 1);
                this.chkPrivate.Checked = ((int)ss.AsEnumerable().FirstOrDefault()["Privates"] == 1);
                this.chkInstitutional.Checked = ((int)ss.AsEnumerable().FirstOrDefault()["Institutional"] == 1);
                this.chkMilitary.Checked = ((int)ss.AsEnumerable().FirstOrDefault()["Military"] == 1);

            }

        }
        catch
        {
            MessageBox.Show("No Record Found");

        }

        con.Close();

    }

However even still when I do not include the checkbox in the where clause I still get the "no record found message" , then once I click out of that message box my results are shown. Any help with either of these two issues would be great.

Body:
Did you tried debugging your code where you are checking if (ss.Rows.Count >0)

this.chkEducational.Checked = ((int)ss.AsEnumerable().FirstOrDefault()["Education"] == 1);
                this.chkDesign.Checked = ((int)ss.AsEnumerable().FirstOrDefault()["DesignBuild"] == 1);
                this.chkMedical.Checked = ((int)ss.AsEnumerable().FirstOrDefault()["Medical"] == 1);
                this.chkReligious.Checked = ((int)ss.AsEnumerable().FirstOrDefault()["Religious"] == 1);
                this.chkMulti.Checked = ((int)ss.AsEnumerable().FirstOrDefault()["MultiFamily"] == 1);
                this.chkStudent.Checked = ((int)ss.AsEnumerable().FirstOrDefault()["Student"] == 1);
                this.chkAssisted.Checked = ((int)ss.AsEnumerable().FirstOrDefault()["Assisted"] == 1);
                this.chkSingleFamily.Checked = ((int)ss.AsEnumerable().FirstOrDefault()["Single"] == 1);
                this.chkBridge.Checked = ((int)ss.AsEnumerable().FirstOrDefault()["Bridge"] == 1);
                this.chkIntersection.Checked = ((int)ss.AsEnumerable().FirstOrDefault()["Intersection"] == 1);
                this.chkRoadway.Checked = ((int)ss.AsEnumerable().FirstOrDefault()["Roadway"] == 1);
                this.chkTransOther.Checked = ((int)ss.AsEnumerable().FirstOrDefault()["TransportationOther"] == 1);
                this.chkRetailSmall.Checked = ((int)ss.AsEnumerable().FirstOrDefault()["SmallRetail"] == 1);
                this.chkRetailLarge.Checked = ((int)ss.AsEnumerable().FirstOrDefault()["LargeRetail"] == 1);
                this.chkParks.Checked = ((int)ss.AsEnumerable().FirstOrDefault()["Parks"] == 1);
                this.chkIndustrial.Checked = ((int)ss.AsEnumerable().FirstOrDefault()["Industrial"] == 1);
                this.chkUtility.Checked = ((int)ss.AsEnumerable().FirstOrDefault()["Utility"] == 1);
                this.chkGCSmall.Checked = ((int)ss.AsEnumerable().FirstOrDefault()["GCSmall"] == 1);
                this.chkGCLarge.Checked = ((int)ss.AsEnumerable().FirstOrDefault()["GCLarge"] == 1);
                this.chkOffice.Checked = ((int)ss.AsEnumerable().FirstOrDefault()["Office"] == 1);
                this.chkOther.Checked = ((int)ss.AsEnumerable().FirstOrDefault()["Other"] == 1);
                this.chkMunicipal.Checked = ((int)ss.AsEnumerable().FirstOrDefault()["Municipal"] == 1);
                this.chkPrivate.Checked = ((int)ss.AsEnumerable().FirstOrDefault()["Privates"] == 1);
                this.chkInstitutional.Checked = ((int)ss.AsEnumerable().FirstOrDefault()["Institutional"] == 1);
                this.chkMilitary.Checked = ((int)ss.AsEnumerable().FirstOrDefault()["Military"] == 1);

You code is breaking somewhere and that's why it is showing error.

Can you please share screen shot and the data coming in your dataset which is ss


问:
Appending text to div using JS
i have a div and i want to use JS to append text to the div. Currently in my code , the text appears but not on the div.

Why is it not appending onto the div panel ?

$('.panel').append(
  '
 ' +
  '
 item.name
' +
  '
'
);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
  <div class="col-md-8">
    <div class="panel" id="panel">
    </div>
  </div>
</div></code>```

答:
Try</p>

```<code>('#panel').append(
        '<div class="container" style=" width:30%"> '+
        '<p class="name">' + item.name+'</p>'+
         '</div>'

    );
</code>```

Title: Appending text to div using JS

Body:
Try

('#panel').append(
        '<div class="container" style=" width:30%"> '+
        '<p class="name">' + item.name+'</p>'+
         '</div>'

    );


问:
Loop using jquery and javascript
I'm having some trouble thinking of how to do this properly.

Right now, I have some jquery that looks like this:

```<code>$( "#person_0" ).click(function() {
    $( "[id^=person_]" ).removeClass("active");
    $( "#person_0" ).addClass("active");
    $( "[id^=bio_]" ).hide();
    $( "#bio_0" ).show();
    $( "[id^=hoverInfo_]" ).hide();
    $( "#hoverInfo_0" ).show();
});

$( "#person_1" ).click(function() {
    $( "[id^=person_]" ).removeClass("active");
    $( "#person_1" ).addClass("active");
    $( "[id^=bio_]" ).hide();
    $( "#bio_1" ).show();
    $( "[id^=hoverInfo_]" ).hide();
    $( "#hoverInfo_1" ).show();
});
...
...
</code>```

Essentially, if you click a person_0 div id, a class of active is added to that and both hoverInfo_0 and bio_0 show up. At the same time, all other ids go and hide (for example, hoverInfo_1, hoverInfo_2, bio_1, bio_2, etc.

This is super inefficient because I want there to be 100+ person_ ids. I feel like I'm overlooking something obvious.

Pseudo code right now:

```<code>    if person_0 div is clicked
        give person_0 div active class
        show hoverInfo_0
        show bio_0
        hide all other hoverInfo_# (say 1-1000)
        hide all other bio_# (say 1-1000)
    else if person_1 div is clicked
        give person_1 div active class
        show hoverInfo_1
        show bio_1
        hide all hoverInfo_# (say 1-1000) that does not equal hoverInfo_1
        hide all bio_# (say 1-1000) that does not equal bio_1
    else if ...
    else if ...
</code>```

I'm having a hard time trying to figure out how I can loop this around or use a variable in place of the _# value to make this more efficient. Any thoughts?

答:
how I can loop this around or use a variable in place of the _# value
  to make this more efficient. Any thoughts?

Try this approach using starts with and filter

```<code>$( "[id^='person_']" ).click(function() {
    var id = $( this )[0].id;
    console.log(id);
    var counter = id.split("_").pop();

    $( "[id^='person_']" ).addClass("active").not( "#person_" + counter ).removeClass("active");
    $( "[id^='bio_']" ).hide().filter( "#bio_" + counter  ).show();
    $( "[id^='hoverInfo_']" ).hide().filter( "#hoverInfo_" + counter).show();
});
</code>```

Demo

$( "[id^='person_']" ).click(function() {
    var id = $( this )[0].id;
    console.log(id);
    var counter = id.split("_").pop();

    $( "[id^='person_']" ).addClass("active").not( "#person_" + counter ).removeClass("active");
    $( "[id^='bio_']" ).hide().filter( "#bio_" + counter  ).show();
    $( "[id^='hoverInfo_']" ).hide().filter( "#hoverInfo_" + counter).show();
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.bio, .hoberInfo
{
   display: none;
   background-color : green;
}</code>```

Person 1

Bio 1

HoverInfo 1

Person 2

Bio 2

HoverInfo 2

Person 3

Bio 3

HoverInfo 3
```

Title: Loop using jquery and javascript

Body:
I'm having some trouble thinking of how to do this properly.

Right now, I have some jquery that looks like this:

$( "#person_0" ).click(function() {
    $( "[id^=person_]" ).removeClass("active");
    $( "#person_0" ).addClass("active");
    $( "[id^=bio_]" ).hide();
    $( "#bio_0" ).show();
    $( "[id^=hoverInfo_]" ).hide();
    $( "#hoverInfo_0" ).show();
});

$( "#person_1" ).click(function() {
    $( "[id^=person_]" ).removeClass("active");
    $( "#person_1" ).addClass("active");
    $( "[id^=bio_]" ).hide();
    $( "#bio_1" ).show();
    $( "[id^=hoverInfo_]" ).hide();
    $( "#hoverInfo_1" ).show();
});
...
...

Essentially, if you click a person_0 div id, a class of active is added to that and both hoverInfo_0 and bio_0 show up. At the same time, all other ids go and hide (for example, hoverInfo_1, hoverInfo_2, bio_1, bio_2, etc.

This is super inefficient because I want there to be 100+ person_ ids. I feel like I'm overlooking something obvious.

Pseudo code right now:

    if person_0 div is clicked
        give person_0 div active class
        show hoverInfo_0
        show bio_0
        hide all other hoverInfo_# (say 1-1000)
        hide all other bio_# (say 1-1000)
    else if person_1 div is clicked
        give person_1 div active class
        show hoverInfo_1
        show bio_1
        hide all hoverInfo_# (say 1-1000) that does not equal hoverInfo_1
        hide all bio_# (say 1-1000) that does not equal bio_1
    else if ...
    else if ...

I'm having a hard time trying to figure out how I can loop this around or use a variable in place of the _# value to make this more efficient. Any thoughts?

Body:
how I can loop this around or use a variable in place of the _# value
  to make this more efficient. Any thoughts?

Try this approach using starts with and filter

$( "[id^='person_']" ).click(function() {
    var id = $( this )[0].id;
    console.log(id);
    var counter = id.split("_").pop();

    $( "[id^='person_']" ).addClass("active").not( "#person_" + counter ).removeClass("active");
    $( "[id^='bio_']" ).hide().filter( "#bio_" + counter  ).show();
    $( "[id^='hoverInfo_']" ).hide().filter( "#hoverInfo_" + counter).show();
});

Demo

$( "[id^='person_']" ).click(function() {
    var id = $( this )[0].id;
    console.log(id);
    var counter = id.split("_").pop();

    $( "[id^='person_']" ).addClass("active").not( "#person_" + counter ).removeClass("active");
    $( "[id^='bio_']" ).hide().filter( "#bio_" + counter  ).show();
    $( "[id^='hoverInfo_']" ).hide().filter( "#hoverInfo_" + counter).show();
});

.bio, .hoberInfo
{
   display: none;
   background-color : green;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="person_1">Person 1</div>
<div id="bio_1" class="bio">Bio 1</div>
<div id="hoverInfo_1" class="hoberInfo">HoverInfo 1</div>

<div id="person_2">Person 2</div>
<div id="bio_2" class="bio">Bio 2</div>
<div id="hoverInfo_2" class="hoberInfo">HoverInfo 2</div>

<div id="person_3">Person 3</div>
<div id="bio_3" class="bio">Bio 3</div>
<div id="hoverInfo_3" class="hoberInfo">HoverInfo 3</div>


问:
How to store variables for further use from User-input in Java Swing Gui?
I currently have a simple Java AWT/Swing code that creates a simple GUI that takes multiple String User-input and stores and displays it in the Intellij terminal like so:

```<code>import javax.swing.*;
import java.awt.*;        // Using AWT container and component classes
import java.awt.event.*;  // Using AWT event classes and listener interfaces
import java.util.ArrayList;
import java.util.Scanner;

// An AWT program inherits from the top-level container java.awt.Frame
public class DateTime extends JFrame implements ActionListener {
    private Label lblCount, lblsource, lbldate1, lbldate2;    // Declare a Label component
    private JTextField tfCount, date1, date2; // Declare a TextField component
    private Button btnCount;   // Declare a Button component
    private int count = 0;     // Counter's value
    static String type = null;
    private JCheckBox source1, source2;
    boolean a = false;
    boolean b= false;
    static String source, datedefined1, datedefined2;
    ArrayList<String> texts = new ArrayList<String>();
    // Constructor to setup GUI components and event handlers
    public DateTime () {
        setLayout(new FlowLayout());
        // "super" Frame, which is a Container, sets its layout to FlowLayout to arrange
        // the components from left-to-right, and flow to next row from top-to-bottom.

        lblCount = new Label("Enter the type of report you want generated; Hourly/ Daily/ Weekly/ EventComparison:");  // construct the Label component
        add(lblCount);                    // "super" Frame container adds Label component

        tfCount = new JTextField("", 20); // construct the TextField component
        tfCount.setEditable(true);       // set to read-only
                          // "super" Frame container adds TextField component

        tfCount.setBounds(10,50,200,40);
        add(tfCount);
        tfCount.addActionListener(this);

        lblsource = new Label("Now choose the source type:");
        add(lblsource);
        source1 = new JCheckBox("Drivetest", a);
        source1.setBounds(10,100,50,30);
        add(source1);
        source2 = new JCheckBox("Ookla Dump",b);
        add(source2);
        source1.addActionListener(this);
        source2.addActionListener(this);

            lbldate1 = new Label("Please enter the Start DATETIME of the chosen duration(YYYY-MM-DD HH:MM:SS) :");
            add(lbldate1);
            date1 = new JTextField("", 30); // construct the TextField component
            date1.setEditable(true);
            add(date1);
            date1.addActionListener(this);
            lbldate2 = new Label("Please enter the end DATETIME of the chosen duration(YYYY-MM-DD HH:MM:SS): ");
            add(lbldate2);
            date2 = new JTextField("",30);
            date2.setEditable(true);
            add(date2);
            date2.addActionListener(this);

            // set to read-only
            // "super" Frame container adds TextField component

        // "btnCount" is the source object that fires an ActionEvent when clicked.
        // The source add "this" instance as an ActionEvent listener, which provides
        //   an ActionEvent handler called actionPerformed().
        // Clicking "btnCount" invokes actionPerformed().

        setTitle("Report Generator");  // "super" Frame sets its title
        setSize(800, 700);        // "super" Frame sets its initial window size

        // For inspecting the Container/Components objects
        // System.out.println(this);
        // System.out.println(lblCount);
        // System.out.println(tfCount);
        // System.out.println(btnCount);

        setVisible(true);         // "super" Frame shows

        // System.out.println(this);
        // System.out.println(lblCount);
        // System.out.println(tfCount);
        // System.out.println(btnCount);
    }

    // The entry main() method
    public static void main(String[] args) {
        // Invoke the constructor to setup the GUI, by allocating an instance
        DateTime app = new DateTime();

        // or simply "new AWTCounter();" for an anonymous instance

    }

    // ActionEvent handler - Called back upon button-click.
    @Override
    public void actionPerformed(ActionEvent evt) {
        Object actionsource = evt.getSource();
        if(actionsource instanceof JTextField){
            JTextField dateget1 = (JTextField) evt.getSource();
            JTextField dateget2 = (JTextField) evt.getSource();

            if (dateget1 == date1){
            datedefined1 = date1.getText();
                System.out.println(datedefined1);}
            else if(dateget2 == date2){

            datedefined2 = date2.getText();
            System.out.println(datedefined2);}
            else{
                type = tfCount.getText();
                System.out.println(type);

            }

        }
        else if(actionsource instanceof JCheckBox){
            JCheckBox cb = (JCheckBox) evt.getSource();
            if(cb == source1){
                source = "Drivetest";
                System.out.println(source);
            }
            else if(cb == source2){
                source = "Ookla Data Dump";
                System.out.println(source);
            }

        }

    }
}
</code>```

The thing is, my main program needs to take in and store multiple string variables(ie. type, source, date1 AND date2) before it should execute.

My code for a normal terminal-style running of the program would look like this:

```<code> System.out.println("Enter the report type you would like: DailyComparison or HourlyComparison or WeeklyComparison or EventComparison; Type the exact words!");
    type = scan.next();
    System.out.println("Now enter the type of data you would like analysed: OOKLA or ManualTest: ");
    source = scan.next();
    if("DailyComparison".equals(type) || "HourlyComparison".equals(type) || "WeeklyComparison".equals(type) ){
        Scanner scan2 = new Scanner((System.in));
        System.out.println("Now enter the lower bound of the DateTime range(FORMAT YYYY-MM-DD HH:00:00):");
        date1 = scan2.nextLine();
        System.out.println("Now enter the upper bound of the DateTime range(FORMAT YYYY-MM-DD HH:00:00):");
        date2 = scan2.nextLine();
    }
</code>```

Where user-input is taken through the terminal as normal.

The user input is then used to run the rest of the program, calling the methods in other classes i have defined:

```<code>Report.report(date1, date2, type, filename, source);// Creates the excel .xlsx file report

MailSender.MailSender(filename, type); // Send a email containing the attached report xlsx file
</code>```

So my question is: How do i extend this GUI code's functionality so that the user-input string variables can ALL be gathered first then used to run the rest of the program?

EDIT:

Thanks for the advice guys.

I sort of got it to work, but I'm not sure if the structure is sound. What was happening previously was that since each component was handling a different variable and i wanted to store all the variables first before calling the main method classes that would process these variables.

So i created an additional button called "Generate Report" and under the actionlistener condition+action for this button, I placed the class.methods like so. Where basically I key in all my variables in the respective components(checkboxes, button etc) THEN press "generate report"

```<code> if (evt.getActionCommand() == "Generate Report") {

                if ("DailyComparison".equals(type)) {
                    filename = "\\Users\\User\\Documents\\Reports\\" + " Daily SpeedTest Telco Comparison Report";
                    datedefined3 = null;
                    datedefined4 = null;
                    datedefined5 = null;
                    datedefined6 = null;
                } else if ("WeeklyComparison".equals(type)) {
                    filename = "\\Users\\User\\Documents\\Reports\\" + " Weekly Telco Comparison Report";
                    datedefined3 = null;
                    datedefined4 = null;
                    datedefined5 = null;
                    datedefined6 = null;
                } else if ("HourlyComparison".equals(type)) {
                    filename = "\\Users\\User\\Documents\\Reports\\" + "Hourly Telco Comparison Report";
                    datedefined3 = null;
                    datedefined4 = null;
                    datedefined5 = null;
                    datedefined6 = null;
                }
                if("HourlyComparison".equals(type)|"DailyComparison".equals(type)|"WeeklyComparison".equals(type)) {
                    Report.report(datedefined1, datedefined2, datedefined3, datedefined4, datedefined5, datedefined6, type, filename, source);// Creates the base excel .xlsx file report
                    LinechartGenerator.chartgen(0, "upload", datedefined1, datedefined2, datedefined3, datedefined4, datedefined5, datedefined6, source, type, filename);
                    LinechartGenerator.chartgen(0, "download", datedefined1, datedefined2, datedefined3, datedefined4, datedefined5, datedefined6, source, type, filename);
                    LinechartGenerator.chartgen(0, "latency", datedefined1, datedefined2, datedefined3, datedefined4, datedefined5, datedefined6, source, type, filename);
        }

    }
</code>```

Although the code has its limitations where I cannot press generate report first or the program will just throw an error seeing as no variables were stored.

I also faced a roadblock where I'm trying to find the Swing-equivalent of the Flush Scanner function to allow the user to generate multiple reports in the same program instance.

答:
I noticed that you set this as the action listener for all the check boxes and textfields. What I think you really want, is to only process the user input when the user clicks the button, right?

Remove lines like these:

```<code>tfCount.addActionListener(this);
</code>```

so that this only handles the click of the button.

Now, you can access all the inputs in the actionPerformed method:

```<code>dateDefined1 = date1.getText();
dateDefined2 = date2.getText();
type = tfCount.getText();
if (source1.isChecked()) {
    source = "Drivertest";
} else {
    source = "Ookla Data Dump"
}
// now you can use dateDefined1, dateDefined2, type and source!
</code>```

Also, why use check boxes but not radio buttons? For this kind of "select one from the below option" usage, radio buttons are better suited.

Body:
I currently have a simple Java AWT/Swing code that creates a simple GUI that takes multiple String User-input and stores and displays it in the Intellij terminal like so:

import javax.swing.*;
import java.awt.*;        // Using AWT container and component classes
import java.awt.event.*;  // Using AWT event classes and listener interfaces
import java.util.ArrayList;
import java.util.Scanner;

// An AWT program inherits from the top-level container java.awt.Frame
public class DateTime extends JFrame implements ActionListener {
    private Label lblCount, lblsource, lbldate1, lbldate2;    // Declare a Label component
    private JTextField tfCount, date1, date2; // Declare a TextField component
    private Button btnCount;   // Declare a Button component
    private int count = 0;     // Counter's value
    static String type = null;
    private JCheckBox source1, source2;
    boolean a = false;
    boolean b= false;
    static String source, datedefined1, datedefined2;
    ArrayList<String> texts = new ArrayList<String>();
    // Constructor to setup GUI components and event handlers
    public DateTime () {
        setLayout(new FlowLayout());
        // "super" Frame, which is a Container, sets its layout to FlowLayout to arrange
        // the components from left-to-right, and flow to next row from top-to-bottom.

        lblCount = new Label("Enter the type of report you want generated; Hourly/ Daily/ Weekly/ EventComparison:");  // construct the Label component
        add(lblCount);                    // "super" Frame container adds Label component

        tfCount = new JTextField("", 20); // construct the TextField component
        tfCount.setEditable(true);       // set to read-only
                          // "super" Frame container adds TextField component

        tfCount.setBounds(10,50,200,40);
        add(tfCount);
        tfCount.addActionListener(this);

        lblsource = new Label("Now choose the source type:");
        add(lblsource);
        source1 = new JCheckBox("Drivetest", a);
        source1.setBounds(10,100,50,30);
        add(source1);
        source2 = new JCheckBox("Ookla Dump",b);
        add(source2);
        source1.addActionListener(this);
        source2.addActionListener(this);

            lbldate1 = new Label("Please enter the Start DATETIME of the chosen duration(YYYY-MM-DD HH:MM:SS) :");
            add(lbldate1);
            date1 = new JTextField("", 30); // construct the TextField component
            date1.setEditable(true);
            add(date1);
            date1.addActionListener(this);
            lbldate2 = new Label("Please enter the end DATETIME of the chosen duration(YYYY-MM-DD HH:MM:SS): ");
            add(lbldate2);
            date2 = new JTextField("",30);
            date2.setEditable(true);
            add(date2);
            date2.addActionListener(this);

            // set to read-only
            // "super" Frame container adds TextField component

        // "btnCount" is the source object that fires an ActionEvent when clicked.
        // The source add "this" instance as an ActionEvent listener, which provides
        //   an ActionEvent handler called actionPerformed().
        // Clicking "btnCount" invokes actionPerformed().

        setTitle("Report Generator");  // "super" Frame sets its title
        setSize(800, 700);        // "super" Frame sets its initial window size

        // For inspecting the Container/Components objects
        // System.out.println(this);
        // System.out.println(lblCount);
        // System.out.println(tfCount);
        // System.out.println(btnCount);

        setVisible(true);         // "super" Frame shows

        // System.out.println(this);
        // System.out.println(lblCount);
        // System.out.println(tfCount);
        // System.out.println(btnCount);
    }

    // The entry main() method
    public static void main(String[] args) {
        // Invoke the constructor to setup the GUI, by allocating an instance
        DateTime app = new DateTime();

        // or simply "new AWTCounter();" for an anonymous instance

    }

    // ActionEvent handler - Called back upon button-click.
    @Override
    public void actionPerformed(ActionEvent evt) {
        Object actionsource = evt.getSource();
        if(actionsource instanceof JTextField){
            JTextField dateget1 = (JTextField) evt.getSource();
            JTextField dateget2 = (JTextField) evt.getSource();

            if (dateget1 == date1){
            datedefined1 = date1.getText();
                System.out.println(datedefined1);}
            else if(dateget2 == date2){

            datedefined2 = date2.getText();
            System.out.println(datedefined2);}
            else{
                type = tfCount.getText();
                System.out.println(type);

            }

        }
        else if(actionsource instanceof JCheckBox){
            JCheckBox cb = (JCheckBox) evt.getSource();
            if(cb == source1){
                source = "Drivetest";
                System.out.println(source);
            }
            else if(cb == source2){
                source = "Ookla Data Dump";
                System.out.println(source);
            }

        }

    }
}

The thing is, my main program needs to take in and store multiple string variables(ie. type, source, date1 AND date2) before it should execute.

My code for a normal terminal-style running of the program would look like this:

 System.out.println("Enter the report type you would like: DailyComparison or HourlyComparison or WeeklyComparison or EventComparison; Type the exact words!");
    type = scan.next();
    System.out.println("Now enter the type of data you would like analysed: OOKLA or ManualTest: ");
    source = scan.next();
    if("DailyComparison".equals(type) || "HourlyComparison".equals(type) || "WeeklyComparison".equals(type) ){
        Scanner scan2 = new Scanner((System.in));
        System.out.println("Now enter the lower bound of the DateTime range(FORMAT YYYY-MM-DD HH:00:00):");
        date1 = scan2.nextLine();
        System.out.println("Now enter the upper bound of the DateTime range(FORMAT YYYY-MM-DD HH:00:00):");
        date2 = scan2.nextLine();
    }

Where user-input is taken through the terminal as normal.

The user input is then used to run the rest of the program, calling the methods in other classes i have defined:

Report.report(date1, date2, type, filename, source);// Creates the excel .xlsx file report

MailSender.MailSender(filename, type); // Send a email containing the attached report xlsx file

So my question is: How do i extend this GUI code's functionality so that the user-input string variables can ALL be gathered first then used to run the rest of the program?

EDIT:

Thanks for the advice guys.

I sort of got it to work, but I'm not sure if the structure is sound. What was happening previously was that since each component was handling a different variable and i wanted to store all the variables first before calling the main method classes that would process these variables.

So i created an additional button called "Generate Report" and under the actionlistener condition+action for this button, I placed the class.methods like so. Where basically I key in all my variables in the respective components(checkboxes, button etc) THEN press "generate report"

 if (evt.getActionCommand() == "Generate Report") {

                if ("DailyComparison".equals(type)) {
                    filename = "\\Users\\User\\Documents\\Reports\\" + " Daily SpeedTest Telco Comparison Report";
                    datedefined3 = null;
                    datedefined4 = null;
                    datedefined5 = null;
                    datedefined6 = null;
                } else if ("WeeklyComparison".equals(type)) {
                    filename = "\\Users\\User\\Documents\\Reports\\" + " Weekly Telco Comparison Report";
                    datedefined3 = null;
                    datedefined4 = null;
                    datedefined5 = null;
                    datedefined6 = null;
                } else if ("HourlyComparison".equals(type)) {
                    filename = "\\Users\\User\\Documents\\Reports\\" + "Hourly Telco Comparison Report";
                    datedefined3 = null;
                    datedefined4 = null;
                    datedefined5 = null;
                    datedefined6 = null;
                }
                if("HourlyComparison".equals(type)|"DailyComparison".equals(type)|"WeeklyComparison".equals(type)) {
                    Report.report(datedefined1, datedefined2, datedefined3, datedefined4, datedefined5, datedefined6, type, filename, source);// Creates the base excel .xlsx file report
                    LinechartGenerator.chartgen(0, "upload", datedefined1, datedefined2, datedefined3, datedefined4, datedefined5, datedefined6, source, type, filename);
                    LinechartGenerator.chartgen(0, "download", datedefined1, datedefined2, datedefined3, datedefined4, datedefined5, datedefined6, source, type, filename);
                    LinechartGenerator.chartgen(0, "latency", datedefined1, datedefined2, datedefined3, datedefined4, datedefined5, datedefined6, source, type, filename);
        }

    }

Although the code has its limitations where I cannot press generate report first or the program will just throw an error seeing as no variables were stored.

I also faced a roadblock where I'm trying to find the Swing-equivalent of the Flush Scanner function to allow the user to generate multiple reports in the same program instance.

Body:
I noticed that you set this as the action listener for all the check boxes and textfields. What I think you really want, is to only process the user input when the user clicks the button, right?

Remove lines like these:

tfCount.addActionListener(this);

so that this only handles the click of the button.

Now, you can access all the inputs in the actionPerformed method:

dateDefined1 = date1.getText();
dateDefined2 = date2.getText();
type = tfCount.getText();
if (source1.isChecked()) {
    source = "Drivertest";
} else {
    source = "Ookla Data Dump"
}
// now you can use dateDefined1, dateDefined2, type and source!

Also, why use check boxes but not radio buttons? For this kind of "select one from the below option" usage, radio buttons are better suited.


问:
Shapefile reader in Python?
Are there any libraries that I can use to read a shp/shx/dbf/sbx set of files? I mainly need to extract some polygons but something that lets me extract any data that I want would be awesome. </p>

答:
To use the Python Shapefile Library download shapefile.py:
http://code.google.com/p/pyshp/source/browse/trunk/shapefile.py

Place it in your working directory or in your Python site-packages directory and you are ready to go.

Just type "import shapefile" in your interpreter or python script and follow usage examples and documentation at the PyShp project on Google Code.

Title: Shapefile reader in Python?


问:
How to insert data to elastic search from search query
I try to copy some data from one elastic db to another elasticsearch db, is there any way to insert data from query results?

Example of results:

```<code>{
  "took": 29,
  "timed_out": false,
  "_shards": {
    "total": 2,
    "successful": 2,
    "failed": 0
  },
  "hits": {
  "total": 572,
  "max_score": 1,
  "hits": [
    {
      "_index": "ref",
      "_type": "dic",
      "_id": "12345",
      "_score": 1,
      "_source": {
        "name": "Test name"
      }
    },
    ...
  ]
}
</code>```

In each db mapping is equals.

答:
I fork some project witch make a bulk data for elasticsearch, json-to-es-bulk

I it's compability with 5.6 es version, you can use it in 2 variants:

```<code>`node index.js -f inputdata.json --index newIndexName --type newIndexType --rewrite true`
</code>```

or

```<code>`node index.js -f inputdata.json --index --type --rewrite false`
</code>```

after run, you'll see a file request-data.txt, just use it to
POST /_bulk
[request-data.txt content]

Input data json file must contains an array of search hits, like this:

[
   {
      "_index": "oldIndexName",
      "_type": "oldIndexName",
      "_id": "SOME_ID-HiTfm",
      "_score": 1,
      "_source": {
         "orderNumber": "2984",
         "refId": "SOME_VALUE"
      }
   },
   ...
]

Body:
I try to copy some data from one elastic db to another elasticsearch db, is there any way to insert data from query results?

Example of results:

{
  "took": 29,
  "timed_out": false,
  "_shards": {
    "total": 2,
    "successful": 2,
    "failed": 0
  },
  "hits": {
  "total": 572,
  "max_score": 1,
  "hits": [
    {
      "_index": "ref",
      "_type": "dic",
      "_id": "12345",
      "_score": 1,
      "_source": {
        "name": "Test name"
      }
    },
    ...
  ]
}

In each db mapping is equals.

Body:
I fork some project witch make a bulk data for elasticsearch, json-to-es-bulk

I it's compability with 5.6 es version, you can use it in 2 variants:

`node index.js -f inputdata.json --index newIndexName --type newIndexType --rewrite true`

or

`node index.js -f inputdata.json --index --type --rewrite false`

after run, you'll see a file request-data.txt, just use it to
POST /_bulk
[request-data.txt content]

Input data json file must contains an array of search hits, like this:

[
   {
      "_index": "oldIndexName",
      "_type": "oldIndexName",
      "_id": "SOME_ID-HiTfm",
      "_score": 1,
      "_source": {
         "orderNumber": "2984",
         "refId": "SOME_VALUE"
      }
   },
   ...
]


问:
Clicking the back button twice to exit an activity
I've noticed this pattern in a lot of Android apps and games recently: when clicking the back button to "exit" the application, a Toast comes up with a message similar to "Please click BACK again to exit".

I was wondering, as I'm seeing it more and more often, is that a built-in feature that you can somehow access in an activity? I've looked at the source code of many classes but I can't seem to find anything about that.

Of course, I can think about a few ways to achieve the same functionality quite easily (the easiest is probably to keep a boolean in the activity that indicates whether the user already clicked once...) but I was wondering if there's something already here.

EDIT: As @LAS_VEGAS mentioned, I didn't really mean "exit" in the traditional meaning. (i.e. terminated) I meant "going back to whatever was open before the application start activity was launched", if that makes sense :)

答:
Here, I have generalized write the code for N tap counts. The code is similarly written for the Enable Developer option in android device phone. Even you can use this to enable features while developer testing the app.

```<code> private Handler tapHandler;
 private Runnable tapRunnable;
 private int mTapCount = 0;
 private int milSecDealy = 2000;

onCreate(){
 ...
tapHandler = new Handler(Looper.getMainLooper());

 }
</code>```

Call askToExit() on backpress or logout option.

```<code>private void askToExit() {
   if (mTapCount >= 2) {
    releaseTapValues();
    /* ========= Exit = TRUE  =========  */
   }

   mTapCount++;
   validateTapCount();
  }

  /* Check with null to avoid create multiple instances of the runnable */
  private void validateTapCount() {
   if (tapRunnable == null) {
    tapRunnable = new Runnable() {
     @Override
     public void run() {
      releaseTapValues();
      /* ========= Exit = FALSE  =========  */
     }
    };
    tapHandler.postDelayed(tapRunnable, milSecDealy);
   }
  }

  private void releaseTapValues() {
   /* Relase the value  */
   if (tapHandler != null) {
    tapHandler.removeCallbacks(tapRunnable);
    tapRunnable = null; /* release the object */
    mTapCount = 0; /* release the value */
   }
  }

  @Override
  protected void onDestroy() {
   super.onDestroy();
   releaseTapValues();
  }
</code>```

Body:
Here, I have generalized write the code for N tap counts. The code is similarly written for the Enable Developer option in android device phone. Even you can use this to enable features while developer testing the app.

 private Handler tapHandler;
 private Runnable tapRunnable;
 private int mTapCount = 0;
 private int milSecDealy = 2000;

onCreate(){
 ...
tapHandler = new Handler(Looper.getMainLooper());

 }

Call askToExit() on backpress or logout option.

private void askToExit() {
   if (mTapCount >= 2) {
    releaseTapValues();
    /* ========= Exit = TRUE  =========  */
   }

   mTapCount++;
   validateTapCount();
  }

  /* Check with null to avoid create multiple instances of the runnable */
  private void validateTapCount() {
   if (tapRunnable == null) {
    tapRunnable = new Runnable() {
     @Override
     public void run() {
      releaseTapValues();
      /* ========= Exit = FALSE  =========  */
     }
    };
    tapHandler.postDelayed(tapRunnable, milSecDealy);
   }
  }

  private void releaseTapValues() {
   /* Relase the value  */
   if (tapHandler != null) {
    tapHandler.removeCallbacks(tapRunnable);
    tapRunnable = null; /* release the object */
    mTapCount = 0; /* release the value */
   }
  }

  @Override
  protected void onDestroy() {
   super.onDestroy();
   releaseTapValues();
  }


问:
Cython setup error : Unable to find pgen, not compiling formal grammar
In order to install cython ( for python 2.7 , windows 8.1 ), made the download in .zip format, extracted the whole file and run the setup.py . Thus, python shell shows this :
Unable to find pgen, not compiling formal grammar.

What is the problem and how it can be solved ?

答:
Try folollowing command,</p>

```<code>sudo apt-get install build-essential python-dev python-pip libev4 libev-dev
sudo apt-get install cython3
</code>```

Body:
Try folollowing command,

sudo apt-get install build-essential python-dev python-pip libev4 libev-dev
sudo apt-get install cython3


问:
Python, using Full .NET?
I was trying out python in my browser using silverlight which is cool. Can i use python with .NET in a console or winform app? I hear silverlight is a stripped down .NET so it will load (or have a smaller download) on client machines. Can i use python with the full power of .NET? (perhaps outside of silver light)</p>

答:
Yep, check out IronPython: http://ironpython.codeplex.com/

It will work in any .NET app.

Title: Python, using Full .NET?


答:
This would invoke some basic principles:

Model-View-Controller - where the "data" is separated from the view and mechanisms used to collect it

Observer pattern - which is used to generate notifications when some state changes so interested parties can take action.

The observer pattern is used extensively in most UI frameworks, which tend to be event driven (something happens, you respond to it), rather then procedural or linear driven.

Typically, you would create a "form" which included the fields which would capture the data you need and some kind of "button", which when pressed, would initiate the next step - validating the data, building the model and generating the notification that the form has been completed.

The observer to this would then take the model and process it as required.

These are just some of the basic concepts used in UI development.  Have a look at:

Creating a GUI With JFC/Swing

How to use buttons

How to write Action Listeners

for some more details

Title: How to store variables for further use from User-input in Java Swing Gui?


问:
Angular 5 No provider for Window
My Angular 5 app is building fine with npm start, but when I navigate to a particular component in Chrome, I'm getting this cryptic error in the console. I can't find a single mention of it in search.

(I'm trying to upgrade this component from Angular 4 to Angular 5.)

```<code>core.js:1350 ERROR Error: Uncaught (in promise): Error: StaticInjectorError[Window]:
  StaticInjectorError[Window]:
    NullInjectorError: No provider for Window!
Error: StaticInjectorError[Window]:
  StaticInjectorError[Window]:
    NullInjectorError: No provider for Window!
    at _NullInjector.get (core.js:923)
    at resolveToken (core.js:1211)
    at tryResolveToken (core.js:1153)
    at StaticInjector.get (core.js:1024)
    at resolveToken (core.js:1211)
    at tryResolveToken (core.js:1153)
    at StaticInjector.get (core.js:1024)
    at resolveNgModuleDep (core.js:10584)
    at NgModuleRef_.get (core.js:11805)
    at resolveNgModuleDep (core.js:10584)
    at _NullInjector.get (core.js:923)
    at resolveToken (core.js:1211)
    at tryResolveToken (core.js:1153)
    at StaticInjector.get (core.js:1024)
    at resolveToken (core.js:1211)
    at tryResolveToken (core.js:1153)
    at StaticInjector.get (core.js:1024)
    at resolveNgModuleDep (core.js:10584)
    at NgModuleRef_.get (core.js:11805)
    at resolveNgModuleDep (core.js:10584)
    at resolvePromise (zone.js:824)
    at resolvePromise (zone.js:795)
    at eval (zone.js:873)
    at ZoneDelegate.invokeTask (zone.js:425)
    at Object.onInvokeTask (core.js:4617)
    at ZoneDelegate.invokeTask (zone.js:424)
    at Zone.runTask (zone.js:192)
    at drainMicroTaskQueue (zone.js:602)
    at <anonymous>
</code>```

答:
Check your module.ts. This error says you have used window but it is not defined in your module.ts Provider.

Example:

```<code>providers: [
    Window
],
</code>```

Title: Angular 5 No provider for Window

Body:
My Angular 5 app is building fine with npm start, but when I navigate to a particular component in Chrome, I'm getting this cryptic error in the console. I can't find a single mention of it in search.

(I'm trying to upgrade this component from Angular 4 to Angular 5.)

core.js:1350 ERROR Error: Uncaught (in promise): Error: StaticInjectorError[Window]:
  StaticInjectorError[Window]:
    NullInjectorError: No provider for Window!
Error: StaticInjectorError[Window]:
  StaticInjectorError[Window]:
    NullInjectorError: No provider for Window!
    at _NullInjector.get (core.js:923)
    at resolveToken (core.js:1211)
    at tryResolveToken (core.js:1153)
    at StaticInjector.get (core.js:1024)
    at resolveToken (core.js:1211)
    at tryResolveToken (core.js:1153)
    at StaticInjector.get (core.js:1024)
    at resolveNgModuleDep (core.js:10584)
    at NgModuleRef_.get (core.js:11805)
    at resolveNgModuleDep (core.js:10584)
    at _NullInjector.get (core.js:923)
    at resolveToken (core.js:1211)
    at tryResolveToken (core.js:1153)
    at StaticInjector.get (core.js:1024)
    at resolveToken (core.js:1211)
    at tryResolveToken (core.js:1153)
    at StaticInjector.get (core.js:1024)
    at resolveNgModuleDep (core.js:10584)
    at NgModuleRef_.get (core.js:11805)
    at resolveNgModuleDep (core.js:10584)
    at resolvePromise (zone.js:824)
    at resolvePromise (zone.js:795)
    at eval (zone.js:873)
    at ZoneDelegate.invokeTask (zone.js:425)
    at Object.onInvokeTask (core.js:4617)
    at ZoneDelegate.invokeTask (zone.js:424)
    at Zone.runTask (zone.js:192)
    at drainMicroTaskQueue (zone.js:602)
    at <anonymous>

Body:
Check your module.ts. This error says you have used window but it is not defined in your module.ts Provider.

Example:

providers: [
    Window
],


答:
Why is it not appending onto the div panel ?

It works as expected, just add some border-color to the container div to verify.

$('.panel').append(
  '
 ' +
  '
 item.name
' +
  '
'

);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.container
{
  border: 1px solid red;
}</code>```

```

Title: Appending text to div using JS

Body:
i have a div and i want to use JS to append text to the div. Currently in my code , the text appears but not on the div.

Why is it not appending onto the div panel ?

$('.panel').append(
  '
 ' +
  '
 item.name
' +
  '
'
);

Body:
Why is it not appending onto the div panel ?

It works as expected, just add some border-color to the container div to verify.

$('.panel').append(
  '<div class="container" style=" width:30%"> ' +
  '<p class="name"> item.name</p>' +
  '</div>'

);

.container
{
  border: 1px solid red;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
  <div class="col-md-8">
    <div class="panel" id="panel"></div>
  </div>
</div>


问:
Fill form via chrome extension popup
I want to load values from fill.js and when the anchor link in extension popup.html is clicked it will autofill form fields on a remote page that has field IDs of #user + #pw. This is what i currently have in my extension but i'm not sure if it's missing something in the manifest file or if back.js is needed.

fill.js

```<code>chrome.runtime.onMessage.addListener(function (msg, sender, sendResponse) {
if (msg.action === "fillFields") {
    $("#user").val("name@email.com")
    $("#pw").val("pass123")
}
});
</code>```

popup.js

```<code>$("#fill").on("click", function(){
chrome.runtime.sendMessage({
    action: 'fillFields'
});
</code>```

});

popup.html

```<code><!DOCTYPE html>
<html>
<head>
<title>Autofill</title>
<script src="jquery.js"></script>
<script src="popup.js"></script>
</head>
<a href="#" id="fill">Fill</a>
</body>
</html>
</code>```

manifest.json

```<code>    {
    "manifest_version": 2,
    "name": "Autofill",
    "description": "",
    "version": "1.0",

    "browser_action": {
      "default_icon": "icon.png",
       "default_title": "Autofill",
       "default_popup": "popup.html"
    },

    "permissions": [
      "tabs",
      "http://*/*",
      "https://*/*"
    ]
  }
</code>```

Remote form fields

```<code><input name="user" type="text" id="user">
<input name="pw" type="text" id="pw">
</code>```

答:
You can't access the #fill element from your fill.js, which is injected into the page (i.e. a content script). The popup runs in one scope, the content in another and background in another.

Injecting the jquery and fill scripts as you're doing on the browser action is better than loading it in the manifest because it'll only inject when needed and the handler will be ready by the time you click fill in the popup.

Add this to popup.html:

```<code><script src="jquery.js"></script>
<script src="popup.js"></script>
</code>```

popup.js:

```<code>$("#fill").on("click", function(){
    chrome.runtime.sendMessage({
        action: 'fillFields'
    });
});
</code>```

fill.js:

```<code>chrome.runtime.onMessage.addListener(function (msg, sender, sendResponse) {
    if (msg.action === "fillFields") {
        $("#user").val("name@email.com")
        $("#pw").val("pass123")
    }
});
</code>```

Lookup run_at to have control over when scripts are injected. You should have no problem as there's a natural delay between browser action click and being able to click fill.

Title: Fill form via chrome extension popup

Body:
I want to load values from fill.js and when the anchor link in extension popup.html is clicked it will autofill form fields on a remote page that has field IDs of #user + #pw. This is what i currently have in my extension but i'm not sure if it's missing something in the manifest file or if back.js is needed.

fill.js

chrome.runtime.onMessage.addListener(function (msg, sender, sendResponse) {
if (msg.action === "fillFields") {
    $("#user").val("name@email.com")
    $("#pw").val("pass123")
}
});

popup.js

$("#fill").on("click", function(){
chrome.runtime.sendMessage({
    action: 'fillFields'
});

});

popup.html

<!DOCTYPE html>

<title>Autofill</title>

Fill

manifest.json

    {
    "manifest_version": 2,
    "name": "Autofill",
    "description": "",
    "version": "1.0",

    "browser_action": {
      "default_icon": "icon.png",
       "default_title": "Autofill",
       "default_popup": "popup.html"
    },

    "permissions": [
      "tabs",
      "http://*/*",
      "https://*/*"
    ]
  }

Remote form fields

<input name="user" type="text" id="user">
<input name="pw" type="text" id="pw">

Body:
You can't access the #fill element from your fill.js, which is injected into the page (i.e. a content script). The popup runs in one scope, the content in another and background in another.

Injecting the jquery and fill scripts as you're doing on the browser action is better than loading it in the manifest because it'll only inject when needed and the handler will be ready by the time you click fill in the popup.

Add this to popup.html:

<script src="jquery.js"></script>
<script src="popup.js"></script>

popup.js:

$("#fill").on("click", function(){
    chrome.runtime.sendMessage({
        action: 'fillFields'
    });
});

fill.js:

chrome.runtime.onMessage.addListener(function (msg, sender, sendResponse) {
    if (msg.action === "fillFields") {
        $("#user").val("name@email.com")
        $("#pw").val("pass123")
    }
});

Lookup run_at to have control over when scripts are injected. You should have no problem as there's a natural delay between browser action click and being able to click fill.


问:
Help! My wxMac app does not accept mouse or keyboard input
I have followed the wxWidgets "hello world" tutorial here: http://www.wxwidgets.org/docs/tutorials/hello.htm

Everything seems fine, the program compiles and starts, but the app is totally unresponsive. I can't click the window to front or move it. What could be wrong?

I am using wxMac on Snow Leopard.

答:
You must create a bundle for Carbon and Cocoa apps on OS X.

If your binary is named "foo" then this works for testing purposes (don't ship like this):

```<code> mkdir -p foo.app/Contents/MacOS
 mv foo foo.app/Contents/MacOS
</code>```

When you get things working you can eventually tweak your build system to make the bundle before the final link step and pass -o foo.app/Contents/MacOS/foo to the linker rather than plain -o foo.

For a Makefile that automates this, see the wxWidgets web forum.

Body:
You must create a bundle for Carbon and Cocoa apps on OS X.

If your binary is named "foo" then this works for testing purposes (don't ship like this):

 mkdir -p foo.app/Contents/MacOS
 mv foo foo.app/Contents/MacOS

When you get things working you can eventually tweak your build system to make the bundle before the final link step and pass -o foo.app/Contents/MacOS/foo to the linker rather than plain -o foo.

For a Makefile that automates this, see the wxWidgets web forum.


问:
Jquery validate plugin change default message
How can I change the default require message in Jquery validation plugin.  I have tried the following, but it still prints the default message:

```<code>$("#form1").validate({
        ignore: [],
        debug: false,
        rules: {
            firstName: {
                required: true,
                minlength: 2,
                maxlength: 200
            }
            message: {
                firstName:{
                    required: "Custom error message."
                }
            }
        }
    });
});
</code>```

UPDATE

I change my message into messages

```<code> messages: {
             firstName:"Custom error message."
}
</code>```

答:
```<code>$("#form1").validate({
    ignore: [],
    debug: false,
    rules: {
        firstName: {
            required: true,
            minlength: 2,
            maxlength: 200
        },
        messages: {
            firstName:{
                required: "Firstname required",
                minlength: "Min length is 2",
                maxlength: "Max length is 200",
            }
        }
    }
});
</code>```

Body:
How can I change the default require message in Jquery validation plugin.  I have tried the following, but it still prints the default message:

$("#form1").validate({
        ignore: [],
        debug: false,
        rules: {
            firstName: {
                required: true,
                minlength: 2,
                maxlength: 200
            }
            message: {
                firstName:{
                    required: "Custom error message."
                }
            }
        }
    });
});

UPDATE

I change my message into messages

 messages: {
             firstName:"Custom error message."
}


问:
Struggling with editing .csv file using php
I am creating a contact list for a school project using Php. I am storing all the contact info inside a .csv file. I managed to dynamically display the csv file inside index.php. each person in the contact list has uniqueid assigned to them. Now I am struggling with editing the csv file based on the uniqueid.
these are the codes I have written so far.</p>

```<code>function
edit_csv($filename, $no_rows, $id){
    $file_open = fopen($filename, 'w');
    foreach ($no_rows as $newRow){
        if($newRow[0] === $id){
            file_put_contents($filename, serialize($newRow));
        }
    }
    fclose($file_open);

}

function edit_Contact($titleEdit,$fnameEdit,$lnameEdit,$emailEdit,$websiteEdit,$cPhoneNumEdit,$hPhoneNumEdit,$oPhoneNumEdit,$twitterEdit,$facebookEdit,$commentEdit){
    $data = read_csv('contract_data.csv'); // just reads the .csv file
    $handle = fopen('ids', 'r');  // unique id stored here.
    $id = fread($handle, filesize('ids'));
    fclose($handle);

        $data[] = array(
        'sr_no' => $id,
        'Title' => $titleEdit,
        'FirstName' => $fnameEdit,
        'LastName' => $lnameEdit,
        'email' => $emailEdit,
        'website' => $websiteEdit,
        'CellPhoneNumber' => $cPhoneNumEdit,
        'HomePhoneNumber' => $hPhoneNumEdit,
        'OfficePhoneNumber' => $oPhoneNumEdit,
        'twitter' => $twitterEdit,
        'Facebook' => $facebookEdit,
        'Comment' => $commentEdit
        );
        edit_csv('contract_data.csv', $data, $id);

        return $data;

}
</code>```

答:
How about using fputcsv instead of file_put_contents like below,

example code:-

```<code>$path = "C:\\path\\to\\your\\file.csv";
if (($handle = fopen($path, "r+")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        if($data[0]==2){ //desired line to update
            $write_data = array(
                        'sr_no' => $id,
                        'Title' => $titleEdit,
                        'FirstName' => $fnameEdit,
                        'LastName' => $lnameEdit,
                        'email' => $emailEdit,
                        'website' => $websiteEdit,
                        'CellPhoneNumber' => $cPhoneNumEdit,
                        'HomePhoneNumber' => $hPhoneNumEdit,
                        'OfficePhoneNumber' => $oPhoneNumEdit,
                        'twitter' => $twitterEdit,
                        'Facebook' => $facebookEdit,
                        'Comment' => $commentEdit
                        );
            fputcsv($handle, $write_data, ',', '"');
            unset($write_data);
        }
    }
    fclose($handle);
}
</code>```

Body:
I am creating a contact list for a school project using Php. I am storing all the contact info inside a .csv file. I managed to dynamically display the csv file inside index.php. each person in the contact list has uniqueid assigned to them. Now I am struggling with editing the csv file based on the uniqueid.
these are the codes I have written so far.

function
edit_csv($filename, $no_rows, $id){
    $file_open = fopen($filename, 'w');
    foreach ($no_rows as $newRow){
        if($newRow[0] === $id){
            file_put_contents($filename, serialize($newRow));
        }
    }
    fclose($file_open);

}

function edit_Contact($titleEdit,$fnameEdit,$lnameEdit,$emailEdit,$websiteEdit,$cPhoneNumEdit,$hPhoneNumEdit,$oPhoneNumEdit,$twitterEdit,$facebookEdit,$commentEdit){
    $data = read_csv('contract_data.csv'); // just reads the .csv file
    $handle = fopen('ids', 'r');  // unique id stored here.
    $id = fread($handle, filesize('ids'));
    fclose($handle);

        $data[] = array(
        'sr_no' => $id,
        'Title' => $titleEdit,
        'FirstName' => $fnameEdit,
        'LastName' => $lnameEdit,
        'email' => $emailEdit,
        'website' => $websiteEdit,
        'CellPhoneNumber' => $cPhoneNumEdit,
        'HomePhoneNumber' => $hPhoneNumEdit,
        'OfficePhoneNumber' => $oPhoneNumEdit,
        'twitter' => $twitterEdit,
        'Facebook' => $facebookEdit,
        'Comment' => $commentEdit
        );
        edit_csv('contract_data.csv', $data, $id);

        return $data;

}

Body:
How about using fputcsv instead of file_put_contents like below,

example code:-

$path = "C:\\path\\to\\your\\file.csv";
if (($handle = fopen($path, "r+")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        if($data[0]==2){ //desired line to update
            $write_data = array(
                        'sr_no' => $id,
                        'Title' => $titleEdit,
                        'FirstName' => $fnameEdit,
                        'LastName' => $lnameEdit,
                        'email' => $emailEdit,
                        'website' => $websiteEdit,
                        'CellPhoneNumber' => $cPhoneNumEdit,
                        'HomePhoneNumber' => $hPhoneNumEdit,
                        'OfficePhoneNumber' => $oPhoneNumEdit,
                        'twitter' => $twitterEdit,
                        'Facebook' => $facebookEdit,
                        'Comment' => $commentEdit
                        );
            fputcsv($handle, $write_data, ',', '"');
            unset($write_data);
        }
    }
    fclose($handle);
}


问:
div into a js button
I have a
 that I have formatted very carefully to look nice, and I need to make it have the functionality of a button. How would I go about doing this?

答:
You can give that div tag a onclick function as follows.

function myfns() {
    console.log("Clicked")
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="btn" onclick="myfns()">Click</div></code>```

Title: div into a js button

Body:
You can give that div tag a onclick function as follows.

function myfns() {
    console.log("Clicked")
}

<div id="btn" onclick="myfns()">Click</div>


问:
Add some specific time while using the linux command "date"
In linux, date can help me to print the current time. If want to print the current time + 1 hour, what option should I give?

答:
We can get it using below code, i was handling a case wherein i required to traverse dates from last 3 months, i used below code to traverse the same

!/bin/sh

```<code>for i in {90..1}
  do
   st_dt=$(date +%F' 00:00:00'  -d "-$i days")
   echo $st_dt
   j=$((i-1))
   end_dt=$(date +%F' 00:00:00'  -d "-$j days")
   echo $end_dt
  done
</code>```

Body:
We can get it using below code, i was handling a case wherein i required to traverse dates from last 3 months, i used below code to traverse the same

!/bin/sh

for i in {90..1}
  do
   st_dt=$(date +%F' 00:00:00'  -d "-$i days")
   echo $st_dt
   j=$((i-1))
   end_dt=$(date +%F' 00:00:00'  -d "-$j days")
   echo $end_dt
  done


问:
Calculating list cumulative sum in Haskell
Write a function that returns the running sum of list. e.g. running [1,2,3,5] is [1,3,6,11]. I write this function below which just can return the final sum of all the values among the list.So how can i separate them one by one?</p>

```<code>sumlist' xx=aux xx 0
    where aux [] a=a
          aux (x:xs) a=aux xs (a+x)
</code>```

答:
You can adjust your function to produce a list by simply prepending a+x to the result on each step and using the empty list as the base case:

```<code>sumlist' xx = aux xx 0
    where aux [] a = []
          aux (x:xs) a = (a+x) : aux xs (a+x)
</code>```

However it is more idiomatic Haskell to express this kind of thing as a fold or scan.

Body:
Write a function that returns the running sum of list. e.g. running [1,2,3,5] is [1,3,6,11]. I write this function below which just can return the final sum of all the values among the list.So how can i separate them one by one?

sumlist' xx=aux xx 0
    where aux [] a=a
          aux (x:xs) a=aux xs (a+x)

Body:
You can adjust your function to produce a list by simply prepending a+x to the result on each step and using the empty list as the base case:

sumlist' xx = aux xx 0
    where aux [] a = []
          aux (x:xs) a = (a+x) : aux xs (a+x)

However it is more idiomatic Haskell to express this kind of thing as a fold or scan.


问:
How to configure filebeat to handle log rotation?

My settings

I have a docker cluster in which supervisord is writing logs to output.log on a shared volume, from which Filebeat is reading and shipping logs to ES. In order to prevent disk-full problems, I have configured supervisord to rotate the logs, and I'm worried that Filebeat might miss out logs or send logs twice.

My problem

I would like Filebeat to consume the logs written to output.log, without duplication or missing out log lines.

My question

How do I configure Filebeat to handle supervisord log rotation?

答:
Seems like supervisord rotation works with filebeat out of the box.

For example, in the program section of supervisord.conf, the following configuration rotated the logs, and filebeat did not miss a single line.

```<code>stdout_logfile_maxbytes=1024
stdout_logfile_backups=5
stderr_logfile_maxbytes=1024
stderr_logfile_backups=5
</code>```

It is worth to mention that in real production system I would use larger values (in the dozens or hundreds of MBs), so that Filebeat will not miss the files when all the files are rotated during its sleep interval.

Body:
Seems like supervisord rotation works with filebeat out of the box.

For example, in the program section of supervisord.conf, the following configuration rotated the logs, and filebeat did not miss a single line.

stdout_logfile_maxbytes=1024
stdout_logfile_backups=5
stderr_logfile_maxbytes=1024
stderr_logfile_backups=5

It is worth to mention that in real production system I would use larger values (in the dozens or hundreds of MBs), so that Filebeat will not miss the files when all the files are rotated during its sleep interval.