问:
C - passing argument 1 of 'strcmp' makes pointer from integer without a cast
My function searchlist asks the user enter a student ID and lists that student ID and name.
Here is my struct:

```<code>struct student {
    int ID;
    char name[40];
    struct student *next;
};
typedef struct student Student;
</code>```

Here is my function:

```<code>void searchlist(Student *SLIST){
    Student *currentstudent = SLIST;
    char str[10], str2[10];

    printf("Enter a student ID: ");
    while(currentstudent != NULL){
        scanf("%d", &str);
        if(strcmp(str, (char)currentstudent->ID) == 0){
            printf("ID#: %d Name: %s", currentstudent->ID, currentstudent->name);
        }
    }
}
</code>```

However, when I try compiling, it gives me a warning: passing argument 1 of 'strcmp' makes pointer from integer without a cast

答:
The strcmp signature looks like this:

```<code>int strcmp(const char *s1, const char *s2);
</code>```

I.e. the second parameter must be of type const char*. But you're giving it a char. Hence the error message you're getting (char is an "integer" type).

Also, scanf("%d", &str); requests scanf to read an integer and store it to str. But str is not an integer type. (This would've been caught by the compiler if you had compilation warnings enabled.)

You need something like this:

```<code>printf("Enter a student ID: ");
int givenID;
scanf("%d", &givenID); // read integer input to integer variable

while(currentstudent != NULL) {
    if(currentstudent->ID == givenID) { // check whether this user has the ID entered by the user
        printf("ID#: %d Name: %s", currentstudent->ID, currentstudent->name);
        break; // we found what we were looking for, stop the loop
    }
    currentstudent = currentstudent->next; // move on to the next student in the list
}
</code>```

Body:
My function searchlist asks the user enter a student ID and lists that student ID and name.
Here is my struct:

struct student {
    int ID;
    char name[40];
    struct student *next;
};
typedef struct student Student;

Here is my function:

void searchlist(Student *SLIST){
    Student *currentstudent = SLIST;
    char str[10], str2[10];

    printf("Enter a student ID: ");
    while(currentstudent != NULL){
        scanf("%d", &str);
        if(strcmp(str, (char)currentstudent->ID) == 0){
            printf("ID#: %d Name: %s", currentstudent->ID, currentstudent->name);
        }
    }
}

However, when I try compiling, it gives me a warning: passing argument 1 of 'strcmp' makes pointer from integer without a cast

Body:
The strcmp signature looks like this:

int strcmp(const char *s1, const char *s2);

I.e. the second parameter must be of type const char*. But you're giving it a char. Hence the error message you're getting (char is an "integer" type).

Also, scanf("%d", &str); requests scanf to read an integer and store it to str. But str is not an integer type. (This would've been caught by the compiler if you had compilation warnings enabled.)

You need something like this:

printf("Enter a student ID: ");
int givenID;
scanf("%d", &givenID); // read integer input to integer variable

while(currentstudent != NULL) {
    if(currentstudent->ID == givenID) { // check whether this user has the ID entered by the user
        printf("ID#: %d Name: %s", currentstudent->ID, currentstudent->name);
        break; // we found what we were looking for, stop the loop
    }
    currentstudent = currentstudent->next; // move on to the next student in the list
}


来源: stackexchange

问:
NetLogo vs. Repast Simphony?
I would like to simulate some scenarios using the multiagent
paradigm, and it seems NetLogo and Repast are the most popular tools for that.

I'd like to know if anyone has had any experience with either one and could tell me more about them? For example, I've noticed that there is a fluxogram-like modeling option for Repast, but I believe it is rather limited. I've looked around the tutorials and documentation in the official site, and the documentation seems to be lacking. While there are some examples with it, I'd say extending it to simulate an ambient which it has not been specifically prepared to seems like an unreachable goal at the moment, despite Repast obviously being very robust and apparently able to handle it, given enough familiarity with it.

On the other hand, NetLogo has more examples and overall I've liked it more for its simplicity, but it seems to be more focused on the simulating propagation of diseases or similar models. I've found a programming book teaching Logo, so I figure it'd be easier to get started with it too.

Currently, I am thinking of simulating botnets and IDSes as multiagents. The problem, however, is that I would have to abstract the network and transport layers to an extent to be able to do it, as well as generate traffic between the nodes. Repast is apparently more fitting for this, but given its complexity and lack of documentation I'm thinking of using NetLogo. While there are some examples of NetLogo with traditional applications (ex: Tetris or Pac-Man), I'm not sure about how appropriate it'd be for that.

答:
If you can already code in Java, you can also look at the following paper for a comparison between RePast, Swarm, Quicksilver, and VSEit, different freely available programming libraries for support of social scientific agent based computer simulation

Tobias, Robert, and Carole Hofmann. "Evaluation of free Java-libraries for social-scientific agent based simulation." Journal of Artificial Societies and Social Simulation 7.1 (2004).

Repast is definitely more flexible than NetLogo but the documentation is not very detailed for RePast Symphony

ContentLicense: CC BY-SA 2.5

Title: NetLogo vs. Repast Simphony?

ContentLicense: CC BY-SA 3.0


问:
Safely Wrapping a Connection Pool
I am trying to implement row level security so our application can enforce more stringent access control.

One of the technologies we are looking into is Oracle's Virtual Private Database, which allows row level security by basically augmenting all queries against specific tables with a where clause predicate. Since we are in a web environment, we need to set up a special context within Oracle, inside a single request's thread. We use connection pooling with a service account.

I started to look into Eclipse Link and Hibernate. Eclipse Link seems to have events that fit perfectly into this model.

This would involve us migrating from hibernate, which is not a problem, but  we would then be bound to EL for these events.

Oracle seems to imply that they implement at the data source level in Web Logic product.

The context is set and cleared by the WebLogic data source code.

Question: Is it more appropriate to do this at the DataSource level with some series of events. What are the events or methods that I should pay the most attention too?

Added Question: How would I extend a connection pool to safely initialize an oracle context with some custom data? I am digging around in Apache, and it seems like extending BasicDataSource doesn't give me access to anything that would allow me to clean up the connection when Spring is done with it.

I need to set up a connection, and clean up a connection as the exit / enter the connection pool. I am hoping for an implementation that is so simple, no one can mess it up by breaking some delicate balance of products.

```<code>- Specifically we are currently using Apache Commons DBCP Basic Data Source
</code>```

This would allow us to use various ways to connect to the database and still have our security enforced. But I don't see a great example or set of events to work with, and rolling my own security life cycle is never a good idea.

答:
I eventually solved my problem by extending some of the Apache components.

First I extended org.apache.commons.pool.impl.GenericObjectPool and overrode both borrowObject() and returnObject(). I knew the type of the objects in the pool (java.sql.Connection) so I could safely cast and work with them.

Since for my case I was using Oracle VPD, I was able to set information in the Application context. I recommend you read about that in more depth. It is a little complicated and there are a lot of different options to hide or share data at various contexts level, and across RAC nodes. Start

In essence what I did was generate a nonce and use it to instantiate a session within oracle, and then set the access level of the user to a variable in that session, that the Oracle VPD policy would then read and use to do the row level filtering.

I instantiated and destroyed that information in my overridden borrowObject() and returnObject() The SQL I ran was something like this:

```<code>CallableStatement callStat =
                    conn.prepareCall("{call namespace.cust_ctx_pkg.set_session_id(" + Math.random() + ")}");
                  callStat.execute();
</code>```

Note math.random() isn't a good nonce.

Next was to simply extend org.apache.commons.dbcp.BasicDataSource and set my object pool by overriding createConnectionPool(). Note that the way I did this disabled some functionality I did not need, so you may need to rewrite more or less than I did.

Title: Safely Wrapping a Connection Pool

Body:
I am trying to implement row level security so our application can enforce more stringent access control.

One of the technologies we are looking into is Oracle's Virtual Private Database, which allows row level security by basically augmenting all queries against specific tables with a where clause predicate. Since we are in a web environment, we need to set up a special context within Oracle, inside a single request's thread. We use connection pooling with a service account.

I started to look into Eclipse Link and Hibernate. Eclipse Link seems to have events that fit perfectly into this model.

This would involve us migrating from hibernate, which is not a problem, but  we would then be bound to EL for these events.

Oracle seems to imply that they implement at the data source level in Web Logic product.

The context is set and cleared by the WebLogic data source code.

Question: Is it more appropriate to do this at the DataSource level with some series of events. What are the events or methods that I should pay the most attention too?

Added Question: How would I extend a connection pool to safely initialize an oracle context with some custom data? I am digging around in Apache, and it seems like extending BasicDataSource doesn't give me access to anything that would allow me to clean up the connection when Spring is done with it.

I need to set up a connection, and clean up a connection as the exit / enter the connection pool. I am hoping for an implementation that is so simple, no one can mess it up by breaking some delicate balance of products.

- Specifically we are currently using Apache Commons DBCP Basic Data Source

This would allow us to use various ways to connect to the database and still have our security enforced. But I don't see a great example or set of events to work with, and rolling my own security life cycle is never a good idea.

Body:
I eventually solved my problem by extending some of the Apache components.

First I extended org.apache.commons.pool.impl.GenericObjectPool and overrode both borrowObject() and returnObject(). I knew the type of the objects in the pool (java.sql.Connection) so I could safely cast and work with them.

Since for my case I was using Oracle VPD, I was able to set information in the Application context. I recommend you read about that in more depth. It is a little complicated and there are a lot of different options to hide or share data at various contexts level, and across RAC nodes. Start

In essence what I did was generate a nonce and use it to instantiate a session within oracle, and then set the access level of the user to a variable in that session, that the Oracle VPD policy would then read and use to do the row level filtering.

I instantiated and destroyed that information in my overridden borrowObject() and returnObject() The SQL I ran was something like this:

CallableStatement callStat =
                    conn.prepareCall("{call namespace.cust_ctx_pkg.set_session_id(" + Math.random() + ")}");
                  callStat.execute();

Note math.random() isn't a good nonce.

Next was to simply extend org.apache.commons.dbcp.BasicDataSource and set my object pool by overriding createConnectionPool(). Note that the way I did this disabled some functionality I did not need, so you may need to rewrite more or less than I did.


问:
How to successfully get out of this do-while loop?
This code was smooth sailing until I SPECIFICALLY include the IF-STATEMENT containing a BREAK inside the DO-WHILE LOOP which SHOULD report a math error if fv1 = 0 (for anything divided by zero is undefined). However, unexpected results were printed.</p>

```<code>#include <iostream>
#include <cmath>
#include <iomanip>

using namespace std;

const double R = 0.082054;
double f(double a,double b,double P,double T,double v);
double f(double a,double b,double P,double T,double v)
{
    double q =P*pow(v,3)-(P*b+R*T)*pow(v,2)+a*v-a*b;
    return q;
}
double fPrime(double a,double b,double P,double T,double v);
double fPrime(double a,double b,double P,double T,double v)
{
    double s =3*P*pow(v,2)-2*(P*b+R*T)*pow(v,1)+a;
    return s;
}
int main()
{
//INPUT STAGE!
cout << "Use gas constant, R: " << R << endl;

double a,b,P,T,Tc;
cout << "\nUse test value, a: ";
cin >> a;
cout << "\nUse test value, b: ";
cin >> b;
cout << "\nUse pressure, P (atm): ";
cin >> P;
cout << "\nUse absolute temperature, T (K): ";
cin >> T;

double v,v1=0,fv,fv1,N,e;
int iteration = 0;
cout << "\nUse initial guess for molal volume, v: ";
cin >> v;
cout << "\nUse maximum number of iterations, N: ";
cin >> N;
cout << "\nUse tolerance, e: ";
cin >> e;
cout << "\n";

do
{
    v = v1;
    fv = f(a,b,P,T,v);
    fv1 = fPrime(a,b,P,T,v);
    if (fv1=0)
    {
       cout << "Math Error";
       break;
    }
    v1 = v-(fv/fv1);
    cout << iteration+1 << setw(12) << v << setw(16) << v1 << setw(16) << abs(v1-v) << endl;
    iteration++;
}
while(iteration<N && abs(v1-v)>e);

return 0;
}
</code>```

答:
Try changing if condition from fv1=0 to fv1==0
This is assignment operator=
whereas this is comparing operator ==

Body:
This code was smooth sailing until I SPECIFICALLY include the IF-STATEMENT containing a BREAK inside the DO-WHILE LOOP which SHOULD report a math error if fv1 = 0 (for anything divided by zero is undefined). However, unexpected results were printed.

#include <iostream>
#include <cmath>
#include <iomanip>

using namespace std;

const double R = 0.082054;
double f(double a,double b,double P,double T,double v);
double f(double a,double b,double P,double T,double v)
{
    double q =P*pow(v,3)-(P*b+R*T)*pow(v,2)+a*v-a*b;
    return q;
}
double fPrime(double a,double b,double P,double T,double v);
double fPrime(double a,double b,double P,double T,double v)
{
    double s =3*P*pow(v,2)-2*(P*b+R*T)*pow(v,1)+a;
    return s;
}
int main()
{
//INPUT STAGE!
cout << "Use gas constant, R: " << R << endl;

double a,b,P,T,Tc;
cout << "\nUse test value, a: ";
cin >> a;
cout << "\nUse test value, b: ";
cin >> b;
cout << "\nUse pressure, P (atm): ";
cin >> P;
cout << "\nUse absolute temperature, T (K): ";
cin >> T;

double v,v1=0,fv,fv1,N,e;
int iteration = 0;
cout << "\nUse initial guess for molal volume, v: ";
cin >> v;
cout << "\nUse maximum number of iterations, N: ";
cin >> N;
cout << "\nUse tolerance, e: ";
cin >> e;
cout << "\n";

do
{
    v = v1;
    fv = f(a,b,P,T,v);
    fv1 = fPrime(a,b,P,T,v);
    if (fv1=0)
    {
       cout << "Math Error";
       break;
    }
    v1 = v-(fv/fv1);
    cout << iteration+1 << setw(12) << v << setw(16) << v1 << setw(16) << abs(v1-v) << endl;
    iteration++;
}
while(iteration<N && abs(v1-v)>e);

return 0;
}


问:
delete occurence in list with regex in python
So I'm reading an .avi file and storing it's index into a list.
Each element corresponds to an index movie frame.
I'm working on a script to delete all the occurrences in the list that start with :

00dc\x10\x00\x00\x00

Here's a short version of the code

```<code>   list = ['00dc\x00\x00\x00\x00\x025,\x00\x08\x19\x00\x00',
        '00dc\x00\x00\x00\x00\x12N,\x00\x0b6\x00\x00',
        '00dc\x10\x00\x00\x00&\x84,\x00\x95D\x01\x00',
        '00dc\x00\x00\x00\x00\xc4\xc8-\x00\xe0l\x00\x00',
        '00dc\x00\x00\x00\x00\xac5.\x00t.\x00\x00']

    regex1 = b'00dc\x10\x00\x00\x00.{8}'
    newlist = [x for x in list if x != regex1]
</code>```

Aaand it doesn't do anything, the list stays the same when I expected the third element to be popped out.

I don't think it matches anything because even when I set the regex1 to :

b'.*'

The list stays the same. Having trouble figuring out where the issue is coming from. Thanks

Body:
So I'm reading an .avi file and storing it's index into a list.
Each element corresponds to an index movie frame.
I'm working on a script to delete all the occurrences in the list that start with :

00dc\x10\x00\x00\x00

Here's a short version of the code

   list = ['00dc\x00\x00\x00\x00\x025,\x00\x08\x19\x00\x00',
        '00dc\x00\x00\x00\x00\x12N,\x00\x0b6\x00\x00',
        '00dc\x10\x00\x00\x00&\x84,\x00\x95D\x01\x00',
        '00dc\x00\x00\x00\x00\xc4\xc8-\x00\xe0l\x00\x00',
        '00dc\x00\x00\x00\x00\xac5.\x00t.\x00\x00']

    regex1 = b'00dc\x10\x00\x00\x00.{8}'
    newlist = [x for x in list if x != regex1]

Aaand it doesn't do anything, the list stays the same when I expected the third element to be popped out.

I don't think it matches anything because even when I set the regex1 to :

b'.*'

The list stays the same. Having trouble figuring out where the issue is coming from. Thanks

Body:
Python doesn't work with regex built-in. You need to import regex module.

import re
list = ['00dc\x00\x00\x00\x00\x025,\x00\x08\x19\x00\x00',
        '00dc\x00\x00\x00\x00\x12N,\x00\x0b6\x00\x00',
        '00dc\x10\x00\x00\x00&\x84,\x00\x95D\x01\x00',
        '00dc\x00\x00\x00\x00\xc4\xc8-\x00\xe0l\x00\x00',
        '00dc\x00\x00\x00\x00\xac5.\x00t.\x00\x00']

pattern = re.compile(b'00dc\x10\x00\x00\x00.{8}')
newlist = [x for x in list if not re.match(pattern,x)]

Output:

['00dc\x00\x00\x00\x00\x025,\x00\x08\x19\x00\x00', '00dc\x00\x00\x00\x00\x12N,\x00\x0b6\x00\x00', '00dc\x00\x00\x00\x00\xc4\xc8-\x00\xe0l\x00\x00', '00dc\x00\x00\x00\x00\xac5.\x00t.\x00\x00']


问:
Is Task.Run appropriate here, wrapping network calls?
I'm studying a pretty popular c# proxy server.  In it there is code such as (I'm hiding the proxy server identity on purpose because I feel bad telling tales, if indeed it is wrong).

```<code>private void OnConnectionAccepted(TcpClient cl)
{
     ....
     Task.Run(async () =>
            {
               await HandleClientRequest();

            });
     Task.Run(async () =>
        {
            TcpClient cl = await listener.AcceptTcpClientAsync();
            OnConnectionAccepted(cl);
        });
}
</code>```

Where HandleClientRequest does some async network calls, such as reading the request from the client and repeating it to the server, like you'd expect a proxy to do.
listener.AcceptTcpClientAsync just waits for the next connection to come from a browser.

So it seems the point of the Task.Run is really just to allow AcceptTcpClientAsync to be called while HandleClientRequest is busy.

This seems to go against the recommendations I've been reading, eg. http://blog.stephencleary.com/2013/10/taskrun-etiquette-and-proper-usage.html because Task.Run is wrapping network, not CPU calls.

So how should it work instead, if this is wrong, should it use ThreadPool.QueueUserWorkerItem?

The context by the way would typically be a console app.

答:
This seems to go against the recommendations I've been reading... because Task.Run is wrapping network, not CPU calls.

In general, Task.Run should not be used for I/O. However, that advice is intended for application code, and even there has several exceptions.

In this case (examining the core accept/process logic of a proxy server), the code we're looking at is more of a framework, with the "application" being inside HandleClientRequest. (Note that this code is hosted in a Console or Win32 service, not within ASP.NET).

To draw a parallel, ASP.NET will listen for connections and will take a thread from the thread pool to process requests. This is perfectly natural for a framework to do.

Here are some reasons to use Task.Run, that may or may not be valid for this particular case:

Some .NET network calls start with a synchronous portion - in particular, HTTP proxy and DNS lookups are done synchronously. This is very unfortunate, but we're stuck with it for backwards compatibility reasons. So even asynchronous network APIs can be partially synchronous. If HandleClientRequest makes use of these APIs, it would make sense to wrap it in a Task.Run.

The code may not want the current SynchronizationContext. This doesn't appear to be the case here, though.

All asynchronous methods begin executing synchronously. If HandleClientRequest does some amount of "housekeeping" before it gets down to its real work, it may be beneficial to wrap it in a Task.Run so that the listener is not blocked.

Recursive asynchronous code can fill the stack if it executes synchronously. E.g., if the second Task.Run wasn't present and a lot of connections were made all at once, then the stack could overflow. I assume this is the purpose of the second Task.Run because I can't think of any other purpose it would have.

So how should it work instead, if this is wrong, should it use ThreadPool.QueueUserWorkerItem?

Absolutely not! Task.Run is the appropriate way of using the thread pool. (Unless you have an extremely smart team and you can show a measurable performance difference).

So it seems the point of the Task.Run is really just to allow AcceptTcpClientAsync to be called while HandleClientRequest is busy.

The usage of Task.Run is still questionable at best, because the tasks should be awaited sooner or later. As it currently stands, any exceptions from HandleClientRequest, AcceptTcpClientAsync, and OnConnectionAccepted will be silently dropped. If HandleClientRequest and OnConnectionAccepted both had top-level try blocks, that would be OK, but any exceptions from AcceptTcpClientAsync would cause the whole proxy server to stop working. And that method can throw exceptions, though it is rare.

Body:
I'm studying a pretty popular c# proxy server.  In it there is code such as (I'm hiding the proxy server identity on purpose because I feel bad telling tales, if indeed it is wrong).

private void OnConnectionAccepted(TcpClient cl)
{
     ....
     Task.Run(async () =>
            {
               await HandleClientRequest();

            });
     Task.Run(async () =>
        {
            TcpClient cl = await listener.AcceptTcpClientAsync();
            OnConnectionAccepted(cl);
        });
}

Where HandleClientRequest does some async network calls, such as reading the request from the client and repeating it to the server, like you'd expect a proxy to do.
listener.AcceptTcpClientAsync just waits for the next connection to come from a browser.

So it seems the point of the Task.Run is really just to allow AcceptTcpClientAsync to be called while HandleClientRequest is busy.

This seems to go against the recommendations I've been reading, eg. http://blog.stephencleary.com/2013/10/taskrun-etiquette-and-proper-usage.html because Task.Run is wrapping network, not CPU calls.

So how should it work instead, if this is wrong, should it use ThreadPool.QueueUserWorkerItem?

The context by the way would typically be a console app.


问:
ReSharper "Cannot resolve symbol" even when project builds
My Tools:

Visual Studio 2012 Ultimate + Update 1

ReSharper v7.1.25.234

My Solution Build Status: Build Successfully

But when I install ReSharper and ReSharper code analysis is enable, many keywords of my code are red with this error:

"Cannot resolve symbol XXX"

Another picture of my project >>

The ReSharper “CANNOT RESOLVE SYMBOL” errors are everywhere, but my project build process is successfully, and it works correctly.

Additional Note: If I disable ReSharper Code Analysis, my project will be Normal, but I want to use ReSharper code analysis.

I tried ReSharper → Options → General → Clear Cache. But I still have this problem!

One month ago, I got these errors when I uninstalled Visual Studio 2012 RC and installed VS 2012 RTM.

I've already uninstalled and installed ReSharper again. But I have this problem yet!

My solution has five projects >> two loaded projects (main project + resource project) and three unloaded projects

I realize that my Visual Studio also has bigger problems (More information on Stack Overflow)

I can't add any reference to my projects (even inside new solutions and new projects)

I can't install any package (by "Packet Manager Console" or Manage NuGet Package)

I can't update any package (by "Packet Manager Console" or Manage NuGet Package)

I've done a lot of suggestions (of myself and others)

Re-resister some DLL files

Using some windows and registry repair tools

Remove ReSharper

Repair Visual Studio

and...

But I could not solve it.

I'm thinking of installing a new Windows :(

What is wrong, and how can I fix it?

答:
What helped in my case after several of the suggestions above didn't:

Removed one project reference (of one of the libraries where ReSharper claimed not to be able to find it even though it was correctly referenced).

Use ReSharper’s "Resolve" on one of its usages to add the reference again.

After that, it worked fine, even though none of the project files were actually modified in the process.

ContentLicense: CC BY-SA 4.0


问:
importing JSON to mongoDB using pymongo
i am trying to import a JSON file i pull from a URL and send it to mongoDB as is, using the pymongo module.

I have the following code

```<code>#!/usr/bin/env python
import sys, urllib2, json, pymongo
from pymongo import MongoClient
myurl = "https://gist.githubusercontent.com/border/775526/raw/b921df18ba00262ab5bba8cadb3c178e1f7748f7/config.json"
response = urllib2.urlopen(myurl)
data = response.read()
connection = MongoClient('mongodb://user:password@localhost.com:27017/database')
connection.database_names()
db = connection.database
posts = db.posts
post_id = posts.insert_many(data).inserted_id
</code>```

upon executing this, i get this error
raise TypeError("documents must be a non-empty list")
TypeError: documents must be a non-empty list

ideally, i want to just be able to pull the json from the url and update the mongoDB as this json file will be updated every week.
Thanks

答:
You need to convert JSON to Python objects, which PyMongo will then convert to BSON for sending to MongoDB. To convert JSON to Python objects use the "bson.json_util" module included with PyMongo:

```<code>from bson import json_util
data = json_util.loads(response.read())
</code>```

The standard Python json.loads() function works, too, but PyMongo's json_util.loads() handles some MongoDB-specific details better.

Title: importing JSON to mongoDB using pymongo

Body:
i am trying to import a JSON file i pull from a URL and send it to mongoDB as is, using the pymongo module.

I have the following code

#!/usr/bin/env python
import sys, urllib2, json, pymongo
from pymongo import MongoClient
myurl = "https://gist.githubusercontent.com/border/775526/raw/b921df18ba00262ab5bba8cadb3c178e1f7748f7/config.json"
response = urllib2.urlopen(myurl)
data = response.read()
connection = MongoClient('mongodb://user:password@localhost.com:27017/database')
connection.database_names()
db = connection.database
posts = db.posts
post_id = posts.insert_many(data).inserted_id

upon executing this, i get this error
raise TypeError("documents must be a non-empty list")
TypeError: documents must be a non-empty list

ideally, i want to just be able to pull the json from the url and update the mongoDB as this json file will be updated every week.
Thanks

Body:
You need to convert JSON to Python objects, which PyMongo will then convert to BSON for sending to MongoDB. To convert JSON to Python objects use the "bson.json_util" module included with PyMongo:

from bson import json_util
data = json_util.loads(response.read())

The standard Python json.loads() function works, too, but PyMongo's json_util.loads() handles some MongoDB-specific details better.


问:
Android Device Monitor File Explorer not working with emulator running API 24+
So, just as question states. Android device monitor is not showing anything in the File Explorer view. This is  only occuring on Virtual Devices running Android API Level 24+.

Any solution?

答:
Another temporary solution is to use the adb shell

First, copy the database to the sdcard

```<code>./adb shell run-as com.yourapplication cp /data/data/com.yourapplication/databases/yourFileName.db /sdcard
</code>```

Then, pull the database file to your computer

```<code>./adb pull /sdcard/yourFileName.db /Users/yourUserName/Desktop
</code>```

Body:
Another temporary solution is to use the adb shell

First, copy the database to the sdcard

./adb shell run-as com.yourapplication cp /data/data/com.yourapplication/databases/yourFileName.db /sdcard

Then, pull the database file to your computer

./adb pull /sdcard/yourFileName.db /Users/yourUserName/Desktop


问:
Android, cannot build app with Retrofit and RxJava 2
Here are the dependencies

```<code>compile 'com.squareup.retrofit2:retrofit:2.2.0'
compile 'io.reactivex.rxjava2:rxjava:2.0.7'
compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
compile 'com.squareup.retrofit2:adapter-rxjava:2.2.0'
compile 'com.google.code.gson:gson:2.7'
compile 'com.squareup.retrofit2:converter-gson:2.0.0'
</code>```

When I try to run the app I get this error

```<code>Error:Execution failed for task ':app:transformResourcesWithMergeJavaResForDebug'.
</code>```

com.android.build.api.transform.TransformException: com.android.builder.packaging.DuplicateFileException: Duplicate files copied in APK META-INF/rxjava.properties
      File1: C:\Users\abondarenco.gradle\caches\modules-2\files-2.1\io.reactivex.rxjava2\rxjava\2.0.7\21734c0092a5d3c3ec99510e50c1ff76bdf0c65a\rxjava-2.0.7.jar
      File2: C:\Users\abondarenco.gradle\caches\modules-2\files-2.1\io.reactivex\rxjava\1.2.0\42bfaf64c94f3848ebf5cf1c2ea4ec9d1b3ac6c8\rxjava-1.2.0.jar

I tried to run app without adapter-rxjava and it works, but when I add the adapter it says that there are duplicate files, it downloads RxJava 1...

答:
Use the proper version of the adapter.</p>

```<code>compile 'com.squareup.retrofit2:adapter-rxjava2:2.2.0'
</code>```

Body:
Here are the dependencies

compile 'com.squareup.retrofit2:retrofit:2.2.0'
compile 'io.reactivex.rxjava2:rxjava:2.0.7'
compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
compile 'com.squareup.retrofit2:adapter-rxjava:2.2.0'
compile 'com.google.code.gson:gson:2.7'
compile 'com.squareup.retrofit2:converter-gson:2.0.0'

When I try to run the app I get this error

Error:Execution failed for task ':app:transformResourcesWithMergeJavaResForDebug'.

com.android.build.api.transform.TransformException: com.android.builder.packaging.DuplicateFileException: Duplicate files copied in APK META-INF/rxjava.properties
      File1: C:\Users\abondarenco.gradle\caches\modules-2\files-2.1\io.reactivex.rxjava2\rxjava\2.0.7\21734c0092a5d3c3ec99510e50c1ff76bdf0c65a\rxjava-2.0.7.jar
      File2: C:\Users\abondarenco.gradle\caches\modules-2\files-2.1\io.reactivex\rxjava\1.2.0\42bfaf64c94f3848ebf5cf1c2ea4ec9d1b3ac6c8\rxjava-1.2.0.jar

I tried to run app without adapter-rxjava and it works, but when I add the adapter it says that there are duplicate files, it downloads RxJava 1...

Body:
Use the proper version of the adapter.

compile 'com.squareup.retrofit2:adapter-rxjava2:2.2.0'


问:
Specify Hadoop mapreduce input keys directly (not from a file)
I'd like to generate some data using a mapreduce.  I'd like to invoke the job with one parameter N, and get Map called with each integer from 1 to N, once.

Obviously I want a Mapper<IntWritable, NullWritable, <my output types>>...that's easy.  But I can't figure out how to generate the input data!  Is there an InputFormat I'm not seeing somewhere that lets me just pull keys + values from a collection directly?

答:
Do you want each mapper to process all integers from 1 to N?  Or do you want to distribute the processing of integers 1 to N across the concurrently running mappers?

If the former, I believe you'll need to create a custom InputFormat.  If the latter, the easiest way might be to generate a text file with integers 1 to N, each integer on one line, and use LineInputFormat.


问:
How to update an HTML Table interactively upon selection of one of 4 form fields
I have an HTML page with a form and a table on it.
Using PHP, I would like to use a set of 4 of the form fields to build a mySql query to update the table in real time as the user selects any of the 4 fields.
The query should be built and executed upon the change of any of the 4 form fields.
Here is my code for the form fields:

```<code><form method="post" action="">
    <table cellspacing="0" border-width="1px" height= "28">
        <tr>
            <td class="style4" style="width: 160px">
                <strong>Location
            </strong>
            </td>
            <td class="style5" style="width: 150px">
                <select name="Location" style="width: 150px" onchange="SetQuery.php">
                <option hidden selected>Select a Location</option>
                <?php   while($record = mysql_fetch_array($myLocations)){
                            echo '<option value="' . $record['location'] . '">' . $record['location'] . '</option>';
                }
                ?>

                </select>
            </td>
            <td style="width: 59px">
        <tr>
            <td class="style4" style="width: 160px">
                <strong>Customer
            </strong>
            </td>
            <td class="style5" style="width: 150px">
                <input name="Customer" type="text" style="width: 150px" onchange="SetQuery.php">
            </td>
        </tr>

        <tr>
            <td class="style4" style="width: 160px">
                <strong>Family
            </strong>
            </td>
            <td class="style5" style="width: 150px">
                <input name="Family" type="text" style="width: 150px" onchange="SetQuery.php">
            </td>
        </tr>

        <tr>
            <td class="style4" style="width: 160px">
                <strong>Customer Part Number
            </strong>
            </td>
            <td class="style5" style="width: 150px">
                <input name="CustomerPartNumber" type="text" style="width: 150px" onchange="SetQuery.php">
            </td>
        </tr>
</code>```

I was thinking of using the onchange function to call a routine (I called it SetQuery.php) to build the query and update the table.
I do not know how to write the routine to update the table upon each selection of one of my 4 fields.

Here is my code to build the table initially. It is just a basic query to get all records just to get things going. In proper flow, the table will not populate until one of the 4 fields are chosen.

```<code><table border="1" cellspacing="1" cellpadding="1" style="font-size: xx-small">
<tr>
 <th><font face="Arial, Helvetica, sans-serif">Description</font></th>
 <th><font face="Arial, Helvetica, sans-serif">West Part Number</font></th>
 <th><font face="Arial, Helvetica, sans-serif">Cavities</font></th>
 <th><font face="Arial, Helvetica, sans-serif">Cycle Time</font></th>
 <th><font face="Arial, Helvetica, sans-serif">Material</font></th>
</tr>

<?php
$i=0;
while ($i < $num) {

?>

<tr>
<td><font face="Arial, Helvetica, sans-serif"><?php echo mysql_result($result2,$i,0); ?></font></td>
<td><font face="Arial, Helvetica, sans-serif"><?php echo mysql_result($result2,$i,1); ?></font></td>
<td><font face="Arial, Helvetica, sans-serif"><?php echo mysql_result($result2,$i,2); ?></font></td>
<td><font face="Arial, Helvetica, sans-serif"><?php echo mysql_result($result2,$i,3); ?></font></td>
<td><font face="Arial, Helvetica, sans-serif"><?php echo mysql_result($result2,$i,4); ?></font></td>
</tr>

<?php
$i++;
}
?>
</table>
</td>
</tr>
</table>
</code>```

Can anyone help with this onchange routine? I need help in writing it and where to put it and how to call it.

Thanks,
Rich

答:
Realize that onchange will trigger a javascript function and not load something from your webserver. For that to happen you'll need more code and I'd advise you to put that code in a separate file or at least in a separate javascript block.

My second advise would be to start using jQuery for now. I'm not sure if it is the best starting point but historically it is widely used, fast and contains everything you need for now.

Start by reading this on the use of the change event:
https://api.jquery.com/change/

And this on using AJAX for loading your changes from PHP:
http://api.jquery.com/jquery.ajax/

Now, you can either have your SetQuery.php return HTML and inject this directly or have it return a data set and convert this to HTML on the front-end. If you don't know JSON, read up on it.

Last but not least, you might want to start by using a framework. PHP has a lot of choices and I think Laravel is a nice one to start with. It has a great learning curve for starters and the free tutorials will get you started on any low to mid-sized application.

Kind regards.

Body:
I have an HTML page with a form and a table on it.
Using PHP, I would like to use a set of 4 of the form fields to build a mySql query to update the table in real time as the user selects any of the 4 fields.
The query should be built and executed upon the change of any of the 4 form fields.
Here is my code for the form fields:

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

                Location

                <select name="Location" style="width: 150px" onchange="SetQuery.php">
                <option hidden selected>Select a Location</option>
                <?php   while($record = mysql_fetch_array($myLocations)){
                            echo '<option value="' . $record['location'] . '">' . $record['location'] . '</option>';
                }
                ?>

                </select>

                Customer

                <input name="Customer" type="text" style="width: 150px" onchange="SetQuery.php">

                Family

                <input name="Family" type="text" style="width: 150px" onchange="SetQuery.php">

                Customer Part Number

                <input name="CustomerPartNumber" type="text" style="width: 150px" onchange="SetQuery.php">

I was thinking of using the onchange function to call a routine (I called it SetQuery.php) to build the query and update the table.
I do not know how to write the routine to update the table upon each selection of one of my 4 fields.

Here is my code to build the table initially. It is just a basic query to get all records just to get things going. In proper flow, the table will not populate until one of the 4 fields are chosen.

 Description
 West Part Number
 Cavities
 Cycle Time
 Material

<?php
$i=0;
while ($i < $num) {

?>

<?php echo mysql_result($result2,$i,0); ?>
<?php echo mysql_result($result2,$i,1); ?>
<?php echo mysql_result($result2,$i,2); ?>
<?php echo mysql_result($result2,$i,3); ?>
<?php echo mysql_result($result2,$i,4); ?>

<?php
$i++;
}
?>

Can anyone help with this onchange routine? I need help in writing it and where to put it and how to call it.

Thanks,
Rich


问:
SAS date subtraction when intck function doesn't cut it
I need to do some date subtraction in my SAS code, but I don't think the INTCK function will work because I would like the answer to present the difference in days:hours:minutes.  I could program this out, but I am guessing there is probably a format or function I'm not aware of to accomplish the task.

For example:

Date1 = 01JAN2000 12:00

Date2 = 02JAN2000 14:30

difference = 1:02:30 (i.e. 1 day, 2 hours, 30 minutes)

In this case, if I used INTCK I would need to keep the units in either days or hours, but I can't get the desired format above.

答:
You should be able to use the %n directive in a PICTURE format.

```<code>proc format;
 picture pictdhmf
  low-high='%0n:%0H:%0M'(datatype=time)
 ;
run;
</code>```

Note you need to use data type of TIME. WARNING: It doesn't produce proper results when running SAS using DBCS support (for example using Shift-JIS encoding).  Or for times that are less than zero.  It does work for non-negative values when using single byte character sets, even with UTF-8 encoding.

So instead you could build a function.

```<code>proc fcmp outlib=work.func.func;
function dhmf(c) $;
  length f $ 10;
  f=catx(':',datepart(abs(c)),put(timepart(abs(c)),tod5.));
  if c < 0 then f='-'||f ;
  return (f);
endsub;
run;
options cmplib=work.func;
</code>```

and then make a format that calls the function.

```<code>proc format;
value dhmf(default=10)
 other=[dhmf()];
run;
</code>```

So if we test both methods and compare to the values that TIME format produces.

```<code>data _null_;
  input (date1 date2) (:datetime24.) ;
  diff = date2 - date1 ;
  if _n_=1 then put 'RAW' @11 'TIME.' @20 'Function' @ 30 'Picture';
  put diff comma9. @11 diff time. @20 diff dhmf. @30 diff pictdhmf.-l ;
cards ;
01JAN2000:02:30 02JAN2000:03:45
01JAN1960:08:00 01JAN1960:17:00
01FEB2017:00:00 04FEB2017:06:23
01FEB2015:00:00 04FEB2017:06:23
04FEB2017:00:00 01FEB2017:06:23
run;
</code>```

We get:

```<code> RAW       TIME.    Function  Picture
    90,900 25:15:00 1:01:15   1:01:15
    32,400  9:00:00 0:09:00   0:09:00
   282,180 78:23:00 3:06:23   3:06:23
  63440580 17622:23 734:06:23 734:06:23
  -236,220   -65:37 -2:17:37  -2:06:23
</code>```

Body:
You should be able to use the %n directive in a PICTURE format.

proc format;
 picture pictdhmf
  low-high='%0n:%0H:%0M'(datatype=time)
 ;
run;

Note you need to use data type of TIME. WARNING: It doesn't produce proper results when running SAS using DBCS support (for example using Shift-JIS encoding).  Or for times that are less than zero.  It does work for non-negative values when using single byte character sets, even with UTF-8 encoding.

So instead you could build a function.

proc fcmp outlib=work.func.func;
function dhmf(c) $;
  length f $ 10;
  f=catx(':',datepart(abs(c)),put(timepart(abs(c)),tod5.));
  if c < 0 then f='-'||f ;
  return (f);
endsub;
run;
options cmplib=work.func;

and then make a format that calls the function.

proc format;
value dhmf(default=10)
 other=[dhmf()];
run;

So if we test both methods and compare to the values that TIME format produces.

data _null_;
  input (date1 date2) (:datetime24.) ;
  diff = date2 - date1 ;
  if _n_=1 then put 'RAW' @11 'TIME.' @20 'Function' @ 30 'Picture';
  put diff comma9. @11 diff time. @20 diff dhmf. @30 diff pictdhmf.-l ;
cards ;
01JAN2000:02:30 02JAN2000:03:45
01JAN1960:08:00 01JAN1960:17:00
01FEB2017:00:00 04FEB2017:06:23
01FEB2015:00:00 04FEB2017:06:23
04FEB2017:00:00 01FEB2017:06:23
run;

We get:

 RAW       TIME.    Function  Picture
    90,900 25:15:00 1:01:15   1:01:15
    32,400  9:00:00 0:09:00   0:09:00
   282,180 78:23:00 3:06:23   3:06:23
  63440580 17622:23 734:06:23 734:06:23
  -236,220   -65:37 -2:17:37  -2:06:23


问:
SAS: Utilizing macro variables as numbers in data step
I am touching up some SAS code I wrote and found a chunk of code I wish to execute more effectively. I have a time-series data set called 'Forecasts' which just consists of date and the 'Forecast' variable for a given date.

I wrote a simple block of code to take this variable and basically chop it up into a series of variables, each one representing one date:

```<code>data forecasts;
set forecasts;
  obs=_n_;
  array r(241);
  do i=1 to dim(r);
    if obs=i then r(i)=Forecast;
  end; drop i; drop obs; drop forecast;
run;
</code>```

However, the 'r(241)' part of this code really annoys me. I already have a macro variable which corresponds to the number of times I need to perform this operation (called 'n'), and I would rather just plug it into the array proclamation directly, something like:

```<code>array r(&n)
</code>```

etc.

However macro variables are obviously considered text, so even when I managed to import the macro variable into the data step, variants r(&n) doesn't work because it doesn't read 'n' as a numeric. Outside of wrapping this entire data step into a broader macro, how can I pull 'n' into the data step then convert it to a numeric so this operation works?

答:
The statement:

```<code>array r(&n) ;
</code>```

should be fine, assuming the macro variable is defined and has an integer value.  Please show how you are trying to use it (and any failing log messages).  You don't need to 'import macro variables into the data step'.  Macro variables are text because their primary job is to resolve to SAS code.

```<code>18   %let n=3;
19   data _null_;
20     array r{&n};
21     do i=1 to dim(r);
22       put i=;
23     end;
24   run;

i=1
i=2
i=3
</code>```

Body:
I am touching up some SAS code I wrote and found a chunk of code I wish to execute more effectively. I have a time-series data set called 'Forecasts' which just consists of date and the 'Forecast' variable for a given date.

I wrote a simple block of code to take this variable and basically chop it up into a series of variables, each one representing one date:

data forecasts;
set forecasts;
  obs=_n_;
  array r(241);
  do i=1 to dim(r);
    if obs=i then r(i)=Forecast;
  end; drop i; drop obs; drop forecast;
run;

However, the 'r(241)' part of this code really annoys me. I already have a macro variable which corresponds to the number of times I need to perform this operation (called 'n'), and I would rather just plug it into the array proclamation directly, something like:

array r(&n)

etc.

However macro variables are obviously considered text, so even when I managed to import the macro variable into the data step, variants r(&n) doesn't work because it doesn't read 'n' as a numeric. Outside of wrapping this entire data step into a broader macro, how can I pull 'n' into the data step then convert it to a numeric so this operation works?

Body:
The statement:

array r(&n) ;

should be fine, assuming the macro variable is defined and has an integer value.  Please show how you are trying to use it (and any failing log messages).  You don't need to 'import macro variables into the data step'.  Macro variables are text because their primary job is to resolve to SAS code.

18   %let n=3;
19   data _null_;
20     array r{&n};
21     do i=1 to dim(r);
22       put i=;
23     end;
24   run;

i=1
i=2
i=3


问:
Can't generate signed APK in Android Studio, 'java.io.IOException'
I have a problem with generating signed APK in Android Studio. It was working fine few days ago, I dont know what went wrong. I'm getting this error for any project I try to fgenerate signed APK of:

Warning:Exception while processing task java.io.IOException: Can't write [/Users/bhaveshmisri/Downloads/littleone-dagger-mvp/app/build/intermediates/transforms/proguard/release/jars/3/1f/main.jar] (Can't read [/Users/bhaveshmisri/Downloads/littleone-dagger-mvp/app/build/intermediates/transforms/RealmTransformer/release/folders/1/1/realm(;;;;;;**.class)] (Can't read [com] (Can't read [crashlytics] (Can't read [android] (Can't read [answers] (Can't read [shim] (Can't read [R.class] (Duplicate zip entry [com/crashlytics/android/answers/shim/R.class]))))))))

Here is my buildTypes Task:

```<code>buildTypes {
    debug {
        shrinkResources false // This must be first
        minifyEnabled false   // This must be after shrinkResources
        multiDexEnabled true
        proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules-debug.pro"
    }
    release {
        shrinkResources true
        minifyEnabled true
        useProguard true
        multiDexEnabled true
        proguardFiles getDefaultProguardFile('proguard-android.txt'), "proguard-rules.pro"
    }
}
</code>```

Here is the code I've written in proguard file:

```<code>-optimizationpasses 5
-dontusemixedcaseclassnames
-dontskipnonpubliclibraryclasses
-dontskipnonpubliclibraryclassmembers
-dontpreverify
-verbose
-dump class_files.txt
-printseeds seeds.txt
-printusage unused.txt
-printmapping mapping.txt
-optimizations !code/simplification/arithmetic,!field/*,!class/merging/*

-allowaccessmodification
-keepattributes *Annotation*
-renamesourcefileattribute SourceFile
-keepattributes SourceFile,LineNumberTable
-keepattributes Signature
-keepattributes Exceptions
-repackageclasses ''

-keep public class * extends android.app.Activity
-keep public class * extends android.app.Application
-keep public class * extends android.app.Service
-keep public class * extends android.content.BroadcastReceiver
-keep public class * extends android.content.ContentProvider
-keep public class * extends android.app.backup.BackupAgentHelper
-keep public class * extends android.preference.Preference
-keep public class * extends android.app.
-keep public class com.android.vending.licensing.ILicensingService

-keep class com.google.common.collect.MapMakerInternalMap$ReferenceEntry
-keep class com.google.common.cache.LocalCache$ReferenceEntry

-dontnote com.android.vending.licensing.ILicensingService

-keepclassmembers class * implements java.io.Serializable {
    static final long serialVersionUID;
    private static final java.io.ObjectStreamField[] serialPersistentFields;
    private void writeObject(java.io.ObjectOutputStream);
    private void readObject(java.io.ObjectInputStream);
    java.lang.Object writeReplace();
    java.lang.Object readResolve();
}

-keepclasseswithmembernames class * {
    native <methods>;
}

-keepclasseswithmembernames class * {
    public <init>(android.content.Context, android.util.AttributeSet);
}

-keepclasseswithmembernames class * {
    public <init>(android.content.Context, android.util.AttributeSet, int);
}

-keepclassmembers class **.R$* {
  public static <fields>;
}

-keepclassmembers enum * {
    public static **[] values();
    public static ** valueOf(java.lang.String);
}

-keep public class * {
    public protected *;
}

-keep class * implements android.os.Parcelable {
  public static final android.os.Parcelable$Creator *;
}

-dontwarn android.support.v7.**
-keep class android.support.v7.** { *; }
-keep interface android.support.v7.* { *; }
-keepattributes *Annotation,Signature
-dontwarn in.mylo.pregnancy.baby.app.**
-keep class in.mylo.pregnancy.baby.app.shapeimageview.**{ *; }

-keep class android.support.v4.app.** { *; }
-keep interface android.support.v4.app.** { *; }
-keep interface com.actionbarsherlock.** { *; }

-keep class butterknife.*
-keepclasseswithmembernames class * {
 @butterknife.* <methods>; }
-keepclasseswithmembernames class * {
 @butterknife.* <fields>; }

-dontwarn javax.annotation.**
-dontwarn javax.inject.**
-dontwarn sun.misc.Unsafe

-dontwarn java.lang.ClassValue
-dontwarn com.google.j2objc.annotations.Weak
-dontwarn org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement

-keep public class * implements com.bumptech.glide.module.GlideModule
-keep public enum com.bumptech.glide.load.resource.bitmap.ImageHeaderParser$** {
  **[] $VALUES;
  public *;
}

-dontwarn com.firebase.**
-dontnote com.firebase.client.core.GaePlatform

-keep class com.firebase.** { *; }

-keepnames class com.fasterxml.jackson.** { *; }
-keepnames class javax.servlet.** { *; }
-keepnames class org.ietf.jgss.** { *; }

-dontwarn com.clevertap.android.sdk.**

-keep class okhttp3.** { *; }
-keep interface okhttp3.** { *; }
-dontwarn okhttp3.**
-dontnote okhttp3.**

-keep class sun.misc.Unsafe { *; }
-dontwarn java.nio.file.*
-dontwarn org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement

-keepclassmembers class * extends android.app.Activity {
   public void *(android.view.View);
}
-keepclassmembers enum * {
    public static **[] values();
    public static ** valueOf(java.lang.String);
}
-keepclassmembers class * implements android.os.Parcelable {
  public static final android.os.Parcelable$Creator CREATOR;
}
-keepclassmembers class **.R$* {
    public static <fields>;
}

-dontwarn android.support.**

-dontwarn com.google.android.gms.**

-dontwarn com.fasterxml.**
-dontwarn okio.**
-dontwarn com.caverock.**
-dontwarn com.github.siyamed.shapeimageview.**

-dontwarn retrofit.**
-keep class retrofit.** { *; }
-dontwarn sun.misc.Unsafe
-dontwarn com.octo.android.robospice.retrofit.RetrofitJackson**
-dontwarn retrofit.appengine.UrlFetchClient
-keepattributes Signature
-keepattributes Exceptions
-keepclasseswithmembers class * {
    @retrofit.http.* <methods>;
}
-keep class com.google.gson.** { *; }
-keep class com.google.inject.** { *; }
-keep class org.apache.http.** { *; }
-keep class org.apache.james.mime4j.** { *; }
-keep class javax.inject.** { *; }
-keep class retrofit.** { *; }
-keep class retrofit2.** { *; }
-dontwarn org.apache.http.**
-dontwarn android.net.http.AndroidHttpClient
-dontwarn retrofit.**
-dontwarn retrofit2.**

-dontwarn sun.misc.**

-keepclassmembers class rx.internal.util.unsafe.*ArrayQueue*Field* {
   long producerIndex;
   long consumerIndex;
}

-keepclassmembers class rx.internal.util.unsafe.BaseLinkedQueueProducerNodeRef {
   long producerNode;
   long consumerNode;
}

-keep class in.mylo.pregnancy.baby.app.retrofit.** { *; }

-keep interface org.parceler.Parcel
-keep @org.parceler.Parcel class * { *; }
-keep class **$$Parcelable { *; }

-keepnames public class * extends io.realm.RealmObject
-keep @io.realm.annotations.RealmModule class *
-keep class io.realm.** { *; }
-dontwarn javax.**
-dontwarn io.realm.**

-keepnames public class * extends io.realm.RealmObject

-dontwarn com.google.android.gms.location.**
-dontwarn com.google.android.gms.gcm.**
-dontwarn com.google.android.gms.iid.**

-keep class com.google.android.gms.gcm.** { *; }
-keep class com.google.android.gms.iid.** { *; }
-keep class com.google.android.gms.location.** { *; }

-keep class com.moe.pushlibrary.activities.** { *; }
-keep class com.moengage.locationlibrary.GeofenceIntentService
-keep class com.moe.pushlibrary.InstallReceiver
-keep class com.moengage.push.MoEPushWorker
-keep class com.moe.pushlibrary.providers.MoEProvider
-keep class com.moengage.receiver.MoEInstanceIDListener
-keep class com.moengage.worker.MoEGCMListenerService
-keep class com.moe.pushlibrary.models.** { *;}
-keep class com.moengage.core.GeoTask
-keep class com.moengage.location.GeoManager
-keep class com.moengage.inapp.InAppManager
-keep class com.moengage.push.PushManager
-keep class com.moengage.inapp.InAppController

-dontwarn com.moengage.location.GeoManager
-dontwarn com.moengage.core.GeoTask
-dontwarn com.moengage.receiver.*
-dontwarn com.moengage.worker.*
-dontwarn com.moengage.inapp.ViewEngine

-keep class com.delight.**  { *; }

-dontwarn com.google.android.gms.location.**
-keep class com.moe.** { *; }
-keep class com.moengage.** { *; }
-keep class com.delight.** { *; }

-keep class com.google.android.gms.ads.** { *; }

-keep class com.facebook.** {
   *;
}

-dontwarn android.databinding.**
-keep class android.databinding.** { *; }
</code>```

Any help appreciated, thanks in advance.

答:
Try excluding answers-shim:</p>

```<code>compile ('io.branch.sdk.android:library:2.+') {
    exclude module: 'answers-shim'
}
</code>```

Body:
I have a problem with generating signed APK in Android Studio. It was working fine few days ago, I dont know what went wrong. I'm getting this error for any project I try to fgenerate signed APK of:

Warning:Exception while processing task java.io.IOException: Can't write [/Users/bhaveshmisri/Downloads/littleone-dagger-mvp/app/build/intermediates/transforms/proguard/release/jars/3/1f/main.jar] (Can't read [/Users/bhaveshmisri/Downloads/littleone-dagger-mvp/app/build/intermediates/transforms/RealmTransformer/release/folders/1/1/realm(;;;;;;**.class)] (Can't read [com] (Can't read [crashlytics] (Can't read [android] (Can't read [answers] (Can't read [shim] (Can't read [R.class] (Duplicate zip entry [com/crashlytics/android/answers/shim/R.class]))))))))

Here is my buildTypes Task:

buildTypes {
    debug {
        shrinkResources false // This must be first
        minifyEnabled false   // This must be after shrinkResources
        multiDexEnabled true
        proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules-debug.pro"
    }
    release {
        shrinkResources true
        minifyEnabled true
        useProguard true
        multiDexEnabled true
        proguardFiles getDefaultProguardFile('proguard-android.txt'), "proguard-rules.pro"
    }
}

Here is the code I've written in proguard file:

-optimizationpasses 5
-dontusemixedcaseclassnames
-dontskipnonpubliclibraryclasses
-dontskipnonpubliclibraryclassmembers
-dontpreverify
-verbose
-dump class_files.txt
-printseeds seeds.txt
-printusage unused.txt
-printmapping mapping.txt
-optimizations !code/simplification/arithmetic,!field/*,!class/merging/*

-allowaccessmodification
-keepattributes *Annotation*
-renamesourcefileattribute SourceFile
-keepattributes SourceFile,LineNumberTable
-keepattributes Signature
-keepattributes Exceptions
-repackageclasses ''

-keep public class * extends android.app.Activity
-keep public class * extends android.app.Application
-keep public class * extends android.app.Service
-keep public class * extends android.content.BroadcastReceiver
-keep public class * extends android.content.ContentProvider
-keep public class * extends android.app.backup.BackupAgentHelper
-keep public class * extends android.preference.Preference
-keep public class * extends android.app.
-keep public class com.android.vending.licensing.ILicensingService

-keep class com.google.common.collect.MapMakerInternalMap$ReferenceEntry
-keep class com.google.common.cache.LocalCache$ReferenceEntry

-dontnote com.android.vending.licensing.ILicensingService

-keepclassmembers class * implements java.io.Serializable {
    static final long serialVersionUID;
    private static final java.io.ObjectStreamField[] serialPersistentFields;
    private void writeObject(java.io.ObjectOutputStream);
    private void readObject(java.io.ObjectInputStream);
    java.lang.Object writeReplace();
    java.lang.Object readResolve();
}

-keepclasseswithmembernames class * {
    native <methods>;
}

-keepclasseswithmembernames class * {
    public <init>(android.content.Context, android.util.AttributeSet);
}

-keepclasseswithmembernames class * {
    public <init>(android.content.Context, android.util.AttributeSet, int);
}

-keepclassmembers class **.R$* {
  public static <fields>;
}

-keepclassmembers enum * {
    public static **[] values();
    public static ** valueOf(java.lang.String);
}

-keep public class * {
    public protected *;
}

-keep class * implements android.os.Parcelable {
  public static final android.os.Parcelable$Creator *;
}

-dontwarn android.support.v7.**
-keep class android.support.v7.** { *; }
-keep interface android.support.v7.* { *; }
-keepattributes *Annotation,Signature
-dontwarn in.mylo.pregnancy.baby.app.**
-keep class in.mylo.pregnancy.baby.app.shapeimageview.**{ *; }

-keep class android.support.v4.app.** { *; }
-keep interface android.support.v4.app.** { *; }
-keep interface com.actionbarsherlock.** { *; }

-keep class butterknife.*
-keepclasseswithmembernames class * {
 @butterknife.* <methods>; }
-keepclasseswithmembernames class * {
 @butterknife.* <fields>; }

-dontwarn javax.annotation.**
-dontwarn javax.inject.**
-dontwarn sun.misc.Unsafe

-dontwarn java.lang.ClassValue
-dontwarn com.google.j2objc.annotations.Weak
-dontwarn org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement

-keep public class * implements com.bumptech.glide.module.GlideModule
-keep public enum com.bumptech.glide.load.resource.bitmap.ImageHeaderParser$** {
  **[] $VALUES;
  public *;
}

-dontwarn com.firebase.**
-dontnote com.firebase.client.core.GaePlatform

-keep class com.firebase.** { *; }

-keepnames class com.fasterxml.jackson.** { *; }
-keepnames class javax.servlet.** { *; }
-keepnames class org.ietf.jgss.** { *; }

-dontwarn com.clevertap.android.sdk.**

-keep class okhttp3.** { *; }
-keep interface okhttp3.** { *; }
-dontwarn okhttp3.**
-dontnote okhttp3.**

-keep class sun.misc.Unsafe { *; }
-dontwarn java.nio.file.*
-dontwarn org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement

-keepclassmembers class * extends android.app.Activity {
   public void *(android.view.View);
}
-keepclassmembers enum * {
    public static **[] values();
    public static ** valueOf(java.lang.String);
}
-keepclassmembers class * implements android.os.Parcelable {
  public static final android.os.Parcelable$Creator CREATOR;
}
-keepclassmembers class **.R$* {
    public static <fields>;
}

-dontwarn android.support.**

-dontwarn com.google.android.gms.**

-dontwarn com.fasterxml.**
-dontwarn okio.**
-dontwarn com.caverock.**
-dontwarn com.github.siyamed.shapeimageview.**

-dontwarn retrofit.**
-keep class retrofit.** { *; }
-dontwarn sun.misc.Unsafe
-dontwarn com.octo.android.robospice.retrofit.RetrofitJackson**
-dontwarn retrofit.appengine.UrlFetchClient
-keepattributes Signature
-keepattributes Exceptions
-keepclasseswithmembers class * {
    @retrofit.http.* <methods>;
}
-keep class com.google.gson.** { *; }
-keep class com.google.inject.** { *; }
-keep class org.apache.http.** { *; }
-keep class org.apache.james.mime4j.** { *; }
-keep class javax.inject.** { *; }
-keep class retrofit.** { *; }
-keep class retrofit2.** { *; }
-dontwarn org.apache.http.**
-dontwarn android.net.http.AndroidHttpClient
-dontwarn retrofit.**
-dontwarn retrofit2.**

-dontwarn sun.misc.**

-keepclassmembers class rx.internal.util.unsafe.*ArrayQueue*Field* {
   long producerIndex;
   long consumerIndex;
}

-keepclassmembers class rx.internal.util.unsafe.BaseLinkedQueueProducerNodeRef {
   long producerNode;
   long consumerNode;
}

-keep class in.mylo.pregnancy.baby.app.retrofit.** { *; }

-keep interface org.parceler.Parcel
-keep @org.parceler.Parcel class * { *; }
-keep class **$$Parcelable { *; }

-keepnames public class * extends io.realm.RealmObject
-keep @io.realm.annotations.RealmModule class *
-keep class io.realm.** { *; }
-dontwarn javax.**
-dontwarn io.realm.**

-keepnames public class * extends io.realm.RealmObject

-dontwarn com.google.android.gms.location.**
-dontwarn com.google.android.gms.gcm.**
-dontwarn com.google.android.gms.iid.**

-keep class com.google.android.gms.gcm.** { *; }
-keep class com.google.android.gms.iid.** { *; }
-keep class com.google.android.gms.location.** { *; }

-keep class com.moe.pushlibrary.activities.** { *; }
-keep class com.moengage.locationlibrary.GeofenceIntentService
-keep class com.moe.pushlibrary.InstallReceiver
-keep class com.moengage.push.MoEPushWorker
-keep class com.moe.pushlibrary.providers.MoEProvider
-keep class com.moengage.receiver.MoEInstanceIDListener
-keep class com.moengage.worker.MoEGCMListenerService
-keep class com.moe.pushlibrary.models.** { *;}
-keep class com.moengage.core.GeoTask
-keep class com.moengage.location.GeoManager
-keep class com.moengage.inapp.InAppManager
-keep class com.moengage.push.PushManager
-keep class com.moengage.inapp.InAppController

-dontwarn com.moengage.location.GeoManager
-dontwarn com.moengage.core.GeoTask
-dontwarn com.moengage.receiver.*
-dontwarn com.moengage.worker.*
-dontwarn com.moengage.inapp.ViewEngine

-keep class com.delight.**  { *; }

-dontwarn com.google.android.gms.location.**
-keep class com.moe.** { *; }
-keep class com.moengage.** { *; }
-keep class com.delight.** { *; }

-keep class com.google.android.gms.ads.** { *; }

-keep class com.facebook.** {
   *;
}

-dontwarn android.databinding.**
-keep class android.databinding.** { *; }

Any help appreciated, thanks in advance.

Body:
Try excluding answers-shim:

compile ('io.branch.sdk.android:library:2.+') {
    exclude module: 'answers-shim'
}


问:
Number of Duplicate Rows in multiple columns (more than 10) in SQL Server
I have a table in SQL Server and I need to find the number of customers and accounts who have different values across the row.

For example

```<code>Customer  Account    X   Y   Z
-------------------------------
A             001   X1   Y1  Z1
A             002   X2   Y1  Z1
A             003   X1   Y1  Z1
B             004   X3   Y2  Z2
B             005   X4   Y2  Z2
C             006   X5   Y3  Z3
C             007   X5   Y3  Z3
</code>```

and I want the result to be Number of Customers with different X,Y,Z are 2, Number of accounts affected are 5.

```<code>Customer  Account   X   Y   Z
-------------------------------
A            001    X1  Y1  Z1
A            002    X2  Y1  Z1
A            003    X1  Y1  Z1
B            004    X3  Y2  Z2
B            005    X4  Y2  Z2
</code>```

答:
My take on this:</p>

```<code>select *
from <table>
where customer in (
    select customer
    from <table>
    group by customer, concat(x,y,z)
    having count(concat(x,y,z)) = 1
                )
</code>```

Body:
I have a table in SQL Server and I need to find the number of customers and accounts who have different values across the row.

For example

Customer  Account    X   Y   Z
-------------------------------
A             001   X1   Y1  Z1
A             002   X2   Y1  Z1
A             003   X1   Y1  Z1
B             004   X3   Y2  Z2
B             005   X4   Y2  Z2
C             006   X5   Y3  Z3
C             007   X5   Y3  Z3

and I want the result to be Number of Customers with different X,Y,Z are 2, Number of accounts affected are 5.

Customer  Account   X   Y   Z
-------------------------------
A            001    X1  Y1  Z1
A            002    X2  Y1  Z1
A            003    X1  Y1  Z1
B            004    X3  Y2  Z2
B            005    X4  Y2  Z2

Body:
My take on this:

select *
from <table>
where customer in (
    select customer
    from <table>
    group by customer, concat(x,y,z)
    having count(concat(x,y,z)) = 1
                )


问:
PHP: echo selected value from a drop down list
I have this drop-down list that I created using one of MySQL table. The drop-down list is working fine but for some reason I am not able to echo the selected value here is my code:

```<code><?php
      require_once('config.php');
      // CONNECT
       mysql_connect('localhost', 'root', 'password');
       mysql_select_db('Database');

 ?>
 // other.php is another php file
 <form action="other.php" method="POST">

            <label>Quantity:</label>
            <input type="number" min="1" name="quantity" value="1"/>
            <br/>
            <hr/>

            <?php
                    echo makeFormEntry('Product Type', 'type', $types);
                    echo makeFormEntry('Product Occasion', 'occasion', $occasions);
                    echo makeFormEntry('Product Size', 'size', $sizes);
            $sql = "SELECT * FROM Table";
            $result = mysql_query($sql);
            echo "<b>Name : </b>" . "<select id='Name' name='Name'>";
            while ($row = mysql_fetch_array($result)) {
             echo "<option value='" . $row['Name'] . "'>" . $row['Name'] . "</option>";
            }
                    echo "</select><br>";
               echo "<input type='submit'/><input type='reset'/>";
  ?>
  </form>
</code>```

here is what I have tried:

```<code>  $n=$_POST['Name'];
   echo $n;
</code>```

答:
The drop down list must be contained in a form. You can't get a value from the $_POST array if it isn't set submitting a form.

You should use this code :

```<code>$sql = "SELECT * FROM TABLE";
$result = mysql_query($sql);
echo "Options" . "<form method='post'><select id='name' name='name'>";
while ($row = mysql_fetch_array($result)) {
     echo "<option value='" . $row['Name'] . "'>" . $row['Name'] . "
     </option>";
}
echo "</select><input type='submit' name='submit'></form><br>";

if(isset($_POST['submit'])) {
    echo $_POST['name'];
}
</code>```

I hope this is going to help you!

Body:
I have this drop-down list that I created using one of MySQL table. The drop-down list is working fine but for some reason I am not able to echo the selected value here is my code:

<?php
      require_once('config.php');
      // CONNECT
       mysql_connect('localhost', 'root', 'password');
       mysql_select_db('Database');

 ?>
 // other.php is another php file
 <form action="other.php" method="POST">

            Quantity:
            <input type="number" min="1" name="quantity" value="1"/>

            <?php
                    echo makeFormEntry('Product Type', 'type', $types);
                    echo makeFormEntry('Product Occasion', 'occasion', $occasions);
                    echo makeFormEntry('Product Size', 'size', $sizes);
            $sql = "SELECT * FROM Table";
            $result = mysql_query($sql);
            echo "Name : " . "<select id='Name' name='Name'>";
            while ($row = mysql_fetch_array($result)) {
             echo "<option value='" . $row['Name'] . "'>" . $row['Name'] . "</option>";
            }
                    echo "</select>
";
               echo "<input type='submit'/><input type='reset'/>";
  ?>
  </form>

here is what I have tried:

  $n=$_POST['Name'];
   echo $n;

Body:
The drop down list must be contained in a form. You can't get a value from the $_POST array if it isn't set submitting a form.

You should use this code :

$sql = "SELECT * FROM TABLE";
$result = mysql_query($sql);
echo "Options" . "<form method='post'><select id='name' name='name'>";
while ($row = mysql_fetch_array($result)) {
     echo "<option value='" . $row['Name'] . "'>" . $row['Name'] . "
     </option>";
}
echo "</select><input type='submit' name='submit'></form><br>";

if(isset($_POST['submit'])) {
    echo $_POST['name'];
}

I hope this is going to help you!


问:
Loop that doesn't end
Here is a piece from my code.
My problem is that this line System.out.println(digit.contains(0)); prints false even when there is a zero in the list "digit".

```<code>    int x = 5;
    int y = 0;
    int z;
    ArrayList<Character> digit = new ArrayList<>();
    char[] new_digit = {};
    boolean end_loop = true;

    do {
        z = x * y;
        new_digit = ("" + z).toCharArray();
        for (int k = 0; k < new_digit.length; k++) {
            if (!digit.contains(new_digit[k])) {
                digit.add(new_digit[k]);
            }
        }
        System.out.println(digit.contains(0));
</code>```

what is the problem exactly?

答:
The list is a list of characters:

```<code>ArrayList<Character> digit = new ArrayList<>();
</code>```

You are checking whether it contains the integer zero:

```<code>digit.contains(0)
</code>```

Because this is an integer and not a character, it will will be implicitly converted to the ASCII character represented by that number, which is NULL. The character 0 is represented in ASCII by the integer 48.

If you want to check whether your list contains the character zero, do this:

```<code>digit.contains('0')
</code>```

Title: Loop that doesn't end

Body:
Here is a piece from my code.
My problem is that this line System.out.println(digit.contains(0)); prints false even when there is a zero in the list "digit".

    int x = 5;
    int y = 0;
    int z;
    ArrayList<Character> digit = new ArrayList<>();
    char[] new_digit = {};
    boolean end_loop = true;

    do {
        z = x * y;
        new_digit = ("" + z).toCharArray();
        for (int k = 0; k < new_digit.length; k++) {
            if (!digit.contains(new_digit[k])) {
                digit.add(new_digit[k]);
            }
        }
        System.out.println(digit.contains(0));

what is the problem exactly?

Body:
The list is a list of characters:

ArrayList<Character> digit = new ArrayList<>();

You are checking whether it contains the integer zero:

digit.contains(0)

Because this is an integer and not a character, it will will be implicitly converted to the ASCII character represented by that number, which is NULL. The character 0 is represented in ASCII by the integer 48.

If you want to check whether your list contains the character zero, do this:

digit.contains('0')


问:
What is the best way to tell users of my library functions that passed variables are not of the correct type
I'm currently in the creation of a javascript function library. Mainly for my own use, but you can never be sure if someone else ends up using it in their projects, I'm atleast creating it as if that could happen.

Most methods only work if the variables that are passed are of the correct datatype. Now my question is: What is the best way to alert users that the variable is not of the correct type? Should one throw an error like this?

```<code>function foo(thisShouldBeAString){ //just pretend that this is a method and not a global function
 if(typeof(thisShouldBeAString) === 'string') {
  throw('foo(var), var should be of type string');
 }
 #yadayada
}
</code>```

I know that javascript does internal type conversion, but this can create very weird results (ie '234' + 5 = '2345' but '234' * 1 = 234) and this could make my methods do very weird things.

EDIT

To make things extra clear: I do not wish to do type conversion, the variables passed should be of the correct type. What is the best way to tell the user of my library that the passed variables are not of the correct type?

答:
How about throw:
https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Statements/throw

Also type of does not distinguish between Array, Null, Object very well. Look at the funciton here: http://javascript.crockford.com/remedial.html, plus there are a few other ways to do it.

Personally I would not do the type checking since it is a step that will just add more processing time to the code. If you care about performance, you would want to chop off as many milliseconds of processing time as possible. Good Documentation will cure the need for the check.

OwnerDisplayName: Pim Jager

Body:
I'm currently in the creation of a javascript function library. Mainly for my own use, but you can never be sure if someone else ends up using it in their projects, I'm atleast creating it as if that could happen.

Most methods only work if the variables that are passed are of the correct datatype. Now my question is: What is the best way to alert users that the variable is not of the correct type? Should one throw an error like this?

function foo(thisShouldBeAString){ //just pretend that this is a method and not a global function
 if(typeof(thisShouldBeAString) === 'string') {
  throw('foo(var), var should be of type string');
 }
 #yadayada
}

I know that javascript does internal type conversion, but this can create very weird results (ie '234' + 5 = '2345' but '234' * 1 = 234) and this could make my methods do very weird things.

EDIT

To make things extra clear: I do not wish to do type conversion, the variables passed should be of the correct type. What is the best way to tell the user of my library that the passed variables are not of the correct type?

LastEditorDisplayName: Mitch Wheat

LastEditorDisplayName: Dreas Grech


问:
Call a function through socket.io
Here i have a button which shows alert box onclick. I'm trying to implement client and server model where data is transferred between client and server. Now when i open the script in two windows, and when i click the button in one window alert should be displayed in both windows, This indicates that user in one windows thinks that the user in another window clicked the button.

here is my index.html file

```<code><html>
<head>

<script>
function myFunction() {
    alert("I am an alert box!");
}
</script>

</head>
<body>

<button id="datasend " type="button " ng-click="doPost "onclick="myFunction()">Send!
</button>

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

Here is my app.js

```<code> $scope.doPost = function () {

                myFunction();

        socket.emit('sendmessage', function (){

                myFunction();
            });

        socket.on('sendmessage', function () {

                $('#datasend').click(function()
      {

      });
            });
          }
</code>```

答:
You can start a VERY basic node server:

server.js

```<code>const io = require('socket.io')(3000);
io.on('connection', function (socket) {
    console.log('a client has connected');
    socket.on('clicked', function() {
        io.emit('clicked');
    });
});
console.log('socket.io server started at port 3000');
</code>```

and open the following index.html in several tabs of your browser:

index.html

```<code><!doctype html>
  <html>
    <head>
      <title>Testing socket.io</title>
    </head>
    <body>
      <button id="button">Send!</button>
      <h2 id="alert"> waiting...</h2>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.7.3/socket.io.min.js"></script>
      <script>
        var socket = io("http://localhost:3000");
        socket.on('connect', function() {
          document.getElementById("button").addEventListener("click", function () {
              socket.emit("clicked");
          });
        });
        socket.on('clicked', function() {
          console.log('clicked');
          document.getElementById("alert").innerHTML = "button clicked";
        });
      </script>
    </body>
  </html>
</code>```

Title: Call a function through socket.io

Body:
Here i have a button which shows alert box onclick. I'm trying to implement client and server model where data is transferred between client and server. Now when i open the script in two windows, and when i click the button in one window alert should be displayed in both windows, This indicates that user in one windows thinks that the user in another window clicked the button.

here is my index.html file

<button id="datasend " type="button " ng-click="doPost "onclick="myFunction()">Send!
</button>

Here is my app.js

 $scope.doPost = function () {

                myFunction();

        socket.emit('sendmessage', function (){

                myFunction();
            });

        socket.on('sendmessage', function () {

                $('#datasend').click(function()
      {

      });
            });
          }

Body:
You can start a VERY basic node server:

server.js

const io = require('socket.io')(3000);
io.on('connection', function (socket) {
    console.log('a client has connected');
    socket.on('clicked', function() {
        io.emit('clicked');
    });
});
console.log('socket.io server started at port 3000');

and open the following index.html in several tabs of your browser:

index.html

<!doctype html>
  <html>
    <head>
      <title>Testing socket.io</title>
    </head>
    <body>
      <button id="button">Send!</button>
      <h2 id="alert"> waiting...</h2>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.7.3/socket.io.min.js"></script>
      <script>
        var socket = io("http://localhost:3000");
        socket.on('connect', function() {
          document.getElementById("button").addEventListener("click", function () {
              socket.emit("clicked");
          });
        });
        socket.on('clicked', function() {
          console.log('clicked');
          document.getElementById("alert").innerHTML = "button clicked";
        });
      </script>
    </body>
  </html>


问:
Messaging system in a website between the users theirselves
I want to add to my website a messaging system where my logged-in users can message other user (like Facebook, Fiverr..).

Doing it by ourselves is a lot of maintenance and development time we do not have.
Using Layer or SendBird is too expensive for us.
Using Quickblox is not recommended by our friends who used it.

Do you know any other messaging sdk`s for Web , where you can easily intergrate this ability to your website and it contain all the complex messaging options (text, files, group message)?

答:
I would suggest you to keep with sendbird free version:
 First : - It has really good documentation, which means easy to follow and implement.
 Second : - It support Javascript which probably your app written by, and react, react native which let you make the web to app/ crossplatform.
 Third  : -It gives you service support, and sample to follow.

The only problem is that Free version supports up to 1000 users, more than that you need to upgrade.
Here is the link have a look:
 https://sendbird.com/pricing


问:
Comparing a char with multiple characters
```<code>for(int j=0 ; j<str.length() ; j++) {
    if(char[j]==(a||e||i||o||u))
        count++;
}
</code>```

I know the result of (a||e||i||o||u) is a Boolean so can't compare but how can we check for multiple character presence?

答:
One more for Java 8:</p>

```<code>count = str.chars()
           .filter(c -> c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' )
           .count();
</code>```

Body:
for(int j=0 ; j<str.length() ; j++) {
    if(char[j]==(a||e||i||o||u))
        count++;
}

I know the result of (a||e||i||o||u) is a Boolean so can't compare but how can we check for multiple character presence?

Body:
One more for Java 8:

count = str.chars()
           .filter(c -> c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' )
           .count();


问:
Read 2D matrix from file to 2D int array in C#
I have problem in reading 2D text from file and import it to an int array. Specifically, my text file looks like below:

2,3,4,5,6

5,2,3,4,5

2,4,6,7,4

2,7,8,5,6

So each cell in matrix is separated by comma and each new row starts with new line.

I tried many ways to make it works but I can't! Simply, I want an int[][] or int[,] array at the end.

P.S: I can read 1-D matrix simply to int[] as below:

```<code>int[] array= File.ReadAllText(fileppath).Split(',').Select(t => int.Parse(t)).ToArray();
</code>```

答:
You first need to add the index of each line to the first dimension and then every 'column 'in the line to the second dimension.

Try the following code:

```<code>int[][] array = File.ReadAllText(filepath).Split('\n')
                .Select(r => (r.Split(','))
                .Select(c => int.Parse(c)).ToArray()).ToArray();
</code>```

Body:
I have problem in reading 2D text from file and import it to an int array. Specifically, my text file looks like below:

2,3,4,5,6

5,2,3,4,5

2,4,6,7,4

2,7,8,5,6

So each cell in matrix is separated by comma and each new row starts with new line.

I tried many ways to make it works but I can't! Simply, I want an int[][] or int[,] array at the end.

P.S: I can read 1-D matrix simply to int[] as below:

int[] array= File.ReadAllText(fileppath).Split(',').Select(t => int.Parse(t)).ToArray();

Body:
You first need to add the index of each line to the first dimension and then every 'column 'in the line to the second dimension.

Try the following code:

int[][] array = File.ReadAllText(filepath).Split('\n')
                .Select(r => (r.Split(','))
                .Select(c => int.Parse(c)).ToArray()).ToArray();


问:
Conv1D on 2D input
Can someone explain to me what happens when a keras Conv1D layer is fed 2D input?
Such as:

```<code>model=Sequential()
model.add(Conv1D(input_shape=(9000,2),kernel_size=200,strides=1,filters=20))
</code>```

Varying the input size between (9000,1) and (9000,2) and calling model.summary(), I see that the output shape stays the same, but the number of parameters changes. So, does that mean that different filters are trained for each channel, but the output is summed/averaged across the 2nd dimension before outputting? Or what?

答:
In the doc you can read that the input MUST be 2D.

Conv1D can be seen as a time-window going over a sequence of vectors. The kernel will 2dimensions window, as large as the vectors length (so the 2nd dimension of your input) and will be as long as your window size...

So indeed it is perfectly normal that your two networks have the same output shape... and the number of parameters is higher because the kernels are 2times bigger due to the second dimension.

I hope this helps :-)

Title: Conv1D on 2D input

Body:
Can someone explain to me what happens when a keras Conv1D layer is fed 2D input?
Such as:

model=Sequential()
model.add(Conv1D(input_shape=(9000,2),kernel_size=200,strides=1,filters=20))

Varying the input size between (9000,1) and (9000,2) and calling model.summary(), I see that the output shape stays the same, but the number of parameters changes. So, does that mean that different filters are trained for each channel, but the output is summed/averaged across the 2nd dimension before outputting? Or what?


问:
How Load View Files from bin Folder in Asp.net MVC
i work on asp.net mvc project and i transfer some view files to other project and enable "copy always" for them (to copy in bin folder of main project).

i create a custom view engine :

```<code>public class CMSViewEngine : WebFormViewEngine
    {
        public CMSViewEngine()
        {
            MasterLocationFormats = new string[]
            {
            "~/bin/Views/{1}/{0}.master",
            "~/bin/Views/Shared/{0}.master"
            };

            ViewLocationFormats = new string[]
            {
            "~/bin/Views/{1}/{0}.cshtml",
            "~/bin/Views/{1}/{0}.vbhtml",
            "~/bin/Views/Shared/{0}.cshtml",
            "~/bin/Views/Shared/{0}.vbhtml",
            "~/bin/Views/{1}/{0}.aspx",
            "~/bin/Views/{1}/{0}.ascx",
            "~/bin/Views/Shared/{0}.aspx",
            "~/bin/Views/Shared/{0}.ascx"
            };
        }
    }
</code>```

then added to mvc ViewEngine in global.ascx

```<code>        ViewEngines.Engines.Add(new CMSViewEngine());

        AreaRegistration.RegisterAllAreas();
        RouteConfig.RegisterRoutes(RouteTable.Routes);
</code>```

but my problem is: for showing view i get under exception:

The view at '~/bin/Views/Forms/Index.cshtml' must derive from
  ViewPage, ViewPage, ViewUserControl, or
  ViewUserControl.

i try add web.config to view folder and also try add @inherits System.Web.Mvc.WebViewPage to view files but not worked.

my web.config file for bin view files is :

```<code><?xml version="1.0"?>

<configuration>
  <configSections>
    <sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
      <section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
      <section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
    </sectionGroup>
  </configSections>

  <system.web.webPages.razor>
    <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    <pages pageBaseType="System.Web.Mvc.WebViewPage">
      <namespaces>
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Routing" />
        <add namespace="TestProj.ContactFormApp" />
      </namespaces>
    </pages>
  </system.web.webPages.razor>

  <appSettings>
    <add key="webpages:Enabled" value="false" />
  </appSettings>

  <system.webServer>
    <handlers>
      <remove name="BlockViewHandler"/>
      <add name="BlockViewHandler" path="*" verb="*" preCondition="integratedMode" type="System.Web.HttpNotFoundHandler" />
    </handlers>
  </system.webServer>

  <system.web>
    <compilation>
      <assemblies>
        <add assembly="System.Web.Mvc, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
      </assemblies>
    </compilation>
  </system.web>
</configuration>
</code>```

how can resolve this problem to load view file?

Resolved:

I must extend CMSViewEngine class from RazorViewEngine class (instead of WebFormViewEngine) to work correctly.

答:
It looks like you are using WebFormViewEngine, if that is the case you should not registere razor view files in WebFormViewEngine, your CMSViewEngine class should only contain WebForm based view files extensions like:

```<code>public class CMSViewEngine : WebFormViewEngine
{
    public CMSViewEngine()
    {
        MasterLocationFormats = new string[]
        {
        "~/bin/Views/{1}/{0}.master",
        "~/bin/Views/Shared/{0}.master"
        };

        ViewLocationFormats = new string[]
        {
        "~/bin/Views/{1}/{0}.aspx",
        "~/bin/Views/{1}/{0}.ascx",
        "~/bin/Views/Shared/{0}.aspx",
        "~/bin/Views/Shared/{0}.ascx"
        };
    }
}
</code>```

Body:
i work on asp.net mvc project and i transfer some view files to other project and enable "copy always" for them (to copy in bin folder of main project).

i create a custom view engine :

public class CMSViewEngine : WebFormViewEngine
    {
        public CMSViewEngine()
        {
            MasterLocationFormats = new string[]
            {
            "~/bin/Views/{1}/{0}.master",
            "~/bin/Views/Shared/{0}.master"
            };

            ViewLocationFormats = new string[]
            {
            "~/bin/Views/{1}/{0}.cshtml",
            "~/bin/Views/{1}/{0}.vbhtml",
            "~/bin/Views/Shared/{0}.cshtml",
            "~/bin/Views/Shared/{0}.vbhtml",
            "~/bin/Views/{1}/{0}.aspx",
            "~/bin/Views/{1}/{0}.ascx",
            "~/bin/Views/Shared/{0}.aspx",
            "~/bin/Views/Shared/{0}.ascx"
            };
        }
    }

then added to mvc ViewEngine in global.ascx

        ViewEngines.Engines.Add(new CMSViewEngine());

        AreaRegistration.RegisterAllAreas();
        RouteConfig.RegisterRoutes(RouteTable.Routes);

but my problem is: for showing view i get under exception:

The view at '~/bin/Views/Forms/Index.cshtml' must derive from
  ViewPage, ViewPage, ViewUserControl, or
  ViewUserControl.

i try add web.config to view folder and also try add @inherits System.Web.Mvc.WebViewPage to view files but not worked.

my web.config file for bin view files is :

<?xml version="1.0"?>

<configuration>
  <configSections>
    <sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">

    </sectionGroup>
  </configSections>

  <system.web.webPages.razor>
    <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    <pages pageBaseType="System.Web.Mvc.WebViewPage">
      <namespaces>
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Routing" />
        <add namespace="TestProj.ContactFormApp" />
      </namespaces>
    </pages>
  </system.web.webPages.razor>

  <appSettings>
    <add key="webpages:Enabled" value="false" />
  </appSettings>

  <system.webServer>
    <handlers>
      <remove name="BlockViewHandler"/>
      <add name="BlockViewHandler" path="*" verb="*" preCondition="integratedMode" type="System.Web.HttpNotFoundHandler" />
    </handlers>
  </system.webServer>

  <system.web>
    <compilation>
      <assemblies>
        <add assembly="System.Web.Mvc, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
      </assemblies>
    </compilation>
  </system.web>
</configuration>

how can resolve this problem to load view file?

Resolved:

I must extend CMSViewEngine class from RazorViewEngine class (instead of WebFormViewEngine) to work correctly.

Body:
It looks like you are using WebFormViewEngine, if that is the case you should not registere razor view files in WebFormViewEngine, your CMSViewEngine class should only contain WebForm based view files extensions like:

public class CMSViewEngine : WebFormViewEngine
{
    public CMSViewEngine()
    {
        MasterLocationFormats = new string[]
        {
        "~/bin/Views/{1}/{0}.master",
        "~/bin/Views/Shared/{0}.master"
        };

        ViewLocationFormats = new string[]
        {
        "~/bin/Views/{1}/{0}.aspx",
        "~/bin/Views/{1}/{0}.ascx",
        "~/bin/Views/Shared/{0}.aspx",
        "~/bin/Views/Shared/{0}.ascx"
        };
    }
}


问:
C - passing argument 1 of 'strcmp' makes pointer from integer without a cast
My function searchlist asks the user enter a student ID and lists that student ID and name.
Here is my struct:

```<code>struct student {
    int ID;
    char name[40];
    struct student *next;
};
typedef struct student Student;
</code>```

Here is my function:

```<code>void searchlist(Student *SLIST){
    Student *currentstudent = SLIST;
    char str[10], str2[10];

    printf("Enter a student ID: ");
    while(currentstudent != NULL){
        scanf("%d", &str);
        if(strcmp(str, (char)currentstudent->ID) == 0){
            printf("ID#: %d Name: %s", currentstudent->ID, currentstudent->name);
        }
    }
}
</code>```

However, when I try compiling, it gives me a warning: passing argument 1 of 'strcmp' makes pointer from integer without a cast

答:
You're not passing the right types of variable to these functions

```<code>    scanf("%d", &str);
</code>```

This is expecting str to be an int but it's a string.

```<code>    if(strcmp(str, (char)currentstudent->ID) == 0){
</code>```

This is expecting two strings (either char * or char[]) but the second parameter is an int and you're casting it to a char.

Since you're reading in an int and wanting to compare it to an int why not write it like this:

```<code>int in_id;
scanf("%d",&in_id);
if(in_id == currentstudent->ID) {
</code>```

Body:
My function searchlist asks the user enter a student ID and lists that student ID and name.
Here is my struct:

struct student {
    int ID;
    char name[40];
    struct student *next;
};
typedef struct student Student;

Here is my function:

void searchlist(Student *SLIST){
    Student *currentstudent = SLIST;
    char str[10], str2[10];

    printf("Enter a student ID: ");
    while(currentstudent != NULL){
        scanf("%d", &str);
        if(strcmp(str, (char)currentstudent->ID) == 0){
            printf("ID#: %d Name: %s", currentstudent->ID, currentstudent->name);
        }
    }
}

However, when I try compiling, it gives me a warning: passing argument 1 of 'strcmp' makes pointer from integer without a cast

Body:
You're not passing the right types of variable to these functions

    scanf("%d", &str);

This is expecting str to be an int but it's a string.

    if(strcmp(str, (char)currentstudent->ID) == 0){

This is expecting two strings (either char * or char[]) but the second parameter is an int and you're casting it to a char.

Since you're reading in an int and wanting to compare it to an int why not write it like this:

int in_id;
scanf("%d",&in_id);
if(in_id == currentstudent->ID) {