问:
Firebase Firestore multiple queries

Hi, I'm trying to add a filter on top of a query, however, it's not working. It's causing useless repetition in the code. Can someone help me?

Is there a way to add more .whereField to an existant Ref?

Thanks!
William

```<code>        var usersRef:Query

    if (DAgeMin == DAgeMax) {
        if (DGender == "Both") {
            usersRef = Firestore.firestore().collection("users")
                .whereField("AccountCompleted", isEqualTo: true)
                .whereField("Banned", isEqualTo: 0)
                .whereField("Age", isEqualTo: DAgeMin as Any)
            // usersRef.limit(to: 1)
        } else {
            usersRef = Firestore.firestore().collection("users")
                .whereField("AccountCompleted", isEqualTo: true)
                .whereField("Banned", isEqualTo: 0)
                .whereField("Gender", isEqualTo: DGender as Any)
                .whereField("Age", isEqualTo: DAgeMin as Any)
            // usersRef.limit(to: 1)
        }
    } else {
        if (DGender == "Both") {

            usersRef = Firestore.firestore().collection("users")
            // Not working, filters aren't being applied
                usersRef
                .whereField("AccountCompleted", isEqualTo: true)
                .whereField("Banned", isEqualTo: 0)
                .whereField("Age", isGreaterThanOrEqualTo: DAgeMin as Any)
                .whereField("Age", isLessThanOrEqualTo: DAgeMax as Any)

            // usersRef.limit(to: 1)
        } else {
            usersRef = Firestore.firestore().collection("users")
                .whereField("AccountCompleted", isEqualTo: true)
                .whereField("Banned", isEqualTo: 0)
                .whereField("Gender", isEqualTo: DGender as Any)
                .whereField("Age", isGreaterThanOrEqualTo: DAgeMin as Any)
                .whereField("Age", isLessThanOrEqualTo: DAgeMax as Any)
            // usersRef.limit(to: 1)

        }
    }
    // How can I apply this filter to all the usersRef, without putting it after each "block"
    usersRef.limit(to: 1)

    usersRef.getDocuments() { (querySnapshot, err) in
</code>```

答:
I ran into a similar problem in javascript. I'm not familiar with swift so the syntax will be different but hopefully it can help you too.

```<code>const userRef = firebase.firestore().collection("users");
var query = userRef.where("AccountCompleted", "==", true);

if (condition) {
    query = query.where("color", "==", "red");
}
else {
    query = query.where("color", "==", "blue");
}

if (differentCondition) {
    query = query.where("number", "==", 10);
}
else {
    query = query.where("number", "==", 12);
}

query = query.limit(1);
</code>```

This allowed me to chain different where() methods depending on the conditions and then you could add the limit() method after you finished building your query.

Title: Firebase Firestore multiple queries

Body:
Hi, I'm trying to add a filter on top of a query, however, it's not working. It's causing useless repetition in the code. Can someone help me?

Is there a way to add more .whereField to an existant Ref?

Thanks!
William

        var usersRef:Query

    if (DAgeMin == DAgeMax) {
        if (DGender == "Both") {
            usersRef = Firestore.firestore().collection("users")
                .whereField("AccountCompleted", isEqualTo: true)
                .whereField("Banned", isEqualTo: 0)
                .whereField("Age", isEqualTo: DAgeMin as Any)
            // usersRef.limit(to: 1)
        } else {
            usersRef = Firestore.firestore().collection("users")
                .whereField("AccountCompleted", isEqualTo: true)
                .whereField("Banned", isEqualTo: 0)
                .whereField("Gender", isEqualTo: DGender as Any)
                .whereField("Age", isEqualTo: DAgeMin as Any)
            // usersRef.limit(to: 1)
        }
    } else {
        if (DGender == "Both") {

            usersRef = Firestore.firestore().collection("users")
            // Not working, filters aren't being applied
                usersRef
                .whereField("AccountCompleted", isEqualTo: true)
                .whereField("Banned", isEqualTo: 0)
                .whereField("Age", isGreaterThanOrEqualTo: DAgeMin as Any)
                .whereField("Age", isLessThanOrEqualTo: DAgeMax as Any)

            // usersRef.limit(to: 1)
        } else {
            usersRef = Firestore.firestore().collection("users")
                .whereField("AccountCompleted", isEqualTo: true)
                .whereField("Banned", isEqualTo: 0)
                .whereField("Gender", isEqualTo: DGender as Any)
                .whereField("Age", isGreaterThanOrEqualTo: DAgeMin as Any)
                .whereField("Age", isLessThanOrEqualTo: DAgeMax as Any)
            // usersRef.limit(to: 1)

        }
    }
    // How can I apply this filter to all the usersRef, without putting it after each "block"
    usersRef.limit(to: 1)

    usersRef.getDocuments() { (querySnapshot, err) in

Body:
I ran into a similar problem in javascript. I'm not familiar with swift so the syntax will be different but hopefully it can help you too.

const userRef = firebase.firestore().collection("users");
var query = userRef.where("AccountCompleted", "==", true);

if (condition) {
    query = query.where("color", "==", "red");
}
else {
    query = query.where("color", "==", "blue");
}

if (differentCondition) {
    query = query.where("number", "==", 10);
}
else {
    query = query.where("number", "==", 12);
}

query = query.limit(1);

This allowed me to chain different where() methods depending on the conditions and then you could add the limit() method after you finished building your query.


来源: stackexchange

问:
Running cloud9 on ec2
Just installed cloud9 on ec2 using the instructions at https://github.com/ajaxorg/cloud9.
All went well.
Opened 3131 in aws security group
Added dir cloud9/projects
IDE pops right up and the crashed when I do pretty much anything

```<code>Console
[ec2-user@ip-172-30-0-35 cloud9]$ bin/cloud9.sh -l 0.0.0.0 -w projects
mkdir -p plugins-client/lib.ace/www/worker
rm -rf /tmp/c9_worker_build
rm: cannot remove ‘/tmp/c9_worker_build/ext/codecomplete’: Permission denied
rm: cannot remove ‘/tmp/c9_worker_build/ext/csslanguage’: Permission denied
rm: cannot remove ‘/tmp/c9_worker_build/ext/linereport’: Permission denied
rm: cannot remove ‘/tmp/c9_worker_build/ext/jslanguage’: Permission denied
rm: cannot remove ‘/tmp/c9_worker_build/ext/linereport_php’: Permission denied
rm: cannot remove ‘/tmp/c9_worker_build/ext/language’: Permission denied
rm: cannot remove ‘/tmp/c9_worker_build/ext/htmllanguage’: Permission denied
rm: cannot remove ‘/tmp/c9_worker_build/ext/linereport_python’: Permission denied
make: *** [plugins-client/lib.ace/www/worker/worker-language.js] Error 1
Linux 64 bit
connect plugin start
Connect server listening at http://x.x.x.x.0:3131 x.x.x.x replaces zeros in url
IDE SERVER PLUGIN:  auth
IDE SERVER PLUGIN:  git
IDE SERVER PLUGIN:  gittools
IDE SERVER PLUGIN:  hg
IDE SERVER PLUGIN:  npm
IDE SERVER PLUGIN:  filelist
IDE SERVER PLUGIN:  search
IDE SERVER PLUGIN:  revisions
IDE SERVER PLUGIN:  settings
IDE SERVER PLUGIN:  shell
IDE SERVER PLUGIN:  state
IDE SERVER PLUGIN:  watcher
IDE SERVER PLUGIN:  node-runtime
IDE SERVER PLUGIN:  npm-runtime
IDE SERVER PLUGIN:  python-runtime
IDE SERVER PLUGIN:  apache-runtime
IDE SERVER PLUGIN:  ruby-runtime
IDE SERVER PLUGIN:  php-runtime
Started '/home/ec2-user/cloud9/configs/default'!
IDE server initialized. Listening on x.x.x.x.0:3131 x.x.x.x replaces zeros in url

events.js:72
        throw er; // Unhandled 'error' event
              ^
Error: spawn ENOENT
    at errnoException (child_process.js:1000:11)
    at Process.ChildProcess._handle.onexit (child_process.js:791:34)
</code>```

Has anyone any experience with this?

答:
In general ENOENT means there's some issue with symlinks, sockets, pipes, files, directories, etc.. either something doesn't exist or you don't have permissions to access it. I'm going to guess something socket or directory related here.

There's also a much easier way to run Cloud9 on EC2 now: https://aws.amazon.com/cloud9/

ContentLicense: CC BY-SA 3.0

Title: Running cloud9 on ec2

Body:
Just installed cloud9 on ec2 using the instructions at https://github.com/ajaxorg/cloud9.
All went well.
Opened 3131 in aws security group
Added dir cloud9/projects
IDE pops right up and the crashed when I do pretty much anything

Console
[ec2-user@ip-172-30-0-35 cloud9]$ bin/cloud9.sh -l 0.0.0.0 -w projects
mkdir -p plugins-client/lib.ace/www/worker
rm -rf /tmp/c9_worker_build
rm: cannot remove ‘/tmp/c9_worker_build/ext/codecomplete’: Permission denied
rm: cannot remove ‘/tmp/c9_worker_build/ext/csslanguage’: Permission denied
rm: cannot remove ‘/tmp/c9_worker_build/ext/linereport’: Permission denied
rm: cannot remove ‘/tmp/c9_worker_build/ext/jslanguage’: Permission denied
rm: cannot remove ‘/tmp/c9_worker_build/ext/linereport_php’: Permission denied
rm: cannot remove ‘/tmp/c9_worker_build/ext/language’: Permission denied
rm: cannot remove ‘/tmp/c9_worker_build/ext/htmllanguage’: Permission denied
rm: cannot remove ‘/tmp/c9_worker_build/ext/linereport_python’: Permission denied
make: *** [plugins-client/lib.ace/www/worker/worker-language.js] Error 1
Linux 64 bit
connect plugin start
Connect server listening at http://x.x.x.x.0:3131 x.x.x.x replaces zeros in url
IDE SERVER PLUGIN:  auth
IDE SERVER PLUGIN:  git
IDE SERVER PLUGIN:  gittools
IDE SERVER PLUGIN:  hg
IDE SERVER PLUGIN:  npm
IDE SERVER PLUGIN:  filelist
IDE SERVER PLUGIN:  search
IDE SERVER PLUGIN:  revisions
IDE SERVER PLUGIN:  settings
IDE SERVER PLUGIN:  shell
IDE SERVER PLUGIN:  state
IDE SERVER PLUGIN:  watcher
IDE SERVER PLUGIN:  node-runtime
IDE SERVER PLUGIN:  npm-runtime
IDE SERVER PLUGIN:  python-runtime
IDE SERVER PLUGIN:  apache-runtime
IDE SERVER PLUGIN:  ruby-runtime
IDE SERVER PLUGIN:  php-runtime
Started '/home/ec2-user/cloud9/configs/default'!
IDE server initialized. Listening on x.x.x.x.0:3131 x.x.x.x replaces zeros in url

events.js:72
        throw er; // Unhandled 'error' event
              ^
Error: spawn ENOENT
    at errnoException (child_process.js:1000:11)
    at Process.ChildProcess._handle.onexit (child_process.js:791:34)

Has anyone any experience with this?


问:
Error Calling Unmanaged DLL Function from Managed Code
I've written a DLL in unmanaged visual C++, and I'm having a little trouble getting it to work with both C# and C++ applications.  Here's what the prototype in the C++ DLL looks like:

```<code>extern "C" __declspec(dllexport) int WINAPI ZBNConnect( UCHAR dev, LPARAM hWnd, ZBCallbackFn rfn, ZBCallbackFn nfn, int DevType, byte * DevAddr, ZBCallbackFn dfn );
</code>```

My C# application can link to the function, no problem, but when it tries to call the function an exception is thrown:

```<code>catch (Exception e) { /* ... */ }
</code>```

e.Message = "Object reference not set to an instance of an object."

Oddly, if I take WINAPI out of the prototype in the DLL, and recompile, the C# application calls the function without any problems.  Unfortunately, the WINAPI must remain because that is how the function is defined in the C++ application.

The function is currently prototyped in the C# application like this:

```<code>public delegate int ZBNConnectDelegate(uint dev, IntPtr hWnd, USBCallbackDelegate rfn, NotifyCallbackDelegate nfn, uint DevType, byte[] DevAddr, ZBdebugCallbackDelegate dfn);
public ZBNConnectDelegate ZBNConnect;

procName = "ZBNConnect";
fUintPtr = Kernel32.GetProcAddress(dllHandle, procName);

if (fUintPtr == UIntPtr.Zero)
{
    throw new ArgumentException(procName);
}

fIntPtr = unchecked((IntPtr)(long)(ulong)fUintPtr);
ZBNConnect = (ZBNConnectDelegate)Marshal.GetDelegateForFunctionPointer(fIntPtr, typeof(ZBNConnectDelegate));
</code>```

How can I modify the C# application to get this working?  Thanks.

EDIT: Additional Information

A static link ([DllImport...]) is not an option because depending on which hardware is attached to the system a different DLL that supports the attached hardware is loaded at run-time.  Both DLLs have the same API calls.

答: Something is basically wrong.  You declared a delegate, as though the function is a callback.  Doesn't look like a callback at all, it look like something you should declare with [DllImport].  To make it work like you did, you'd have to pinvoke LoadLibrary and GetProcAddress().  What [DllImport] does under the hood.  I don't see you using that.</p>

ContentLicense: CC BY-SA 2.5

Body:
I've written a DLL in unmanaged visual C++, and I'm having a little trouble getting it to work with both C# and C++ applications.  Here's what the prototype in the C++ DLL looks like:

extern "C" __declspec(dllexport) int WINAPI ZBNConnect( UCHAR dev, LPARAM hWnd, ZBCallbackFn rfn, ZBCallbackFn nfn, int DevType, byte * DevAddr, ZBCallbackFn dfn );

My C# application can link to the function, no problem, but when it tries to call the function an exception is thrown:

catch (Exception e) { /* ... */ }

e.Message = "Object reference not set to an instance of an object."

Oddly, if I take WINAPI out of the prototype in the DLL, and recompile, the C# application calls the function without any problems.  Unfortunately, the WINAPI must remain because that is how the function is defined in the C++ application.

The function is currently prototyped in the C# application like this:

public delegate int ZBNConnectDelegate(uint dev, IntPtr hWnd, USBCallbackDelegate rfn, NotifyCallbackDelegate nfn, uint DevType, byte[] DevAddr, ZBdebugCallbackDelegate dfn);
public ZBNConnectDelegate ZBNConnect;

procName = "ZBNConnect";
fUintPtr = Kernel32.GetProcAddress(dllHandle, procName);

if (fUintPtr == UIntPtr.Zero)
{
    throw new ArgumentException(procName);
}

fIntPtr = unchecked((IntPtr)(long)(ulong)fUintPtr);
ZBNConnect = (ZBNConnectDelegate)Marshal.GetDelegateForFunctionPointer(fIntPtr, typeof(ZBNConnectDelegate));

How can I modify the C# application to get this working?  Thanks.

EDIT: Additional Information

A static link ([DllImport...]) is not an option because depending on which hardware is attached to the system a different DLL that supports the attached hardware is loaded at run-time.  Both DLLs have the same API calls.


问:
How to write prototype for command "ext_skel"?
when i develop PECL extension of some function,I could write func.def like follows:

string return_hello()

string return_name()

then,I run command like follows:

```<code>./ext_skel --extname=newextension --proto=func.def
</code>```

But I don't know how to write the file func.def above,when i want to develop some  extension class for php. I don't find a whole manual about that.

答:
take a look at extSkel, the basic usage is :

```<code>php extSkel --proto="path/to/file" --extension=extname
</code>```

to define a class proto file you need to define a class with a $protoType = 'class';

there are another full examples in the examples directory

Body:
when i develop PECL extension of some function,I could write func.def like follows:

string return_hello()

string return_name()

then,I run command like follows:

./ext_skel --extname=newextension --proto=func.def

But I don't know how to write the file func.def above,when i want to develop some  extension class for php. I don't find a whole manual about that.

Body:
take a look at extSkel, the basic usage is :

php extSkel --proto="path/to/file" --extension=extname

to define a class proto file you need to define a class with a $protoType = 'class';

there are another full examples in the examples directory


问:
Is okay to use so much NEW statement?
I have this code that handles my commands:

```<code>public class CommandHandler {

    public static final CommandParser parser = new CommandParser();
    public static HashMap<String, Command> commands = new HashMap<>();

    public static void handleCommand(CommandParser.CommandContainer cmd) {

        if (commands.containsKey(cmd.invoke)) {
            commands.get(cmd.invoke).action(cmd.event, cmd.args);
            commands.get(cmd.invoke).postAction(cmd.event, cmd.args);
        }
        /* else
            System.err.println("CMD NOT EXIST!"); */
    }
}

public static HashMap<String, Command> commands = new HashMap<>();

private static void addCommands() {
    commands.put(new cmdConfig().getCommand(), new cmdConfig());
    commands.put(new cmdHelp().getCommand(), new cmdHelp());
    commands.put(new cmdPing().getCommand(), new cmdPing());
}
</code>```

This is a short code, but I have 157 commands.
Each command extends from an interface who has this methods:

```<code>public interface Command {
    public String getCommand();
    public String help();
    public void action(String[] args);
    public void postAction(String[] args);
}
</code>```

Also, I use this code too:

```<code>String input = "random";

if (new cmdPing().getCommand().equals(input)) {
    new cmdPing().help();
}
else if (new cmdConfig().getCommand().equals(input)) {
    new cmdConfig().help();
}
else {
    printError(input + " is not a valid command");
}
</code>```

and  I want to know if is okay to use to many NEW statements when i use commands.putand inside of if() statements too.

答:
It’s very weird that you are creating a HashMap<String, Command> commands containing all commands and then, not using that map to look up the commands, which is the very purpose of creating such a map.

```<code>public static final List<Command> ALL_COMMANDS
    = Collections.unmodifiableList(Arrays.asList(
        new cmdConfig(), new cmdHelp(), new cmdPing(), …
    ));
public static Map<String, Command> ALL_COMMANDS_BY_NAME
    = ALL_COMMANDS.stream()
                  .collect(Collectors.toMap(Command::getCommand, Function.identity()));
</code>```

```<code>String input = "random";
Command cmd = ALL_COMMANDS_BY_NAME.get(input);
if(cmd != null) cmd.help();
else printError(input + " is not a valid command");
</code>```

If the actual implementations of the individual commands is rather short, you may consider implementing all of them in a single enum implementing Command. Then, you get the linear ALL_COMMANDS list for free, due to the generated values() method returning an array of all constants. The rest of the application logic stays the same.

Title: Is okay to use so much NEW statement?

Body:
I have this code that handles my commands:

public class CommandHandler {

    public static final CommandParser parser = new CommandParser();
    public static HashMap<String, Command> commands = new HashMap<>();

    public static void handleCommand(CommandParser.CommandContainer cmd) {

        if (commands.containsKey(cmd.invoke)) {
            commands.get(cmd.invoke).action(cmd.event, cmd.args);
            commands.get(cmd.invoke).postAction(cmd.event, cmd.args);
        }
        /* else
            System.err.println("CMD NOT EXIST!"); */
    }
}

public static HashMap<String, Command> commands = new HashMap<>();

private static void addCommands() {
    commands.put(new cmdConfig().getCommand(), new cmdConfig());
    commands.put(new cmdHelp().getCommand(), new cmdHelp());
    commands.put(new cmdPing().getCommand(), new cmdPing());
}

This is a short code, but I have 157 commands.
Each command extends from an interface who has this methods:

public interface Command {
    public String getCommand();
    public String help();
    public void action(String[] args);
    public void postAction(String[] args);
}

Also, I use this code too:

String input = "random";

if (new cmdPing().getCommand().equals(input)) {
    new cmdPing().help();
}
else if (new cmdConfig().getCommand().equals(input)) {
    new cmdConfig().help();
}
else {
    printError(input + " is not a valid command");
}

and  I want to know if is okay to use to many NEW statements when i use commands.putand inside of if() statements too.

Body:
It’s very weird that you are creating a HashMap<String, Command> commands containing all commands and then, not using that map to look up the commands, which is the very purpose of creating such a map.

public static final List<Command> ALL_COMMANDS
    = Collections.unmodifiableList(Arrays.asList(
        new cmdConfig(), new cmdHelp(), new cmdPing(), …
    ));
public static Map<String, Command> ALL_COMMANDS_BY_NAME
    = ALL_COMMANDS.stream()
                  .collect(Collectors.toMap(Command::getCommand, Function.identity()));

String input = "random";
Command cmd = ALL_COMMANDS_BY_NAME.get(input);
if(cmd != null) cmd.help();
else printError(input + " is not a valid command");

If the actual implementations of the individual commands is rather short, you may consider implementing all of them in a single enum implementing Command. Then, you get the linear ALL_COMMANDS list for free, due to the generated values() method returning an array of all constants. The rest of the application logic stays the same.


问:
Read content using curl
Using Curl i am sending some post data to a server.This is the Header reponse iam getting

HTTP/1.1 100 Continue HTTP/1.1 200 OK Content-Length: 30 Content-Type: text/html;charset=ISO-8859-1 Server: Microsoft-IIS/7.0 X-Powered-By: Servlet 2.5; JBoss-5.0/JBossWeb-2.1 Set-Cookie: JSESSIONID=XXXXXXXXXXXXXXXXXXXXXXX; Path=/thegateway; Secure P3P: CP="CAO PSA OUR" X-Powered-By: ASP.NET Date: Sat, 22 Jan 2011 00:07:25 GMT

how do i read the rest of the content?

答:
Maybe you forgot to set the CURLOPT_RETURNTRANSFER option in the curl call?
When it is set, the content of the response is returned by the curl_exec() function itself.

This is a code from a working project of mine:

```<code>    $options = array(
            CURLOPT_SSL_VERIFYPEER => false,

            CURLOPT_RETURNTRANSFER => $this->return_content,     // return web page
            CURLOPT_HEADER         => false,    // don't return headers, they are processed through callback
            CURLOPT_FOLLOWLOCATION => $this->follow_redirects,     // follow redirects
            CURLOPT_ENCODING       => "",       // handle all encodings
            CURLOPT_USERAGENT      => $this->user_agent, // who am i
            CURLOPT_CONNECTTIMEOUT => $this->connect_timeout,      // timeout on connect
            CURLOPT_TIMEOUT        => $this->request_timeout,      // timeout on response
            CURLOPT_BINARYTRANSFER => true,
            );
    $extraheaders = array();

    $res = curl_init( $url );
    curl_setopt_array( $res, $options );
    $content = curl_exec( $res );
</code>```

Title: Read content using curl

Body:
Maybe you forgot to set the CURLOPT_RETURNTRANSFER option in the curl call?
When it is set, the content of the response is returned by the curl_exec() function itself.

This is a code from a working project of mine:

    $options = array(
            CURLOPT_SSL_VERIFYPEER => false,

            CURLOPT_RETURNTRANSFER => $this->return_content,     // return web page
            CURLOPT_HEADER         => false,    // don't return headers, they are processed through callback
            CURLOPT_FOLLOWLOCATION => $this->follow_redirects,     // follow redirects
            CURLOPT_ENCODING       => "",       // handle all encodings
            CURLOPT_USERAGENT      => $this->user_agent, // who am i
            CURLOPT_CONNECTTIMEOUT => $this->connect_timeout,      // timeout on connect
            CURLOPT_TIMEOUT        => $this->request_timeout,      // timeout on response
            CURLOPT_BINARYTRANSFER => true,
            );
    $extraheaders = array();

    $res = curl_init( $url );
    curl_setopt_array( $res, $options );
    $content = curl_exec( $res );


问:
How to record one vote per user php
So I am trying to write a php script that records one vote increment per user. Voters a are presented with a list of prospective candidates then clicks once on their name.
Now on attempt of a second time i hope to get a notification allowing this action. Please help.</p>

```<code><?php

if(isset($_POST['vote']))
{
    $sql3='INSERT INTO sessions (memberID, postid, email, voted) VALUES ("","", "", 1;)';

    $result3 =   mysqli_query($con, $sql3);
}
//  $count  =   mysqli_num_rows($result2);
$candidate_name = null;
$vote = $_POST['vote'];
mysqli_query($con, "UPDATE tbCandidates SET candidate_votes=candidate_votes+1 WHERE  position_id='$vote'");

// $count  =   mysqli_num_rows($result2);

if ( $count<1) {
    //$sql3='INSERT INTO sessions (memberID, postid, voted) VALUES ("", memberbers.memberID,"1")';
    //$result = mysqlI_query("select id from Users where username ='".$_SESSION['email']."'");
    //$result =   mysqli_query($con, $sql3);
    // $count  =   mysqli_num_rows($result2);
} else {
     echo"You have voted already";
}
</code>```

答:
Put a "unique" flag on your memberID column in your SQL table. In that case when you try to insert a new row with the same memberID, it will not work.

Then catch the SQL write fail, and display a message if it gets to it.

Title: How to record one vote per user php

Body:
So I am trying to write a php script that records one vote increment per user. Voters a are presented with a list of prospective candidates then clicks once on their name.
Now on attempt of a second time i hope to get a notification allowing this action. Please help.

<?php

if(isset($_POST['vote']))
{
    $sql3='INSERT INTO sessions (memberID, postid, email, voted) VALUES ("","", "", 1;)';

    $result3 =   mysqli_query($con, $sql3);
}
//  $count  =   mysqli_num_rows($result2);
$candidate_name = null;
$vote = $_POST['vote'];
mysqli_query($con, "UPDATE tbCandidates SET candidate_votes=candidate_votes+1 WHERE  position_id='$vote'");

// $count  =   mysqli_num_rows($result2);

if ( $count<1) {
    //$sql3='INSERT INTO sessions (memberID, postid, voted) VALUES ("", memberbers.memberID,"1")';
    //$result = mysqlI_query("select id from Users where username ='".$_SESSION['email']."'");
    //$result =   mysqli_query($con, $sql3);
    // $count  =   mysqli_num_rows($result2);
} else {
     echo"You have voted already";
}


问:
Launch app from Android Studio stopped to work
There is very weird issue... One time I opened my project and noticed that I don't have opportunity to launch app from studio... Triangle sing cover with black color like it disable

But if I build the apk file and install it with adb command adb install -r path_to_apk it does work.

I have already tried to delete and download new android studio, but nothing changed...

And one more, if I am connecting my device and trying to attach debugger to android process so, android studio doesn't see my device as well as virtual device...

What I need to check? It look like some studio configuration broke or I don't know

Fell free to ask

My plugins

My configuration

答:
Actually I forgot to switch build module to the app (next to launch triangle you have some options, so you need to choose app)

And then I got sdk location issue

I fixed it with help of this answer

intelliJ IDEA 13 error: please select Android SDK

My Problem: "please select Android SDK", But everything is okey :( -> I think one of IntelliJ file was crashed (after blue screen of death)

My resolution:

File -> Settings -> Android SDK -> Android SDK Location Edit -> Next, Next (Android SDK is up to date.), Finished

... and crashed file was repaired!

I hope this will help!


问:
Laravel Eloquent with the max in second table?
I've got two tables: listings, which holds the details of a product, and bids, which holds the bid history of the site.

For brief relevance, imagine that listings has the following fields: name, category_id, tagline, short_description, and seller_notes.

In bids we have two relevant fields: listing_id, and bid_amount.

For reasons relevant elsewhere, this needs to be in Eloquent as I need access to the model.

The issue seems to be with the MAX bid amount line or the evaluation of the bid_amount—no matter how I approach it, I always end up with an irrelevant result, but there's no apparent error that I can see.

```<code>$listings = \App\Listing::join('bids', 'listings.id', '=', 'bids.listing_id')->select('listings.*','MAX(bids.bid_amount)');

if( !empty($request->keyword) ) {
    $listings = $listings->where('listings.name','LIKE','%'.$request->keyword.'%')
                ->orWhere('listings.tagline','LIKE','%'.$request->keyword.'%')
                ->orWhere('listings.short_description','LIKE','%'.$request->keyword.'%')
                ->orWhere('listings.seller_notes','LIKE','%'.$request->keyword.'%');
}

if( !empty($request->category) ) {
    $listings = $listings->where('listings.category_id','=',$request->category);
}

if( !empty($request->minimum_bid) && !empty($request->maximum_bid) ) {
    $listings = $listings->whereBetween('bid_amount', [$request->minimum_bid, $request->maximum_bid]);
} else {
    if( !empty($request->minimum_bid) ) {
        $listings = $listings->where('bid_amount', '>', $request->minimum_bid);
    }

    if( !empty($request->maximum_bid) ) {
        $listings = $listings->where('bid_amount', '<', $request->maximum_bid);
    }
}
</code>```

The search is to find results with a current highest bid between minimum_bid and maximum_bid (fields from the search box). The problem presenting is that there may be multiple listings (listing_id) that have a current highest bid (MAX(bid_amount)) between those amounts. I want to display the listings where the MAX(bid_amount) for that bid.listing_id is between minimum_bid and maximum_bid. This could potentially result in multiple listings.

The equivalent MySQL query should be:

SELECT *
FROM   listings
       JOIN (SELECT listing_id,
                    Max(bid_amount) AS bid_amount
             FROM   bids
             GROUP  BY listing_id) bids
         ON bids.listing_id = listings.id
WHERE  ( listings.NAME LIKE '%keyword%'
          OR listings.tagline LIKE '%keyword%'
          OR listings.short_description LIKE' %keyword%'
          OR listings.seller_notes LIKE '%keyword%' )
       AND ( bids.bid_amount > minimum_bid )
       AND ( bids.bid_amount < maximum_bid )
```

I know this is something stupid that I'm doing wrong, I just could really use a fresh set of eyes. Thank you for any help you can provide.

答:
The problem with the code in the question is that it creates a query that tries to find the maximum bid amount over all of the bids when we actually need the max for each group of bids per listing. Let's take a look at how to do this with Eloquent. We'll use local query scopes to encapsulate the logic and clean up the API so that we can call it like this:

$listings = Listing::withMaximumBidAmount()
    ->forOptionalCategory($request->category)
    ->forOptionalBidRange($request->minimum_bid, $request->maximum_bid)
    ->forOptionalKeyword($request->keyword)
    ->paginate($pageSize);
```

<p>I'm assuming that the <code>Listing</code> model contains a <code>bids()</code> relationship to the <code>Bid</code> model:</p>

<pre class="lang-php prettyprint-override"><code>class Listing extends Model
{
    ...
    public function bids()
    {
        return $this->hasMany(\App\Bid::class);
    }
</code>```

Next, let's add the most important scope that maps the maximum bid amount to the model:

public function scopeWithMaximumBidAmount($query)
{
    $bids = $this->bids();
    $bidsTable = $bids->getRelated()->getTable();
    $listingKey = $bids->getForeignKeyName();

    $bidsQuery = \App\Bid::select($listingKey)
        ->selectRaw('MAX(bid_amount) as bid_amount')
        ->groupBy($listingKey);

    $subquery = DB::raw("({$bidsQuery->toSql()}) " . $bidsTable);

    return $query->select($this->getTable() . '.*', 'bid_amount')
        ->join($subquery, function ($join) use ($bids) {
            $join->on(
                $bids->getQualifiedForeignKeyName(),
                '=',
                $bids->getQualifiedParentKeyName()
            );
        });
}
```

<p>This implementation uses metadata on the models and relations to set the table names and columns for the query so we don't need to update this method if those change. As we can see, we first build a subquery to join on that calculates the highest bid for each listing. Unfortunately, much of this isn't documented—the Laravel source code is a necessary reference for advanced cases.</p>

<p>The example above shows how we can provide a raw SQL subquery for the joined table and pass a closure instead of column names to add any specialized clauses for the join. We create the subquery using the standard Eloquent query builder—so we can safely bind parameters if needed—and convert it to the SQL string using the <code>toSql()</code> method. This scope adds a <code>bid_amount</code> attribute to each <code>Listing</code> returned by the call which contains the highest bid.</p>

<p>Here are the remaining query scopes. These are pretty self-explanatory: </p>

<pre class="lang-php prettyprint-override"><code>public function scopeForOptionalKeyword($query, $keyword)
{
    if (empty($keyword)) {
        return $query;
    }

    return $query->where(function ($query) use ($keyword) {
        $query->where('name', 'LIKE', "%{$keyword}%")
            ->orWhere('tagline', 'LIKE', "%{$keyword}%")
            ->orWhere('short_description', 'LIKE', "%{$keyword}%")
            ->orWhere('seller_notes', 'LIKE', "%{$keyword}%");
    });
}

public function scopeForOptionalCategory($query, $category)
{
    if (empty($category)) {
        return $query;
    }

    return $query->where('category_id', $category);
}

public function scopeForOptionalBidRange($query, $minimum, $maximum)
{
    if (! empty($minimum)) {
        $query->where('bid_amount', '>=', $minimum);
    }

    if (! empty($maximum)) {
        $query->where('bid_amount', '<=', $maximum);
    }

    return $query;
}
</code>```

When we have a desired SQL query to match, the toSql() method really helps when constructing a complex query builder object. We may also want to check the indexes on our tables if we experience performance issues. It may be worth indexing bids.bid_amount or tuning keyword lookup columns if we have the resources.

Body:
I've got two tables: listings, which holds the details of a product, and bids, which holds the bid history of the site.

For brief relevance, imagine that listings has the following fields: name, category_id, tagline, short_description, and seller_notes.

In bids we have two relevant fields: listing_id, and bid_amount.

For reasons relevant elsewhere, this needs to be in Eloquent as I need access to the model.

The issue seems to be with the MAX bid amount line or the evaluation of the bid_amount—no matter how I approach it, I always end up with an irrelevant result, but there's no apparent error that I can see.

$listings = \App\Listing::join('bids', 'listings.id', '=', 'bids.listing_id')->select('listings.*','MAX(bids.bid_amount)');

if( !empty($request->keyword) ) {
    $listings = $listings->where('listings.name','LIKE','%'.$request->keyword.'%')
                ->orWhere('listings.tagline','LIKE','%'.$request->keyword.'%')
                ->orWhere('listings.short_description','LIKE','%'.$request->keyword.'%')
                ->orWhere('listings.seller_notes','LIKE','%'.$request->keyword.'%');
}

if( !empty($request->category) ) {
    $listings = $listings->where('listings.category_id','=',$request->category);
}

if( !empty($request->minimum_bid) && !empty($request->maximum_bid) ) {
    $listings = $listings->whereBetween('bid_amount', [$request->minimum_bid, $request->maximum_bid]);
} else {
    if( !empty($request->minimum_bid) ) {
        $listings = $listings->where('bid_amount', '>', $request->minimum_bid);
    }

    if( !empty($request->maximum_bid) ) {
        $listings = $listings->where('bid_amount', '<', $request->maximum_bid);
    }
}

The search is to find results with a current highest bid between minimum_bid and maximum_bid (fields from the search box). The problem presenting is that there may be multiple listings (listing_id) that have a current highest bid (MAX(bid_amount)) between those amounts. I want to display the listings where the MAX(bid_amount) for that bid.listing_id is between minimum_bid and maximum_bid. This could potentially result in multiple listings.

The equivalent MySQL query should be:

SELECT *
FROM   listings
       JOIN (SELECT listing_id,
                    Max(bid_amount) AS bid_amount
             FROM   bids
             GROUP  BY listing_id) bids
         ON bids.listing_id = listings.id
WHERE  ( listings.NAME LIKE '%keyword%'
          OR listings.tagline LIKE '%keyword%'
          OR listings.short_description LIKE' %keyword%'
          OR listings.seller_notes LIKE '%keyword%' )
       AND ( bids.bid_amount > minimum_bid )
       AND ( bids.bid_amount < maximum_bid )

I know this is something stupid that I'm doing wrong, I just could really use a fresh set of eyes. Thank you for any help you can provide.

Body:
The problem with the code in the question is that it creates a query that tries to find the maximum bid amount over all of the bids when we actually need the max for each group of bids per listing. Let's take a look at how to do this with Eloquent. We'll use local query scopes to encapsulate the logic and clean up the API so that we can call it like this:

$listings = Listing::withMaximumBidAmount()
    ->forOptionalCategory($request->category)
    ->forOptionalBidRange($request->minimum_bid, $request->maximum_bid)
    ->forOptionalKeyword($request->keyword)
    ->paginate($pageSize);

I'm assuming that the Listing model contains a bids() relationship to the Bid model:

class Listing extends Model
{
    ...
    public function bids()
    {
        return $this->hasMany(\App\Bid::class);
    }

Next, let's add the most important scope that maps the maximum bid amount to the model:

public function scopeWithMaximumBidAmount($query)
{
    $bids = $this->bids();
    $bidsTable = $bids->getRelated()->getTable();
    $listingKey = $bids->getForeignKeyName();

    $bidsQuery = \App\Bid::select($listingKey)
        ->selectRaw('MAX(bid_amount) as bid_amount')
        ->groupBy($listingKey);

    $subquery = DB::raw("({$bidsQuery->toSql()}) " . $bidsTable);

    return $query->select($this->getTable() . '.*', 'bid_amount')
        ->join($subquery, function ($join) use ($bids) {
            $join->on(
                $bids->getQualifiedForeignKeyName(),
                '=',
                $bids->getQualifiedParentKeyName()
            );
        });
}

This implementation uses metadata on the models and relations to set the table names and columns for the query so we don't need to update this method if those change. As we can see, we first build a subquery to join on that calculates the highest bid for each listing. Unfortunately, much of this isn't documented—the Laravel source code is a necessary reference for advanced cases.

The example above shows how we can provide a raw SQL subquery for the joined table and pass a closure instead of column names to add any specialized clauses for the join. We create the subquery using the standard Eloquent query builder—so we can safely bind parameters if needed—and convert it to the SQL string using the toSql() method. This scope adds a bid_amount attribute to each Listing returned by the call which contains the highest bid.

Here are the remaining query scopes. These are pretty self-explanatory:

public function scopeForOptionalKeyword($query, $keyword)
{
    if (empty($keyword)) {
        return $query;
    }

    return $query->where(function ($query) use ($keyword) {
        $query->where('name', 'LIKE', "%{$keyword}%")
            ->orWhere('tagline', 'LIKE', "%{$keyword}%")
            ->orWhere('short_description', 'LIKE', "%{$keyword}%")
            ->orWhere('seller_notes', 'LIKE', "%{$keyword}%");
    });
}

public function scopeForOptionalCategory($query, $category)
{
    if (empty($category)) {
        return $query;
    }

    return $query->where('category_id', $category);
}

public function scopeForOptionalBidRange($query, $minimum, $maximum)
{
    if (! empty($minimum)) {
        $query->where('bid_amount', '>=', $minimum);
    }

    if (! empty($maximum)) {
        $query->where('bid_amount', '<=', $maximum);
    }

    return $query;
}

When we have a desired SQL query to match, the toSql() method really helps when constructing a complex query builder object. We may also want to check the indexes on our tables if we experience performance issues. It may be worth indexing bids.bid_amount or tuning keyword lookup columns if we have the resources.


问:
Filtering data-frame on multiple criteria
I have a dataframe df which has a head that looks like:

```<code>               Shop       Opening date
0            London                NaT
22         Brighton         01/03/2016
27       Manchester         01/31/2017
54          Bristol         03/31/2017
69          Glasgow         04/09/2017
</code>```

I also have a variable startPeriod which is set to 1/04/2017 date and endPeriod variable that has a value of 30/06/17

I am trying to create a new dataframe based on df that filters out any rows that do not have a date (so removing any rows with an Opening date of NaT) and also filter out any rows with an opening date between the startPeriod and endPeriod.  So in the above example I would be left with the following new dataframe:

```<code>                 Shop       Opening date
22           Brighton         01/03/2016
69            Glasgow         04/09/2017
</code>```

I have tried to filter out the 'NaT' using the following:

```<code>df1 = df['Opening date '] != 'NaT'
</code>```

but am unsure how to also filter out any Opening date that are inside the startPeriod/endPeriod range.

答:
You can use between with boolean indexing:

```<code>df['date'] = pd.to_datetime(df['date'])
df = df[df['date'].between('2016-03-01', '2017-04-05')]
print (df)
   Shop     Opening       date
2    27  Manchester 2017-01-31
3    54     Bristol 2017-03-31
</code>```

I think filtering out NaNs is not necessary, but if need it chain new condition:

```<code>df = df[df['date'].between('2016-03-01', '2017-04-05') & df['date'].notnull()]
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a dataframe df which has a head that looks like:

               Shop       Opening date
0            London                NaT
22         Brighton         01/03/2016
27       Manchester         01/31/2017
54          Bristol         03/31/2017
69          Glasgow         04/09/2017

I also have a variable startPeriod which is set to 1/04/2017 date and endPeriod variable that has a value of 30/06/17

I am trying to create a new dataframe based on df that filters out any rows that do not have a date (so removing any rows with an Opening date of NaT) and also filter out any rows with an opening date between the startPeriod and endPeriod.  So in the above example I would be left with the following new dataframe:

                 Shop       Opening date
22           Brighton         01/03/2016
69            Glasgow         04/09/2017

I have tried to filter out the 'NaT' using the following:

df1 = df['Opening date '] != 'NaT'

but am unsure how to also filter out any Opening date that are inside the startPeriod/endPeriod range.

Body:
You can use between with boolean indexing:

df['date'] = pd.to_datetime(df['date'])
df = df[df['date'].between('2016-03-01', '2017-04-05')]
print (df)
   Shop     Opening       date
2    27  Manchester 2017-01-31
3    54     Bristol 2017-03-31

I think filtering out NaNs is not necessary, but if need it chain new condition:

df = df[df['date'].between('2016-03-01', '2017-04-05') & df['date'].notnull()]


问:
Hibernate throws org.hibernate.AnnotationException: No identifier specified for entity: com..domain.idea.MAE_MFEView
Why am I getting this exception?

```<code>package com.domain.idea;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;

import org.hibernate.annotations.AccessType;

/**
 * object model for the view [InvestmentReturn].[vMAE_MFE]
 */
@Entity
@Table(name="vMAE_MFE", schema="InvestmentReturn")
@AccessType("field")
public class MAE_MFEView
{
    /**
     * trade property is a SuggestdTradeRecommendation object
     */
    @OneToOne(fetch = FetchType.LAZY , cascade = { CascadeType.PERSIST })
    @JoinColumn(name = "suggestedTradeRecommendationID")
    private SuggestedTradeRecommendation trade;

    /**
     * Most Adeverse Excursion value
     */
    private int MAE;

    public int getMAE()
    {
        return MAE;
    }

    /**
     * Most Favorable Excursion value
     */
    private int MFE;

    public int getMFE()
    {
        return MFE;
    }

    /**
     * @return trade property
     * see #trade
     */
    public SuggestedTradeRecommendation getTrade()
    {
        return trade;
    }
}
</code>```

Update: I've changed my code to look like this:

```<code>package com.domain.idea;

import javax.persistence.CascadeType;
import javax.persistence.FetchType;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;

import org.hibernate.annotations.AccessType;

/**
 * object model for the view [InvestmentReturn].[vMAE_MFE]
 */
@Entity
@Table(name="vMAE_MFE", schema="InvestmentReturn")
@AccessType("field")
public class MAE_MFEView
{
    /**
     * trade property is a SuggestdTradeRecommendation object
     */
    @Id
    @OneToOne(fetch = FetchType.LAZY , cascade = { CascadeType.PERSIST })
    @JoinColumn(name = "suggestedTradeRecommendationID")
    private SuggestedTradeRecommendation trade;

    /**
     * Most Adeverse Excursion value
     */
    private int MAE;

    public int getMAE()
    {
        return MAE;
    }

    /**
     * Most Favorable Excursion value
     */
    private int MFE;

    public int getMFE()
    {
        return MFE;
    }

    /**
     * @return trade property
     * see #trade
     */
    public SuggestedTradeRecommendation getTrade()
    {
        return trade;
    }
}
</code>```

but now I'm getting this exception:

```<code>Caused by: org.hibernate.MappingException: Could not determine type for: com.domain.idea.SuggestedTradeRecommendation, at table: vMAE_MFE, for columns: [org.hibernate.mapping.Column(trade)]
    at org.hibernate.mapping.SimpleValue.getType(SimpleValue.java:292)
    at org.hibernate.mapping.SimpleValue.isValid(SimpleValue.java:276)
    at org.hibernate.mapping.RootClass.validate(RootClass.java:216)
    at org.hibernate.cfg.Configuration.validate(Configuration.java:1135)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1320)
    at org.hibernate.cfg.AnnotationConfiguration.buildSessionFactory(AnnotationConfiguration.java:867)
    at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:669)
    ... 145 more
</code>```

答:
This error can be thrown when you import a different library for @Id than Javax.persistance.Id ; You might need to pay attention this case too

In my case I had

```<code>import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Table;

import org.springframework.data.annotation.Id;

@Entity
public class Status {

    @Id
    @GeneratedValue
    private int id;
</code>```

when I change the code like this, it got worked

```<code>import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Table;

import javax.persistence.Id;

@Entity
public class Status {

    @Id
    @GeneratedValue
    private int id;
</code>```

Body:
Why am I getting this exception?

package com.domain.idea;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;

import org.hibernate.annotations.AccessType;

/**
 * object model for the view [InvestmentReturn].[vMAE_MFE]
 */
@Entity
@Table(name="vMAE_MFE", schema="InvestmentReturn")
@AccessType("field")
public class MAE_MFEView
{
    /**
     * trade property is a SuggestdTradeRecommendation object
     */
    @OneToOne(fetch = FetchType.LAZY , cascade = { CascadeType.PERSIST })
    @JoinColumn(name = "suggestedTradeRecommendationID")
    private SuggestedTradeRecommendation trade;

    /**
     * Most Adeverse Excursion value
     */
    private int MAE;

    public int getMAE()
    {
        return MAE;
    }

    /**
     * Most Favorable Excursion value
     */
    private int MFE;

    public int getMFE()
    {
        return MFE;
    }

    /**
     * @return trade property
     * see #trade
     */
    public SuggestedTradeRecommendation getTrade()
    {
        return trade;
    }
}

Update: I've changed my code to look like this:

package com.domain.idea;

import javax.persistence.CascadeType;
import javax.persistence.FetchType;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;

import org.hibernate.annotations.AccessType;

/**
 * object model for the view [InvestmentReturn].[vMAE_MFE]
 */
@Entity
@Table(name="vMAE_MFE", schema="InvestmentReturn")
@AccessType("field")
public class MAE_MFEView
{
    /**
     * trade property is a SuggestdTradeRecommendation object
     */
    @Id
    @OneToOne(fetch = FetchType.LAZY , cascade = { CascadeType.PERSIST })
    @JoinColumn(name = "suggestedTradeRecommendationID")
    private SuggestedTradeRecommendation trade;

    /**
     * Most Adeverse Excursion value
     */
    private int MAE;

    public int getMAE()
    {
        return MAE;
    }

    /**
     * Most Favorable Excursion value
     */
    private int MFE;

    public int getMFE()
    {
        return MFE;
    }

    /**
     * @return trade property
     * see #trade
     */
    public SuggestedTradeRecommendation getTrade()
    {
        return trade;
    }
}

but now I'm getting this exception:

Caused by: org.hibernate.MappingException: Could not determine type for: com.domain.idea.SuggestedTradeRecommendation, at table: vMAE_MFE, for columns: [org.hibernate.mapping.Column(trade)]
    at org.hibernate.mapping.SimpleValue.getType(SimpleValue.java:292)
    at org.hibernate.mapping.SimpleValue.isValid(SimpleValue.java:276)
    at org.hibernate.mapping.RootClass.validate(RootClass.java:216)
    at org.hibernate.cfg.Configuration.validate(Configuration.java:1135)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1320)
    at org.hibernate.cfg.AnnotationConfiguration.buildSessionFactory(AnnotationConfiguration.java:867)
    at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:669)
    ... 145 more

Body:
This error can be thrown when you import a different library for @Id than Javax.persistance.Id ; You might need to pay attention this case too

In my case I had

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Table;

import org.springframework.data.annotation.Id;

@Entity
public class Status {

    @Id
    @GeneratedValue
    private int id;

when I change the code like this, it got worked

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Table;

import javax.persistence.Id;

@Entity
public class Status {

    @Id
    @GeneratedValue
    private int id;


问:
Table with position: fixed doesn't scroll with overflow: scroll
I have two tables: the first is a header, the second contains data. I want to see the header when I scroll down, so its table has position: fixed. The tables can be too large to be shown on the screen at once, so I wrapped them in a div with overflow: scroll;.

My problem can be see here: https://jsfiddle.net/xa86wgw9/3/

When I scroll down, the header doesn't move; that's what I want. But when I scroll to the right, the header stay on the left... is there a way to have the two table stay aligned ? css and javascript can be used.

EDIT: I'm currently working on IE10, so position: sticky isn't an option.

答:
Check this example. make sure window is having in a size with both scroll bars are visible.

I used two tables, one for header and another for content. The header is fixed positioned. when you scroll horizontally, its left offset is changing accordingly.

sorry for the rough styles and lengthy markup!

$(window).scroll(function (){
     var scrollxValue = $(window).scrollLeft();
     $('.vertically-fixed').css('left', -scrollxValue)
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>table{
                width: 2120px;
            }
            .vertically-fixed{
                position: fixed;
                height: 40px;
            }
            th,td{
                padding: 5px 10px;
                margin: 0 2px 2px 0;
                width: 110px;
                height: 110px;
                float: left;
            }
            th{
                background: #ddd;
            }
            td{
                background: #eee;
            }
            tbody {
                height: 100px;
                overflow-y: auto;
                overflow-x: hidden;
            }</code>```

                    Lorem ipsum
                    dolor
                    cursus
                    tincidunt
                    porttitor
                    Maecenas
                    Fusce tincidunt
                    Vivamus
                    Lorem ipsum
                    dolor
                    cursus
                    tincidunt
                    porttitor
                    Maecenas
                    Fusce tincidunt
                    Vivamus

                    01
                    02
                    03
                    04
                    05
                    06
                    07
                    08
                    01
                    02
                    03
                    04
                    05
                    06
                    07
                    08

                    01
                    02
                    03
                    04
                    05
                    06
                    07
                    08
                    01
                    02
                    03
                    04
                    05
                    06
                    07
                    08

                    01
                    02
                    03
                    04
                    05
                    06
                    07
                    08
                    01
                    02
                    03
                    04
                    05
                    06
                    07
                    08

                    01
                    02
                    03
                    04
                    05
                    06
                    07
                    08
                    01
                    02
                    03
                    04
                    05
                    06
                    07
                    08

                    01
                    02
                    03
                    04
                    05
                    06
                    07
                    08
                    01
                    02
                    03
                    04
                    05
                    06
                    07
                    08

                    01
                    02
                    03
                    04
                    05
                    06
                    07
                    08
                    01
                    02
                    03
                    04
                    05
                    06
                    07
                    08

                    01
                    02
                    03
                    04
                    05
                    06
                    07
                    08
                    01
                    02
                    03
                    04
                    05
                    06
                    07
                    08

                    01
                    02
                    03
                    04
                    05
                    06
                    07
                    08
                    01
                    02
                    03
                    04
                    05
                    06
                    07
                    08

                    01
                    02
                    03
                    04
                    05
                    06
                    07
                    08
                    01
                    02
                    03
                    04
                    05
                    06
                    07
                    08

                    01
                    02
                    03
                    04
                    05
                    06
                    07
                    08
                    01
                    02
                    03
                    04
                    05
                    06
                    07
                    08

                    01
                    02
                    03
                    04
                    05
                    06
                    07
                    08
                    01
                    02
                    03
                    04
                    05
                    06
                    07
                    08

                    01
                    02
                    03
                    04
                    05
                    06
                    07
                    08
                    01
                    02
                    03
                    04
                    05
                    06
                    07
                    08

                    01
                    02
                    03
                    04
                    05
                    06
                    07
                    08
                    01
                    02
                    03
                    04
                    05
                    06
                    07
                    08

                    01
                    02
                    03
                    04
                    05
                    06
                    07
                    08
                    01
                    02
                    03
                    04
                    05
                    06
                    07
                    08

                    01
                    02
                    03
                    04
                    05
                    06
                    07
                    08
                    01
                    02
                    03
                    04
                    05
                    06
                    07
                    08

                    01
                    02
                    03
                    04
                    05
                    06
                    07
                    08
                    01
                    02
                    03
                    04
                    05
                    06
                    07
                    08

                    01
                    02
                    03
                    04
                    05
                    06
                    07
                    08
                    01
                    02
                    03
                    04
                    05
                    06
                    07
                    08

                    01
                    02
                    03
                    04
                    05
                    06
                    07
                    08
                    01
                    02
                    03
                    04
                    05
                    06
                    07
                    08

                    01
                    02
                    03
                    04
                    05
                    06
                    07
                    08
                    01
                    02
                    03
                    04
                    05
                    06
                    07
                    08

                    01
                    02
                    03
                    04
                    05
                    06
                    07
                    08
                    01
                    02
                    03
                    04
                    05
                    06
                    07
                    08

                    01
                    02
                    03
                    04
                    05
                    06
                    07
                    08
                    01
                    02
                    03
                    04
                    05
                    06
                    07
                    08

                    01
                    02
                    03
                    04
                    05
                    06
                    07
                    08
                    01
                    02
                    03
                    04
                    05
                    06
                    07
                    08

                    01
                    02
                    03
                    04
                    05
                    06
                    07
                    08
                    01
                    02
                    03
                    04
                    05
                    06
                    07
                    08

                    01
                    02
                    03
                    04
                    05
                    06
                    07
                    08
                    01
                    02
                    03
                    04
                    05
                    06
                    07
                    08

                    01
                    02
                    03
                    04
                    05
                    06
                    07
                    08
                    01
                    02
                    03
                    04
                    05
                    06
                    07
                    08

```

Body:
Check this example. make sure window is having in a size with both scroll bars are visible.

I used two tables, one for header and another for content. The header is fixed positioned. when you scroll horizontally, its left offset is changing accordingly.

sorry for the rough styles and lengthy markup!

$(window).scroll(function (){
     var scrollxValue = $(window).scrollLeft();
     $('.vertically-fixed').css('left', -scrollxValue)
});

table{
                width: 2120px;
            }
            .vertically-fixed{
                position: fixed;
                height: 40px;
            }
            th,td{
                padding: 5px 10px;
                margin: 0 2px 2px 0;
                width: 110px;
                height: 110px;
                float: left;
            }
            th{
                background: #ddd;
            }
            td{
                background: #eee;
            }
            tbody {
                height: 100px;
                overflow-y: auto;
                overflow-x: hidden;
            }

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="vertically-fixed">
            <thead>
                <tr>
                    <th>Lorem ipsum</th>
                    <th>dolor</th>
                    <th>cursus</th>
                    <th>tincidunt</th>
                    <th>porttitor</th>
                    <th>Maecenas</th>
                    <th>Fusce tincidunt</th>
                    <th>Vivamus</th>
                    <th>Lorem ipsum</th>
                    <th>dolor</th>
                    <th>cursus</th>
                    <th>tincidunt</th>
                    <th>porttitor</th>
                    <th>Maecenas</th>
                    <th>Fusce tincidunt</th>
                    <th>Vivamus</th>
                </tr>
            </thead>
        </table>

        <table class="content">
            <tbody>
                <tr>
                    <td>01</td>
                    <td>02</td>
                    <td>03</td>
                    <td>04</td>
                    <td>05</td>
                    <td>06</td>
                    <td>07</td>
                    <td>08</td>
                    <td>01</td>
                    <td>02</td>
                    <td>03</td>
                    <td>04</td>
                    <td>05</td>
                    <td>06</td>
                    <td>07</td>
                    <td>08</td>
                </tr>
                <tr>
                    <td>01</td>
                    <td>02</td>
                    <td>03</td>
                    <td>04</td>
                    <td>05</td>
                    <td>06</td>
                    <td>07</td>
                    <td>08</td>
                    <td>01</td>
                    <td>02</td>
                    <td>03</td>
                    <td>04</td>
                    <td>05</td>
                    <td>06</td>
                    <td>07</td>
                    <td>08</td>
                </tr>
                <tr>
                    <td>01</td>
                    <td>02</td>
                    <td>03</td>
                    <td>04</td>
                    <td>05</td>
                    <td>06</td>
                    <td>07</td>
                    <td>08</td>
                    <td>01</td>
                    <td>02</td>
                    <td>03</td>
                    <td>04</td>
                    <td>05</td>
                    <td>06</td>
                    <td>07</td>
                    <td>08</td>
                </tr>
                <tr>
                    <td>01</td>
                    <td>02</td>
                    <td>03</td>
                    <td>04</td>
                    <td>05</td>
                    <td>06</td>
                    <td>07</td>
                    <td>08</td>
                    <td>01</td>
                    <td>02</td>
                    <td>03</td>
                    <td>04</td>
                    <td>05</td>
                    <td>06</td>
                    <td>07</td>
                    <td>08</td>
                </tr>
                <tr>
                    <td>01</td>
                    <td>02</td>
                    <td>03</td>
                    <td>04</td>
                    <td>05</td>
                    <td>06</td>
                    <td>07</td>
                    <td>08</td>
                    <td>01</td>
                    <td>02</td>
                    <td>03</td>
                    <td>04</td>
                    <td>05</td>
                    <td>06</td>
                    <td>07</td>
                    <td>08</td>
                </tr>
                <tr>
                    <td>01</td>
                    <td>02</td>
                    <td>03</td>
                    <td>04</td>
                    <td>05</td>
                    <td>06</td>
                    <td>07</td>
                    <td>08</td>
                    <td>01</td>
                    <td>02</td>
                    <td>03</td>
                    <td>04</td>
                    <td>05</td>
                    <td>06</td>
                    <td>07</td>
                    <td>08</td>
                </tr>
                <tr>
                    <td>01</td>
                    <td>02</td>
                    <td>03</td>
                    <td>04</td>
                    <td>05</td>
                    <td>06</td>
                    <td>07</td>
                    <td>08</td>
                    <td>01</td>
                    <td>02</td>
                    <td>03</td>
                    <td>04</td>
                    <td>05</td>
                    <td>06</td>
                    <td>07</td>
                    <td>08</td>
                </tr>
                <tr>
                    <td>01</td>
                    <td>02</td>
                    <td>03</td>
                    <td>04</td>
                    <td>05</td>
                    <td>06</td>
                    <td>07</td>
                    <td>08</td>
                    <td>01</td>
                    <td>02</td>
                    <td>03</td>
                    <td>04</td>
                    <td>05</td>
                    <td>06</td>
                    <td>07</td>
                    <td>08</td>
                </tr>
                <tr>
                    <td>01</td>
                    <td>02</td>
                    <td>03</td>
                    <td>04</td>
                    <td>05</td>
                    <td>06</td>
                    <td>07</td>
                    <td>08</td>
                    <td>01</td>
                    <td>02</td>
                    <td>03</td>
                    <td>04</td>
                    <td>05</td>
                    <td>06</td>
                    <td>07</td>
                    <td>08</td>
                </tr>
                <tr>
                    <td>01</td>
                    <td>02</td>
                    <td>03</td>
                    <td>04</td>
                    <td>05</td>
                    <td>06</td>
                    <td>07</td>
                    <td>08</td>
                    <td>01</td>
                    <td>02</td>
                    <td>03</td>
                    <td>04</td>
                    <td>05</td>
                    <td>06</td>
                    <td>07</td>
                    <td>08</td>
                </tr>
                <tr>
                    <td>01</td>
                    <td>02</td>
                    <td>03</td>
                    <td>04</td>
                    <td>05</td>
                    <td>06</td>
                    <td>07</td>
                    <td>08</td>
                    <td>01</td>
                    <td>02</td>
                    <td>03</td>
                    <td>04</td>
                    <td>05</td>
                    <td>06</td>
                    <td>07</td>
                    <td>08</td>
                </tr>
                <tr>
                    <td>01</td>
                    <td>02</td>
                    <td>03</td>
                    <td>04</td>
                    <td>05</td>
                    <td>06</td>
                    <td>07</td>
                    <td>08</td>
                    <td>01</td>
                    <td>02</td>
                    <td>03</td>
                    <td>04</td>
                    <td>05</td>
                    <td>06</td>
                    <td>07</td>
                    <td>08</td>
                </tr>
                <tr>
                    <td>01</td>
                    <td>02</td>
                    <td>03</td>
                    <td>04</td>
                    <td>05</td>
                    <td>06</td>
                    <td>07</td>
                    <td>08</td>
                    <td>01</td>
                    <td>02</td>
                    <td>03</td>
                    <td>04</td>
                    <td>05</td>
                    <td>06</td>
                    <td>07</td>
                    <td>08</td>
                </tr>
                <tr>
                    <td>01</td>
                    <td>02</td>
                    <td>03</td>
                    <td>04</td>
                    <td>05</td>
                    <td>06</td>
                    <td>07</td>
                    <td>08</td>
                    <td>01</td>
                    <td>02</td>
                    <td>03</td>
                    <td>04</td>
                    <td>05</td>
                    <td>06</td>
                    <td>07</td>
                    <td>08</td>
                </tr>
                <tr>
                    <td>01</td>
                    <td>02</td>
                    <td>03</td>
                    <td>04</td>
                    <td>05</td>
                    <td>06</td>
                    <td>07</td>
                    <td>08</td>
                    <td>01</td>
                    <td>02</td>
                    <td>03</td>
                    <td>04</td>
                    <td>05</td>
                    <td>06</td>
                    <td>07</td>
                    <td>08</td>
                </tr>
                <tr>
                    <td>01</td>
                    <td>02</td>
                    <td>03</td>
                    <td>04</td>
                    <td>05</td>
                    <td>06</td>
                    <td>07</td>
                    <td>08</td>
                    <td>01</td>
                    <td>02</td>
                    <td>03</td>
                    <td>04</td>
                    <td>05</td>
                    <td>06</td>
                    <td>07</td>
                    <td>08</td>
                </tr>
                <tr>
                    <td>01</td>
                    <td>02</td>
                    <td>03</td>
                    <td>04</td>
                    <td>05</td>
                    <td>06</td>
                    <td>07</td>
                    <td>08</td>
                    <td>01</td>
                    <td>02</td>
                    <td>03</td>
                    <td>04</td>
                    <td>05</td>
                    <td>06</td>
                    <td>07</td>
                    <td>08</td>
                </tr>
                <tr>
                    <td>01</td>
                    <td>02</td>
                    <td>03</td>
                    <td>04</td>
                    <td>05</td>
                    <td>06</td>
                    <td>07</td>
                    <td>08</td>
                    <td>01</td>
                    <td>02</td>
                    <td>03</td>
                    <td>04</td>
                    <td>05</td>
                    <td>06</td>
                    <td>07</td>
                    <td>08</td>
                </tr>
                <tr>
                    <td>01</td>
                    <td>02</td>
                    <td>03</td>
                    <td>04</td>
                    <td>05</td>
                    <td>06</td>
                    <td>07</td>
                    <td>08</td>
                    <td>01</td>
                    <td>02</td>
                    <td>03</td>
                    <td>04</td>
                    <td>05</td>
                    <td>06</td>
                    <td>07</td>
                    <td>08</td>
                </tr>
                <tr>
                    <td>01</td>
                    <td>02</td>
                    <td>03</td>
                    <td>04</td>
                    <td>05</td>
                    <td>06</td>
                    <td>07</td>
                    <td>08</td>
                    <td>01</td>
                    <td>02</td>
                    <td>03</td>
                    <td>04</td>
                    <td>05</td>
                    <td>06</td>
                    <td>07</td>
                    <td>08</td>
                </tr>
                <tr>
                    <td>01</td>
                    <td>02</td>
                    <td>03</td>
                    <td>04</td>
                    <td>05</td>
                    <td>06</td>
                    <td>07</td>
                    <td>08</td>
                    <td>01</td>
                    <td>02</td>
                    <td>03</td>
                    <td>04</td>
                    <td>05</td>
                    <td>06</td>
                    <td>07</td>
                    <td>08</td>
                </tr>
                <tr>
                    <td>01</td>
                    <td>02</td>
                    <td>03</td>
                    <td>04</td>
                    <td>05</td>
                    <td>06</td>
                    <td>07</td>
                    <td>08</td>
                    <td>01</td>
                    <td>02</td>
                    <td>03</td>
                    <td>04</td>
                    <td>05</td>
                    <td>06</td>
                    <td>07</td>
                    <td>08</td>
                </tr>
                <tr>
                    <td>01</td>
                    <td>02</td>
                    <td>03</td>
                    <td>04</td>
                    <td>05</td>
                    <td>06</td>
                    <td>07</td>
                    <td>08</td>
                    <td>01</td>
                    <td>02</td>
                    <td>03</td>
                    <td>04</td>
                    <td>05</td>
                    <td>06</td>
                    <td>07</td>
                    <td>08</td>
                </tr>
                <tr>
                    <td>01</td>
                    <td>02</td>
                    <td>03</td>
                    <td>04</td>
                    <td>05</td>
                    <td>06</td>
                    <td>07</td>
                    <td>08</td>
                    <td>01</td>
                    <td>02</td>
                    <td>03</td>
                    <td>04</td>
                    <td>05</td>
                    <td>06</td>
                    <td>07</td>
                    <td>08</td>
                </tr>
                <tr>
                    <td>01</td>
                    <td>02</td>
                    <td>03</td>
                    <td>04</td>
                    <td>05</td>
                    <td>06</td>
                    <td>07</td>
                    <td>08</td>
                    <td>01</td>
                    <td>02</td>
                    <td>03</td>
                    <td>04</td>
                    <td>05</td>
                    <td>06</td>
                    <td>07</td>
                    <td>08</td>
                </tr>
            </tbody>
        </table>


问:
Resolving a relative url path to its absolute path
Is there a library in python that works like this?</p>

```<code>>>> resolvePath("http://www.asite.com/folder/currentpage.html", "anotherpage.html")
'http://www.asite.com/folder/anotherpage.html'
>>> resolvePath("http://www.asite.com/folder/currentpage.html", "folder2/anotherpage.html")
'http://www.asite.com/folder/folder2/anotherpage.html'
>>> resolvePath("http://www.asite.com/folder/currentpage.html", "/folder3/anotherpage.html")
'http://www.asite.com/folder3/anotherpage.html'
>>> resolvePath("http://www.asite.com/folder/currentpage.html", "../finalpage.html")
'http://www.asite.com/finalpage.html'
</code>```

答:
Yes, there is urlparse.urljoin, or urllib.parse.urljoin for Python 3.

```<code>>>> try: from urlparse import urljoin # Python2
... except ImportError: from urllib.parse import urljoin # Python3
...
>>> urljoin("http://www.asite.com/folder/currentpage.html", "anotherpage.html")
'http://www.asite.com/folder/anotherpage.html'
>>> urljoin("http://www.asite.com/folder/currentpage.html", "folder2/anotherpage.html")
'http://www.asite.com/folder/folder2/anotherpage.html'
>>> urljoin("http://www.asite.com/folder/currentpage.html", "/folder3/anotherpage.html")
'http://www.asite.com/folder3/anotherpage.html'
>>> urljoin("http://www.asite.com/folder/currentpage.html", "../finalpage.html")
'http://www.asite.com/finalpage.html'
</code>```

for copy-and-paste:

```<code>try:
    from urlparse import urljoin  # Python2
except ImportError:
    from urllib.parse import urljoin  # Python3
</code>```

Body:
Is there a library in python that works like this?

>>> resolvePath("http://www.asite.com/folder/currentpage.html", "anotherpage.html")
'http://www.asite.com/folder/anotherpage.html'
>>> resolvePath("http://www.asite.com/folder/currentpage.html", "folder2/anotherpage.html")
'http://www.asite.com/folder/folder2/anotherpage.html'
>>> resolvePath("http://www.asite.com/folder/currentpage.html", "/folder3/anotherpage.html")
'http://www.asite.com/folder3/anotherpage.html'
>>> resolvePath("http://www.asite.com/folder/currentpage.html", "../finalpage.html")
'http://www.asite.com/finalpage.html'

Body:
Yes, there is urlparse.urljoin, or urllib.parse.urljoin for Python 3.

>>> try: from urlparse import urljoin # Python2
... except ImportError: from urllib.parse import urljoin # Python3
...
>>> urljoin("http://www.asite.com/folder/currentpage.html", "anotherpage.html")
'http://www.asite.com/folder/anotherpage.html'
>>> urljoin("http://www.asite.com/folder/currentpage.html", "folder2/anotherpage.html")
'http://www.asite.com/folder/folder2/anotherpage.html'
>>> urljoin("http://www.asite.com/folder/currentpage.html", "/folder3/anotherpage.html")
'http://www.asite.com/folder3/anotherpage.html'
>>> urljoin("http://www.asite.com/folder/currentpage.html", "../finalpage.html")
'http://www.asite.com/finalpage.html'

for copy-and-paste:

try:
    from urlparse import urljoin  # Python2
except ImportError:
    from urllib.parse import urljoin  # Python3

OwnerDisplayName: Alabaster Codify


问:
Decoding a crontab command
This is my first question on stackoverflow :)

I need to add the following cPanel's crontab for a site I just migrated to hostgator, however I am having trouble understanding it.

Here is cron command that was passed:

```<code>*/30    *    *    *    *    /usr/local/bin/php /data/web/vhosts/advisorcheck.com/cron/geocode_paid_members.php
0        9,15       *       *       *       /usr/bin/wget http://www.advisorbackgroundcheck.com/--spider
</code>```

I need help in decoding the above and adding it to the crontab!

答:
The first command will be executed every 30 minutes, while the second one will be executed twice a day (at 900 and 1500).

Here's an explanation of crontab syntax: http://en.wikipedia.org/wiki/Cron#Examples

Title: Decoding a crontab command

Body:
This is my first question on stackoverflow :)

I need to add the following cPanel's crontab for a site I just migrated to hostgator, however I am having trouble understanding it.

Here is cron command that was passed:

*/30    *    *    *    *    /usr/local/bin/php /data/web/vhosts/advisorcheck.com/cron/geocode_paid_members.php
0        9,15       *       *       *       /usr/bin/wget http://www.advisorbackgroundcheck.com/--spider

I need help in decoding the above and adding it to the crontab!


问:
How to properly use JQuery and Bootstrap in latest Angular versions
Yes, this question may be repeated. But I just don't get this setup working in any way.

I tried prettty much everything:

Getting the libraries directly into the index.html through a CDN.

Installing them via NPM and then adding them to angular-cli.json script field.

Importing the modules directly into my components, both with aliased JQuery (import * as $ from 'jquery') and just plain import (import 'jquery').

I tried other setups, like doing the imports in the root component, importing these libraries in various locations... but I don't get this working.

Currently, I need to get working one Bootstrap modal, and one Datepicker component which also works with JQuery, but it's being impossible for me. Sometimes I get the '$ is undefined' and sometimes I get other errors.

So now, I will ask: which is the real solution for this problem in latest Angular versions? How should I make the imports?

Thank you!

EDIT: Current situation:

Added the dependencies to the angular-cli.json file:

"styles": [
        "styles.css",
        "../node_modules/bootstrap/dist/css/bootstrap.min.css",
        "../node_modules/font-awesome/css/font-awesome.css"
      ],
      "scripts": [
      "../node_modules/jquery/dist/jquery.min.js",
      "../node_modules/bootstrap/dist/js/bootstrap.bundle.min.js"
    ],

I try to call the .modal() function that bootstrap has to add to Jquery:

( $('#myModal')).modal({
  backdrop: true,
  focus: true,
  show: true
})

But it just throws...:

```<code>SegmentsComponent.html:15 ERROR ReferenceError: $ is not defined
    at SegmentsComponent.openModal (segments.component.ts:55)
    at Object.eval [as handleEvent] (SegmentsComponent.html:15)
    at handleEvent (core.js:13255)
    at callWithDebugContext (core.js:14740)
    at Object.debugHandleEvent [as handleEvent] (core.js:14327)
    at dispatchEvent (core.js:9704)
    at eval (core.js:10318)
    at HTMLAnchorElement.eval (platform-browser.js:2614)
    at ZoneDelegate.invokeTask (zone.js:425)
    at Object.onInvokeTask (core.js:4620)
</code>```

Any help?

答:
mmmmm .. it looks very strange .. the only reason why it can gives to you $ is not defined is because you DON'T INCLUDE IT well..

so what i can suggest to you is to DOUBLE check your jquery path in the scripts :[] section ..

REMEMBER .. the path is intended from the src(or your root: entry) folder!

ALSO check the jquery version .. I saw that NPM don't include jquery when you do install bootstrap ... so install jquery manually and get the right version ..

AND in your .ts file .. have you declare var $ : any in the head of your ts file? ...

Hope it helps you!

Body:
Yes, this question may be repeated. But I just don't get this setup working in any way.

I tried prettty much everything:

Getting the libraries directly into the index.html through a CDN.

Installing them via NPM and then adding them to angular-cli.json script field.

Importing the modules directly into my components, both with aliased JQuery (import * as $ from 'jquery') and just plain import (import 'jquery').

I tried other setups, like doing the imports in the root component, importing these libraries in various locations... but I don't get this working.

Currently, I need to get working one Bootstrap modal, and one Datepicker component which also works with JQuery, but it's being impossible for me. Sometimes I get the '$ is undefined' and sometimes I get other errors.

So now, I will ask: which is the real solution for this problem in latest Angular versions? How should I make the imports?

Thank you!

EDIT: Current situation:

Added the dependencies to the angular-cli.json file:

"styles": [
        "styles.css",
        "../node_modules/bootstrap/dist/css/bootstrap.min.css",
        "../node_modules/font-awesome/css/font-awesome.css"
      ],
      "scripts": [
      "../node_modules/jquery/dist/jquery.min.js",
      "../node_modules/bootstrap/dist/js/bootstrap.bundle.min.js"
    ],

I try to call the .modal() function that bootstrap has to add to Jquery:

( $('#myModal')).modal({
  backdrop: true,
  focus: true,
  show: true
})

But it just throws...:

SegmentsComponent.html:15 ERROR ReferenceError: $ is not defined
    at SegmentsComponent.openModal (segments.component.ts:55)
    at Object.eval [as handleEvent] (SegmentsComponent.html:15)
    at handleEvent (core.js:13255)
    at callWithDebugContext (core.js:14740)
    at Object.debugHandleEvent [as handleEvent] (core.js:14327)
    at dispatchEvent (core.js:9704)
    at eval (core.js:10318)
    at HTMLAnchorElement.eval (platform-browser.js:2614)
    at ZoneDelegate.invokeTask (zone.js:425)
    at Object.onInvokeTask (core.js:4620)

Any help?


问:
Android: how to play video from assets?
I am making an application in which I have to show video from assets folder in a Fragment. Can anyone help me do this? Do I need to use VideoView in XML?

答:
I have already suffered from same problem, u should prefer project's res/raw folder instead of assets. Create raw folder under res folder. Save video file in a supported format (3gp, wmv, mp4 ) and named with lowercase, numerics, underscores and dots in its filename likewise:filename.3gp into the raw folder.

```<code>VideoView videoview = (VideoView) findViewById(R.id.VideoView);

String uriPath = "android.resource://your application package name/raw/your
wmv/mp4/3gp file in res/raw path without extension";

videoview.setVideoURI(Uri.parse(uriPath));

videoview.start();
</code>```

Title: Android: how to play video from assets?

Body:
I have already suffered from same problem, u should prefer project's res/raw folder instead of assets. Create raw folder under res folder. Save video file in a supported format (3gp, wmv, mp4 ) and named with lowercase, numerics, underscores and dots in its filename likewise:filename.3gp into the raw folder.

VideoView videoview = (VideoView) findViewById(R.id.VideoView);

String uriPath = "android.resource://your application package name/raw/your
wmv/mp4/3gp file in res/raw path without extension";

videoview.setVideoURI(Uri.parse(uriPath));

videoview.start();


问:
Swift: How to get everything after a certain set of characters
Given the following string:

```<code>var snippet = "1111 West Main Street Beverly Hills, CA 90210 Phone: 123.456.7891"
</code>```

How can I extract everything that comes after "Phone:"

So in this case I want

```<code>phone = 123.456.7891
</code>```

I've tried this:

```<code>    if let range = snippet.rangeOfString("Phone:") {

        let phone = snippet.substringToIndex(range.startIndex)
        print(phone) // prints 1111 West Main Street Beverly Hills, CA 90210
    }
</code>```

But this prints everything BEFORE, I need everything AFTER.

答:
for a very basic way and assuming you can guarantee the format of the string you could use .components(separatedBy: "Phone: ") so  anything before will be at index 0 and after index 1

```<code>var snippet = "1111 West Main Street Beverly Hills, CA 90210 Phone: 123.456.7891"
let phoneNumber = snippet.components(separatedBy: "Phone: ")[1]
print(phoneNumber)
//prints everything that appears after "Phone: " in your snippet string
//"123.456.7891"
</code>```

Body:
Given the following string:

var snippet = "1111 West Main Street Beverly Hills, CA 90210 Phone: 123.456.7891"

How can I extract everything that comes after "Phone:"

So in this case I want

phone = 123.456.7891

I've tried this:

    if let range = snippet.rangeOfString("Phone:") {

        let phone = snippet.substringToIndex(range.startIndex)
        print(phone) // prints 1111 West Main Street Beverly Hills, CA 90210
    }

But this prints everything BEFORE, I need everything AFTER.

Body:
for a very basic way and assuming you can guarantee the format of the string you could use .components(separatedBy: "Phone: ") so  anything before will be at index 0 and after index 1

var snippet = "1111 West Main Street Beverly Hills, CA 90210 Phone: 123.456.7891"
let phoneNumber = snippet.components(separatedBy: "Phone: ")[1]
print(phoneNumber)
//prints everything that appears after "Phone: " in your snippet string
//"123.456.7891"


问:
Ajax - send button value to php
I have a problem with send data to php. I want to send button value via jquery ajax. This is my code:
HTML

```<code>    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script>
$(document).ready(function(){
    $.ajax({
        url: "try.php",
        type: "POST",
        data: {
            data: val    // removed ; after val.
        }
    });
});

</script>

    <body>

      <button id="1" name="1"  value="some_value">1</button>
      <button id="2" name="2"  value="some_value">2</button>

    </body>
</code>```

PHP:

```<code><?php

$name = $_POST['data'];
echo $name;

?>
</code>```

It doesn't working...

答:
Make proper json string to send data. You are having extra ; there.

```<code>$(document).ready(function(){
    $.ajax({
        url: "try.php",
        type: "POST",
        data: {
            data: val    // removed ; after val.
        }
    });
});
</code>```

And get it with data key in php.

```<code><?php

$name = $_POST['data'];
echo $name;
?>
</code>```

Also, write your event listeners inside document.ready(). Currently your listeners are not getting applied as the script is on the top and is not able to find the <button> as they are not yet present.

Title: Ajax - send button value to php

Body:
I have a problem with send data to php. I want to send button value via jquery ajax. This is my code:
HTML

      <button id="1" name="1"  value="some_value">1</button>
      <button id="2" name="2"  value="some_value">2</button>

PHP:

<?php

$name = $_POST['data'];
echo $name;

?>

It doesn't working...

Body:
Make proper json string to send data. You are having extra ; there.

$(document).ready(function(){
    $.ajax({
        url: "try.php",
        type: "POST",
        data: {
            data: val    // removed ; after val.
        }
    });
});

And get it with data key in php.

<?php

$name = $_POST['data'];
echo $name;
?>

Also, write your event listeners inside document.ready(). Currently your listeners are not getting applied as the script is on the top and is not able to find the <button> as they are not yet present.


问:
Android: ListView non-enabled items draw invisible divider
If I have a ListView with two different kinds of items, enabled and disabled ones (meaning selectable and non-selectable), Android draws a small divider correctly between the enabled items, but not between disabled items. Instead it draws a transparent divider, which causes really bad design issues. This has already been discussed here (Google Groups), but without any solution.

What I'm looking for is a way to force Android to draw the same divider which is being used between enabled items also to being used between disabled items instead of just leaving a transparent space.

答: yes is not cool at all! I ran into the same issue. The way to fix it is add a View type line into your xml file and set your divider to 0 height like so: android:dividerHeight="0dp" Note: this is on list view itself.</p>


问:
MS BOT Framework: Attachments
I am trying to work with attachments in the MS Bot Framework using the example from the site:

function(session) {
  console.log('here')
  builder.Prompts.text(session, "Please upload the latest report now")
},
function(session, results) {
  console.log(session)
  var msg = session.message;
  if (msg.attachments && msg.attachments.length > 0) {
    // Echo back attachment
    var attachment = msg.attachments[0];
    session.send({
      text: "You sent:",
      attachments: [{
        contentType: attachment.contentType,
        contentUrl: attachment.contentUrl,
        name: attachment.name
      }]
    });
  } else {
    // Echo back users text
    session.send("You said: %s", session.message.text);
  }
}```

This works when you enter text but not when you attach (via the option in the Bot Emulator) either an image or a spreadsheet.  I have no clue as to why this isn't working :(

EDIT 1: So when you add an image, the console logs

/ - Session.beginDialog(siteOwnerRefresh:/)

.siteOwnerRefresh:/ - waterfall() step 1 of 2

.siteOwnerRefresh:/ - Session.beginDialog(BotBuilder:prompt-text)

..BotBuilder:prompt-text - Session.send()

..BotBuilder:prompt-text - Session.sendBatch() sending 1 message(s)

WARN: ChatConnector: receive - emulator running without security enabled.

ChatConnector: message received.

UniversalBot("*") routing 1 attachment(s) from "emulator"

Library("BotBuilder").findRoutes() explanation:

ActiveDialog(0.1)

..BotBuilder:prompt-text - WARN: Prompt - no intent handler found for null

..BotBuilder:prompt-text - Session.send()

..BotBuilder:prompt-text - Session.sendBatch() sending 1 message(s)

答: It turned out that the bot didn't work from with a second step of the cascade.  I moved it out it was the first step in the cascade and it now works.</p>

Title: MS BOT Framework: Attachments

Body:
I am trying to work with attachments in the MS Bot Framework using the example from the site:

function(session) {
  console.log('here')
  builder.Prompts.text(session, "Please upload the latest report now")
},
function(session, results) {
  console.log(session)
  var msg = session.message;
  if (msg.attachments && msg.attachments.length > 0) {
    // Echo back attachment
    var attachment = msg.attachments[0];
    session.send({
      text: "You sent:",
      attachments: [{
        contentType: attachment.contentType,
        contentUrl: attachment.contentUrl,
        name: attachment.name
      }]
    });
  } else {
    // Echo back users text
    session.send("You said: %s", session.message.text);
  }
}

This works when you enter text but not when you attach (via the option in the Bot Emulator) either an image or a spreadsheet.  I have no clue as to why this isn't working :(

EDIT 1: So when you add an image, the console logs

/ - Session.beginDialog(siteOwnerRefresh:/)

.siteOwnerRefresh:/ - waterfall() step 1 of 2

.siteOwnerRefresh:/ - Session.beginDialog(BotBuilder:prompt-text)

..BotBuilder:prompt-text - Session.send()

..BotBuilder:prompt-text - Session.sendBatch() sending 1 message(s)

WARN: ChatConnector: receive - emulator running without security enabled.

ChatConnector: message received.

UniversalBot("*") routing 1 attachment(s) from "emulator"

Library("BotBuilder").findRoutes() explanation:

ActiveDialog(0.1)

..BotBuilder:prompt-text - WARN: Prompt - no intent handler found for null

..BotBuilder:prompt-text - Session.send()

..BotBuilder:prompt-text - Session.sendBatch() sending 1 message(s)


问:
How to import data into star schema data warehouse.
I have searched everywhere on the web to find out how I can import data into a star schema data warehouse. A lot of the stuff online explain the design of the star schema and data warehouse but none explain how exactly data is loaded into the DW. Here is what i've done so far:

I am trying to make an application of high school basketball statistics for each player.

I have:

A list of all of the players name, height, position and number

A list of all of the high schools

list of all of the schedules

list of conferences

statistics(points, rebounds, steals, games played, etc)  for each player for the current year.

I assume the the stats would be my fact table and the rest are my dim tables.

Now the million dollar question --How in the world do get the data into that format appropriately?

I tried simply importing them to their respective tables but dont know how they connect.

Example: there are 800 players and 400 schools. each schools has a unique id (primary key). I upload the players into dim players and schools into dim schools. Now how do I connect them?

Please help. Thanks in advance. Sorry for the rambling :)

答:
You can use SQL server data tools for this project.
SQL server Data tools consists of a SSIS,SSAS and SSRS.

Use SSIS to create a ETL process for your data in your database.
Use SSAS to create dimensions, fact tables and cubes (You can do a lot more in this).
Use SSRS to present the data in a user friendly way.

Lot of videos are available youtube.