问:
Delphi 2009, DbExpress with Oracle : Unable to load oci.dll
i've setup a demo to test datasnap 2009, and i've got a problem with dbexpress.

The dbexpress error message, (same at design time or runtime) :
"Cannot load oci.dll library (Error code 127). The OCI.dll library may be missing from the system path."

I'm using Oracle 8.0.5. The path to oci.dll (c:\orant\BIN) is in my system path, in front of the line. I've Delphi 2005 installed too and the exact same configuration just works fine. I've moved dbexpress delphi 2005 related files, i've rebooted many times, tried to copy oci.dll in c:\windows\system or c:\windows\system32\, everytime the same error.

I'm running out of solutions. Maybe it's a problem related with the fact i've got D2005 installed too... ?

Does someone can please help me ?

Thanks

EDIT:
Here is the event log, in the IDE during build, we can see that it FOUND and LOAD OCI.dll, so the error (Cannot load oci.dll) may not be the good one :

```<code>Début du Thread : ID du thread : 5588. Processus Server.exe (5548)

Début du processus : C:\Documents and Settings\frplante\Mes documents\Développement\Projets\Démo DataSnap2009\Server\Server.exe. Adresse de base : $00400000. Processus Server.exe (5548)

Chargement du module : Server.exe. Contient des infos de débogage. Adresse de base : $00400000. Processus Server.exe (5548)

Chargement du module : ntdll.dll. Pas d'informations de débogage. Adresse de base : $7C910000. Processus Server.exe (5548)

Chargement du module : KERNEL32.dll. Pas d'informations de débogage. Adresse de base : $7C800000. Processus Server.exe (5548)

Chargement du module : OLEAUT32.dll. Pas d'informations de débogage. Adresse de base : $770E0000. Processus Server.exe (5548)

Chargement du module : ADVAPI32.dll. Pas d'informations de débogage. Adresse de base : $77DA0000. Processus Server.exe (5548)

Chargement du module : RPCRT4.dll. Pas d'informations de débogage. Adresse de base : $77E50000. Processus Server.exe (5548)

Chargement du module : Secur32.dll. Pas d'informations de débogage. Adresse de base : $77FC0000. Processus Server.exe (5548)

Chargement du module : GDI32.dll. Pas d'informations de débogage. Adresse de base : $77EF0000. Processus Server.exe (5548)

Chargement du module : USER32.dll. Pas d'informations de débogage. Adresse de base : $7E390000. Processus Server.exe (5548)

Chargement du module : msvcrt.dll. Pas d'informations de débogage. Adresse de base : $77BE0000. Processus Server.exe (5548)

Chargement du module : ole32.dll. Pas d'informations de débogage. Adresse de base : $774A0000. Processus Server.exe (5548)

Chargement du module : MSIMG32.dll. Pas d'informations de débogage. Adresse de base : $76310000. Processus Server.exe (5548)

Chargement du module : VERSION.dll. Pas d'informations de débogage. Adresse de base : $77BD0000. Processus Server.exe (5548)

Chargement du module : COMCTL32.dll. Pas d'informations de débogage. Adresse de base : $77390000. Processus Server.exe (5548)

Chargement du module : SHLWAPI.dll. Pas d'informations de débogage. Adresse de base : $77F40000. Processus Server.exe (5548)

Chargement du module : wxvault.dll. Pas d'informations de débogage. Adresse de base : $10000000. Processus Server.exe (5548)

Chargement du module : PSAPI.DLL. Pas d'informations de débogage. Adresse de base : $76BA0000. Processus Server.exe (5548)

Chargement du module : MPR.dll. Pas d'informations de débogage. Adresse de base : $71A60000. Processus Server.exe (5548)

Chargement du module : detoured.dll. Pas d'informations de débogage. Adresse de base : $00370000. Processus Server.exe (5548)

Chargement du module : SHELL32.dll. Pas d'informations de débogage. Adresse de base : $7C9D0000. Processus Server.exe (5548)

Chargement du module : IMM32.dll. Pas d'informations de débogage. Adresse de base : $76320000. Processus Server.exe (5548)

Chargement du module : UxTheme.dll. Pas d'informations de débogage. Adresse de base : $5B090000. Processus Server.exe (5548)

Chargement du module : **dbxora.dll**. Pas d'informations de débogage. Adresse de base : $00FC0000. Processus Server.exe (5548)

Chargement du module : **OCI.dll**. Pas d'informations de débogage. Adresse de base : $003F0000. Processus Server.exe (5548)

Chargement du module : ORA805.dll. Pas d'informations de débogage. Adresse de base : $01430000. Processus Server.exe (5548)

Chargement du module : CORE40.dll. Pas d'informations de débogage. Adresse de base : $015C0000. Processus Server.exe (5548)

Chargement du module : NLSRTL33.dll. Pas d'informations de débogage. Adresse de base : $01620000. Processus Server.exe (5548)

Chargement du module : WINMM.dll. Pas d'informations de débogage. Adresse de base : $76AE0000. Processus Server.exe (5548)

Chargement du module : NL80.dll. Pas d'informations de débogage. Adresse de base : $01660000. Processus Server.exe (5548)

Chargement du module : WSOCK32.dll. Pas d'informations de débogage. Adresse de base : $71A10000. Processus Server.exe (5548)

Chargement du module : WS2_32.dll. Pas d'informations de débogage. Adresse de base : $719F0000. Processus Server.exe (5548)

Chargement du module : WS2HELP.dll. Pas d'informations de débogage. Adresse de base : $719E0000. Processus Server.exe (5548)

Chargement du module : OTRACE80.dll. Pas d'informations de débogage. Adresse de base : $01680000. Processus Server.exe (5548)

Chargement du module : NS80.dll. Pas d'informations de débogage. Adresse de base : $016B0000. Processus Server.exe (5548)

Chargement du module : nasns80.dll. Pas d'informations de débogage. Adresse de base : $016F0000. Processus Server.exe (5548)

Chargement du module : nz80.dll. Pas d'informations de débogage. Adresse de base : $01720000. Processus Server.exe (5548)

Chargement du module : NNFG80.dll. Pas d'informations de débogage. Adresse de base : $01770000. Processus Server.exe (5548)

Chargement du module : NNCI80.dll. Pas d'informations de débogage. Adresse de base : $01780000. Processus Server.exe (5548)

Chargement du module : NNG80.dll. Pas d'informations de débogage. Adresse de base : $01790000. Processus Server.exe (5548)

Chargement du module : NMP80.dll. Pas d'informations de débogage. Adresse de base : $017B0000. Processus Server.exe (5548)

Chargement du module : NPL80.dll. Pas d'informations de débogage. Adresse de base : $017C0000. Processus Server.exe (5548)

Chargement du module : NR80.dll. Pas d'informations de débogage. Adresse de base : $017D0000. Processus Server.exe (5548)

Chargement du module : NT80.dll. Pas d'informations de débogage. Adresse de base : $017F0000. Processus Server.exe (5548)

Chargement du module : NCR80.dll. Pas d'informations de débogage. Adresse de base : $01800000. Processus Server.exe (5548)

Chargement du module : NMS80.dll. Pas d'informations de débogage. Adresse de base : $01840000. Processus Server.exe (5548)

Chargement du module : NNFD80.dll. Pas d'informations de débogage. Adresse de base : $01850000. Processus Server.exe (5548)

Chargement du module : NNFN80.dll. Pas d'informations de débogage. Adresse de base : $01860000. Processus Server.exe (5548)

Chargement du module : NI80.dll. Pas d'informations de débogage. Adresse de base : $01870000. Processus Server.exe (5548)

Chargement du module : PLS805.dll. Pas d'informations de débogage. Adresse de base : $01880000. Processus Server.exe (5548)

Chargement du module : NDWSI80.DLL. Pas d'informations de débogage. Adresse de base : $01A80000. Processus Server.exe (5548)

Exception déclenchée à $7C812AEB. Classe d'exception TDBXError avec message '**Cannot load oci.dll library** (error code 127).  The oci.dll library may be missing from the system path'. Processus Server.exe (5548)
</code>```

答:
If you are running this on Windows Vista,  did you check that your program have access rights to oci.dll? </p>

<p>If not one of answers work, then you should contact CodeGear to confirm if Oracle 8.0.5 is still supported. Even Oracle in drivers does not support access to 8.0.5 for several years now. There was an article on Metalink that describes what version of server can be accessed by specific client versions. </p>

OwnerDisplayName: Fred

Body:
i've setup a demo to test datasnap 2009, and i've got a problem with dbexpress.

The dbexpress error message, (same at design time or runtime) :
"Cannot load oci.dll library (Error code 127). The OCI.dll library may be missing from the system path."

I'm using Oracle 8.0.5. The path to oci.dll (c:\orant\BIN) is in my system path, in front of the line. I've Delphi 2005 installed too and the exact same configuration just works fine. I've moved dbexpress delphi 2005 related files, i've rebooted many times, tried to copy oci.dll in c:\windows\system or c:\windows\system32\, everytime the same error.

I'm running out of solutions. Maybe it's a problem related with the fact i've got D2005 installed too... ?

Does someone can please help me ?

Thanks

EDIT:
Here is the event log, in the IDE during build, we can see that it FOUND and LOAD OCI.dll, so the error (Cannot load oci.dll) may not be the good one :

Début du Thread : ID du thread : 5588. Processus Server.exe (5548)

Début du processus : C:\Documents and Settings\frplante\Mes documents\Développement\Projets\Démo DataSnap2009\Server\Server.exe. Adresse de base : $00400000. Processus Server.exe (5548)

Chargement du module : Server.exe. Contient des infos de débogage. Adresse de base : $00400000. Processus Server.exe (5548)

Chargement du module : ntdll.dll. Pas d'informations de débogage. Adresse de base : $7C910000. Processus Server.exe (5548)

Chargement du module : KERNEL32.dll. Pas d'informations de débogage. Adresse de base : $7C800000. Processus Server.exe (5548)

Chargement du module : OLEAUT32.dll. Pas d'informations de débogage. Adresse de base : $770E0000. Processus Server.exe (5548)

Chargement du module : ADVAPI32.dll. Pas d'informations de débogage. Adresse de base : $77DA0000. Processus Server.exe (5548)

Chargement du module : RPCRT4.dll. Pas d'informations de débogage. Adresse de base : $77E50000. Processus Server.exe (5548)

Chargement du module : Secur32.dll. Pas d'informations de débogage. Adresse de base : $77FC0000. Processus Server.exe (5548)

Chargement du module : GDI32.dll. Pas d'informations de débogage. Adresse de base : $77EF0000. Processus Server.exe (5548)

Chargement du module : USER32.dll. Pas d'informations de débogage. Adresse de base : $7E390000. Processus Server.exe (5548)

Chargement du module : msvcrt.dll. Pas d'informations de débogage. Adresse de base : $77BE0000. Processus Server.exe (5548)

Chargement du module : ole32.dll. Pas d'informations de débogage. Adresse de base : $774A0000. Processus Server.exe (5548)

Chargement du module : MSIMG32.dll. Pas d'informations de débogage. Adresse de base : $76310000. Processus Server.exe (5548)

Chargement du module : VERSION.dll. Pas d'informations de débogage. Adresse de base : $77BD0000. Processus Server.exe (5548)

Chargement du module : COMCTL32.dll. Pas d'informations de débogage. Adresse de base : $77390000. Processus Server.exe (5548)

Chargement du module : SHLWAPI.dll. Pas d'informations de débogage. Adresse de base : $77F40000. Processus Server.exe (5548)

Chargement du module : wxvault.dll. Pas d'informations de débogage. Adresse de base : $10000000. Processus Server.exe (5548)

Chargement du module : PSAPI.DLL. Pas d'informations de débogage. Adresse de base : $76BA0000. Processus Server.exe (5548)

Chargement du module : MPR.dll. Pas d'informations de débogage. Adresse de base : $71A60000. Processus Server.exe (5548)

Chargement du module : detoured.dll. Pas d'informations de débogage. Adresse de base : $00370000. Processus Server.exe (5548)

Chargement du module : SHELL32.dll. Pas d'informations de débogage. Adresse de base : $7C9D0000. Processus Server.exe (5548)

Chargement du module : IMM32.dll. Pas d'informations de débogage. Adresse de base : $76320000. Processus Server.exe (5548)

Chargement du module : UxTheme.dll. Pas d'informations de débogage. Adresse de base : $5B090000. Processus Server.exe (5548)

Chargement du module : **dbxora.dll**. Pas d'informations de débogage. Adresse de base : $00FC0000. Processus Server.exe (5548)

Chargement du module : **OCI.dll**. Pas d'informations de débogage. Adresse de base : $003F0000. Processus Server.exe (5548)

Chargement du module : ORA805.dll. Pas d'informations de débogage. Adresse de base : $01430000. Processus Server.exe (5548)

Chargement du module : CORE40.dll. Pas d'informations de débogage. Adresse de base : $015C0000. Processus Server.exe (5548)

Chargement du module : NLSRTL33.dll. Pas d'informations de débogage. Adresse de base : $01620000. Processus Server.exe (5548)

Chargement du module : WINMM.dll. Pas d'informations de débogage. Adresse de base : $76AE0000. Processus Server.exe (5548)

Chargement du module : NL80.dll. Pas d'informations de débogage. Adresse de base : $01660000. Processus Server.exe (5548)

Chargement du module : WSOCK32.dll. Pas d'informations de débogage. Adresse de base : $71A10000. Processus Server.exe (5548)

Chargement du module : WS2_32.dll. Pas d'informations de débogage. Adresse de base : $719F0000. Processus Server.exe (5548)

Chargement du module : WS2HELP.dll. Pas d'informations de débogage. Adresse de base : $719E0000. Processus Server.exe (5548)

Chargement du module : OTRACE80.dll. Pas d'informations de débogage. Adresse de base : $01680000. Processus Server.exe (5548)

Chargement du module : NS80.dll. Pas d'informations de débogage. Adresse de base : $016B0000. Processus Server.exe (5548)

Chargement du module : nasns80.dll. Pas d'informations de débogage. Adresse de base : $016F0000. Processus Server.exe (5548)

Chargement du module : nz80.dll. Pas d'informations de débogage. Adresse de base : $01720000. Processus Server.exe (5548)

Chargement du module : NNFG80.dll. Pas d'informations de débogage. Adresse de base : $01770000. Processus Server.exe (5548)

Chargement du module : NNCI80.dll. Pas d'informations de débogage. Adresse de base : $01780000. Processus Server.exe (5548)

Chargement du module : NNG80.dll. Pas d'informations de débogage. Adresse de base : $01790000. Processus Server.exe (5548)

Chargement du module : NMP80.dll. Pas d'informations de débogage. Adresse de base : $017B0000. Processus Server.exe (5548)

Chargement du module : NPL80.dll. Pas d'informations de débogage. Adresse de base : $017C0000. Processus Server.exe (5548)

Chargement du module : NR80.dll. Pas d'informations de débogage. Adresse de base : $017D0000. Processus Server.exe (5548)

Chargement du module : NT80.dll. Pas d'informations de débogage. Adresse de base : $017F0000. Processus Server.exe (5548)

Chargement du module : NCR80.dll. Pas d'informations de débogage. Adresse de base : $01800000. Processus Server.exe (5548)

Chargement du module : NMS80.dll. Pas d'informations de débogage. Adresse de base : $01840000. Processus Server.exe (5548)

Chargement du module : NNFD80.dll. Pas d'informations de débogage. Adresse de base : $01850000. Processus Server.exe (5548)

Chargement du module : NNFN80.dll. Pas d'informations de débogage. Adresse de base : $01860000. Processus Server.exe (5548)

Chargement du module : NI80.dll. Pas d'informations de débogage. Adresse de base : $01870000. Processus Server.exe (5548)

Chargement du module : PLS805.dll. Pas d'informations de débogage. Adresse de base : $01880000. Processus Server.exe (5548)

Chargement du module : NDWSI80.DLL. Pas d'informations de débogage. Adresse de base : $01A80000. Processus Server.exe (5548)

Exception déclenchée à $7C812AEB. Classe d'exception TDBXError avec message '**Cannot load oci.dll library** (error code 127).  The oci.dll library may be missing from the system path'. Processus Server.exe (5548)

LastEditorDisplayName: Fred

Body:
If you are running this on Windows Vista,  did you check that your program have access rights to oci.dll?

If not one of answers work, then you should contact CodeGear to confirm if Oracle 8.0.5 is still supported. Even Oracle in drivers does not support access to 8.0.5 for several years now. There was an article on Metalink that describes what version of server can be accessed by specific client versions.


来源: stackexchange

问: How to remove only one inline

答:
I have never used WordPress but installed it on my localhost and tried to modify the (e.g.) h1 tag with class="site-title" on the default template.
Just search on the folder for 'site-title' and found the header.php according to the activated template or your custom template.

Some code is generated by php and then sent to user so maybe to try to find a class that hasn't the same name in your php files than you see in your html received files. Try to find class/id in some tags near the one you want to change.

I hope it helps.

ContentLicense: CC BY-SA 3.0

Title: How to remove only one inline <style> from Wordpress head

Body:
I'm designing a Wordpress site that's not yet live. There is a block of inline css in the head of the home page that needs to go. I'm not sure where it's being generated from but the I've modified the css since and the inline css isn't updating to match it.

I've tried overruling it by using !important in my custom.css.

I've tried adding my style sheet just above the  so it loads last.

<link rel='stylesheet' href='http://mywebsite/wpnew/wp-content/themes/mytheme/custom.css?counter=1491147962' type='text/css' media='all' />

I've tried adding this to my functions.php:

wp_enqueue_style( 'customcss', get_template_directory_uri() . '/custom.css', array(), time() );

I've deleted the widget that the css belongs to thinking the page might render without the inline css since the widget was gone but it's still there.

I'm at a loss. I'm not a programmer and not entirely comfortable with php. I found a plugin that strips all inline tags but I only want to get rid of this one block of css.

Any help would be appreciated!


问:
How to remove exterior punctuation from a string using regular expressions
Given a string like below, remove any leading and trailing punctuation via regular expressions:

```<code>String a = "!?Don't.;, .:delete !the@ $actual string%";
String b = "Hyphenated-words, too!";
</code>```

I know that the regex [\P{Alnum}] will target all non-alphanumeric characters, but how do I target ONLY the leading and trailing punctuation so I get...

```<code>a = "Don't delete the actual string";
b = "Hyphenated-words too";
</code>```

... instead of:

```<code>a = "Dont delete the actual string";
b = "Hyphenated words too";
</code>```

I just need the regular expression; not the actual code to remove the punctuation.

答: You can use ^ and $. ^ matches the start of the string and $ the end. The regex ^\W* should match all non-alphanumeric character in the beginning and \W*$ those in the end. You can simply replace these regexes with an empty string to get rid of the non-alphanumeric characters. Obviously, you have to escape the \ in the Java string (assuming you are using Java).

Body:
Given a string like below, remove any leading and trailing punctuation via regular expressions:

String a = "!?Don't.;, .:delete !the@ $actual string%";
String b = "Hyphenated-words, too!";

I know that the regex [\P{Alnum}] will target all non-alphanumeric characters, but how do I target ONLY the leading and trailing punctuation so I get...

a = "Don't delete the actual string";
b = "Hyphenated-words too";

... instead of:

a = "Dont delete the actual string";
b = "Hyphenated words too";

I just need the regular expression; not the actual code to remove the punctuation.


问:
How to check a type is of a given template type
I have a template type:

```<code>template<class T>
struct Shadow {
   T field[100];
};
</code>```

I want to create a tuple, whose types are instantiations of Shadow, but should not allow any other types. For example,

```<code>tuple< Shadow<int>, Shadow<double> > x; // correct instantiation.
tuple< Shadow<int>, double > x; // incorrect instantiation.
</code>```

How can I achieve this (and have compiler flag an error in case of incorrect instantiation)?

答:
A solution that I can imagine is wrap the tuple in a variadic template struct (or class)</p>

```<code>#include <tuple>

template <typename T>
struct Shadow
 { T field[100]; };

template <typename ... Ts>
struct wrapTShadow
 { std::tuple<Shadow<Ts>...> val; };

int main ()
 {
   // contain a std::tuple<Shadow<int>, Shadow<double>>
   wrapTShadow<int, double>  wts;
 }
</code>```

Body:
I have a template type:

template<class T>
struct Shadow {
   T field[100];
};

I want to create a tuple, whose types are instantiations of Shadow, but should not allow any other types. For example,

tuple< Shadow<int>, Shadow<double> > x; // correct instantiation.
tuple< Shadow<int>, double > x; // incorrect instantiation.

How can I achieve this (and have compiler flag an error in case of incorrect instantiation)?

Body:
A solution that I can imagine is wrap the tuple in a variadic template struct (or class)

#include <tuple>

template <typename T>
struct Shadow
 { T field[100]; };

template <typename ... Ts>
struct wrapTShadow
 { std::tuple<Shadow<Ts>...> val; };

int main ()
 {
   // contain a std::tuple<Shadow<int>, Shadow<double>>
   wrapTShadow<int, double>  wts;
 }


问:
Error while compiling the Xcode project (IPhone)
I added ffmpeg iphone port into my library and I can able to use a few of its functions like avcodec_init(),.. without any errors.
But when I include this function call "avcodec_register_all" Xcode is giving error after compilation

The error message is :

*---------------
ld: ldr 12-bit displacement out of range (4276 max +/-4096) in _CFRelease$stub in _CFRelease$stub from /Users/foxit/Documents/CameraTest/build/CameraTest.build/Debug-iphoneos/CameraTest.build/Objects-normal/armv6/CameraTest

Command /Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/gcc-4.2 failed with exit code 1

*-------------

Does anyone know whats wrong with this ?

Regards,

Raghu

答:
For me on 4.2 and using ffmpeg, solution was to specify "Optimized (armv7)" in field "Architectures" instead "Standard (armv6 armv7)"
if this can help you...</p>

ContentLicense: CC BY-SA 2.5


问:
How to pass a single variable from one PHP page to external Javascript function
I am very new to all this and have spent the last few hours looking at multiple sections of code on various pages.  I am trying to pass a single variable from a PHP page to a javascript function page.  The PHP variable will be filled from a database entry. On the javascript function page, I am going to use the variable in an if statement to decide what to do.
Below is the section of code I have in the PHP file.

```<code>if($UserName == $username && $UserPass == $password){
    $_SESSION['useris'] = $UserID;
    $_SESSION['access_level'] = $Authlevel;
    echo json_encode($Authlevel);
    header('Location:../HTML/AdminModal.html'); //removed for testing of the auth level
}
</code>```

I do not think that I have actually sent the data anywhere as yet.

Then in the javascript file, I am totally lost as to how to get the information I have passed.

I know there is a lot of big examples of various data being passed back and forth but I am struggling to understand or work out how to adapt to my needs.

Thanks

答:
You need to make an AJAX call to your server.

Javascript must be like

```<code>$.ajax({
    type: "POST",
    url: "ajax_post.php",
    data: {user: userid, pass: password}, // any data you would like to send with request
    dataType: "JSON",
    beforeSend: function(){
        // you may want to show a loader or any message before sending request
    },
    success: function(response){
        console.log(response);
        // do further processing of your response and carry out any redirections from here, if required, using window.location.href = "../HTML/AdminModal.html";
    }
});
</code>```

You server side file i.e. ajax_post.php would contain

```<code>..
if($UserName == $username && $UserPass == $password){
    $_SESSION['useris'] = $UserID;
    $_SESSION['access_level'] = $Authlevel;
    echo json_encode($Authlevel);
}
</code>```

Body:
I am very new to all this and have spent the last few hours looking at multiple sections of code on various pages.  I am trying to pass a single variable from a PHP page to a javascript function page.  The PHP variable will be filled from a database entry. On the javascript function page, I am going to use the variable in an if statement to decide what to do.
Below is the section of code I have in the PHP file.

if($UserName == $username && $UserPass == $password){
    $_SESSION['useris'] = $UserID;
    $_SESSION['access_level'] = $Authlevel;
    echo json_encode($Authlevel);
    header('Location:../HTML/AdminModal.html'); //removed for testing of the auth level
}

I do not think that I have actually sent the data anywhere as yet.

Then in the javascript file, I am totally lost as to how to get the information I have passed.

I know there is a lot of big examples of various data being passed back and forth but I am struggling to understand or work out how to adapt to my needs.

Thanks

Body:
You need to make an AJAX call to your server.

Javascript must be like

$.ajax({
    type: "POST",
    url: "ajax_post.php",
    data: {user: userid, pass: password}, // any data you would like to send with request
    dataType: "JSON",
    beforeSend: function(){
        // you may want to show a loader or any message before sending request
    },
    success: function(response){
        console.log(response);
        // do further processing of your response and carry out any redirections from here, if required, using window.location.href = "../HTML/AdminModal.html";
    }
});

You server side file i.e. ajax_post.php would contain

..
if($UserName == $username && $UserPass == $password){
    $_SESSION['useris'] = $UserID;
    $_SESSION['access_level'] = $Authlevel;
    echo json_encode($Authlevel);
}


问:
How do i list items(render) from a nested JSON response Angular.js
my home controller returns this, this is what i see on.
This lists the authors i have and the rating star, i wanted to include the titles of each authors. and i tried this but didn't work for me, what am i missing??

```<code>[
  {
    "_id": "58dd21c3cb77090b930b6063",
    "bookAuthor": "George Orwell",
    "titles": [
      {
        "title": "Animal Farm",
        "_id": "58dd3f2701cc081056135dae",
        "reviews": [
          {
            "author": "Lisa",
            "rating": 4,
            "reviewText": "this is a review",
            "_id": "58dd8e13876c0f16b17cd7dc",
            "createdOn": "2017-03-30T23:00:35.662Z"
          }
        ],
        "favouredBy": [
          "bb, aa, cc"
        ]
      },
      {
        "title": "1984",
        "_id": "58dd42a59f12f110d1756f08",
        "reviews": [
          {
            "author": "jessy",
            "rating": 5,
            "reviewText": "REVIEW FOR SECOND TITLE",
            "_id": "58dd8ef46d4aaa16e4545c76",
            "createdOn": "2017-03-30T23:04:20.609Z"
          }
        ],
        "favouredBy": [
          "all"
        ]
      }
    ]
  }
]
</code>```

and there is my home.view.html

```<code>    <navigation></navigation>
<div class="container">
   <page-header content="vm.pageHeader"></page-header>
   <div class="row">
      <div class="col-xs-12 col-sm-8">
         <div class="error">{{ vm.message }}</div>
         <div class="row list-group">
            <div class="col-xs-12 list-group-item" ng-repeat="book in vm.data.books | filter : textFilter">
               <h4>
                  <small class="rating-stars" rating-stars rating="book.rating"></small>
               </h4>
               <p class="Author">{{ book.bookAuthor }}</p>
            </div>
            <div class="col-xs-12 list-group-item2" ng-repeat="book in vm.data.books | filter : textFilter">
               <h4>
                  { book.titles.title }}
               </h4>
            </div>
         </div>
      </div>
      <div class="col-xs-12 col-sm-4">
         <p class="lead">{{ vm.sidebar.content }}</p>
      </div>
   </div>
   <footer-generic></footer-generic>
</div>
</code>```

答:
Yous should use
 also you should place the nested loop inside the first div and then access do a ng-repeat for the child item.

```<code><div ng-repeat="eachbook in book.titles">
</code>```

DEMO

var myApp=angular.module('myApp',[])
 myApp.controller('myController',function(){
  this.data={};
  this.data.books= [
  {
    "_id": "58dd21c3cb77090b930b6063",
    "bookAuthor": "George Orwell",
    "titles": [
      {
        "title": "Animal Farm",
        "_id": "58dd3f2701cc081056135dae",
        "reviews": [
          {
            "author": "Lisa",
            "rating": 4,
            "reviewText": "this is a review",
            "_id": "58dd8e13876c0f16b17cd7dc",
            "createdOn": "2017-03-30T23:00:35.662Z"
          }
        ],
        "favouredBy": [
          "bb, aa, cc"
        ]
      },
      {
        "title": "1984",
        "_id": "58dd42a59f12f110d1756f08",
        "reviews": [
          {
            "author": "jessy",
            "rating": 5,
            "reviewText": "REVIEW FOR SECOND TITLE",
            "_id": "58dd8ef46d4aaa16e4545c76",
            "createdOn": "2017-03-30T23:04:20.609Z"
          }
        ],
        "favouredBy": [
          "all"
        ]
      }
    ]
  }
];
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<div ng-app='myApp' ng-controller='myController as vm'>
    <div class="row">
        <div class="row list-group">
            <div class="col-xs-12 list-group-item" ng-repeat="book in vm.data.books | filter : textFilter">
                <h4>
                    <small class="rating-stars" rating-stars rating="book.rating"></small> {{book.bookAuthor}}
                </h4>
                <div ng-repeat="eachbook in book.titles">
                    <ul>
                        <li>
                            {{eachbook.title}}
                        </li>
                    </ul>
                </div>
            </div>
        </div>
    </div>
</div></code>```

Body:
my home controller returns this, this is what i see on.
This lists the authors i have and the rating star, i wanted to include the titles of each authors. and i tried this but didn't work for me, what am i missing??

[
  {
    "_id": "58dd21c3cb77090b930b6063",
    "bookAuthor": "George Orwell",
    "titles": [
      {
        "title": "Animal Farm",
        "_id": "58dd3f2701cc081056135dae",
        "reviews": [
          {
            "author": "Lisa",
            "rating": 4,
            "reviewText": "this is a review",
            "_id": "58dd8e13876c0f16b17cd7dc",
            "createdOn": "2017-03-30T23:00:35.662Z"
          }
        ],
        "favouredBy": [
          "bb, aa, cc"
        ]
      },
      {
        "title": "1984",
        "_id": "58dd42a59f12f110d1756f08",
        "reviews": [
          {
            "author": "jessy",
            "rating": 5,
            "reviewText": "REVIEW FOR SECOND TITLE",
            "_id": "58dd8ef46d4aaa16e4545c76",
            "createdOn": "2017-03-30T23:04:20.609Z"
          }
        ],
        "favouredBy": [
          "all"
        ]
      }
    ]
  }
]

and there is my home.view.html

    <navigation></navigation>

   <page-header content="vm.pageHeader"></page-header>

{{ vm.message }}

{{ book.bookAuthor }}

                  { book.titles.title }}

{{ vm.sidebar.content }}

Body:
Yous should use <div ng-app='myApp' ng-controller='myController as vm'> also you should place the nested loop inside the first div and then access do a ng-repeat for the child item.

<div ng-repeat="eachbook in book.titles">

DEMO

var myApp=angular.module('myApp',[])
 myApp.controller('myController',function(){
  this.data={};
  this.data.books= [
  {
    "_id": "58dd21c3cb77090b930b6063",
    "bookAuthor": "George Orwell",
    "titles": [
      {
        "title": "Animal Farm",
        "_id": "58dd3f2701cc081056135dae",
        "reviews": [
          {
            "author": "Lisa",
            "rating": 4,
            "reviewText": "this is a review",
            "_id": "58dd8e13876c0f16b17cd7dc",
            "createdOn": "2017-03-30T23:00:35.662Z"
          }
        ],
        "favouredBy": [
          "bb, aa, cc"
        ]
      },
      {
        "title": "1984",
        "_id": "58dd42a59f12f110d1756f08",
        "reviews": [
          {
            "author": "jessy",
            "rating": 5,
            "reviewText": "REVIEW FOR SECOND TITLE",
            "_id": "58dd8ef46d4aaa16e4545c76",
            "createdOn": "2017-03-30T23:04:20.609Z"
          }
        ],
        "favouredBy": [
          "all"
        ]
      }
    ]
  }
];
});

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<div ng-app='myApp' ng-controller='myController as vm'>
    <div class="row">
        <div class="row list-group">
            <div class="col-xs-12 list-group-item" ng-repeat="book in vm.data.books | filter : textFilter">
                <h4>
                    <small class="rating-stars" rating-stars rating="book.rating"></small> {{book.bookAuthor}}
                </h4>
                <div ng-repeat="eachbook in book.titles">
                    <ul>
                        <li>
                            {{eachbook.title}}
                        </li>
                    </ul>
                </div>
            </div>
        </div>
    </div>
</div>


问:
What is wrong with my JavaScript? Function not working
I am trying to get it so that when I click on a box, it'l turn black.

function colorize() {
  document.getElementsByClassName('boardpic').innerHTML.src = "images/black.png";
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{
  font-family: 'Raleway', sans-serif;
  margin: 0;
  background: #87e0fd;
  background: -moz-linear-gradient(top, #87e0fd 0%, #53cbf1 74%, #05abe0 100%);
  background: -webkit-linear-gradient(top, #87e0fd 0%,#53cbf1 74%,#05abe0 100%);
  background: linear-gradient(to bottom, #87e0fd 0%,#53cbf1 74%,#05abe0 100%);
  filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#87e0fd', endColorstr='#05abe0',GradientType=0 );
}

#title{
  text-align: center;
  font-size: 96px;
  margin-bottom: 12px;
}

.boardpic{
  margin: 0;
  padding: 0;
  width: 32px;
  height: 32px;
}

#container{
  display: flex;
}

#board{
  border-color: black;
  border-width: 3px;
  border-radius: 3px;
  border-style: solid;
  background-color: white;
  padding: 3px;
  width: 512px;
  height: 512px;
  font-size: 0;
  margin: auto;
  margin-bottom: 12px;
}

#colorpicker{
  font-size: 0;
  border-color: black;
  border-width: 3px;
  border-radius: 3px;
  border-style: solid;
  width: 256px;
  margin: auto;
}</code>```

    <title>
      Drawify | 0.0.1
    </title>
    <link rel="stylesheet" type="text/css" href="styles.css">
    <link href="https://fonts.googleapis.com/css?family=Raleway:700" rel="stylesheet">

      Drawify

```

Whenever I click, the box doesn't change

I was pretty sure I was setting it up all right, but I guess not. So yeah, I am quite new to coding, so please explain with simple terms. :)

答:
Binding a function to each element inside the DOM isn't effective and looks messy. I would suggest you to catch every element with boardpic class and just bind event listener which changes the src attribute of clicked element.

var elems = document.getElementsByClassName('boardpic');
Array.from(elems).forEach(v => v.addEventListener('click', function() {
  this.src = 'https://placehold.it/350x150';
}));```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  font-family: 'Raleway', sans-serif;
  margin: 0;
  background: #87e0fd;
  background: -moz-linear-gradient(top, #87e0fd 0%, #53cbf1 74%, #05abe0 100%);
  background: -webkit-linear-gradient(top, #87e0fd 0%, #53cbf1 74%, #05abe0 100%);
  background: linear-gradient(to bottom, #87e0fd 0%, #53cbf1 74%, #05abe0 100%);
  filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#87e0fd', endColorstr='#05abe0', GradientType=0);
}

#title {
  text-align: center;
  font-size: 96px;
  margin-bottom: 12px;
}

.boardpic {
  margin: 0;
  padding: 0;
  width: 32px;
  height: 32px;
}

#container {
  display: flex;
}

#board {
  border-color: black;
  border-width: 3px;
  border-radius: 3px;
  border-style: solid;
  background-color: white;
  padding: 3px;
  width: 512px;
  height: 512px;
  font-size: 0;
  margin: auto;
  margin-bottom: 12px;
}

#colorpicker {
  font-size: 0;
  border-color: black;
  border-width: 3px;
  border-radius: 3px;
  border-style: solid;
  width: 256px;
  margin: auto;
}</code>```

  Drawify

```

Body:
I am trying to get it so that when I click on a box, it'l turn black.

function colorize() {
  document.getElementsByClassName('boardpic').innerHTML.src = "images/black.png";
}

body{
  font-family: 'Raleway', sans-serif;
  margin: 0;
  background: #87e0fd;
  background: -moz-linear-gradient(top, #87e0fd 0%, #53cbf1 74%, #05abe0 100%);
  background: -webkit-linear-gradient(top, #87e0fd 0%,#53cbf1 74%,#05abe0 100%);
  background: linear-gradient(to bottom, #87e0fd 0%,#53cbf1 74%,#05abe0 100%);
  filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#87e0fd', endColorstr='#05abe0',GradientType=0 );
}

#title{
  text-align: center;
  font-size: 96px;
  margin-bottom: 12px;
}

.boardpic{
  margin: 0;
  padding: 0;
  width: 32px;
  height: 32px;
}

#container{
  display: flex;
}

#board{
  border-color: black;
  border-width: 3px;
  border-radius: 3px;
  border-style: solid;
  background-color: white;
  padding: 3px;
  width: 512px;
  height: 512px;
  font-size: 0;
  margin: auto;
  margin-bottom: 12px;
}

#colorpicker{
  font-size: 0;
  border-color: black;
  border-width: 3px;
  border-radius: 3px;
  border-style: solid;
  width: 256px;
  margin: auto;
}

    <title>
      Drawify | 0.0.1
    </title>
    <link rel="stylesheet" type="text/css" href="styles.css">
    <link href="https://fonts.googleapis.com/css?family=Raleway:700" rel="stylesheet">

      Drawify

Whenever I click, the box doesn't change

I was pretty sure I was setting it up all right, but I guess not. So yeah, I am quite new to coding, so please explain with simple terms. :)

Body:
Binding a function to each element inside the DOM isn't effective and looks messy. I would suggest you to catch every element with boardpic class and just bind event listener which changes the src attribute of clicked element.

var elems = document.getElementsByClassName('boardpic');
Array.from(elems).forEach(v => v.addEventListener('click', function() {
  this.src = 'https://placehold.it/350x150';
}));

body {
  font-family: 'Raleway', sans-serif;
  margin: 0;
  background: #87e0fd;
  background: -moz-linear-gradient(top, #87e0fd 0%, #53cbf1 74%, #05abe0 100%);
  background: -webkit-linear-gradient(top, #87e0fd 0%, #53cbf1 74%, #05abe0 100%);
  background: linear-gradient(to bottom, #87e0fd 0%, #53cbf1 74%, #05abe0 100%);
  filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#87e0fd', endColorstr='#05abe0', GradientType=0);
}

#title {
  text-align: center;
  font-size: 96px;
  margin-bottom: 12px;
}

.boardpic {
  margin: 0;
  padding: 0;
  width: 32px;
  height: 32px;
}

#container {
  display: flex;
}

#board {
  border-color: black;
  border-width: 3px;
  border-radius: 3px;
  border-style: solid;
  background-color: white;
  padding: 3px;
  width: 512px;
  height: 512px;
  font-size: 0;
  margin: auto;
  margin-bottom: 12px;
}

#colorpicker {
  font-size: 0;
  border-color: black;
  border-width: 3px;
  border-radius: 3px;
  border-style: solid;
  width: 256px;
  margin: auto;
}

<h1 id="title">
  Drawify
</h1>
<div id="container">
  <div id="board">
    <div class="line">
      <img class="boardpic" src="images/white.png" />
      <img class="boardpic" src="images/white.png" />
      <img class="boardpic" src="images/white.png" />
      <img class="boardpic" src="images/white.png" />
      <img class="boardpic" src="images/white.png" />
      <img class="boardpic" src="images/white.png" />
    </div>
  </div>
</div>


问:
android App closes with no error when imageview is clicked
I am creating a simple imageview with an id and trying to start an activity when it is clicked but when i click it in the emulator, the app just crashes and gives me (wait or close the app prompt)
here is my:

XML:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true"
android:orientation="vertical">

<ImageView
    android:id="@+id/about"
    android:layout_width="match_parent"
    android:layout_height="450dp"
    android:background="@color/colorPrimaryDark"
    android:src="@drawable/twoth" />

</LinearLayout>
</code>```

and here is my java code

```<code>public class MainUi extends AppCompatActivity {

    //Variables Declaration.
    private Button btn1, btn2, btn3, btn4;
    private ImageView img;

    //Called when the activity is first created.
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main_ui);
        //Variables Initialization and OnClick Method

        img = (ImageView) findViewById(R.id.about);
        img.setOnClickListener(new View.OnClickListener() {
            public void onClick(View arg0) {
                //Start another activity
                Intent myIntent = new Intent(MainUi.this, Query.class);
                startActivity(myIntent);
            }
        });

    }

}
</code>```

答:
here is the full code, I added the rest of the code just in case you can handle it from the outer (Query) class and not within Async Class.</p>

```<code>public class Query extends AppCompatActivity {
    private ArrayList<String[]> BB;
    private ArrayList<String[]> AA = new ArrayList<String[]>();
    private Socket socket = null;
    private ObjectInputStream in = null;
    private DataOutputStream out = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_query);
        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }
        try {
            AA = new AsyncAction().execute().get();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            setTextViews();

        }
    }

    public void setTextViews() {
        View linearLayout = findViewById(R.id.info);
        for (int y = 0; y < AA.size(); y++) {
            // for (int x = 0; x < AA.get(0).length; x++) {}
            TextView name = new TextView(this);
            name.setText(AA.get(y)[0]);
            name.setId(y);
            name.setGravity(Gravity.CENTER);
            name.setTextSize(30);
            name.setPadding(0, 30, 0, 0);
            name.setTextColor(this.getResources().getColor(R.color.icons));
            name.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, 0));

            ProgressBar pb = new ProgressBar(this, null, android.R.attr.progressBarStyleHorizontal);
            Drawable drawable = pb.getProgressDrawable();
            drawable.setColorFilter(new LightingColorFilter(0xFF000000, this.getResources().getColor(R.color.colorPrimary)));
            pb.setProgress(100);

            final int finalY = y;
            name.setOnClickListener(new View.OnClickListener() {
                public void onClick(View arg0) {
                    Bundle b = new Bundle();
                    b.putStringArray("list", AA.get(finalY));
                    Intent i = new Intent(Query.this, Info.class);
                    i.putExtras(b);
                    startActivity(i);
                }
            });
            ((LinearLayout) linearLayout).addView(name);
            ((LinearLayout) linearLayout).addView(pb);

        }
    }

    private class AsyncAction extends AsyncTask<String, Void, ArrayList> {

        protected ArrayList doInBackground(String... args) {
            try {

                socket = new Socket(port, 8888);
                out = new DataOutputStream(socket.getOutputStream());
                in = new ObjectInputStream(socket.getInputStream());
//                action
                out.writeInt(2);
                try {

                    in = new ObjectInputStream(socket.getInputStream());
                    BB = (ArrayList<String[]>) in.readObject();

                    in.close();
                    socket.close();

                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            } catch (UnknownHostException e1) {
                e1.printStackTrace();
            } catch (IOException e1) {
                e1.printStackTrace();
            }

            return BB;//returns what you want to pass to the onPostExecute()
        }

        protected void onPostExecute(ArrayList result) {
            AA = result;

        }
    }
}
</code>```

Body:
I am creating a simple imageview with an id and trying to start an activity when it is clicked but when i click it in the emulator, the app just crashes and gives me (wait or close the app prompt)
here is my:

XML:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true"
android:orientation="vertical">

<ImageView
    android:id="@+id/about"
    android:layout_width="match_parent"
    android:layout_height="450dp"
    android:background="@color/colorPrimaryDark"
    android:src="@drawable/twoth" />

</LinearLayout>

and here is my java code

public class MainUi extends AppCompatActivity {

    //Variables Declaration.
    private Button btn1, btn2, btn3, btn4;
    private ImageView img;

    //Called when the activity is first created.
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main_ui);
        //Variables Initialization and OnClick Method

        img = (ImageView) findViewById(R.id.about);
        img.setOnClickListener(new View.OnClickListener() {
            public void onClick(View arg0) {
                //Start another activity
                Intent myIntent = new Intent(MainUi.this, Query.class);
                startActivity(myIntent);
            }
        });

    }

}

Body:
here is the full code, I added the rest of the code just in case you can handle it from the outer (Query) class and not within Async Class.

public class Query extends AppCompatActivity {
    private ArrayList<String[]> BB;
    private ArrayList<String[]> AA = new ArrayList<String[]>();
    private Socket socket = null;
    private ObjectInputStream in = null;
    private DataOutputStream out = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_query);
        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }
        try {
            AA = new AsyncAction().execute().get();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            setTextViews();

        }
    }

    public void setTextViews() {
        View linearLayout = findViewById(R.id.info);
        for (int y = 0; y < AA.size(); y++) {
            // for (int x = 0; x < AA.get(0).length; x++) {}
            TextView name = new TextView(this);
            name.setText(AA.get(y)[0]);
            name.setId(y);
            name.setGravity(Gravity.CENTER);
            name.setTextSize(30);
            name.setPadding(0, 30, 0, 0);
            name.setTextColor(this.getResources().getColor(R.color.icons));
            name.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, 0));

            ProgressBar pb = new ProgressBar(this, null, android.R.attr.progressBarStyleHorizontal);
            Drawable drawable = pb.getProgressDrawable();
            drawable.setColorFilter(new LightingColorFilter(0xFF000000, this.getResources().getColor(R.color.colorPrimary)));
            pb.setProgress(100);

            final int finalY = y;
            name.setOnClickListener(new View.OnClickListener() {
                public void onClick(View arg0) {
                    Bundle b = new Bundle();
                    b.putStringArray("list", AA.get(finalY));
                    Intent i = new Intent(Query.this, Info.class);
                    i.putExtras(b);
                    startActivity(i);
                }
            });
            ((LinearLayout) linearLayout).addView(name);
            ((LinearLayout) linearLayout).addView(pb);

        }
    }

    private class AsyncAction extends AsyncTask<String, Void, ArrayList> {

        protected ArrayList doInBackground(String... args) {
            try {

                socket = new Socket(port, 8888);
                out = new DataOutputStream(socket.getOutputStream());
                in = new ObjectInputStream(socket.getInputStream());
//                action
                out.writeInt(2);
                try {

                    in = new ObjectInputStream(socket.getInputStream());
                    BB = (ArrayList<String[]>) in.readObject();

                    in.close();
                    socket.close();

                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            } catch (UnknownHostException e1) {
                e1.printStackTrace();
            } catch (IOException e1) {
                e1.printStackTrace();
            }

            return BB;//returns what you want to pass to the onPostExecute()
        }

        protected void onPostExecute(ArrayList result) {
            AA = result;

        }
    }
}


问:
Custom login password check with Laravel 5.4
If a user tries to log into my Laravel application and the password won't match with the "password" column in the database, I want to check it against another password column ("old_system_password") too.

I'm using the default Laravel authentication system, and as far as I understand I should be able to create a new "AuthController" and override the built in authentication methods. But I don't find any methods dealing with password matching in the vendor folder, and neither do I know how to tell Laravel to use my method instead of the default.

I've searched the web for this, but any solutions I find seems to be only for older versions of Laravel.

Any ideas?

答:
First Solution: Just override public function authenticate() in LoginController.php

```<code>public function authenticate()
{
    if (Auth::attempt(['email' => $email, 'password' => $password])) {
        // Authentication passed...
        return redirect()->intended('dashboard');
    } else if(Auth::attempt(['email' => $email, 'password' => $old_password]) {
        return redirect()->intended('dashboard');
    }
}
</code>```

Check :https://laravel.com/docs/5.4/authentication#authenticating-users

Second Solution:

1:Run php artisan event:generate to generate laravel events.

2:Run php artisan make:event CheckOldPassword

3:Add Event in EventServiceProvider.php 'Illuminate\Auth\Events\Failed' => ['App\Listeners\CheckOldPassword'],

4:Create function public function handle(Failed $event){}

5:Manually check logins in event.

Body:
First Solution: Just override public function authenticate() in LoginController.php

public function authenticate()
{
    if (Auth::attempt(['email' => $email, 'password' => $password])) {
        // Authentication passed...
        return redirect()->intended('dashboard');
    } else if(Auth::attempt(['email' => $email, 'password' => $old_password]) {
        return redirect()->intended('dashboard');
    }
}

Check :https://laravel.com/docs/5.4/authentication#authenticating-users

Second Solution:

1:Run php artisan event:generate to generate laravel events.

2:Run php artisan make:event CheckOldPassword

3:Add Event in EventServiceProvider.php 'Illuminate\Auth\Events\Failed' => ['App\Listeners\CheckOldPassword'],

4:Create function public function handle(Failed $event){}

5:Manually check logins in event.


问:
Node.js API to spawn off a call to another API
I created a Node.js API.
When this API gets called I return to the caller fairly quickly.  Which is good.

But now I also want API to call or launch an different API or function or something that will go off and run on it's own. Kind of like calling a child process with child.unref().  In fact, I would use child.spawn() but I don't see how to have spawn() call another API.  Maybe that alone would be my answer?

Of this other process, I don't care if it crashes or finishes without error.
 So it doesn't need to be attached to anything.  But if it does remain attached to the Node.js console then icing on the cake.

I'm still thinking about how to identify & what to do if the spawn somehow gets caught up in running a really long time.  But ready to cross that part of this yet.

Your thoughts on what I might be able to do?

答:
You need to specify exactly what the other spawned thing is supposed to do.  If it is calling an HTTP API, with Node.js you should not launch a new process to do that.  Node is built to run HTTP requests asynchronously.

The normal pattern, if you really need some stuff to happen in a different process, is to use something like a message queue, the cluster module, or other messaging/queue between processes that the worker will monitor, and the worker is usually set up to handle some particular task or set of tasks this way.  It is pretty unusual to be spawning another process after receiving an HTTP request since launching new processes is pretty heavy-weight and can use up all of your server resources if you aren't careful, and due to Node's async capabilities usually isn't necessary especially for things mainly involving IO.


问:
Polling Laravel Queue after All Jobs are Complete
Are there any best practices for identifying when jobs/workers finish processing a Laravel queue?  The only approach I can think of is to poll the jobs table to see when there are no more jobs in the queue.

The challenge I have is that I'll periodically dispatch 1,000 jobs to the queue and then some time later another 1,000 and then another.  I'd like to be able to trigger an event once each batch of jobs is complete, if possible.

Thanks for any suggestions or pointers.

答:
No, there is no such functionality. However, it's simple to implement by listening for the Illuminate\Queue\Events\Looping event (was illuminate.queue.looping before Laravel 5.4) and check the queue size.

```<code><?php

use Illuminate\Contracts\Events\Dispatcher;
use Illuminate\Queue\Events\Looping;

class QueueSizeCheckerAndEventThingieSubscriber {

    public function subscribe(Dispatcher $events) {
        $events->listen(Looping::class, self::class . '@onQueueLoop'); // >= 5.4
        $events->listen('illuminate.queue.looping', self::class . '@onQueueLoop'); // < 5.4
    }

    public function onQueueLoop() {
        $queueName = 'my-queue';
        $queueSize = Queue::size($queueName);

        if ($queueSize === 0) {
            // Trigger your event.
        }
    }

}
</code>```

Body:
No, there is no such functionality. However, it's simple to implement by listening for the Illuminate\Queue\Events\Looping event (was illuminate.queue.looping before Laravel 5.4) and check the queue size.

<?php

use Illuminate\Contracts\Events\Dispatcher;
use Illuminate\Queue\Events\Looping;

class QueueSizeCheckerAndEventThingieSubscriber {

    public function subscribe(Dispatcher $events) {
        $events->listen(Looping::class, self::class . '@onQueueLoop'); // >= 5.4
        $events->listen('illuminate.queue.looping', self::class . '@onQueueLoop'); // < 5.4
    }

    public function onQueueLoop() {
        $queueName = 'my-queue';
        $queueSize = Queue::size($queueName);

        if ($queueSize === 0) {
            // Trigger your event.
        }
    }

}


问:
I can't get my drawing on the canvas as its own function
So in my class we're learning how to make animations in HTML5. we were given a sample of just 4 shapes and So I made a cloud. However, as you see, there is a function drawCircle();, and if I put the code to draw my cloud under that, it will appear in the canvas, but if i make a function drawCloud();, it won't show up at all. I even call the function at the end of the code and still nothing. Anyone know why or how to fix this?

```<code><!DOCTYPE html>
<!-- Demonstrates canvas drawing using drawing methods -->
<html>
<body style="text-align:center">
  <h1>HTML5 Canvas Drawing</h1>
  <canvas id="myCanvas" width="800" height="500" style="border:2px solid #BBBBBB;">
  </canvas>

    <script>
        var canv=document.getElementById("myCanvas");
        var c=canv.getContext("2d");

        var w = canv.width;
        var h = canv.height;

        function drawRectangle(){
            c.fillStyle="rgb(100,200, 240)";
            c.fillRect(100,100,200,200);

            c.strokeStyle="black";
            c.lineWidth=4;
            c.strokeRect(100,100,200,200);
        }

//        function drawCircle(){
//            c.fillStyle="red";
//            c.strokeStyle="black";
//            c.lineWidth=2;
//            c.beginPath();
//            c.arc(550, 200, 100, 0, Math.PI*2);  //x, y, radius, start angle, end angle
//            c.closePath();
//            c.fill();
//            c.stroke();
//        }

        function drawCircle(){
            c.beginPath();
            c.moveTo(170, 80);
            c.bezierCurveTo(130, 100, 130, 150, 230, 150);
              c.bezierCurveTo(250, 180, 320, 180, 340, 150);
              c.bezierCurveTo(420, 150, 420, 120, 390, 100);
              c.bezierCurveTo(430, 40, 370, 30, 340, 50);
              c.bezierCurveTo(320, 5, 250, 20, 250, 50);
              c.bezierCurveTo(200, 5, 150, 20, 170, 80);

            // complete custom shape
              c.closePath();
              c.lineWidth = 5;
              c.strokeStyle = 'red';
              c.stroke();
        }

        function drawTriangle(){
            c.beginPath();
            c.lineWidth=3;
            c.strokeStyle="Blue";
            c.moveTo(200,350);
            c.lineTo(100,450);
            c.lineTo(300,450);
            c.lineTo(200,350);
            c.fillStyle="yellow";
            c.closePath();
            c.fill();
            c.stroke();
        }

    drawRectangle();
    drawCircle();
    drawArc();
    drawTriangle();
    drawCloud();

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

答:
The issue is, there isn't any function called drawCloud. You named the function drawCircle that is suppose to draw a cloud. Rename that function to drawCloud and comment out the actual drawCircle function. Also, there is no need to use closePath() method.

Here's the fixed version of your code

var canv = document.getElementById("myCanvas");
var c = canv.getContext("2d");
var w = canv.width;
var h = canv.height;

function drawRectangle() {
    c.fillStyle = "rgb(100,200, 240)";
    c.fillRect(100, 100, 200, 200);
    c.strokeStyle = "black";
    c.lineWidth = 4;
    c.strokeRect(100, 100, 200, 200);
}

function drawCircle() {
    c.fillStyle = "red";
    c.strokeStyle = "black";
    c.lineWidth = 2;
    c.beginPath();
    c.arc(550, 200, 100, 0, Math.PI * 2); //x, y, radius, start angle, end angle
    c.fill();
    c.stroke();
}

function drawCloud() {
    c.beginPath();
    c.moveTo(170, 80);
    c.bezierCurveTo(130, 100, 130, 150, 230, 150);
    c.bezierCurveTo(250, 180, 320, 180, 340, 150);
    c.bezierCurveTo(420, 150, 420, 120, 390, 100);
    c.bezierCurveTo(430, 40, 370, 30, 340, 50);
    c.bezierCurveTo(320, 5, 250, 20, 250, 50);
    c.bezierCurveTo(200, 5, 150, 20, 170, 80);
    // complete custom shape
    c.lineWidth = 5;
    c.strokeStyle = 'red';
    c.stroke();
}

function drawTriangle() {
    c.beginPath();
    c.lineWidth = 3;
    c.strokeStyle = "Blue";
    c.moveTo(200, 350);
    c.lineTo(100, 450);
    c.lineTo(300, 450);
    c.lineTo(200, 350);
    c.fillStyle = "yellow";
    c.fill();
    c.stroke();
}

drawRectangle();
drawCircle();
drawCloud();
drawTriangle();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><canvas id="myCanvas" width="800" height="500" style="border:2px solid #BBBBBB;"></canvas></code>```

Body:
So in my class we're learning how to make animations in HTML5. we were given a sample of just 4 shapes and So I made a cloud. However, as you see, there is a function drawCircle();, and if I put the code to draw my cloud under that, it will appear in the canvas, but if i make a function drawCloud();, it won't show up at all. I even call the function at the end of the code and still nothing. Anyone know why or how to fix this?

<!DOCTYPE html>

HTML5 Canvas Drawing

  <canvas id="myCanvas" width="800" height="500" style="border:2px solid #BBBBBB;">
  </canvas>

Body:
The issue is, there isn't any function called drawCloud. You named the function drawCircle that is suppose to draw a cloud. Rename that function to drawCloud and comment out the actual drawCircle function. Also, there is no need to use closePath() method.

Here's the fixed version of your code

var canv = document.getElementById("myCanvas");
var c = canv.getContext("2d");
var w = canv.width;
var h = canv.height;

function drawRectangle() {
    c.fillStyle = "rgb(100,200, 240)";
    c.fillRect(100, 100, 200, 200);
    c.strokeStyle = "black";
    c.lineWidth = 4;
    c.strokeRect(100, 100, 200, 200);
}

function drawCircle() {
    c.fillStyle = "red";
    c.strokeStyle = "black";
    c.lineWidth = 2;
    c.beginPath();
    c.arc(550, 200, 100, 0, Math.PI * 2); //x, y, radius, start angle, end angle
    c.fill();
    c.stroke();
}

function drawCloud() {
    c.beginPath();
    c.moveTo(170, 80);
    c.bezierCurveTo(130, 100, 130, 150, 230, 150);
    c.bezierCurveTo(250, 180, 320, 180, 340, 150);
    c.bezierCurveTo(420, 150, 420, 120, 390, 100);
    c.bezierCurveTo(430, 40, 370, 30, 340, 50);
    c.bezierCurveTo(320, 5, 250, 20, 250, 50);
    c.bezierCurveTo(200, 5, 150, 20, 170, 80);
    // complete custom shape
    c.lineWidth = 5;
    c.strokeStyle = 'red';
    c.stroke();
}

function drawTriangle() {
    c.beginPath();
    c.lineWidth = 3;
    c.strokeStyle = "Blue";
    c.moveTo(200, 350);
    c.lineTo(100, 450);
    c.lineTo(300, 450);
    c.lineTo(200, 350);
    c.fillStyle = "yellow";
    c.fill();
    c.stroke();
}

drawRectangle();
drawCircle();
drawCloud();
drawTriangle();

<canvas id="myCanvas" width="800" height="500" style="border:2px solid #BBBBBB;"></canvas>


问:
This class is not key value coding-compliant with @IBInspectable
I created a @IBDesignable on a custom view to set a property from IB. But i get this class is not key value coding-compliant despite i have that attribute in my class.

```<code>@IBDesignable class ExclusiveSelectorView: UIView {
    @IBInspectable var cellWidth: CGFloat?
}
</code>```

Failed to set (cellWidth) user defined inspected property on (Test.ExclusiveSelectorView): [ setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key cellWidth.

And this is my class

答:
You cannot define primitives as nullable for @IBInspectables.

When you attempt to do so, and set the value for one of these properties, you'll get the following warning at IBDesignable time:

@IBDesignable class TestDesignable
   IB Designables: Ignoring user defined runtime attribute for key path "testInt" on instance of "TestDesignable". Hit an exception when attempting to set its value: [ setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key testInt.

And at runtime, you'll get the following error:

Failed to set (testInt) user defined inspected property on (TestDesignable): [ setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key testInt.

To fix it, change it from an optional to non-optional, and give it some zero default value.

Invalid:

```<code>@IBDesignable class TestDesignable: UIView {
  @IBInspectable var testInt: Int? = nil // crash
  @IBInspectable var testFloat: CGFloat? = nil // crash
  @IBInspectable var testPoint: CGPoint? = nil // crash
  @IBInspectable var testColor: UIColor? = nil
}
</code>```

Valid:

```<code>@IBDesignable class TestDesignable: UIView {
  @IBInspectable var testInt: Int = 0
  @IBInspectable var testFloat: CGFloat = 0
  @IBInspectable var testPoint: CGPoint = .zero
  @IBInspectable var testColor: UIColor? = nil
}
</code>```

Body:
I created a @IBDesignable on a custom view to set a property from IB. But i get this class is not key value coding-compliant despite i have that attribute in my class.

@IBDesignable class ExclusiveSelectorView: UIView {
    @IBInspectable var cellWidth: CGFloat?
}

Failed to set (cellWidth) user defined inspected property on (Test.ExclusiveSelectorView): [ setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key cellWidth.

And this is my class

Body:
You cannot define primitives as nullable for @IBInspectables.

When you attempt to do so, and set the value for one of these properties, you'll get the following warning at IBDesignable time:

@IBDesignable class TestDesignable
   IB Designables: Ignoring user defined runtime attribute for key path "testInt" on instance of "TestDesignable". Hit an exception when attempting to set its value: [ setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key testInt.

And at runtime, you'll get the following error:

Failed to set (testInt) user defined inspected property on (TestDesignable): [ setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key testInt.

To fix it, change it from an optional to non-optional, and give it some zero default value.

Invalid:

@IBDesignable class TestDesignable: UIView {
  @IBInspectable var testInt: Int? = nil // crash
  @IBInspectable var testFloat: CGFloat? = nil // crash
  @IBInspectable var testPoint: CGPoint? = nil // crash
  @IBInspectable var testColor: UIColor? = nil
}

Valid:

@IBDesignable class TestDesignable: UIView {
  @IBInspectable var testInt: Int = 0
  @IBInspectable var testFloat: CGFloat = 0
  @IBInspectable var testPoint: CGPoint = .zero
  @IBInspectable var testColor: UIColor? = nil
}


问:
onClick method error & App crashes when I press the button
I have a simple app to increase and decrease a number with button press. but unfortunately my app crashes when I press the button. Here is the MainActivity.java code :

```<code>package com.example.sparker.asafool;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

int quantity = 1;

public void decrement(View view) {
    quantity = quantity - 1;
    displayIt(quantity);
}

public void increment(View view) {
    quantity = quantity + 1;
    displayIt(quantity);
}

public void displayIt(int xyz){
    TextView quantityTextView = (TextView)findViewById(R.id.textView);
    quantityTextView.setText(xyz);
}
</code>```

}

decrement and increment methods are in the xml file.

Here is the logcat:

答:
Eventually you have to convert int into String. You can't set integer on TextView. As from the logs you can see, here O.S. thinking you passed resource id of String resource which never found and it throw ResourceNotFoundException.

```<code>public void displayIt(int xyz) {
 TextView quantityTextView = (TextView)findViewById(R.id.textView);
 quantityTextView.setText(""+ xyz); // convert into String
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a simple app to increase and decrease a number with button press. but unfortunately my app crashes when I press the button. Here is the MainActivity.java code :

package com.example.sparker.asafool;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

int quantity = 1;

public void decrement(View view) {
    quantity = quantity - 1;
    displayIt(quantity);
}

public void increment(View view) {
    quantity = quantity + 1;
    displayIt(quantity);
}

public void displayIt(int xyz){
    TextView quantityTextView = (TextView)findViewById(R.id.textView);
    quantityTextView.setText(xyz);
}

}

decrement and increment methods are in the xml file.

Here is the logcat:

Body:
Eventually you have to convert int into String. You can't set integer on TextView. As from the logs you can see, here O.S. thinking you passed resource id of String resource which never found and it throw ResourceNotFoundException.

public void displayIt(int xyz) {
 TextView quantityTextView = (TextView)findViewById(R.id.textView);
 quantityTextView.setText(""+ xyz); // convert into String
}


问:
Systems.Timers.Timer works in debug, but not release
```<code>System.Timers.Timer timer= new System.Timers.Timer(1);
            timer.AutoReset = true;
            timer.Elapsed += (s, e) =>
            {
                Console.WriteLine("fired");
            };
timer.Start();
</code>```

The event is consistently fired in debug mode, and consistently not fired in release mode. I tried disabling compiler optimizations, but it didn't help.

I am trying to run this in an asp.net mvc application .net 4.6 framework

答:
Hope the following solution helps!

Problem:

The following code always works as expected by showing the current clock time.

```<code> class Program
 {
        static void TimerProcedure(object param)
        {
            Console.Clear();
            Console.WriteLine(DateTime.Now.TimeOfDay);

            GC.Collect();

        }

        static void Main(string[] args)
        {
            Console.Title = "Desktop Clock";
            Console.SetWindowSize(20, 2);
            Timer timer = new Timer(TimerProcedure, null,
                TimeSpan.Zero, TimeSpan.FromSeconds(1));
            Console.ReadLine();
        }
    }
</code>```

However, if you run the same code in release mode, it shows current time only for the first time but it never updates after that.

Solution

A simple tweak by adding GC.KeepAlive(object) will make it work in Release mode also as expected. Refer to code below.

```<code>class Program
    {
        static void TimerProcedure(object param)
        {
            Console.Clear();
            Console.WriteLine(DateTime.Now.TimeOfDay);
            #region Hidden
            GC.Collect();
            #endregion
        }

        static void Main(string[] args)
        {
            Console.Title = "Desktop Clock";
            Console.SetWindowSize(20, 2);
            Timer timer = new Timer(TimerProcedure, null,
                TimeSpan.Zero, TimeSpan.FromSeconds(1));
            Console.ReadLine();
            GC.KeepAlive(timer);
        }
    }
</code>```

Coming to your specific problem, verify if the scope of timer variable is local to a method. If that is true, you can keep it alive as shown above.

Alternate solution: is making timer a class level static variable

Body:
System.Timers.Timer timer= new System.Timers.Timer(1);
            timer.AutoReset = true;
            timer.Elapsed += (s, e) =>
            {
                Console.WriteLine("fired");
            };
timer.Start();

The event is consistently fired in debug mode, and consistently not fired in release mode. I tried disabling compiler optimizations, but it didn't help.

I am trying to run this in an asp.net mvc application .net 4.6 framework

Body:
Hope the following solution helps!

Problem:

The following code always works as expected by showing the current clock time.

 class Program
 {
        static void TimerProcedure(object param)
        {
            Console.Clear();
            Console.WriteLine(DateTime.Now.TimeOfDay);

            GC.Collect();

        }

        static void Main(string[] args)
        {
            Console.Title = "Desktop Clock";
            Console.SetWindowSize(20, 2);
            Timer timer = new Timer(TimerProcedure, null,
                TimeSpan.Zero, TimeSpan.FromSeconds(1));
            Console.ReadLine();
        }
    }

However, if you run the same code in release mode, it shows current time only for the first time but it never updates after that.

Solution

A simple tweak by adding GC.KeepAlive(object) will make it work in Release mode also as expected. Refer to code below.

class Program
    {
        static void TimerProcedure(object param)
        {
            Console.Clear();
            Console.WriteLine(DateTime.Now.TimeOfDay);
            #region Hidden
            GC.Collect();
            #endregion
        }

        static void Main(string[] args)
        {
            Console.Title = "Desktop Clock";
            Console.SetWindowSize(20, 2);
            Timer timer = new Timer(TimerProcedure, null,
                TimeSpan.Zero, TimeSpan.FromSeconds(1));
            Console.ReadLine();
            GC.KeepAlive(timer);
        }
    }

Coming to your specific problem, verify if the scope of timer variable is local to a method. If that is true, you can keep it alive as shown above.

Alternate solution: is making timer a class level static variable


问:
A helper named could not be found when trying to render component in Ember
I have the following router setup:

```<code>Router.map(function() {
  this.route("login");
  this.route("dashboard");
  this.route("projects", function() {
    this.route("show", {path: "/:project_id"});

    this.route('tasks', {path: "/:project_id/tasks" },function() {
      this.route('new', {path: "/new"});
      this.route('show', {path: "/:task_id"});
    });
  });
});
</code>```

And, in templates/projects/show.hbs, I'd like to render the component for creating a new task ( the component is automatically generated by ember, but I have my own template and controllers at controllers/projects/tasks/new.js and templates/projects/tasks/new.hbs  ). I tried the following:

```<code>  {{tasks/new model=model}}
</code>```

But I receive this error:

```<code>Assertion Failed: A helper named "tasks/new" could not be found
</code>```

What is the proper way of fixing this?

答:
{{tasks/new here task/new can be a Component or Helper but can't be template hbs.
If you want to include tasks/new inside templates/projects/show.hbs then I would encourage you to create component for tasks/new and include it where ever you require.

You can give it try by mentioning different templateName for template hbs. using templateName property.
Inside show.js route file define templateName: 'projects/tasks/new'

Body:
I have the following router setup:

Router.map(function() {
  this.route("login");
  this.route("dashboard");
  this.route("projects", function() {
    this.route("show", {path: "/:project_id"});

    this.route('tasks', {path: "/:project_id/tasks" },function() {
      this.route('new', {path: "/new"});
      this.route('show', {path: "/:task_id"});
    });
  });
});

And, in templates/projects/show.hbs, I'd like to render the component for creating a new task ( the component is automatically generated by ember, but I have my own template and controllers at controllers/projects/tasks/new.js and templates/projects/tasks/new.hbs  ). I tried the following:

  {{tasks/new model=model}}

But I receive this error:

Assertion Failed: A helper named "tasks/new" could not be found

What is the proper way of fixing this?


问:
Android button link to another page when login is correct
I have the code below that currently has a login of an id and password, when the link is clicked I want it to go to a profile page only if the login is correct, at the minute you can enter whatever you want or nothing at all and click Login and this will take you to the profile page. Can someone show me how I can improve my code so that the Login button will only link to the profile page if the login details are correct, according to what is in the database? I have more code that I can upload if you need it. Thanks

```<code>public class MainActivity extends ActionBarActivity {

EditText doctor_number, password;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    doctor_number = (EditText)findViewById(R.id.etDoctorNumber);
    password = (EditText)findViewById(R.id.etPassword);
    final Button btnLogin = (Button) findViewById(R.id.btnLogin);

    btnLogin.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            OnLogin(v);
            //Intent profileIntent = new Intent(MainActivity.this, Profile.class);
            //MainActivity.this.startActivity(profileIntent);
        }
    });
}

public void OnLogin(View view){
    String str_doctor_number = doctor_number.getText().toString();
    String str_password = password.getText().toString();
    String type = "Login";

    BackgroundWorker backgroundWorker = new BackgroundWorker(this);
    backgroundWorker.execute(type, str_doctor_number, str_password);
}
}
</code>```

====
BackgroundWorker.java

```<code>public class BackgroundWorker extends AsyncTask<String, Void, String> {
    Context context;
    AlertDialog alertDialog;
    BackgroundWorker (Context ctx){
        context = ctx;
     }

@Override
protected String doInBackground(String... params) {
    String type = params[0];
    String login_url = "";
    String register_url = "";
    if (type.equals("Login")) {
        try {
            String doctorNumber = params[1];
            String password = params[2];
            URL url = new URL(login_url);
            HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            OutputStream outputStream = httpURLConnection.getOutputStream();
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
            String post_data = URLEncoder.encode("doctor_number", "UTF-8")+"="+URLEncoder.encode(doctorNumber, "utf-8")+"&"
            +URLEncoder.encode("password", "UTF-8")+"="+URLEncoder.encode(password, "utf-8");
            bufferedWriter.write(post_data);
            bufferedWriter.flush();
            bufferedWriter.close();
            outputStream.close();
            InputStream inputStream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
            String result ="";
            String line ="";
            while ((line = bufferedReader.readLine()) != null){
                result += line;
            }
            bufferedReader.close();
            inputStream.close();
            httpURLConnection.disconnect();
            return result;
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    } else if (type.equals("Register")){
        try {
            String patient_name = params[1];
            String check_in_date = params[2];
            String room_number = params[3];
            String bed_number = params[4];
            String notes = params[5];
            URL url = new URL(register_url);
            HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            OutputStream outputStream = httpURLConnection.getOutputStream();
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
            String post_data = URLEncoder.encode("patient_name", "UTF-8")+"="+URLEncoder.encode(patient_name, "utf-8")+"&"
                    + URLEncoder.encode("check_in_date", "UTF-8")+"="+URLEncoder.encode(check_in_date, "utf-8")+"&"
                    + URLEncoder.encode("room_number", "UTF-8")+"="+URLEncoder.encode(room_number, "utf-8")+"&"
                    + URLEncoder.encode("bed_number", "UTF-8")+"="+URLEncoder.encode(bed_number, "utf-8")+"&"
                    + URLEncoder.encode("notes", "UTF-8")+"="+URLEncoder.encode(notes, "utf-8");
            bufferedWriter.write(post_data);
            bufferedWriter.flush();
            bufferedWriter.close();
            outputStream.close();
            InputStream inputStream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
            String result ="";
            String line ="";
            while ((line = bufferedReader.readLine()) != null){
                result += line;
            }
            bufferedReader.close();
            inputStream.close();
            httpURLConnection.disconnect();
            return result;
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return null;
}

@Override
protected void onPreExecute() {
    alertDialog = new AlertDialog.Builder(context).create();
    alertDialog.setTitle("Login status: ");
}

@Override
protected void onPostExecute(String result) {
    if (result.contains("Login Successful")){
        Intent profileIntent = new Intent(context, Profile.class);
        context.startActivity(profileIntent);
    } else {
        alertDialog.setMessage(result);
        alertDialog.show();
    }
}

@Override
protected void onProgressUpdate(Void... values) {
    super.onProgressUpdate(values);
}
}
</code>```

答:
Your java code seems fine so try putting this in your php file at the end of it</p>

```<code>mysqli_close($db);
  exit();
</code>```

Body:
I have the code below that currently has a login of an id and password, when the link is clicked I want it to go to a profile page only if the login is correct, at the minute you can enter whatever you want or nothing at all and click Login and this will take you to the profile page. Can someone show me how I can improve my code so that the Login button will only link to the profile page if the login details are correct, according to what is in the database? I have more code that I can upload if you need it. Thanks

public class MainActivity extends ActionBarActivity {

EditText doctor_number, password;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    doctor_number = (EditText)findViewById(R.id.etDoctorNumber);
    password = (EditText)findViewById(R.id.etPassword);
    final Button btnLogin = (Button) findViewById(R.id.btnLogin);

    btnLogin.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            OnLogin(v);
            //Intent profileIntent = new Intent(MainActivity.this, Profile.class);
            //MainActivity.this.startActivity(profileIntent);
        }
    });
}

public void OnLogin(View view){
    String str_doctor_number = doctor_number.getText().toString();
    String str_password = password.getText().toString();
    String type = "Login";

    BackgroundWorker backgroundWorker = new BackgroundWorker(this);
    backgroundWorker.execute(type, str_doctor_number, str_password);
}
}

====
BackgroundWorker.java

public class BackgroundWorker extends AsyncTask<String, Void, String> {
    Context context;
    AlertDialog alertDialog;
    BackgroundWorker (Context ctx){
        context = ctx;
     }

@Override
protected String doInBackground(String... params) {
    String type = params[0];
    String login_url = "";
    String register_url = "";
    if (type.equals("Login")) {
        try {
            String doctorNumber = params[1];
            String password = params[2];
            URL url = new URL(login_url);
            HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            OutputStream outputStream = httpURLConnection.getOutputStream();
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
            String post_data = URLEncoder.encode("doctor_number", "UTF-8")+"="+URLEncoder.encode(doctorNumber, "utf-8")+"&"
            +URLEncoder.encode("password", "UTF-8")+"="+URLEncoder.encode(password, "utf-8");
            bufferedWriter.write(post_data);
            bufferedWriter.flush();
            bufferedWriter.close();
            outputStream.close();
            InputStream inputStream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
            String result ="";
            String line ="";
            while ((line = bufferedReader.readLine()) != null){
                result += line;
            }
            bufferedReader.close();
            inputStream.close();
            httpURLConnection.disconnect();
            return result;
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    } else if (type.equals("Register")){
        try {
            String patient_name = params[1];
            String check_in_date = params[2];
            String room_number = params[3];
            String bed_number = params[4];
            String notes = params[5];
            URL url = new URL(register_url);
            HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            OutputStream outputStream = httpURLConnection.getOutputStream();
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
            String post_data = URLEncoder.encode("patient_name", "UTF-8")+"="+URLEncoder.encode(patient_name, "utf-8")+"&"
                    + URLEncoder.encode("check_in_date", "UTF-8")+"="+URLEncoder.encode(check_in_date, "utf-8")+"&"
                    + URLEncoder.encode("room_number", "UTF-8")+"="+URLEncoder.encode(room_number, "utf-8")+"&"
                    + URLEncoder.encode("bed_number", "UTF-8")+"="+URLEncoder.encode(bed_number, "utf-8")+"&"
                    + URLEncoder.encode("notes", "UTF-8")+"="+URLEncoder.encode(notes, "utf-8");
            bufferedWriter.write(post_data);
            bufferedWriter.flush();
            bufferedWriter.close();
            outputStream.close();
            InputStream inputStream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
            String result ="";
            String line ="";
            while ((line = bufferedReader.readLine()) != null){
                result += line;
            }
            bufferedReader.close();
            inputStream.close();
            httpURLConnection.disconnect();
            return result;
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return null;
}

@Override
protected void onPreExecute() {
    alertDialog = new AlertDialog.Builder(context).create();
    alertDialog.setTitle("Login status: ");
}

@Override
protected void onPostExecute(String result) {
    if (result.contains("Login Successful")){
        Intent profileIntent = new Intent(context, Profile.class);
        context.startActivity(profileIntent);
    } else {
        alertDialog.setMessage(result);
        alertDialog.show();
    }
}

@Override
protected void onProgressUpdate(Void... values) {
    super.onProgressUpdate(values);
}
}

Body:
Your java code seems fine so try putting this in your php file at the end of it

mysqli_close($db);
  exit();


问:
Deselecting all cells in a collectionView while changing the visual state
I have a block of code that should deselect all cells in a collection view (myHobbiesCV), while updating their visual state based on cellForItemAt (just an alpha change! nothing crazy.)

All of the selected cells are added into a string array called: myHobbiesArraySelected. When a button is pressed [Deselect All Hobbies], it should wipe out the myHobbieArraySelected array, and change all of the cells to the unselected visual state.

```<code>@IBAction func deselectAllPressed(_ sender: UIButton) {
    let allSelected = myHobbiesCV.indexPathsForSelectedItems
    for deselect in allSelected! {
        print("deselected all")
        myHobbiesCV.deselectItem(at: deselect, animated: true)
        // This is essentially doing nothing :(
    }
    myHobbiesArraySelected.removeAll()
    print(myHobbiesArraySelected)
}
</code>```

It's clearing out the array with removeAll, however the visual state of the cells are not changing at all.

How can I change the cells visual state to unselected, along with wiping out the array?

答:
How about enumerate through all visible cells and change theirs appearance
 (If you want to deselect them anyway)?</p>

```<code>for cell in collectionView.visibleCells {
    // Change alpha
}
</code>```

Body:
I have a block of code that should deselect all cells in a collection view (myHobbiesCV), while updating their visual state based on cellForItemAt (just an alpha change! nothing crazy.)

All of the selected cells are added into a string array called: myHobbiesArraySelected. When a button is pressed [Deselect All Hobbies], it should wipe out the myHobbieArraySelected array, and change all of the cells to the unselected visual state.

@IBAction func deselectAllPressed(_ sender: UIButton) {
    let allSelected = myHobbiesCV.indexPathsForSelectedItems
    for deselect in allSelected! {
        print("deselected all")
        myHobbiesCV.deselectItem(at: deselect, animated: true)
        // This is essentially doing nothing :(
    }
    myHobbiesArraySelected.removeAll()
    print(myHobbiesArraySelected)
}

It's clearing out the array with removeAll, however the visual state of the cells are not changing at all.

How can I change the cells visual state to unselected, along with wiping out the array?

Body:
How about enumerate through all visible cells and change theirs appearance
 (If you want to deselect them anyway)?

for cell in collectionView.visibleCells {
    // Change alpha
}


问:
How not to calculate a value twice in select?
psql (9.6.1, server 9.5.5)

employees

```<code>     Column     |            Type             |                            Modifiers                            | Storage  | Stats target | Description
----------------+-----------------------------+-----------------------------------------------------------------+----------+--------------+----    ---------
 employee_id    | integer                     | not null default nextval('employees_employee_id_seq'::regclass) | plain    |              |
 first_name     | character varying(20)       |                                                                 | extended |              |
 last_name      | character varying(25)       | not null                                                        | extended |              |
 email          | character varying(25)       | not null                                                        | extended |              |
 phone_number   | character varying(20)       |                                                                 | extended |              |
 hire_date      | timestamp without time zone | not null                                                        | plain    |              |
 job_id         | character varying(10)       | not null                                                        | extended |              |
 salary         | numeric(8,2)                |                                                                 | main     |              |
 commission_pct | numeric(2,2)                |                                                                 | main     |              |
 manager_id     | integer                     |                                                                 | plain    |              |
 department_id  | integer
</code>```

I need to extract employee number, last name, salary, salary increased by 15.5 % (expressed as a whole number), and the difference between the new and old salary.

I have done like this:

```<code>select employee_id,
    last_name,
    salary,
    round(salary * 1.155, 0) as "New Salary",
    round(salary * 1.155, 0) - salary as "Increase"
from employees;
</code>```

What troubles me is that I have calculated the new salary twice.

I tried to use alias in the same select. Experimented like this:

```<code>select 2 as val_a, val_a - 4; --not working
</code>```

Well, my solution outputs acceptable result. But isn't there a better solution?

答:
That calculation is really nothing if you are worried about performance. Some optimizers may even reuse the calculations internally.

If you must do it yourself, you can use subquery like this:

```<code>select t.*,
    New_Salary - salary as Increase
from (
    select employee_id,
        last_name,
        salary,
        round(salary * 1.155, 0) as New_Salary,
    from employees
    ) t;
</code>```

Body:
psql (9.6.1, server 9.5.5)

employees

     Column     |            Type             |                            Modifiers                            | Storage  | Stats target | Description
----------------+-----------------------------+-----------------------------------------------------------------+----------+--------------+----    ---------
 employee_id    | integer                     | not null default nextval('employees_employee_id_seq'::regclass) | plain    |              |
 first_name     | character varying(20)       |                                                                 | extended |              |
 last_name      | character varying(25)       | not null                                                        | extended |              |
 email          | character varying(25)       | not null                                                        | extended |              |
 phone_number   | character varying(20)       |                                                                 | extended |              |
 hire_date      | timestamp without time zone | not null                                                        | plain    |              |
 job_id         | character varying(10)       | not null                                                        | extended |              |
 salary         | numeric(8,2)                |                                                                 | main     |              |
 commission_pct | numeric(2,2)                |                                                                 | main     |              |
 manager_id     | integer                     |                                                                 | plain    |              |
 department_id  | integer

I need to extract employee number, last name, salary, salary increased by 15.5 % (expressed as a whole number), and the difference between the new and old salary.

I have done like this:

select employee_id,
    last_name,
    salary,
    round(salary * 1.155, 0) as "New Salary",
    round(salary * 1.155, 0) - salary as "Increase"
from employees;

What troubles me is that I have calculated the new salary twice.

I tried to use alias in the same select. Experimented like this:

select 2 as val_a, val_a - 4; --not working

Well, my solution outputs acceptable result. But isn't there a better solution?

Body:
That calculation is really nothing if you are worried about performance. Some optimizers may even reuse the calculations internally.

If you must do it yourself, you can use subquery like this:

select t.*,
    New_Salary - salary as Increase
from (
    select employee_id,
        last_name,
        salary,
        round(salary * 1.155, 0) as New_Salary,
    from employees
    ) t;