Programs & Examples On #Deployment

A series of activities that makes a program available for use (usually in test or production environments)

How to deploy correctly when using Composer's develop / production switch?


There is IMHO a good reason why Composer will use the --dev flag by default (on install and update) nowadays. Composer is mostly run in scenario's where this is desired behavior:

The basic Composer workflow is as follows:

  • A new project is started: composer.phar install --dev, json and lock files are commited to VCS.
  • Other developers start working on the project: checkout of VCS and composer.phar install --dev.
  • A developer adds dependancies: composer.phar require <package>, add --dev if you want the package in the require-dev section (and commit).
  • Others go along: (checkout and) composer.phar install --dev.
  • A developer wants newer versions of dependencies: composer.phar update --dev <package> (and commit).
  • Others go along: (checkout and) composer.phar install --dev.
  • Project is deployed: composer.phar install --no-dev

As you can see the --dev flag is used (far) more than the --no-dev flag, especially when the number of developers working on the project grows.

Production deploy

What's the correct way to deploy this without installing the "dev" dependencies?

Well, the composer.json and composer.lock file should be committed to VCS. Don't omit composer.lock because it contains important information on package-versions that should be used.

When performing a production deploy, you can pass the --no-dev flag to Composer:

composer.phar install --no-dev

The composer.lock file might contain information about dev-packages. This doesn't matter. The --no-dev flag will make sure those dev-packages are not installed.

When I say "production deploy", I mean a deploy that's aimed at being used in production. I'm not arguing whether a composer.phar install should be done on a production server, or on a staging server where things can be reviewed. That is not the scope of this answer. I'm merely pointing out how to composer.phar install without installing "dev" dependencies.


The --optimize-autoloader flag might also be desirable on production (it generates a class-map which will speed up autoloading in your application):

composer.phar install --no-dev --optimize-autoloader

Or when automated deployment is done:

composer.phar install --no-ansi --no-dev --no-interaction --no-plugins --no-progress --no-scripts --optimize-autoloader

If your codebase supports it, you could swap out --optimize-autoloader for --classmap-authoritative. More info here

How do you migrate an IIS 7 site to another server?

I'd say export your server config in IIS manager:

  1. In IIS manager, click the Server node
  2. Go to Shared Configuration under "Management"
  3. Click “Export Configuration”. (You can use a password if you are sending them across the internet, if you are just gonna move them via a USB key then don't sweat it.)
  4. Move these files to your new server

  5. On the new server, go back to the “Shared Configuration” section and check “Enable shared configuration.” Enter the location in physical path to these files and apply them.

  6. It should prompt for the encryption password(if you set it) and reset IIS.

BAM! Go have a beer!

Deployment error:Starting of Tomcat failed, the server port 8080 is already in use

I resolved it by replacing Tomcat 8.5.* with Tomcat 7.0.* version.

How to automatically update an application without ClickOnce?

There are a lot of questions already about this, so I will refer you to those.

One thing you want to make sure to prevent the need for uninstallation, is that you use the same upgrade code on every release, but change the product code. These values are located in the Installshield project properties.

Some references:

The type initializer for 'CrystalDecisions.CrystalReports.Engine.ReportDocument' threw an exception

The type initializer for CrystalDecisions.CrystalReports.Engine.ReportDocument threw an exception.

I changed the target platform from x86 to Any CPU and it resolved the issue.

How to specify maven's distributionManagement organisation wide?

There's no need for a parent POM.

You can omit the distributionManagement part entirely in your poms and set it either on your build server or in settings.xml.

To do it on the build server, just pass to the mvn command:


See for details which options can be set.

It's also possible to set this in your settings.xml.

Just create a profile there which is enabled and contains the property.

Example settings.xml:




Make sure that credentials for "snapshots" and "releases" are in the <servers> section of your settings.xml

The properties altSnapshotDeploymentRepository and altReleaseDeploymentRepository are introduced with maven-deploy-plugin version 2.8. Older versions will fail with the error message

Deployment failed: repository element was not specified in the POM inside distributionManagement element or in -DaltDeploymentRepository=id::layout::url parameter

To fix this, you can enforce a newer version of the plug-in:


"Untrusted App Developer" message when installing enterprise iOS Application

For iOS 13.6

Go to settings -> General -> Device Management -> Click on Trust « Apple Development » -> Click on the red trust button and you’re all set! Enjoy

Hot deploy on JBoss - how do I make JBoss "see" the change?

Solution for Netbeans 8.02 and 8.1 IDE and JBOSS EAP 6.4:

  1. From the services tab of Netbeans, add JBOSS server to your "servers" node.
  2. If you are using MAVEN, netbeans compiles files and maven copies files to ./target directory. You need to create a symbolic link from .\target to JBOSS_HOME\standalone\deployments. Under windows, an example command would be

    cd %JBOSS_HOME%\standalone\deployments mklink /d MyWebApplication.war %PROJECTS_HOME%\MyWebApplication\target\MyWebApplication-1.0.0

    The above creates a symbolic link from %JBOSS_HOME%\standalone\deployments\MyWebApplication.war to \target\MyWebApplication-1.0.0 which is where maven transfers all files after compilation, or after a jsp, html or any other file changes.

  3. Last think to do is to create a CentralManagement.war.dodeploy file in %JBOSS_HOME%\standalone\deployments. This file will tell JBOSS to deploy the war "file" as a web application

How do I deploy Node.js applications as a single executable file?

JXcore will allow you to turn any nodejs application into a single executable, including all dependencies, in either Windows, Linux, or Mac OS X.

Here is a link to the installer:

And here is a link to how to set it up:

It is very easy to use and I have tested it in both Windows 8.1 and Ubuntu 14.04.

FYI: JXcore is a fork of NodeJS so it is 100% NodeJS compatible, with some extra features.

Enterprise app deployment doesn't work on iOS 7.1

Our team uses dropbox for ad-hoc distribution which uses https but still our app was failing to install. After much trouble-shooting we realized that the title field is required too. Whenever we sent out a link without this field safari ignored the link and did not prompt the user to install. Sometimes for quick development tests we skipped over the title node in the xml and not populate it. In case this is helpful for anyone having this issue make sure that your .plist contains the following nodes populated:

     <string>Your App Name</string>

Can not deserialize instance of java.lang.String out of START_OBJECT token

You're mapping this JSON

    "id": 2,
    "socket": "0c317829-69bf-43d6-b598-7c0c550635bb",
    "type": "getDashboard",
    "data": {
        "workstationUuid": "ddec1caa-a97f-4922-833f-632da07ffc11"
    "reply": true

that contains an element named data that has a JSON object as its value. You are trying to deserialize the element named workstationUuid from that JSON object into this setter.

public void setWorkstation(String workstationUUID) {

This won't work directly because Jackson sees a JSON_OBJECT, not a String.

Try creating a class Data

public class Data { // the name doesn't matter 
    private String workstationUuid;
    // getter and setter

the switch up your method

public void setWorkstation(Data data) {
    // use getter to retrieve it

Ant error when trying to build file, can't find tools.jar?

You need JDK for that.

Set JAVA_HOME to point to the JDK.

Git command to checkout any branch and overwrite local changes

The new git-switch command (starting in GIT 2.23) also has a flag --discard-changes which should help you. git pull might be necessary afterwards.

Warning: it's still considered to be experimental.

How do I copy directories recursively with gulp?

If you want to copy the entire contents of a folder recursively into another folder, you can execute the following windows command from gulp:

xcopy /path/to/srcfolder /path/to/destfolder /s /e /y

The /y option at the end is to suppress the overwrite confirmation message.

In Linux, you can execute the following command from gulp:

cp -R /path/to/srcfolder /path/to/destfolder

you can use gulp-exec or gulp-run plugin to execute system commands from gulp.

Related Links:

  1. xcopy usage

  2. gulp-exec and gulp-run

System.IO.FileNotFoundException: Could not load file or assembly 'X' or one of its dependencies when deploying the application

's up guys i read every single forum about this topic i still had problem (occurred trying to project from git)

after 4 hours and a lot of swearing i solved this issue by myself just by changing target framework setting in project properties (right click on project -> properties) -> application and changed target framework from .net core 3.0 to .net 5.0 i hope it will help anybody

happy coding gl hf nerds

Create a directly-executable cross-platform GUI app using Python

Since python is installed on nearly every non-Windows OS by default now, the only thing you really need to make sure of is that all of the non-standard libraries you use are installed.

Having said that, it is possible to build executables that include the python interpreter, and any libraries you use. This is likely to create a large executable, however.

MacOS X even includes support in the Xcode IDE for creating full standalone GUI apps. These can be run by any user running OS X.

Install windows service without InstallUtil.exe

Topshelf is an OSS project which was started after this question was answered and it makes Windows service much, MUCH easier.I highly recommend looking into it.

Causes of getting a java.lang.VerifyError

Minimal example that generates the error

One simple possibility is to use Jasmin, or to manually edit the bytecode with a binary file editor.

Lets create void method without a return instruction (generated by the return; statement in Java), which the JVMS says is illegal.

In Jasmin we could write:

.class public Main
.super java/lang/Object

.method public static main([Ljava/lang/String;)V
   aload_0 ; Just so that we won't get another verify error for empty code.
.end method

We then do javac Main.j and javap -v Main says that we have compiled:

public static void main(java.lang.String[]);
  descriptor: ([Ljava/lang/String;)V
    stack=1, locals=1, args_size=1
       0: aload_0

so really there is no return instruction.

Now if we try to run java Main we get:

Error: A JNI error has occurred, please check your installation and try again
Exception in thread "main" java.lang.VerifyError: (class: NoReturn, method: main signature: ([Ljava/lang/String;)V) Falling off the end of the code
        at java.lang.Class.getDeclaredMethods0(Native Method)
        at java.lang.Class.privateGetDeclaredMethods(
        at java.lang.Class.privateGetMethodRecursive(
        at java.lang.Class.getMethod0(
        at java.lang.Class.getMethod(
        at sun.launcher.LauncherHelper.validateMainClass(
        at sun.launcher.LauncherHelper.checkAndLoadMain(

This error can never happen in Java normally, since the Java compiler adds an implicit return to void methods for us. This is why we don't need to add a return to our main methods. You can check this with javap.


VerifyError happens when you try to run certain types of illegal class file as specified by JVMS 7 chapter 4.5

The JVMS says that when Java loads a file, it must run a series of checks to see that the class file is OK before running it.

Such errors cannot be generated on a single compile and run cycle of Java code, because JVMS 7 4.10 says:

Even though a compiler for the Java programming language must only produce class files that satisfy all the static and structural constraints [... ]

So to see a minimal failure example, we will need to generate the source code without javac.

Android Studio - local path doesn't exist

If your project is not a Gradle project,

And you got this "local path doesn't exist" error after updating Android Studio to 0.9.2+ version

You should open the .iml file of the project and remove this:

<facet type="android-gradle" name="Android-Gradle">
    <option name="GRADLE_PROJECT_PATH" />

It solved the problem for me.

Parser Error when deploy ASP.NET application

I've solve the issue. The solution is to not making virtual dir manualy and then copy app files here, but use 'Add Application...' option. Here is post that helped me

Deploy a project using Git push

I use two solutions for post-receive hook:


#  /git-repo/hooks/post-receive - file content on server (chmod as 755 to be executed)

    export GIT_DIR=/git/repo-bare.git
    export GIT_BRANCH1=master
    export GIT_TARGET1=/var/www/html
    export GIT_BRANCH2=dev
    export GIT_TARGET2=/var/www/dev
    echo "GIT DIR:  $GIT_DIR/"
    echo "GIT TARGET1:  $GIT_TARGET1/"
    echo "GIT BRANCH1:  $GIT_BRANCH1/"
    echo "GIT TARGET2:  $GIT_TARGET2/"
    echo "GIT BRANCH2:  $GIT_BRANCH2/"
    echo ""

    cd $GIT_DIR/

while read oldrev newrev refname
    branch=$(git rev-parse --abbrev-ref $refname)
    if [[ $branch =~ $BRANCH_REGEX ]] ; then
        export GIT_WORK_TREE=$GIT_TARGET1/.
        echo "Checking out branch: $branch";
        echo "Checking out to workdir: $GIT_WORK_TREE"; 

        git checkout -f $branch

    if [[ $branch =~ $BRANCH_REGEX ]] ; then
        export GIT_WORK_TREE=$GIT_TARGET2/.
        echo "Checking out branch: $branch";
        echo "Checking out to workdir: $GIT_WORK_TREE"; 

        git checkout -f $branch


#  /git-repo/hooks/post-receive - file content on server (chmod as 755 to be executed)

    export GIT_DIR=/git/repo-bare.git
    export GIT_BRANCH1=master
    export GIT_TARGET1=/var/www/html
    export GIT_BRANCH2=dev
    export GIT_TARGET2=/var/www/dev
    export GIT_TEMP_DIR1=/tmp/deploy1
    export GIT_TEMP_DIR2=/tmp/deploy2
    echo "GIT DIR:  $GIT_DIR/"
    echo "GIT TARGET1:  $GIT_TARGET1/"
    echo "GIT BRANCH1:  $GIT_BRANCH1/"
    echo "GIT TARGET2:  $GIT_TARGET2/"
    echo "GIT BRANCH2:  $GIT_BRANCH2/"
    echo "GIT TEMP DIR1:  $GIT_TEMP_DIR1/"
    echo "GIT TEMP DIR2:  $GIT_TEMP_DIR2/"
    echo ""

    cd $GIT_DIR/

while read oldrev newrev refname
    branch=$(git rev-parse --abbrev-ref $refname)
    if [[ $branch =~ $BRANCH_REGEX ]] ; then
        export GIT_WORK_TREE=$GIT_TARGET1/.
        echo "Checking out branch: $branch";
        echo "Checking out to workdir: $GIT_WORK_TREE"; 

        # DEPLOY SOLUTION 2: 
        cd $GIT_DIR/; mkdir -p $GIT_TEMP_DIR1; 
        export GIT_WORK_TREE=$GIT_TEMP_DIR1/.
        git checkout -f $branch
        export GIT_WORK_TREE=$GIT_TARGET1/.
        rsync $GIT_TEMP_DIR1/. -v -q --delete --delete-after -av $GIT_TARGET1/.
        rm -rf $GIT_TEMP_DIR1

    if [[ $branch =~ $BRANCH_REGEX ]] ; then
        export GIT_WORK_TREE=$GIT_TARGET2/.
        echo "Checking out branch: $branch";
        echo "Checking out to workdir: $GIT_WORK_TREE"; 

        # DEPLOY SOLUTION 2: 
        cd $GIT_DIR/; mkdir -p $GIT_TEMP_DIR2; 
        export GIT_WORK_TREE=$GIT_TEMP_DIR2/.
        git checkout -f $branch
        export GIT_WORK_TREE=$GIT_TARGET2/.
        rsync $GIT_TEMP_DIR2/. -v -q --delete --delete-after -av $GIT_TARGET2/.
        rm -rf $GIT_TEMP_DIR2

Both solutions are based on earlier solutions available in this thread.

Note, the BRANCH_REGEX='^${GIT_BRANCH1}.$' filters for the branch names matching "master" or "dev*" string, and deploys the work tree, if the pushed branch matches. This makes possible to deploy a dev version and master version to different places.

DEPLOY SOLUTION 1 removes only files, which are part of the repo, and was removed by a commit. It is faster than Deployment Solution 2.

DEPLOY SOLUTION 2 has the advantage, that it will remove any new files from the production directory, which was added on server side, no matter if it was added to the repo or not. It will be always clean dupe of the repo. It is slower than Deployment Solution 1.

Permission denied (publickey) when deploying heroku code. fatal: The remote end hung up unexpectedly

For all those who tried everything mentioned above on Windows 7 and still it didn't work, here is what I've done: - open GitBash.exe from the Git directory C:\Program Files (x86)\Git\ (don't open a command prompt, this won't work). - add the following as mentioned above, but you have to delete the #

Port 22 
IdentitiesOnly yes 
IdentityFile ~/.ssh/ssh-dss
TCPKeepAlive yes 
User [email protected]

now run git push heroku master and it should work.

Install a .NET windows service without InstallUtil.exe

In the case of trying to install a command line application as a Windows service try the 'NSSM' utility. Related ServerFault details found here.

error: This is probably not a problem with npm. There is likely additional logging output above

Novice mistake. Make sure your package.json file is coded correctly. I had:

"start": "index node.js"
instead of:
"start": "node index.js"


Delete your package-lock.json file and node_modules folder. Then do npm cache clean

npm cache clean --force do npm install

Error when deploying an artifact in Nexus

For 400 error, check the repository "Deployment policy" usually its "Disable redeploy". Most of the time your library version is already there that is why you received a message "Could not PUT put 'https://yoururl/some.jar'. Received status code 400 from server: Repository does not allow updating assets: "your repository name"

So, you have a few options to resolve this. 1- allow redeploy 2- delete the version from your repository which you are trying to upload 3- change the version number

Run command on the Ansible host

ansible your_server_name -i custom_inventory_file_name -m -a "uptime"

The default module is command module, hence command keyword is not required.

If you need to issue any command with elevated privileges use -b at the end of the same command.

ansible your_server_name -i custom_inventory_file_name -m -a "uptime" -b

/usr/bin/codesign failed with exit code 1

Kinda old question, but still happens it seems. Another solution:

Occurred for me after reverting a branch in git. Tried cleaning, cleaning builds, deleting derived and restarting Xcode, but no luck.

Try rebooting the comp.

FAIL - Application at context path /Hello could not be started

check web.xml file maybe servletContextlistener not doing well . in my case i added servletContextlistener and let him an empty and gave me the same error, i tried to delete it from project files but it still in web.xml file .finally i delete it from the web.xml and save the file . run the project and it stated successfully

Best way to deploy Visual Studio application that can run without installing

First you need to publish the file by:

  1. BUILD -> PUBLISH or by right clicking project on Solution Explorer -> properties -> publish or select project in Solution Explorer and press Alt + Enter NOTE: if you are using Visual Studio 2013 then in properties you have to go to BUILD and then you have to disable define DEBUG constant and define TRACE constant and you are ready to go. Representation

  2. Save your file to a particular folder. Find the produced files (the EXE file and the .config, .manifest, and .application files, along with any DLL files, etc.) - they are all in the same folder and typically in the bin\Debug folder below the project file (.csproj). In Visual Studio they are in the Application Files folder and inside that you just need the .exe and dll files. (You have to delete ClickOnce and other files and then make this folder a zip file and distribute it.)

NOTE: The ClickOnce application does install the project to system, but it has one advantage. You DO NOT require administrative privileges here to run (if your application follows the normal guidelines for which folders to use for application data, etc.).

ERROR Could not load file or assembly 'AjaxControlToolkit' or one of its dependencies

Might sound obvious but do you definitely have AjaxControlToolkit.dll in your bin?

Heroku deployment error H10 (App crashed)

I had H10 with Heroku and Node due to wrong name of the main code file. Edit package.json:



  "main": "correct_file_name.js",


  "scripts": {
    "start": "node correct_file_name.js"

Or rename the file.

Deploying Maven project throws invalid LOC header (bad signature)

You need to check which jar is giving problem. It must be corrupted. Delete that jar and run mvn spring-boot:run command again. May be more that one jar has corrupted so every time you need to run that command to delete that jar. In my case mysql, jackson, aspect jars was corrupted mvn spring-boot:run command 3 times and I figure out this and deleted the jars from .m2 folder. Now the issue has resolved.

How to manage local vs production settings in Django?

Making multiple versions of is an anti pattern for 12 Factor App methodology. use python-decouple or django-environ instead.

.war vs .ear file

war - web archive. It is used to deploy web applications according to the servlet standard. It is a jar file containing a special directory called WEB-INF and several files and directories inside it (web.xml, lib, classes) as well as all the HTML, JSP, images, CSS, JavaScript and other resources of the web application

ear - enterprise archive. It is used to deploy enterprise application containing EJBs, web applications, and 3rd party libraries. It is also a jar file, it has a special directory called APP-INF that contains the application.xml file, and it contains jar and war files.

How do I update a Tomcat webapp without restarting the entire service?

In conf directory of apache tomcat you can find context.xml file. In that edit tag as <Context reloadable="true">. this should solve the issue and you need not restart the server

Android device chooser - My device seems offline

I found that my Pantech Burst had a problem similar to what you all described. After reading through many such posts everywhere I noticed many people reported having to use a USB cable that they got else where other than the phone manufacturer. What I decided to do was use a different USB port on my PC and the problem was fixed. My Pantech Burst does not go offline in the middle of a debug session any more. The port I used to use was the front port on my box, but it was wired to the motherboard without shielding inside the box. Now I use the port on the back of the box that is directly attached to the motherboard.

repository element was not specified in the POM inside distributionManagement element or in -DaltDep loymentRepository=id::layout::url parameter

In your pom.xml you should add distributionManagement configuration to where to deploy.

In the following example I have used file system as the locations.

         <name>Internal repo</name>

you can add another location while deployment by using the following command (but to avoid above error you should have at least 1 repository configured) :

mvn deploy -DaltDeploymentRepository=internal.repo::default::file:///home/thara/testesb/in

Checking out Git tag leads to "detached HEAD state"

Yes, it is normal. This is because you checkout a single commit, that doesnt have a head. Especially it is (sooner or later) not a head of any branch.

But there is usually no problem with that state. You may create a new branch from the tag, if this makes you feel safer :)

How to resolve Error listenerStart when deploying web-app in Tomcat 5.5?

I encountered this error when the JDK that I compiled the app under was different from the tomcat JVM. I verified that the Tomcat manager was running jvm 1.6.0 but the app was compiled under java 1.7.0.

After upgrading Java and changing JAVA_HOME in our startup script (/etc/init.d/tomcat) the error went away.

What are some good SSH Servers for windows?

You can run OpenSSH on Cygwin, and even install it as a Windows service.

I once used it this way to easily add backups of a Unix system - it would rsync a bunch of files onto the Windows server, and the Windows server had full tape backups.

how to upload a file to my server using html

You need enctype="multipart/form-data" otherwise you will load only the file name and not the data.

Get value of input field inside an iframe


Accessing session from TWIG template

I found that the cleanest way to do this is to create a custom TwigExtension and override its getGlobals() method. Rather than using $_SESSION, it's also better to use Symfony's Session class since it handles automatically starting/stopping the session.

I've got the following extension in /src/AppBundle/Twig/AppExtension.php:

namespace AppBundle\Twig;

use Symfony\Component\HttpFoundation\Session\Session;

class AppExtension extends \Twig_Extension {

    public function getGlobals() {
        $session = new Session();
        return array(
            'session' => $session->all(),

    public function getName() {
        return 'app_extension';

Then add this in /app/config/services.yml:

        class: AppBundle\Twig\AppExtension
        public: false
            - { name: twig.extension }

Then the session can be accessed from any view using:

{{ session.my_variable }}

Rebuild or regenerate 'ic_launcher.png' from images in Android Studio

Use the website mentioned in previous posts to create the icons: Unzip folder and Go into you file explorer on (windows or mac) find AndroidStudioProjects > "app name" > app > src > main (replace the web one here)> res (replace the rest with the one from the unzipped folder the you already downloaded)

*Close android studio so that you can make changes and when android studio is opened again the changes will appear

Where does Vagrant download its .box files to?

On Windows 10 with Vagrant 2.2.2, setting the environment variable VAGRANT_HOME will ensure that boxes are downloaded to a subfolder of the folder specified for VAGRANT_HOME.

In my case I set VAGRANT_HOME to e:\vagrant_home, and the boxes get stored under e:\vagrant_home\boxes.

This works for me.

That's where the boxes are stored. The virtual machines are being created in the folder configured in Virtual Box. To set the VirtualBox VM storage folder, go to: VirtualBox GUI --> File --> Preferences --> General --> Default Machine Folder.

CSS: create white glow around image

Depends on what your target browsers are. In newer ones it's as simple as:

   -moz-box-shadow: 0 0 5px #fff;
-webkit-box-shadow: 0 0 5px #fff;
        box-shadow: 0 0 5px #fff;

For older browsers you have to implement workarounds, e.g., based on this example, but you will most probably need extra mark-up.

PHP: If internet explorer 6, 7, 8 , or 9

I do this


$isIE7  = (bool)preg_match('/msie 7./i', $u );
$isIE8  = (bool)preg_match('/msie 8./i', $u );
$isIE9  = (bool)preg_match('/msie 9./i', $u );
$isIE10 = (bool)preg_match('/msie 10./i', $u );

if ($isIE9) {
    //do ie9 stuff

if...else within JSP or JSTL

You can write if-else condition inside <% %> in jsp pages and html code outside of <% %>

For example:

        String username = (String)session.getAttribute("username");
        if(username==null)  {
        <p> username is null</p> //html code
        } else {
        <p> username is not null</p> //html code

Fatal error: Call to undefined function sqlsrv_connect()

First check that the extension is properly loaded in phpinfo(); (something like sqlsrv should appear). If not, the extension isn't properly loaded. You also need to restart apache after installing an extension.

Can I exclude some concrete urls from <url-pattern> inside <filter-mapping>?

I have encounterd the same issue, but I find a anwser showing below.


 <!-- set this param value for the filter-->

strFreePages = config.getInitParameter("freePages"); //get the exclue pattern from config file
isFreePage(strRequestPage)  //decide the exclude path

this way you don't have to harass the concrete Filter class.

increase legend font size ggplot2

You can use theme_get() to display the possible options for theme. You can control the legend font size using:

+ theme(legend.text=element_text(size=X))

replacing X with the desired size.

How does HTTP file upload work?

Let's take a look at what happens when you select a file and submit your form (I've truncated the headers for brevity):

POST /upload?upload_progress_id=12344 HTTP/1.1
Host: localhost:3000
Content-Length: 1325
Origin: http://localhost:3000
... other headers ...
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryePkpFF7tjBAqx29L

Content-Disposition: form-data; name="MAX_FILE_SIZE"

Content-Disposition: form-data; name="uploadedfile"; filename="hello.o"
Content-Type: application/x-object

... contents of file goes here ...

NOTE: each boundary string must be prefixed with an extra --, just like in the end of the last boundary string. The example above already includes this, but it can be easy to miss. See comment by @Andreas below.

Instead of URL encoding the form parameters, the form parameters (including the file data) are sent as sections in a multipart document in the body of the request.

In the example above, you can see the input MAX_FILE_SIZE with the value set in the form, as well as a section containing the file data. The file name is part of the Content-Disposition header.

The full details are here.

How can I clear the Scanner buffer in Java?

Other people have suggested using in.nextLine() to clear the buffer, which works for single-line input. As comments point out, however, sometimes input can be multi-line.

You can instead create a new Scanner object where you want to clear the buffer if you are using and not some other InputStream.

in = new Scanner(;

If you do this, don't call in.close() first. Doing so will close, and so you will get NoSuchElementExceptions on subsequent calls to in.nextInt(); probably shouldn't be closed during your program.

(The above approach is specific to It might not be appropriate for other input streams.)

If you really need to close your Scanner object before creating a new one, this StackOverflow answer suggests creating an InputStream wrapper for that has its own close() method that doesn't close the wrapped stream. This is overkill for simple programs, though.

Using Rsync include and exclude options to include directory and file by pattern

The problem is that --exclude="*" says to exclude (for example) the 1260000000/ directory, so rsync never examines the contents of that directory, so never notices that the directory contains files that would have been matched by your --include.

I think the closest thing to what you want is this:

rsync -nrv --include="*/" --include="file_11*.jpg" --exclude="*" /Storage/uploads/ /website/uploads/

(which will include all directories, and all files matching file_11*.jpg, but no other files), or maybe this:

rsync -nrv --include="/[0-9][0-9][0-9]0000000/" --include="file_11*.jpg" --exclude="*" /Storage/uploads/ /website/uploads/

(same concept, but much pickier about the directories it will include).

Adding options to a <select> using jQuery?


mySelect.innerHTML+= '<option value=1>My option</option>';

btn.onclick= _=> mySelect.innerHTML+= `<option selected>${+new Date}</option>`
<button id="btn">Add option</button>

<select id="mySelect"></select>

How to implement HorizontalScrollView like Gallery?

I have created a horizontal ListView in every row of ListView if you want single You can do the following

Here I am just creating horizontalListView of Thumbnail of Videos Like this

enter image description here

The idea is just continuously add the ImageView to the child of LinearLayout in HorizontalscrollView

Note: remember to fire .removeAllViews(); before next time load other wise it will add duplicate child

Cursor mImageCursor = db.getPlaylistVideoImage(playlistId);
if (mImageCursor != null && mImageCursor.getCount() > 0) {
    for (int index = 0; index < mImageCursor.getCount(); index++) {
        ImageView iv = (ImageView) imageViewInfalter.inflate(
            R.layout.image_view, null);
                    name = mImageCursor.getString(mImageCursor
        logoFile = new File(MyApplication.LOCAL_LOGO_PATH, name);
                    if (logoFile.exists()) {    
                Uri uri = Uri.fromFile(logoFile);
    mImageCursor = null;
    } else {
        ImageView iv = (ImageView) imageViewInfalter.inflate(
                    R.layout.image_view, null);
        String name = "";
        File logoFile;
        name = mImageCursor.getString(mImageCursor
        logoFile = new File(MyApplication.LOCAL_LOGO_PATH, name);
        if (logoFile.exists()) {
            Uri uri = Uri.fromFile(logoFile);

My xml for HorizontalListView

    android:paddingTop="@dimen/Playlist_TopBottom_margin" >

        android:orientation="horizontal" >

and Also my Image View as each child

<?xml version="1.0" encoding="utf-8"?>
<ImageView xmlns:android=""

    android:src="@drawable/loading" />

To learn More you can follow the following links which have some easy samples

  2. Horizontal ListView in Android?

error: function returns address of local variable

Neither malloc or call by reference are needed. You can declare a pointer within the function and set it to the string/array you'd like to return.

Using @Gewure's code as the basis:

char *getStringNoMalloc(void){
    char string[100] = {};
    char *s_ptr = string;

    strcat(string, "bla");
    strcat(string, "/");
    strcat(string, "blub");
    //INSIDE this function "string" is OK
    printf("string : '%s'\n", string);

    return s_ptr; 

works perfectly.

With a non-loop version of the code in the original question:

char *foo(int x){    
    char a[1000];
    char *a_ptr = a;
    char *b = "blah";       

    strcpy(a, b);

    return a_ptr;

Why I'm getting 'Non-static method should not be called statically' when invoking a method in a Eloquent model?

I've literally just arrived at the answer in my case. I'm creating a system that has implemented a create method, so I was getting this actual error because I was accessing the overridden version not the one from Eloquent.

Hope that help?

AngularJS custom filter function

You can use it like this:

Like you found, filter accepts predicate function which accepts item by item from the array. So, you just have to create an predicate function based on the given criteria.

In this example, criteriaMatch is a function which returns a predicate function which matches the given criteria.


<div ng-repeat="item in items | filter:criteriaMatch(criteria)">
  {{ item }}


$scope.criteriaMatch = function( criteria ) {
  return function( item ) {
    return ===;

Reactjs setState() with a dynamic key name?

I just wanted to add, that you can also use de-structuring to refactor the code and make it look neater.

inputChangeHandler: function ({ target: { id, value }) {
    this.setState({ [id]: value });

No mapping found for HTTP request with URI Spring MVC

I have the same problem.... I change my project name and i have this solution was the checking project refences and use / in my web.xml (instead of /*)

Start an activity from a fragment

Start new Activity From a Fragment:

Intent intent = new Intent(getActivity(), TargetActivity.class);

Start new Activity From a Activity:

Intent intent = new Intent(this, TargetActivity.class);

/exclude in xcopy just for a file type

Change *.cs to .cs in the excludefileslist.txt

maximum value of int

I know it's an old question but maybe someone can use this solution:

int size = 0; // Fill all bits with zero (0)
size = ~size; // Negate all bits, thus all bits are set to one (1)

So far we have -1 as result 'till size is a signed int.

size = (unsigned int)size >> 1; // Shift the bits of size one position to the right.

As Standard says, bits that are shifted in are 1 if variable is signed and negative and 0 if variable would be unsigned or signed and positive.

As size is signed and negative we would shift in sign bit which is 1, which is not helping much, so we cast to unsigned int, forcing to shift in 0 instead, setting the sign bit to 0 while letting all other bits remain 1.

cout << size << endl; // Prints out size which is now set to maximum positive value.

We could also use a mask and xor but then we had to know the exact bitsize of the variable. With shifting in bits front, we don't have to know at any time how many bits the int has on machine or compiler nor need we include extra libraries.

How to make multiple divs display in one line but still retain width?

You can float your column divs using float: left; and give them widths.

And to make sure none of your other content gets messed up, you can wrap the floated divs within a parent div and give it some clear float styling.

Hope this helps.

Use grep to report back only line numbers

To count the number of lines matched the pattern:

grep -n "Pattern" in_file.ext | wc -l 

To extract matched pattern

sed -n '/pattern/p' file.est

To display line numbers on which pattern was matched

grep -n "pattern" file.ext | cut -f1 -d:

Custom designing EditText

Use the below code in your rounded_edittext.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="" >

    <solid android:color="#FFFFFF" />

        android:color="#2f6699" />


This should work

Replace Fragment inside a ViewPager

I followed the answers by @wize and @mdelolmo and I got the solution. Thanks Tons. But, I tuned these solutions a little bit to improve the memory consumption.

Problems I observed:

They save the instance of Fragment which is replaced. In my case, it is a Fragment which holds MapView and I thought its costly. So, I am maintaining the FragmentPagerPositionChanged (POSITION_NONE or POSITION_UNCHANGED) instead of Fragment itself.

Here is my implementation.

  public static class DemoCollectionPagerAdapter extends FragmentStatePagerAdapter {

    private SwitchFragListener mSwitchFragListener;
    private Switch mToggle;
    private int pagerAdapterPosChanged = POSITION_UNCHANGED;
    private static final int TOGGLE_ENABLE_POS = 2;

    public DemoCollectionPagerAdapter(FragmentManager fm, Switch toggle) {
        mToggle = toggle;

        mSwitchFragListener = new SwitchFragListener();
        mToggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

    public Fragment getItem(int i) {
        switch (i)
            case TOGGLE_ENABLE_POS:
                    return TabReplaceFragment.getInstance();
                    return DemoTab2Fragment.getInstance(i);

                return DemoTabFragment.getInstance(i);

    public int getCount() {
        return 5;

    public CharSequence getPageTitle(int position) {
        return "Tab " + (position + 1);

    public int getItemPosition(Object object) {

        //  This check make sures getItem() is called only for the required Fragment
        if (object instanceof TabReplaceFragment
                ||  object instanceof DemoTab2Fragment)
            return pagerAdapterPosChanged;

        return POSITION_UNCHANGED;

     * Switch fragments Interface implementation
    private final class SwitchFragListener implements
            SwitchFragInterface {

        SwitchFragListener() {}

        public void onSwitchToNextFragment() {

            pagerAdapterPosChanged = POSITION_NONE;

     * Interface to switch frags
    private interface SwitchFragInterface{
        void onSwitchToNextFragment();

Demo link here..

For demo purpose, used 2 fragments TabReplaceFragment and DemoTab2Fragment at position two. In all the other cases I'm using DemoTabFragment instances.


I'm passing Switch from Activity to the DemoCollectionPagerAdapter. Based on the state of this switch we will display correct fragment. When the switch check is changed, I'm calling the SwitchFragListener's onSwitchToNextFragment method, where I'm changing the value of pagerAdapterPosChanged variable to POSITION_NONE. Check out more about POSITION_NONE. This will invalidate the getItem and I have logics to instantiate the right fragment over there. Sorry, if the explanation is a bit messy.

Once again big thanks to @wize and @mdelolmo for the original idea.

Hope this is helpful. :)

Let me know if this implementation has any flaws. That will be greatly helpful for my project.

Factory Pattern. When to use factory methods?

if you want to create a different object in terms of using. It is useful.

public class factoryMethodPattern {
      static String planName = "COMMERCIALPLAN";
      static int units = 3;
      public static void main(String args[]) {
          GetPlanFactory planFactory = new GetPlanFactory();
          Plan p = planFactory.getPlan(planName);
          System.out.print("Bill amount for " + planName + " of  " + units
                        + " units is: ");

abstract class Plan {
      protected double rate;

      abstract void getRate();

      public void calculateBill(int units) {
            System.out.println(units * rate);

class DomesticPlan extends Plan {
      // @override
      public void getRate() {
            rate = 3.50;

class CommercialPlan extends Plan {
      // @override
      public void getRate() {
            rate = 7.50;

class InstitutionalPlan extends Plan {
      // @override
      public void getRate() {
            rate = 5.50;

class GetPlanFactory {

      // use getPlan method to get object of type Plan
      public Plan getPlan(String planType) {
            if (planType == null) {
                  return null;
            if (planType.equalsIgnoreCase("DOMESTICPLAN")) {
                  return new DomesticPlan();
            } else if (planType.equalsIgnoreCase("COMMERCIALPLAN")) {
                  return new CommercialPlan();
            } else if (planType.equalsIgnoreCase("INSTITUTIONALPLAN")) {
                  return new InstitutionalPlan();
            return null;

Android widget: How to change the text of a button

//text button:

        android:text=" text button" />

// color text button:

        android:text="text button" 
        android:textColor="@android:color/color text"/>

// background button

        android:text="text button" 
        android:background="@android:color/ background button"/>

// text size button

        android:text="text button" 
        android:textSize="text size"/>

Search for a string in Enum and return the Enum

I marked OregonGhost's answer +1, then I tried to use the iteration and realised it wasn't quite right because Enum.GetNames returns strings. You want Enum.GetValues:

public MyColours GetColours(string colour)
   foreach (MyColours mc in Enum.GetValues(typeof(MyColours))) 
   if (mc.ToString() == surveySystem) 
      return mc;

   return MyColors.Default;

Create a global variable in TypeScript

Okay, so this is probably even uglier that what you did, but anyway...

but I do the same so...

What you can do to do it in pure TypeScript, is to use the eval function like so :

declare var something: string;
eval("something = 'testing';")

And later you'll be able to do

if (something === 'testing')

This is nothing more than a hack to force executing the instruction without TypeScript refusing to compile, and we declare var for TypeScript to compile the rest of the code.

How to load image to WPF in runtime?

Make sure that your sas.png is marked as Build Action: Content and Copy To Output Directory: Copy Always in its Visual Studio Properties...

I think the C# source code goes like this...

Image image = new Image();
image.Source = (new ImageSourceConverter()).ConvertFromString("pack://application:,,,/Bilder/sas.png") as ImageSource;

and XAML should be

<Image Height="200" HorizontalAlignment="Left" Margin="12,12,0,0" 
       Name="image1" Stretch="Fill" VerticalAlignment="Top" 
       Width="350" />  


Dynamically I think XAML would provide best way to load Images ...

<Image Source="{Binding Converter={StaticResource MyImageSourceConverter}}"

where image.DataContext is string path.

MyImage.DataContext = "pack://application:,,,/Bilder/sas.png";

public class MyImageSourceConverter : IValueConverter
    public object Convert(object value_, Type targetType_, 
    object parameter_, System.Globalization.CultureInfo culture_)
        return (new ImageSourceConverter()).ConvertFromString (value.ToString());

    public object ConvertBack(object value, Type targetType, 
    object parameter, CultureInfo culture)
          throw new NotImplementedException();

Now as you set a different data context, Image would be automatically loaded at runtime.

Warning: Each child in an array or iterator should have a unique "key" prop. Check the render method of `ListView`

Seems like both the conditions are met, perhaps key('contact') is the issue

 if(store.telefon) {
    detailItems.push( new DetailItem('contact', store.telefon, 'Anrufen', 'fontawesome|phone') );
if( {
    detailItems.push( new DetailItem('contact',, 'Email', 'fontawesome|envelope') );

Kendo grid date column not formatting

As far as I'm aware in order to format a date value you have to handle it in parameterMap,

            dataSource: {
                type: 'json',
                serverPaging: true,
                pageSize: 10,
                transport: {
                    read: {
                        url: '@Url.Action("_ListMy", "Placement")',
                        data: refreshGridParams,
                        type: 'POST'
                    parameterMap: function (options, operation) {
                        if (operation != "read") {
                            var d = new Date(options.StartDate);
                            options.StartDate = kendo.toString(new Date(d), "dd/MM/yyyy");
                            return options;
                        else { return options; }

                schema: {
                    model: {
                        id: 'Id',
                        fields: {
                            Id: { type: 'number' },
                            StartDate: { type: 'date', format: 'dd/MM/yyyy' },
                            Area: { type: 'string' },
                            Length: { type: 'string' },
                            Display: { type: 'string' },
                            Status: { type: 'string' },
                            Edit: { type: 'string' }
                    data: "Data",
                    total: "Count"
            scrollable: false,
                        field: 'StartDate',
                        title: 'Start Date',
                        format: '{0:dd/MM/yyyy}',
                        width: 100

If you follow the above example and just renames objects like 'StartDate' then it should work (ignore 'data: refreshGridParams,')

For further details check out below link or just search for kendo grid parameterMap ans see what others have done.

remove legend title in ggplot

Since you may have more than one legends in a plot, a way to selectively remove just one of the titles without leaving an empty space is to set the name argument of the scale_ function to NULL, i.e.

scale_fill_discrete(name = NULL)

(kudos to @pascal for a comment on another thread)

How to add fixed button to the bottom right of page

You are specifying .fixedbutton in your CSS (a class) and specifying the id on the element itself.

Change your CSS to the following, which will select the id fixedbutton

#fixedbutton {
    position: fixed;
    bottom: 0px;
    right: 0px; 

Here's a jsFiddle courtesy of JoshC.

Remove all line breaks from a long string of text

You can try using string replace:

string = string.replace('\r', '').replace('\n', '')

PHP: How can I determine if a variable has a value that is between two distinct constant values?

Guessing from the tag 'operand' you want to check a value?

$myValue = 5;
$minValue = 1;
$maxValue = 10;

if ($myValue >= $minValue && $myValue <= $maxValue) { 
  //do something

Update row with data from another row in the same table

Try this:

                        FROM data_table
                       WHERE VALUE IS NOT NULL AND VALUE != '') t1
 WHERE t.ID = t1.ID
   AND t.NAME = t1.NAME

Found a swap file by the name

I've also had this error when trying to pull the changes into a branch which is not created from the upstream branch from which I'm trying to pull.

Eg - This creates a new branch matching night-version of upstream

git checkout upstream/night-version -b testnightversion

This creates a branch testmaster in local which matches the master branch of upstream.

git checkout upstream/master -b testmaster 

Now if I try to pull the changes of night-version into testmaster branch leads to this error.

git pull upstream night-version //while I'm in `master` cloned branch

I managed to solve this by navigating to proper branch and pull the changes.

git checkout testnightversion
git pull upstream night-version // works fine.

Is there an SQLite equivalent to MySQL's DESCRIBE [table]?

To prevent that people are mislead by some of the comments to the other answers:

  1. If .schema or query from sqlite_master not gives any output, it indicates a non-existent tablename, e.g. this may also be caused by a ; semicolon at the end for .schema, .tables, ... Or just because the table really not exists. That .schema just doesn't work is very unlikely and then a bug report should be filed at the sqlite project.

... .schema can only be used from a command line; the above commands > can be run as a query through a library (Python, C#, etc.). – Mark Rushakoff Jul 25 '10 at 21:09

  1. 'can only be used from a command line' may mislead people. Almost any (likely every?) programming language can call other programs/commands. Therefore the quoted comment is unlucky as calling another program, in this case sqlite, is more likely to be supported than that the language provides a wrapper/library for every program (which not only is prone to incompleteness by the very nature of the masses of programs out there, but also is counter acting single-source principle, complicating maintenance, furthering the chaos of data in the world).

SQL Server: Filter output of sp_who2

based on

i have created following script ,
which resolves finding active connections to any datbase using DMV this works under sql 2005 , 2008 and 2008R2

Following script uses sys.dm_exec_sessions , sys.dm_exec_requests , sys.dm_exec_connections , sys.dm_tran_locks

Declare @dbName varchar(1000)
set @dbName='abc'

;WITH DBConn(SPID,[Status],[Login],HostName,DBName,Command,LastBatch,ProgramName)
    SPID = s.session_id,
    [Login] = s.login_name,
    HostName = COALESCE
            '  .'
    Command = COALESCE
    LastBatch = COALESCE
    ProgramName = COALESCE
    sys.dm_exec_sessions s
    sys.dm_exec_requests r
    s.session_id = r.session_id
    sys.dm_exec_connections c
    s.session_id = c.session_id
        database_id = MAX(resource_database_id)
) t
    s.session_id = t.request_session_id
    sys.dm_os_waiting_tasks wt
    s.session_id = wt.session_id
    sys.dm_os_tasks ot
    s.session_id = ot.session_id
        CPU_Time = MAX(usermode_time)
        sys.dm_os_tasks ot
        sys.dm_os_workers ow
        ot.worker_address = ow.worker_address
        sys.dm_os_threads oth
        ow.thread_address = oth.thread_address
) tt
    s.session_id = tt.session_id
    ) >= COALESCE

Select * from DBConn
where DBName like '%'+@dbName+'%'

How to access at request attributes in JSP?

EL expression:


There are several implicit objects in JSP EL. See Expression Language under the "Implicit Objects" heading.

How to prevent caching of my Javascript file?

You can add a random (or datetime string) as query string to the url that points to your script. Like so:

<script type="text/javascript" src="test.js?q=123"></script> 

Every time you refresh the page you need to make sure the value of 'q' is changed.

Specified argument was out of the range of valid values. Parameter name: site

I had the same issue with VS2017. Following solved the issue.

  1. Run Command prompt as Administrator.
  2. Write following two commands which will update your registry.

reg add HKLM\Software\WOW6432Node\Microsoft\InetStp /v MajorVersion /t REG_DWORD /d 10 /f

reg add HKLM\Software\Microsoft\InetStp /v MajorVersion /t REG_DWORD /d 10 /f

This should solve your problem. Refer to this link for more details.

What is the difference between a "line feed" and a "carriage return"?

Since I can not comment because of not having enough reward points I have to answer to correct answer given by @Burhan Khalid.
In very layman language Enter key press is combination of carriage return and line feed.
Carriage return points the cursor to the beginning of the line horizontly and Line feed shifts the cursor to the next line vertically.Combination of both gives you new line(\n) effect.
Reference -

OpenCV Error: (-215)size.width>0 && size.height>0 in function imshow

I have also met this issue. In my case, the image path is wrong, so the img read is NoneType. After I correct the image path, I can show it without any issue.

MySQL ORDER BY multiple column ASC and DESC

Ok, I THINK I understand what you want now, and let me clarify to confirm before the query. You want 1 record for each user. For each user, you want their BEST POINTS score record. Of the best points per user, you want the one with the best average time. Once you have all users "best" values, you want the final results sorted with best points first... Almost like ranking of a competition.

So now the query. If the above statement is accurate, you need to start with getting the best point/average time per person and assigning a "Rank" to that entry. This is easily done using MySQL @ variables. Then, just include a HAVING clause to only keep those records ranked 1 for each person. Finally apply the order by of best points and shortest average time.

      @UserRank := if( @lastUserID = PreSortedPerUser.User_ID, @UserRank +1, 1 ) FinalRank,
      @lastUserID := PreSortedPerUser.User_ID
      ( select
              Scores S
           order by
              S.point DESC,
              S.Avg_Time ) PreSortedPerUser
         JOIN Users U
            on PreSortedPerUser.user_ID = U.ID,
      ( select @lastUserID := 0,
               @UserRank := 0 ) sqlvars 
      FinalRank = 1
   order by
      Point Desc,

Results as handled by SQLFiddle

Note, due to the inline @variables needed to get the answer, there are the two extra columns at the end of each row. These are just "left-over" and can be ignored in any actual output presentation you are trying to do... OR, you can wrap the entire thing above one more level to just get the few columns you want like

      ( entire query above pasted here ) as PQ

Use StringFormat to add a string to a WPF XAML binding

Please note that using StringFormat in Bindings only seems to work for "text" properties. Using this for Label.Content will not work

How to ping an IP address

Even though this does not rely on ICMP on Windows, this implementation works pretty well with the new Duration API

public static Duration ping(String host) {
    Instant startTime =;
    try {
        InetAddress address = InetAddress.getByName(host);
        if (address.isReachable(1000)) {
            return Duration.between(startTime,;
    } catch (IOException e) {
        // Host not available, nothing to do here
    return Duration.ofDays(1);

Python: How to create a unique file name?

If you want to make temporary files in Python, there's a module called tempfile in Python's standard libraries. If you want to launch other programs to operate on the file, use tempfile.mkstemp() to create files, and os.fdopen() to access the file descriptors that mkstemp() gives you.

Incidentally, you say you're running commands from a Python program? You should almost certainly be using the subprocess module.

So you can quite merrily write code that looks like:

import subprocess
import tempfile
import os

(fd, filename) = tempfile.mkstemp()
    tfile = os.fdopen(fd, "w")
    tfile.write("Hello, world!\n")
    subprocess.Popen(["/bin/cat", filename]).wait()        

Running that, you should find that the cat command worked perfectly well, but the temporary file was deleted in the finally block. Be aware that you have to delete the temporary file that mkstemp() returns yourself - the library has no way of knowing when you're done with it!

(Edit: I had presumed that NamedTemporaryFile did exactly what you're after, but that might not be so convenient - the file gets deleted immediately when the temp file object is closed, and having other processes open the file before you've closed it won't work on some platforms, notably Windows. Sorry, fail on my part.)

Java synchronized method lock on object, or method?

Yes, it will block the other method because synchronized method applies to the WHOLE class object as pointed .... but anyway it will block the other thread execution ONLY while performing the sum in whatever method addA or addB it enters, because when it finish ... the one thread will FREE the object and the other thread will access the other method and so on perfectly working.

I mean the "synchronized" is made precisely for blocking the other thread from accessing another while in a specific code execution. SO FINALLY THIS CODE WILL WORK FINE.

As a final note, if there is an 'a' and 'b' variables, not just an unique variable 'a' or whatever other name, there is no need to synchronize this methods cause it is perfectly safe accesing other var (Other memory location).

class X {

private int a;
private int b;

public void addA(){

public void addB(){

Will work as well

How to update primary key

If you are sure that this change is suitable for the environment you're working in: set the FK conditions on the secondary tables to UPDATE CASCADING.

For example, if using SSMS as GUI:

  1. right click on the key
  2. select Modify
  3. Fold out 'INSERT And UPDATE Specific'
  4. For 'Update Rule', select Cascade.
  5. Close the dialog and save the key.

When you then update a value in the PK column in your primary table, the FK references in the other tables will be updated to point at the new value, preserving data integrity.

Show tables, describe tables equivalent in redshift

Or simply:

\dt to show tables

\d+ <table name> to describe a table

Edit: Works using the psql command line client

bootstrap popover not showing on top of all elements

I had a similar issue with 2 fixed elements - even though the z-index heirachy was correct, the bootstrap tooltip was hidden behind the one element wth a lower z-index.

Adding data-container="body" resolved the issue and now works as expected.

TimePicker Dialog from clicking EditText

You can use the below code in the onclick listener of edittext

  TimePickerDialog timePickerDialog = new TimePickerDialog(MainActivity.this,
    new TimePickerDialog.OnTimeSetListener() {

        public void onTimeSet(TimePicker view, int hourOfDay,
                              int minute) {

            tv_time.setText(hourOfDay + ":" + minute);
    }, hour, minute, false);;

You can see the full code at Android timepicker example

Margin on child element moves parent element

Found an alternative at Child elements with margins within DIVs You can also add:

.parent { overflow: auto; }


.parent { overflow: hidden; }

This prevents the margins to collapse. Border and padding do the same. Hence, you can also use the following to prevent a top-margin collapse:

.parent {
    padding-top: 1px;
    margin-top: -1px;

Update by popular request: The whole point of collapsing margins is handling textual content. For example:

h1, h2, p, ul {_x000D_
  margin-top: 1em;_x000D_
  margin-bottom: 1em;_x000D_
<div class="text">_x000D_
<div class="text">_x000D_
    <li>list item</li>_x000D_

Because the browser collapses margins, the text would appear as you'd expect, and the <div> wrapper tags don't influence the margins. Each element ensures it has spacing around it, but spacing won't be doubled. The margins of the <h2> and <p> won't add up, but slide into each other (they collapse). The same happens for the <p> and <ul> element.

Sadly, with modern designs this idea can bite you when you explicitly want a container. This is called a new block formatting context in CSS speak. The overflow or margin trick will give you that.

How to remove the arrows from input[type="number"] in Opera

I've been using some simple CSS and it seems to remove them and work fine.

input[type=number]::-webkit-inner-spin-button, _x000D_
input[type=number]::-webkit-outer-spin-button { _x000D_
    -webkit-appearance: none;_x000D_
    -moz-appearance: none;_x000D_
    appearance: none;_x000D_
    margin: 0; _x000D_
<input type="number" step="0.01"/>

This tutorial from CSS Tricks explains in detail & also shows how to style them

How to get the selected row values of DevExpress XtraGrid?

Which one of their Grids are you using? XtraGrid or AspXGrid? Here is a piece taken from one of my app using XtraGrid.

private void grdContactsView_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
    _selectedContact = GetSelectedRow((DevExpress.XtraGrid.Views.Grid.GridView)sender);

private Contact GetSelectedRow(DevExpress.XtraGrid.Views.Grid.GridView view)
    return (Contact)view.GetRow(view.FocusedRowHandle);

My Grid have a list of Contact objects bound to it. Every time a row is clicked I load the selected row into _selectedContact. Hope this helps. You will find lots of information on using their controls buy visiting their support and documentation sites.

Post parameter is always null

If you are sure about your sent JSON then you must trace your API carefully:

  1. Install Microsoft.AspNet.WebApi.Tracing package
  2. Add config.EnableSystemDiagnosticsTracing(); in the WebApiConfig class inside Register method.

Now look at the Debug output and you will probably find an invalid ModelState log entry.

If ModelState is invalid you may find the real cause in its Errors:

No one can even guess such an exception:

Could not load file or assembly 'Newtonsoft.Json, Version=, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

Make div 100% Width of Browser Window

There are new units that you can use:

vw - viewport width

vh - viewport height

   width: 100%; //fallback
   width: 100vw;

Help / MDN

Opera Mini does not support this, but you can use it in all other modern browsers.


enter image description here

How do I (or can I) SELECT DISTINCT on multiple columns?


is roughly equivalent to:

SELECT a,b,c FROM t GROUP BY a,b,c

It's a good idea to get used to the GROUP BY syntax, as it's more powerful.

For your query, I'd do it like this:

UPDATE sales
SET status='ACTIVE'
    SELECT id
    FROM sales S
        SELECT saleprice, saledate
        FROM sales
        GROUP BY saleprice, saledate
        HAVING COUNT(*) = 1 
    ) T
    ON S.saleprice=T.saleprice AND s.saledate=T.saledate

Array definition in XML?

No, there is no simpler way. You only can lose the type=array.


Extract column values of Dataframe as List in Apache Spark

sqlContext.sql(" select filename from tempTable") => r(0)).collect.toList.foreach(out_streamfn.println) //remove brackets

it works perfectly

Razor Views not seeing System.Web.Mvc.HtmlHelper

I was dealing with this issue after upgrading from Visual Studio 2013 to Visual Studio 2015 After trying most of the advice found in this and other similar SO posts, I finally found the problem. The first part of the fix was to update all of my NuGet stuff to the latest version (you might need to do this in VS13 if you are experiencing the Nuget bug) after, I had to, as you may need to, fix the versions listed in the Views Web.config. This includes:

  1. Fix MVC versions and its child libraries to the new version (expand the References then right click onSytem.Web.MVC then Properties to get your version)
  2. Fix the Razor version.

Mine looked like this:

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

    <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    <pages pageBaseType="System.Web.Mvc.WebViewPage">
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Optimization"/>
        <add namespace="System.Web.Routing" />

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

      <add path="*" verb="*" type="System.Web.HttpNotFoundHandler"/>
      pageParserFilterType="System.Web.Mvc.ViewTypeParserFilter, System.Web.Mvc, Version=, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
      pageBaseType="System.Web.Mvc.ViewPage, System.Web.Mvc, Version=, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
      userControlBaseType="System.Web.Mvc.ViewUserControl, System.Web.Mvc, Version=, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
        <add assembly="System.Web.Mvc, Version=, Culture=neutral, PublicKeyToken=31BF3856AD364E35" namespace="System.Web.Mvc" tagPrefix="mvc" />

    <validation validateIntegratedModeConfiguration="false" />

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

Setting focus on an HTML input box on page load

This is one of the common issues with IE and fix for this is simple. Add .focus() twice to the input.

Fix :-

function FocusOnInput() {
    var element = document.getElementById('txtContactMobileNo');
    setTimeout(function () { element.focus(); }, 1);

And call FocusOnInput() on $(document).ready(function () {.....};

htons() function in socket programing

htons is host-to-network short

This means it works on 16-bit short integers. i.e. 2 bytes.

This function swaps the endianness of a short.

Your number starts out at:

0001 0011 1000 1001 = 5001

When the endianness is changed, it swaps the two bytes:

1000 1001 0001 0011 = 35091

c++ exception : throwing std::string

All these work:

#include <iostream>
using namespace std;

//Good, because manual memory management isn't needed and this uses
//less heap memory (or no heap memory) so this is safer if
//used in a low memory situation
void f() { throw string("foo"); }

//Valid, but avoid manual memory management if there's no reason to use it
void g() { throw new string("foo"); }

//Best.  Just a pointer to a string literal, so no allocation is needed,
//saving on cleanup, and removing a chance for an allocation to fail.
void h() { throw "foo"; }

int main() {
  try { f(); } catch (string s) { cout << s << endl; }
  try { g(); } catch (string* s) { cout << *s << endl; delete s; }
  try { h(); } catch (const char* s) { cout << s << endl; }
  return 0;

You should prefer h to f to g. Note that in the least preferable option you need to free the memory explicitly.

Entity Framework. Delete all rows in table

var data = (from n in db.users select n);

How to include route handlers in multiple files in Express?

And build yet more on the previous answer, this version of routes/index.js will ignore any files not ending in .js (and itself)

var fs = require('fs');

module.exports = function(app) {
    fs.readdirSync(__dirname).forEach(function(file) {
        if (file === "index.js" || file.substr(file.lastIndexOf('.') + 1) !== 'js')
        var name = file.substr(0, file.indexOf('.'));
        require('./' + name)(app);

How do I check in SQLite whether a table exists?



to prevent all records from being read.

How to scale images to screen size in Pygame

If you scale 1600x900 to 1280x720 you have

scale_x = 1280.0/1600
scale_y = 720.0/900

Then you can use it to find button size, and button position

button_width  = 300 * scale_x
button_height = 300 * scale_y

button_x = 1440 * scale_x
button_y = 860  * scale_y

If you scale 1280x720 to 1600x900 you have

scale_x = 1600.0/1280
scale_y = 900.0/720

and rest is the same.

I add .0 to value to make float - otherwise scale_x, scale_y will be rounded to integer - in this example to 0 (zero) (Python 2.x)

SQL WITH clause example

This has been fully answered here.

See Oracle's docs on SELECT to see how subquery factoring works, and Mark's example:

WITH employee AS (SELECT * FROM Employees)
SELECT * FROM employee WHERE ID < 20
SELECT * FROM employee WHERE Sex = 'M'

Android: how to get the current day of the week (Monday, etc...) in the user's language?

If you are using ThreetenABP date library bt Jake Warthon you can do:

dayOfWeek.getDisplayName(TextStyle.FULL, Locale.getDefault()

on your dayOfWeek instance. More at:

How can I calculate divide and modulo for integers in C#?

Fun fact!

The 'modulus' operation is defined as:

a % n ==> a - (a/n) * n

Ref:Modular Arithmetic

So you could roll your own, although it will be FAR slower than the built in % operator:

public static int Mod(int a, int n)
    return a - (int)((double)a / n) * n;

Edit: wow, misspoke rather badly here originally, thanks @joren for catching me

Now here I'm relying on the fact that division + cast-to-int in C# is equivalent to Math.Floor (i.e., it drops the fraction), but a "true" implementation would instead be something like:

public static int Mod(int a, int n)
    return a - (int)Math.Floor((double)a / n) * n;

In fact, you can see the differences between % and "true modulus" with the following:

var modTest =
    from a in Enumerable.Range(-3, 6)
    from b in Enumerable.Range(-3, 6)
    where b != 0
    let op = (a % b)
    let mod = Mod(a,b)
    let areSame = op == mod
    select new 
        A = a,
        B = b,
        Operator = op, 
        Mod = mod, 
        Same = areSame
Console.WriteLine("A      B     A%B   Mod(A,B)   Equal?");
foreach (var result in modTest)
        "{0,-3} | {1,-3} | {2,-5} | {3,-10} | {4,-6}", 


A      B     A%B   Mod(A,B)   Equal?
-3  | -3  | 0     | 0          | True  
-3  | -2  | -1    | -1         | True  
-3  | -1  | 0     | 0          | True  
-3  | 1   | 0     | 0          | True  
-3  | 2   | -1    | 1          | False 
-2  | -3  | -2    | -2         | True  
-2  | -2  | 0     | 0          | True  
-2  | -1  | 0     | 0          | True  
-2  | 1   | 0     | 0          | True  
-2  | 2   | 0     | 0          | True  
-1  | -3  | -1    | -1         | True  
-1  | -2  | -1    | -1         | True  
-1  | -1  | 0     | 0          | True  
-1  | 1   | 0     | 0          | True  
-1  | 2   | -1    | 1          | False 
0   | -3  | 0     | 0          | True  
0   | -2  | 0     | 0          | True  
0   | -1  | 0     | 0          | True  
0   | 1   | 0     | 0          | True  
0   | 2   | 0     | 0          | True  
1   | -3  | 1     | -2         | False 
1   | -2  | 1     | -1         | False 
1   | -1  | 0     | 0          | True  
1   | 1   | 0     | 0          | True  
1   | 2   | 1     | 1          | True  
2   | -3  | 2     | -1         | False 
2   | -2  | 0     | 0          | True  
2   | -1  | 0     | 0          | True  
2   | 1   | 0     | 0          | True  
2   | 2   | 0     | 0          | True  

async at console app in C#?

As a quick and very scoped solution:


Both Task.Result and Task.Wait won't allow to improving scalability when used with I/O, as they will cause the calling thread to stay blocked waiting for the I/O to end.

When you call .Result on an incomplete Task, the thread executing the method has to sit and wait for the task to complete, which blocks the thread from doing any other useful work in the meantime. This negates the benefit of the asynchronous nature of the task.


tell pip to install the dependencies of packages listed in a requirement file

simplifily, use:

pip install -r requirement.txt

it can install all listed in requirement file.

Connection to SQL Server Works Sometimes

It turned out that TCP/IP was enabled for the IPv4 address, but not for the IPv6 address, of THESERVER.

Apparently some connection attempts ended up using IPv4 and others used IPv6.

Enabling TCP/IP for both IP versions resolved the issue.

The fact that SSMS worked turned out to be coincidental (the first few attempts presumably used IPv4). Some later attempts to connect through SSMS resulted in the same error message.

To enable TCP/IP for additional IP addresses:

  • Start Sql Server Configuration Manager
  • Open the node SQL Server Network Configuration
  • Left-click Protocols for MYSQLINSTANCE
  • In the right-hand pane, right-click TCP/IP
  • Click Properties
  • Select the IP Addresses tab
  • For each listed IP address, ensure Active and Enabled are both Yes.

Facebook Like-Button - hide count?

It is now officially supported by Facebook. Just select the 'Button' layout.

Split by comma and strip whitespace in Python

Just remove the white space from the string before you split it.

mylist = my_string.replace(' ','').split(',')

Check if input is integer type in C

This is a more user-friendly one I guess :


/* This program checks if the entered input is an integer
 * or provides an option for the user to re-enter.

int getint()
  int x;
  char c;
  printf("\nEnter an integer (say -1 or 26 or so ): ");
  while( scanf("%d",&x) != 1 )

    printf("You have entered ");
    printf(" in the input which is not an integer");

    while ( getchar() != '\n' )
     ; //wasting the buffer till the next new line

    printf("\nEnter an integer (say -1 or 26 or so ): ");


return x;

int main(void)
  int x;

  printf("Main Function =>\n");
  printf("Integer : %d\n",x);

 return 0;

Formatting floats in a numpy array

You can use round function. Here some example

numpy.round([2.15295647e+01, 8.12531501e+00, 3.97113829e+00, 1.00777250e+01],2)
array([ 21.53,   8.13,   3.97,  10.08])

IF you want change just display representation, I would not recommended to alter printing format globally, as it suggested above. I would format my output in place.

>>a=np.array([2.15295647e+01, 8.12531501e+00, 3.97113829e+00, 1.00777250e+01])
>>> print([ "{:0.2f}".format(x) for x in a ])
['21.53', '8.13', '3.97', '10.08']

In JavaScript, why is "0" equal to false, but when tested by 'if' it is not false by itself?

The reason is because when you explicitly do "0" == false, both sides are being converted to numbers, and then the comparison is performed.

When you do: if ("0") console.log("ha"), the string value is being tested. Any non-empty string is true, while an empty string is false.

Equal (==)

If the two operands are not of the same type, JavaScript converts the operands then applies strict comparison. If either operand is a number or a boolean, the operands are converted to numbers if possible; else if either operand is a string, the other operand is converted to a string if possible. If both operands are objects, then JavaScript compares internal references which are equal when operands refer to the same object in memory.

(From Comparison Operators in Mozilla Developer Network)

Defining a variable with or without export

To illustrate what the other answers are saying:

$ foo="Hello, World"
$ echo $foo
Hello, World
$ bar="Goodbye"
$ export foo
$ bash
bash-3.2$ echo $foo
Hello, World
bash-3.2$ echo $bar


remove inner shadow of text input

I'm working on firefox. and I was having the same issue, input type text are auto defined something looks like boxshadow inset, but it's not. the you want to change is border... just setting border:0; and you're done.

How should a model be structured in MVC?

In my case I have a database class that handle all the direct database interaction such as querying, fetching, and such. So if I had to change my database from MySQL to PostgreSQL there won't be any problem. So adding that extra layer can be useful.

Each table can have its own class and have its specific methods, but to actually get the data, it lets the database class handle it:

File Database.php

class Database {
    private static $connection;
    private static $current_query;

    public static function query($sql) {
        if (!self::$connection){
        self::$current_query = $sql;
        $result = mysql_query($sql,self::$connection);

        if (!$result){
            // throw custom error
            // The query failed for some reason. here is query :: self::$current_query
            $error = new Error(2,"There is an Error in the query.\n<b>Query:</b>\n{$sql}\n");
        return $result;

    public static function find_by_sql($sql){
        if (!is_string($sql))
            return false;

        $result_set = self::query($sql);
        $obj_arr = array();
        while ($row = self::fetch_array($result_set))
            $obj_arr[] = self::instantiate($row);
        return $obj_arr;

Table object classL

class DomainPeer extends Database {

    public static function getDomainInfoList() {
        $sql = 'SELECT ';
        $sql .='d.`id`,';
        $sql .='d.`name`,';
        $sql .='d.`shortName`,';
        $sql .='d.`created_at`,';
        $sql .='d.`updated_at`,';
        $sql .='count( as queries ';
        $sql .='FROM `domains` d ';
        $sql .='LEFT JOIN queries q on q.domainId = ';
        $sql .='GROUP BY';
        return self::find_by_sql($sql);


I hope this example helps you create a good structure.

What MIME type should I use for CSV?

RFC 7111

There is an RFC which covers it and says to use text/csv.

This RFC updates RFC 4180.


Recently I discovered an explicit mimetype for Excel application/ It was registered with IANA in '96. Note the concerns raised about being at the mercy of the sender and having your machine violated.

Media Type: application/

Name Microsoft Excel (tm)

Required parameters: None

Optional parameters: name

Encoding considerations: base64 preferred

Security considerations: As with most application types this data is intended for interpretation by a program that understands the data on the recipient's system. Recipients need to understand that they are at the "mercy" of the sender, when receiving this type of data, since data will be executed on their system, and the security of their machines can be violated.

OID { org-id ms-files(4) ms-excel (3) }

Object type spreadsheet

Comments This Media Type/OID is used to identify Microsoft Excel generically (i.e., independent of version, subtype, or platform format).

I wasn't aware that vendor extensions were allowed. Check out this answer to find out more - thanks starbeamrainbowlabs for the reference.

Adding placeholder text to textbox

This is a extension method for the texbox. Simply Add the Placeholder Text programmatically:

myTextBox.AddPlaceholderText("Hello World!");

The extension method:

public static void AddPlaceholderText(this TextBox textBox, string placeholderText)
            if (string.IsNullOrWhiteSpace(textBox.Text))
                textBox.Text = placeholderText;
                textBox.Text != placeholderText
                    ? "SystemControlForegroundBaseHighBrush"
                    : "SystemControlForegroundBaseMediumBrush");
            var ignoreSelectionChanged = false;
            textBox.SelectionChanged += (sender, args) =>
                if (ignoreSelectionChanged) { ignoreSelectionChanged = false; return; }
                if (textBox.Text != placeholderText) return;
                ignoreSelectionChanged = true;
                textBox.Select(0, 0);
            var lastText = textBox.Text;
            var ignoreTextChanged = false;
            textBox.TextChanged += (sender, args) =>
                if (ignoreTextChanged) { ignoreTextChanged = false; return; }
                if (string.IsNullOrWhiteSpace(textBox.Text))
                    ignoreTextChanged = true;
                    textBox.Text = placeholderText;
                    textBox.Select(0, 0);
                else if (lastText == placeholderText)
                    ignoreTextChanged = true;
                    textBox.Text = textBox.Text.Substring(0, 1);
                    textBox.Select(1, 0);

                    textBox.Text != placeholderText
                        ? "SystemControlForegroundBaseHighBrush"
                        : "SystemControlForegroundBaseMediumBrush");
                lastText = textBox.Text;

Happy coding, BierDav

Can I invoke an instance method on a Ruby module without including it?

If a method on a module is turned into a module function you can simply call it off of Mods as if it had been declared as

module Mods
     puts ""

The module_function approach below will avoid breaking any classes which include all of Mods.

module Mods
  def foo
    puts ""

class Includer
  include Mods

Mods.module_eval do
  public :foo
end # this would break without public :foo above

class Thing
  def bar

However, I'm curious why a set of unrelated functions are all contained within the same module in the first place?

Edited to show that includes still work if public :foo is called after module_function :foo

Simplest way to set image as JPanel background

Draw the image on the background of a JPanel that is added to the frame. Use a layout manager to normally add your buttons and other components to the panel. If you add other child panels, perhaps you want to set child.setOpaque(false).

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;

public class BackgroundImageApp {
    private JFrame frame;

    private BackgroundImageApp create() {
        frame = createFrame();

        return this;

    private JFrame createFrame() {
        JFrame frame = new JFrame(getClass().getName());

        return frame;

    private void show() {

    private Component createContent() {
        final Image image = requestImage();

        JPanel panel = new JPanel() {
            protected void paintComponent(Graphics g) {
                g.drawImage(image, 0, 0, null);

        panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
        for (String label : new String[]{"One", "Dois", "Drei", "Quatro", "Peace"}) {
            JButton button = new JButton(label);
            panel.add(Box.createRigidArea(new Dimension(15, 15)));

        panel.setPreferredSize(new Dimension(500, 500));

        return panel;

    private Image requestImage() {
        Image image = null;

        try {
            image = URL(""));
        } catch (IOException e) {

        return image;

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new BackgroundImageApp().create().show();

What is the size of column of int(11) in mysql in bytes?

Though this answer is unlikely to be seen, I think the following clarification is worth making:

  • the (n) behind an integer data type in MySQL is specifying the display width
  • the display width does NOT limit the length of the number returned from a query
  • the display width DOES limit the number of zeroes filled for a zero filled column so the total number matches the display width (so long as the actual number does not exceed the display width, in which case the number is shown as is)
  • the display width is also meant as a useful tool for developers to know what length the value should be padded to

the display width is, apparently, intended to provide some metadata about how many zeros to display in a zero filled number.
It does NOT actually limit the length of a number returned from a query if that number goes above the display width specified.
To know what length/width is actually allowed for an integer data type in MySQL see the list & link: (types: TINYINT, SMALLINT, MEDIUMINT, INT, BIGINT);
So having said the above, you can expect the display width to have no affect on the results from a standard query, unless the columns are specified as ZEROFILL columns
in the case the data is being pulled into an application & that application is collecting the display width to use for some other sort of padding.

Primary Reference:

How can I specify working directory for popen

subprocess.Popen takes a cwd argument to set the Current Working Directory; you'll also want to escape your backslashes ('d:\\test\\local'), or use r'd:\test\local' so that the backslashes aren't interpreted as escape sequences by Python. The way you have it written, the \t part will be translated to a tab.

So, your new line should look like:

subprocess.Popen(r'c:\mytool\tool.exe', cwd=r'd:\test\local')

To use your Python script path as cwd, import os and define cwd using this:


ERROR 1044 (42000): Access denied for user ''@'localhost' to database 'db'

You might want to try the full login command:

mysql -h host -u root -p 

where host would be

Do this just to make sure cooperation exists.

Using mysql -u root -p allows me to do a a lot of database searching, but refuses any database creation due to a path setting.

Angular cli generate a service and include the provider in one step

In Command prompt go to project folder and execute following:

ng g s servicename

avrdude: stk500v2_ReceiveMessage(): timeout

Another possible reason for this error for the Mega 2560 is if your code has three exclamation marks in a row. Perhaps in a recently added string.

3 bang marks in a row causes the Mega 2560 bootloader to go into Monitor mode from which it can not finish programming.

"!!!" <--- breaks Mega 2560 bootloader.

To fix, unplug the Arduino USB to reset the COM port and then recompile with only two exclamation points or with spaces between or whatever. Then reconnect the Arduino and program as usual.

Yes, this bit me yesterday and today I tracked down the culprit. Here is a link with more information:

Processing Symbol Files in Xcode

In Xcode Version 6.1.1 (6A2008a), after "Processing Symbol Files", a folder containing symbols associated with the device (including iOS version and CPU type) was created in ~/Library/Developer/Xcode/iOS DeviceSupport/ like this:

enter image description here

In Chart.js set chart title, name of x axis and y axis?

just use this:

  var ctx = document.getElementById("myChart").getContext('2d');
  var myChart = new Chart(ctx, {
    type: 'bar',
    data: {
      labels: ["1","2","3","4","5","6","7","8","9","10","11",],
      datasets: [{
        label: 'YOUR LABEL',
        backgroundColor: [
        data: [12, 19, 3, 17, 28, 24, 7, 2,4,14,6],            
    options : {
      scales: {
        yAxes: [{
          scaleLabel: {
            display: true,
            labelString: 'probability'

How to get a subset of a javascript object's properties

TypeScript solution:

function pick<T extends object, U extends keyof T>(
  obj: T,
  paths: Array<U>
): Pick<T, U> {
  const ret = Object.create(null);
  for (const k of paths) {
    ret[k] = obj[k];
  return ret;

The typing information even allows for auto-completion:

Credit to DefinitelyTyped for U extends keyof T trick!

TypeScript Playground

What are the differences and similarities between ffmpeg, libav, and avconv?

Confusing messages

These messages are rather misleading and understandably a source of confusion. Older Ubuntu versions used Libav which is a fork of the FFmpeg project. FFmpeg returned in Ubuntu 15.04 "Vivid Vervet".

The fork was basically a non-amicable result of conflicting personalities and development styles within the FFmpeg community. It is worth noting that the maintainer for Debian/Ubuntu switched from FFmpeg to Libav on his own accord due to being involved with the Libav fork.

The real ffmpeg vs the fake one

For a while both Libav and FFmpeg separately developed their own version of ffmpeg.

Libav then renamed their bizarro ffmpeg to avconv to distance themselves from the FFmpeg project. During the transition period the "not developed anymore" message was displayed to tell users to start using avconv instead of their counterfeit version of ffmpeg. This confused users into thinking that FFmpeg (the project) is dead, which is not true. A bad choice of words, but I can't imagine Libav not expecting such a response by general users.

This message was removed upstream when the fake "ffmpeg" was finally removed from the Libav source, but, depending on your version, it can still show up in Ubuntu because the Libav source Ubuntu uses is from the ffmpeg-to-avconv transition period.

In June 2012, the message was re-worded for the package libav - 4:0.8.3-0ubuntu0.12.04.1. Unfortunately the new "deprecated" message has caused additional user confusion.

Starting with Ubuntu 15.04 "Vivid Vervet", FFmpeg's ffmpeg is back in the repositories again.

libav vs Libav

To further complicate matters, Libav chose a name that was historically used by FFmpeg to refer to its libraries (libavcodec, libavformat, etc). For example the libav-user mailing list, for questions and discussions about using the FFmpeg libraries, is unrelated to the Libav project.

How to tell the difference

If you are using avconv then you are using Libav. If you are using ffmpeg you could be using FFmpeg or Libav. Refer to the first line in the console output to tell the difference: the copyright notice will either mention FFmpeg or Libav.

Secondly, the version numbering schemes differ. Each of the FFmpeg or Libav libraries contains a version.h header which shows a version number. FFmpeg will end in three digits, such as 57.67.100, and Libav will end in one digit such as 57.67.0. You can also view the library version numbers by running ffmpeg or avconv and viewing the console output.

If you want to use the real ffmpeg

Ubuntu 15.04 "Vivid Vervet" or newer

The real ffmpeg is in the repository, so you can install it with:

apt-get install ffmpeg

For older Ubuntu versions

Your options are:

These methods are non-intrusive, reversible, and will not interfere with the system or any repository packages.

Another possible option is to upgrade to Ubuntu 15.04 "Vivid Vervet" or newer and just use ffmpeg from the repository.

Also see

For an interesting blog article on the situation, as well as a discussion about the main technical differences between the projects, see The FFmpeg/Libav situation.

Curl Command to Repeat URL Request

You can use any bash looping constructs like FOR, with is compatible to Linux and Mac.

In your specific case you can define N iterations, with N is a number defining how many curl executions you want.

for n in {1..N}; do curl <arguments>; done


for n in {1..20}; do curl -d @notification.json -H 'Content-Type: application/json' localhost:3000/dispatcher/notify; done

how can get index & count in vuejs

Why its printing 0,1,2...?

Because those are indexes of the items in array, and index always starts from 0 to array.length-1.

To print the item count instead of index, use index+1. Like this:

<li v-for="(catalog, index) in catalogs">this index : {{index + 1}}</li>

And to show the total count use array.length, Like this:

<p>Total Count: {{ catalogs.length }}</p>

As per DOC:

v-for also supports an optional second argument (not first) for the index of the current item.

jQuery: find element by text

You can use the :contains selector to get elements based on their content.

Demo here

$('div:contains("test")').css('background-color', 'red');
<div>This is a test</div>_x000D_
<div>Another Div</div>_x000D_
<script src=""></script>

How to loop over directories in Linux?

If you want to execute multiple commands in a for loop, you can save the result of find with mapfile (bash >= 4) as an variable and go through the array with ${dirlist[@]}. It also works with directories containing spaces.

The find command is based on the answer by Boldewyn. Further information about the find command can be found there.

mapfile -t dirlist < <( find . -maxdepth 1 -mindepth 1 -type d -printf '%f\n' )
for dir in ${dirlist[@]}; do
    echo ">${dir}<"
    # more commands can go here ...

RSA: Get exponent and modulus given a public key

Apart from the above answers, we can use asn1parse to get the values

$ openssl asn1parse -i -in pub0.der -inform DER -offset 24
0:d=0  hl=4 l= 266 cons: SEQUENCE
4:d=1  hl=4 l= 257 prim:  INTEGER           :C9131430CCE9C42F659623BDC73A783029A23E4BA3FAF74FE3CF452F9DA9DAF29D6F46556E423FB02610BC4F84E19F87333EAD0BB3B390A3EFA7FB392E935065D80A27589A21CA051FA226195216D8A39F151BD0334965551744566AD3DAEB53EBA27783AE08BAAACA406C27ED8BE614518C8CD7D14BBE7AFEBE1D8D03374DAE7B7564CF1182A7B3BA115CD9416AB899C5803388EE66FA3676750A77AC870EDA027DC95E57B9B4E864A3C98F1BA99A4726C085178EA8FC6C549BE5EDF970CCB8D8F9AEDEE3F5CFDE574327D05ED04060B2525FB6711F1D78254FF59089199892A9ECC7D4E4950E0CD2246E1E613889722D73DB56B24E57F3943E11520776BC4F
265:d=1  hl=2 l= 3 prim:  INTEGER           :010001

Now, to get to this offset,we try the default asn1parse

$ openssl asn1parse -i -in pub0.der -inform DER
 0:d=0  hl=4 l= 290 cons: SEQUENCE
 4:d=1  hl=2 l=  13 cons:  SEQUENCE
 6:d=2  hl=2 l=   9 prim:   OBJECT            :rsaEncryption
17:d=2  hl=2 l=   0 prim:   NULL
19:d=1  hl=4 l= 271 prim:  BIT STRING

We need to get to the BIT String part, so we add the sizes

depth_0_header(4) + depth_1_full_size(2 + 13) + Container_1_EOC_bit + BIT_STRING_header(4) = 24

This can be better visialized at: ASN.1 Parser, if you hover at tags, you will see the offsets

Another amazing resource: Microsoft's ASN.1 Docs

CSS: 100% width or height while keeping aspect ratio?

Use JQuery or so, as CSS is a general misconception (the countless questions and discussions here about simple design goals show that).

It is not possible with CSS to do what you seem to wish: image shall have width of 100%, but if this width results in a height that is too large, a max-height shall apply - and of course the correct proportions shall be preserved.

Stop an input field in a form from being submitted

You can write an event handler for onsubmit that removes the name attribute from all of the input fields that you want not to be included in the form submission.

Here's a quick untested example:

var noSubmitElements = [ 'someFormElementID1', 'someFormElementID2' ]; //...
function submitForm() {
    for( var i = 0, j = noSubmitElements.length; i < j; i++ ) {
form.onsubmit = submitForm;

How to Correctly handle Weak Self in Swift Blocks with Arguments

EDIT: Reference to an updated solution by LightMan

See LightMan's solution. Until now I was using:

input.action = { [weak self] value in
    guard let this = self else { return }
    this.someCall(value) // 'this' isn't nil


input.action = { [weak self] value in
    self?.someCall(value) // call is done if self isn't nil

Usually you don't need to specify the parameter type if it's inferred.

You can omit the parameter altogether if there is none or if you refer to it as $0 in the closure:

input.action = { [weak self] in
    self?.someCall($0) // call is done if self isn't nil

Just for completeness; if you're passing the closure to a function and the parameter is not @escaping, you don't need a weak self:

[1,2,3,4,5].forEach { self.someCall($0) }

"Instantiating" a List in Java?

In Java, List is an interface. That is, it cannot be instantiated directly.

Instead you can use ArrayList which is an implementation of that interface that uses an array as its backing store (hence the name).

Since ArrayList is a kind of List, you can easily upcast it:

List<T> mylist = new ArrayList<T>();

This is in contrast with .NET, where, since version 2.0, List<T> is the default implementation of the IList<T> interface.

How can the Euclidean distance be calculated with NumPy?

import numpy as np
from scipy.spatial import distance
input_arr = np.array([[0,3,0],[2,0,0],[0,1,3],[0,1,2],[-1,0,1],[1,1,1]]) 
test_case = np.array([0,0,0])
for i in range(0,6):
    temp = distance.euclidean(test_case,input_arr[i])

How to generate different random numbers in a loop in C++?

Stop seeding the generator every time. Pull the srand call out of the loop

Best way to determine user's locale within browser

There's a difference between the user's preferred languages and the system/browser locale.

A user can configure preferred languages in the browser, and these will be used for navigator.language(s), and used when requesting resources from a server, to request content according to a list of language priorities.

However, the browser locale will decide how to render number, date, time and currency. This setting is likely the highest ranking language, but there is no guarantee. On Mac and Linux, the locale is decided by the system regardless of the user language preferences. On Windows is can be elected among the languages in the preferred list on Chrome.

By using Intl (, developers can override/set the locale to use to render these things, but there are elements that cannot be overridden, such as the <input type="date"> format.

To properly extract this language, the only way I've found is:

(new Intl.NumberFormat()).resolvedOptions().locale

(Intl.NumberFormat().resolvedOptions().locale also seems to work)

This will create a new NumberFormat instance for the default locale and then reading back the locale of those resolved options.

Output first 100 characters in a string

String formatting using % is a great way to handle this. Here are some examples.

The formatting code '%s' converts '12345' to a string, but it's already a string.

>>> '%s' % '12345'


'%.3s' specifies to use only the first three characters.

>>> '%.3s' % '12345'


'%.7s' says to use the first seven characters, but there are only five. No problem.

>>> '%.7s' % '12345'


'%7s' uses up to seven characters, filling missing characters with spaces on the left.

>>> '%7s' % '12345'

'  12345'

'%-7s' is the same thing, except filling missing characters on the right.

>>> '%-7s' % '12345'

'12345  '

'%5.3' says use the first three characters, but fill it with spaces on the left to total five characters.

>>> '%5.3s' % '12345'

'  123'

Same thing except filling on the right.

>>> '%-5.3s' % '12345'

'123  '

Can handle multiple arguments too!

>>> 'do u no %-4.3sda%3.2s wae' % ('12345', 6789)

'do u no 123 da 67 wae'

If you require even more flexibility, str.format() is available too. Here is documentation for both.

How to print a specific row of a pandas DataFrame?

Use ix operator:

print df.ix[159220]

Can't connect to local MySQL server through socket '/tmp/mysql.sock

Looked around online too long not to contribute. After trying to type in the mysql prompt from the command line, I was continuing to receive this message:

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)

This was due to the fact that my local mysql server was no longer running. In order to restart the server, I navigated to

shell> cd /user/local/bin

where my mysql.server was located. From here, simply type:

shell> mysql.server start

This will relaunch the local mysql server.

From there you can reset the root password if need be..

mysql> UPDATE mysql.user SET Password=PASSWORD('MyNewPass')
->                   WHERE User='root';

Difference between git checkout --track origin/branch and git checkout -b branch origin/branch

The book seems to indicate that those commands yield the same effect:

The simple case is the example you just saw, running git checkout -b [branch] [remotename]/[branch]. If you have Git version 1.6.2 or later, you can also use the --track shorthand:

$ git checkout --track origin/serverfix 
Branch serverfix set up to track remote branch serverfix from origin. 
Switched to a new branch 'serverfix' 

To set up a local branch with a different name than the remote branch, you can easily use the first version with a different local branch name:

$ git checkout -b sf origin/serverfix

That's particularly handy when your bash or oh-my-zsh git completions are able to pull the origin/serverfix name for you - just append --track (or -t) and you are on your way.

constant pointer vs pointer on a constant value

The first is a constant pointer to a char and the second is a pointer to a constant char. You didn't touch all the cases in your code:

char * const pc1 = &a; /* You can't make pc1 point to anything else */
const char * pc2 = &a; /* You can't dereference pc2 to write. */

*pc1 = 'c' /* Legal. */
*pc2 = 'c' /* Illegal. */

pc1 = &b; /* Illegal, pc1 is a constant pointer. */
pc2 = &b; /* Legal, pc2 itself is not constant. */

CSS media queries for screen sizes

For all smartphones and large screens use this format of media query

/* Smartphones (portrait and landscape) ----------- */

@media only screen and (min-device-width : 320px) and (max-device-width : 480px) {
/* Styles */

/* Smartphones (landscape) ----------- */

@media only screen and (min-width : 321px) {
/* Styles */

/* Smartphones (portrait) ----------- */

@media only screen and (max-width : 320px) {
/* Styles */

/* iPads (portrait and landscape) ----------- */

@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) {
/* Styles */

/* iPads (landscape) ----------- */

@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : landscape) {
/* Styles */

/* iPads (portrait) ----------- */

@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : portrait) {
/* Styles */

iPad 3

@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : landscape) and (-webkit-min-device-pixel-ratio : 2) {
/* Styles */

@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : portrait) and (-webkit-min-device-pixel-ratio : 2) {
/* Styles */

/* Desktops and laptops ----------- */

@media only screen  and (min-width : 1224px) {
/* Styles */

/* Large screens ----------- */
@media only screen  and (min-width : 1824px) {
/* Styles */

/* iPhone 4 ----------- */

@media only screen and (min-device-width : 320px) and (max-device-width : 480px) and (orientation : landscape) and (-webkit-min-device-pixel-ratio : 2) {
/* Styles */

@media only screen and (min-device-width : 320px) and (max-device-width : 480px) and (orientation : portrait) and (-webkit-min-device-pixel-ratio : 2) {
/* Styles */

/* iPhone 5 ----------- */

@media only screen and (min-device-width: 320px) and (max-device-height: 568px) and (orientation : landscape) and (-webkit-device-pixel-ratio: 2){
/* Styles */

@media only screen and (min-device-width: 320px) and (max-device-height: 568px) and (orientation : portrait) and (-webkit-device-pixel-ratio: 2){
/* Styles */

/* iPhone 6 ----------- */

@media only screen and (min-device-width: 375px) and (max-device-height: 667px) and (orientation : landscape) and (-webkit-device-pixel-ratio: 2){
/* Styles */

@media only screen and (min-device-width: 375px) and (max-device-height: 667px) and (orientation : portrait) and (-webkit-device-pixel-ratio: 2){
/* Styles */

/* iPhone 6+ ----------- */

@media only screen and (min-device-width: 414px) and (max-device-height: 736px) and (orientation : landscape) and (-webkit-device-pixel-ratio: 2){
/* Styles */

@media only screen and (min-device-width: 414px) and (max-device-height: 736px) and (orientation : portrait) and (-webkit-device-pixel-ratio: 2){
/* Styles */

/* Samsung Galaxy S3 ----------- */

@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation : landscape) and (-webkit-device-pixel-ratio: 2){
/* Styles */

@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation : portrait) and (-webkit-device-pixel-ratio: 2){
/* Styles */

/* Samsung Galaxy S4 ----------- */
@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation : landscape) and (-webkit-device-pixel-ratio: 3){
/* Styles */

@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation : portrait) and (-webkit-device-pixel-ratio: 3){
/* Styles */

/* Samsung Galaxy S5 ----------- */

@media only screen and (min-device-width: 360px) and (max-device-height: 640px) and (orientation : landscape) and (-webkit-device-pixel-ratio: 3){
/* Styles */

@media only screen and (min-device-width: 360px) and (max-device-height: 640px) and (orientation : portrait) and (-webkit-device-pixel-ratio: 3){
/* Styles */

Using .htaccess to make all .html pages to run as .php files?

here put this in your .htaccess

AddType application/x-httpd-php .php .htm .html

more info on this page

java- reset list iterator to first element of the list

What you may actually want to use is an Iterable that can return a fresh Iterator multiple times by calling iterator().

//A function that needs to iterate multiple times can be given one Iterable:
public void func(Iterable<Type> ible) {
    Iterator<Type> it = ible.iterator(); //Gets an iterator
    while (it.hasNext()) {;
    it = ible.iterator(); //Gets a NEW iterator, also from the beginning
    while (it.hasNext()) {;

You must define what the iterator() method does just once beforehand:

void main() {
    LinkedList<String> list; //This could be any type of object that has an iterator
    //Define an Iterable that knows how to retrieve a fresh iterator
    Iterable<Type> ible = new Iterable<Type>() {
        public Iterator<Type> iterator() {
            return list.listIterator(); //Define how to get a fresh iterator from any object
    //Now with a single instance of an Iterable,
    func(ible); //you can iterate through it multiple times.

How to get item count from DynamoDB?

With the aws dynamodb cli you can get it via scan as follows:

aws dynamodb scan --table-name <TABLE_NAME> --select "COUNT"

The response will look similar to this:

    "Count": 123,
    "ScannedCount": 123,
    "ConsumedCapacity": null

notice that this information is in real time in contrast to the describe-table api

Error: TypeError: $(...).dialog is not a function

Here are the complete list of scripts required to get rid of this problem. (Make sure the file exists at the given file path)

   <script src="@Url.Content("~/Scripts/jquery-1.8.2.js")" type="text/javascript">
    <script src="@Url.Content("~/Scripts/jquery-ui-1.8.24.js")" type="text/javascript">
    <script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript">
    <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript">
    <script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript">

and also include the below css link in _Layout.cshtml for a stylish popup.

<link rel="stylesheet" type="text/css" href="../../Content/themes/base/jquery-ui.css" />

JS Client-Side Exif Orientation: Rotate and Mirror JPEG Images

Wunderbart's post worked for me combined with statler's improvements. Adding a few more comments and syntax cleanup, and also passing back the orientation value and I have the following code feel free to use. Just call readImageFile() function below and you get back the transformed image and the original orientation.

const JpegOrientation = [

//Provided a image file, determines the orientation of the file based on the EXIF information.
//Calls the "callback" function with an index into the JpegOrientation array. 
//If the image is not a JPEG, returns 0. If  the orientation value cannot be read (corrupted file?) return -1.
function getOrientation(file, callback) {
    const reader = new FileReader();
    reader.onload = (e) => {

        const view = new DataView(;
        if (view.getUint16(0, false) !== 0xFFD8) {
            return callback(0);  //NOT A JPEG FILE
        const length = view.byteLength;
        let offset = 2;
        while (offset < length) {
            if (view.getUint16(offset+2, false) <= 8)   //unknown?
                return callback(-1);
            const marker = view.getUint16(offset, false);
            offset += 2;
            if (marker === 0xFFE1) {
                if (view.getUint32(offset += 2, false) !== 0x45786966) 
                    return callback(-1); //unknown?

                const little = view.getUint16(offset += 6, false) === 0x4949;
                offset += view.getUint32(offset + 4, little);
                const tags = view.getUint16(offset, little);
                offset += 2;
                for (var i = 0; i < tags; i++) {
                    if (view.getUint16(offset + (i * 12), little) === 0x0112) {
                        return callback(view.getUint16(offset + (i * 12) + 8, little));   //found orientation code
            else if ((marker & 0xFF00) !== 0xFF00) {
            else { 
                offset += view.getUint16(offset, false);
        return callback(-1); //unknown?

//Takes a jpeg image file as base64 and transforms it back to original, providing the
//transformed image in callback.  If the image is not a jpeg or is already in normal orientation,
//just calls the callback directly with the source.
//Set type to the desired output type if transformed, default is image/jpeg for speed.
function resetOrientation(srcBase64, srcOrientation, callback, type = "image/jpeg") {
    if (srcOrientation <= 1) {  //no transform needed
    const img = new Image();    

    img.onload = () => {
        const width = img.width;
        const height = img.height;
        const canvas = document.createElement('canvas');
        const ctx = canvas.getContext("2d");

        // set proper canvas dimensions before transform & export
        if (4 < srcOrientation && srcOrientation < 9) {
            canvas.width = height;
            canvas.height = width;
        } else {
            canvas.width = width;
            canvas.height = height;

        // transform context before drawing image
        switch (srcOrientation) {
              //case 1: normal, no transform needed
              case 2:  
                  ctx.transform(-1, 0, 0, 1, width, 0); 
              case 3:
                  ctx.transform(-1, 0, 0, -1, width, height); 
              case 4: 
                  ctx.transform(1, 0, 0, -1, 0, height); 
              case 5: 
                  ctx.transform(0, 1, 1, 0, 0, 0); 
              case 6: 
                  ctx.transform(0, 1, -1, 0, height, 0); 
              case 7: 
                  ctx.transform(0, -1, -1, 0, height, width); 
              case 8: 
                  ctx.transform(0, -1, 1, 0, 0, width); 

        // draw image
        ctx.drawImage(img, 0, 0);

        //export base64
        callback(canvas.toDataURL(type), srcOrientation);

    img.src = srcBase64;

//Read an image file, providing the returned data to callback. If the image is jpeg
//and is transformed according to EXIF info, transform it first.
//The callback function receives the image data and the orientation value (index into JpegOrientation)
export function readImageFile(file, callback) {

    getOrientation(file, (orientation) => {

        console.log("Read file \"" + + "\" with orientation: " + JpegOrientation[orientation]);

        const reader = new FileReader();
        reader.onload = () => {  //when reading complete

            const img = reader.result;
            resetOrientation(img, orientation, callback);
        reader.readAsDataURL(file);  //start read

download csv file from web api in angular js

I had to implement this recently. Thought of sharing what I had figured out;

To make it work in Safari, I had to set target: '_self',. Don't worry about filename in Safari. Looks like it's not supported as mentioned here; (

The below code works fine for me in Mozilla, Chrome & Safari;

  var anchor = angular.element('<a/>');
  anchor.css({display: 'none'});
    href: 'data:attachment/csv;charset=utf-8,' + encodeURIComponent(data),
    target: '_self',
    download: 'data.csv'

How to use ScrollView in Android?

There are two options. You can make your entire layout to be scrollable or only the TextView to be scrollable.

For the first case,

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android=""
    android:layout_height="fill_parent" >

        android:layout_height="fill_parent" >

            android:stretchColumns="1" >


                    android:tint="#55ff0000" >


                    android:text="  Name " >

                    android:text="Veer" >


                    android:text="  Age" >

                    android:text="23" >


                    android:text="  Gender" >

                    android:text="Male" >


                    android:text="  Professsion" >

                    android:text="Mobile Developer" >


                    android:text="  Phone" >

                    android:text="03333736767" >


                    android:text="  Email" >

                    android:text="[email protected]" >


                    android:text="  Hobby" >

                    android:text="Play Games" >


                    android:text="  I like" >

                    android:text="Java, Objective-c" >


                    android:text="  I dislike" >

                    android:text="Microsoft" >


                    android:text="  Address" >

                    android:text="Johar Mor" >



or, as I said you can use scrollView for TextView alone.

How to create an executable .exe file from a .m file

If your code is more of a data analysis routine (vs. visualization / GUI), try GNU Octave. It's free and many of its functions are compatible with MATLAB. (Not 100% but maybe 99.5%.)

lvalue required as left operand of assignment

You cannot assign an rvalue to an rvalue.

if (strcmp("hello", "hello") = 0)

is wrong. Suggestions:

if (strcmp("hello", "hello") == 0)

= is the assign operator.
== is the equal to operator.
I know many new programmers are confused with this fact.

Merging two CSV files using Python

You need to store all of the extra rows in the files in your dictionary, not just one of them:

dict1 = {row[0]: row[1:] for row in r}
dict2 = {row[0]: row[1:] for row in r}

Then, since the values in the dictionaries are lists, you need to just concatenate the lists together:

w.writerows([[key] + dict1.get(key, []) + dict2.get(key, []) for key in keys])

Have a fixed position div that needs to scroll if content overflows

The problem with using height:100% is that it will be 100% of the page instead of 100% of the window (as you would probably expect it to be). This will cause the problem that you're seeing, because the non-fixed content is long enough to include the fixed content with 100% height without requiring a scroll bar. The browser doesn't know/care that you can't actually scroll that bar down to see it

You can use fixed to accomplish what you're trying to do.

.fixed-content {
    top: 0;

This fork of your fiddle shows my fix:

How print out the contents of a HashMap<String, String> in ascending order based on its values?

while (itr.hasNext()) {
    Vehicle vc=(Vehicle);
    if(vc.getVehicleType().equalsIgnoreCase(s)) {

how do I insert a column at a specific column index in pandas?

see docs:

using loc = 0 will insert at the beginning

df.insert(loc, column, value)

df = pd.DataFrame({'B': [1, 2, 3], 'C': [4, 5, 6]})

   B  C
0  1  4
1  2  5
2  3  6

idx = 0
new_col = [7, 8, 9]  # can be a list, a Series, an array or a scalar   
df.insert(loc=idx, column='A', value=new_col)

   A  B  C
0  7  1  4
1  8  2  5
2  9  3  6

YouTube Autoplay not working

You can use embed player with opacity over on a cover photo with a right positioned play icon. After this you can check the activeElement of your document.

Of course I know this is not an optimal solution, but works on mobile devices too.

<div style="position: relative;">
   <img src="" style="position:absolute;top:0;left:0;opacity:1;" id="cover">
   <iframe width="560" height="315" src="" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in- picture" allowfullscreen style="position: absolute;top:0;left:0;opacity:0;" id="player"></iframe>
      if(document.activeElement instanceof HTMLIFrameElement){
    } , 50);

Try it on codepen:

How to remove pip package after deleting it manually

I met the same issue while experimenting with my own Python library and what I've found out is that pip freeze will show you the library as installed if your current directory contains lib.egg-info folder. And pip uninstall <lib> will give you the same error message.

  1. Make sure your current directory doesn't have any egg-info folders
  2. Check pip show <lib-name> to see the details about the location of the library, so you can remove files manually.

Python - Get Yesterday's date as a string in YYYY-MM-DD format

You Just need to subtract one day from today's date. In Python datetime.timedelta object lets you create specific spans of time as a timedelta object.

datetime.timedelta(1) gives you the duration of "one day" and is subtractable from a datetime object. After you subtracted the objects you can use datetime.strftime in order to convert the result --which is a date object-- to string format based on your format of choice:

>>> from datetime import datetime, timedelta
>>> yesterday = - timedelta(1)

>>> type(yesterday)                                                                                                                                                                                    
>>> datetime.datetime    

>>> datetime.strftime(yesterday, '%Y-%m-%d')

Note that instead of calling the datetime.strftime function, you can also directly use strftime method of datetime objects:

>>> ( - timedelta(1)).strftime('%Y-%m-%d')

As a function:

def yesterday(string=False):
    yesterday = - timedelta(1)
    if string:
        return yesterday.strftime('%Y-%m-%d')
    return yesterday

What does /p mean in set /p?

For future reference, you can get help for any command by using the /? switch, which should explain what switches do what.

According to the set /? screen, the format for set /p is SET /P variable=[promptString] which would indicate that the p in /p is "prompt." It just prints in your example because <nul passes in a nul character which immediately ends the prompt so it just acts like it's printing. It's still technically prompting for input, it's just immediately receiving it.

/L in for /L generates a List of numbers.

From ping /?:

Usage: ping [-t] [-a] [-n count] [-l size] [-f] [-i TTL] [-v TOS]
            [-r count] [-s count] [[-j host-list] | [-k host-list]]
            [-w timeout] [-R] [-S srcaddr] [-4] [-6] target_name

    -t             Ping the specified host until stopped.
                   To see statistics and continue - type Control-Break;
                   To stop - type Control-C.
    -a             Resolve addresses to hostnames.
    -n count       Number of echo requests to send.
    -l size        Send buffer size.
    -f             Set Don't Fragment flag in packet (IPv4-only).
    -i TTL         Time To Live.
    -v TOS         Type Of Service (IPv4-only. This setting has been deprecated
                   and has no effect on the type of service field in the IP Header).
    -r count       Record route for count hops (IPv4-only).
    -s count       Timestamp for count hops (IPv4-only).
    -j host-list   Loose source route along host-list (IPv4-only).
    -k host-list   Strict source route along host-list (IPv4-only).
    -w timeout     Timeout in milliseconds to wait for each reply.
    -R             Use routing header to test reverse route also (IPv6-only).
    -S srcaddr     Source address to use.
    -4             Force using IPv4.
    -6             Force using IPv6.

Evaluate empty or null JSTL c tags

Here's an example of how to validate a int and a String that you pass from the Java Controller to the JSP file.

public ModelAndView getImportJavaToJSP() {
    ModelAndView model2= new ModelAndView("importJavaToJSPExamples");

    int someNumberValue=6;
    String someStringValue="abcdefg";
    //model2.addObject("someNumber", someNumberValue);
    model2.addObject("someString", someStringValue);

    return model2;


<%@ taglib prefix="c" uri=""%>
<c:if test="${not empty someNumber}">
    <p>someNumber is Not Empty</p>
<c:if test="${empty someNumber}">
    <p>someNumber is Empty</p>
<c:if test="${not empty someString}">
    <p>someString is Not Empty</p>
<c:if test="${empty someString}">
    <p>someString is Empty</p>

Spring @PropertySource using YAML

I have tried all of the listed questions, but all of them not work for my task: using specific yaml file for some unit test. In my case, it works like this:

@ContextConfiguration(initializers = {ConfigFileApplicationContextInitializer.class})
@TestPropertySource(properties = {"spring.config.location=file:../path/to/specific/config/application.yml"})
public class SomeTest {

    private String value;

    public void test() {
        System.out.println("value = " + value);


jQuery or JavaScript auto click


Suppose this would work too.

Extending the User model with custom fields in Django

Simple and effective approach is

from django.contrib.auth.models import User
class CustomUser(User):
     profile_pic = models.ImageField(upload_to='...')
     other_field = models.CharField()

Float a div right, without impacting on design

If you don't want the image to affect the layout at all (and float on top of other content) you can apply the following CSS to the image:


If you want it to float at the right of a particular parent section, you can add position: relative to that section.

How to execute a shell script from C in Linux?

A simple way is.....

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

#define SHELLSCRIPT "\
#/bin/bash \n\
echo \"hello\" \n\
echo \"how are you\" \n\
echo \"today\" \n\
/*Also you can write using char array without using MACRO*/
/*You can do split it with many strings finally concatenate 
  and send to the system(concatenated_string); */

int main()
    puts("Will execute sh with the following script :");
    puts("Starting now:");
    system(SHELLSCRIPT);    //it will run the script inside the c code. 
    return 0;

Say thanks to
Yoda @

How to set commands output as a variable in a batch file

I found this thread on that there Interweb thing. Boils down to:

@echo off 
setlocal enableextensions 
for /f "tokens=*" %%a in ( 
) do ( 
set myvar=%%a 

You can also redirect the output of a command to a temporary file, and then put the contents of that temporary file into your variable, likesuchashereby. It doesn't work with multiline input though.

cmd > tmpFile 
set /p myvar= < tmpFile 
del tmpFile 

Credit to the thread on Tom's Hardware.

How do I find out my MySQL URL, host, port and username?

If you use phpMyAdmin, click on Home, then Variables on the top menu. Look for the port setting on the page. The value it is set to is the port your MySQL server is running on.

Listing all the folders subfolders and files in a directory using php

Late to the show, but to build off of the accepted answer...

If you want to have all the files and directories in as array (that can be prettied-up nicely with JSON.stringify in javascript), you can modify the function to:

function listFolderFiles($dir) { 
    $arr = array();
    $ffs = scandir($dir);

    foreach($ffs as $ff) {
        if($ff != '.' && $ff != '..') {
            $arr[$ff] = array();
            if(is_dir($dir.'/'.$ff)) {
                $arr[$ff] = listFolderFiles($dir.'/'.$ff);

    return $arr;

For the Newbies...

To use the aforementioned JSON.stringify, your JS/jQuery would be something like:

var ajax = $.ajax({
    method: 'POST',
    data: {list_dirs: true}
}).done(function(msg) {
        'FILE LAYOUT<br/>' + 
            JSON.stringify(JSON.parse(msg), null, 4)

^ This is assuming you have a <pre> element in your HTML somewhere. Any flavour of AJAX will do, but I figure most people are using something similar to the jQuery above.

And the accompanying PHP:

if(isset($_POST['list_dirs'])) {
    echo json_encode(listFolderFiles($rootPath));

where you already have listFolderFiles from before.

In my case, I've set my $rootPath to the root directory of the site...

if(!isset($rootPath)) {
    $rootPath = $_SERVER['DOCUMENT_ROOT'];

The end result is something like...

|    some_file_1487.smthng    []
|    some_file_8752.smthng    []
|    CSS    
|    |    some_file_3615.smthng    []
|    |    some_file_8151.smthng    []
|    |    some_file_7571.smthng    []
|    |    some_file_5641.smthng    []
|    |    some_file_7305.smthng    []
|    |    some_file_9527.smthng    []
|    IMAGES    
|    |    some_file_4515.smthng    []
|    |    some_file_1335.smthng    []
|    |    some_file_1819.smthng    []
|    |    some_file_9188.smthng    []
|    |    some_file_4760.smthng    []
|    |    some_file_7347.smthng    []
|    JSScripts    
|    |    some_file_6449.smthng    []
|    |    some_file_7864.smthng    []
|    |    some_file_3899.smthng    []
|    |    google-code-prettify    
|    |    |    some_file_2090.smthng    []
|    |    |    some_file_5169.smthng    []
|    |    |    some_file_3426.smthng    []
|    |    |    some_file_8208.smthng    []
|    |    |    some_file_7581.smthng    []
|    |    |    some_file_4618.smthng    []
|    |    
|    |    some_file_3883.smthng    []
|    |    some_file_3713.smthng    []

... and so on...

Note: Yours will not look exactly like this - I've modified JSON.stringify to display tabs (vertical pipes), align all keyed values, remove quotes off of keys, and a couple other things. I will modify this answer with a link if I ever get to uploading it, or get enough interest.

Changing datagridview cell color based on condition

I know this is an old post, but I found my way here in 2018, so maybe someone else will too. In my opinion, the OP had a better approach (using dgv_DataBindingComplete event) than any of the answers provided. At the time of writing, all of the answers are written using paint events or cellformatting events which seems inefficient.

The OP was 99% of the way there, all they had to do was loop through their rows, test the cell value of each row, and set the BackColor, ForeColor, or whatever other property you want to set.

Please excuse the vb.NET syntax, but I think its close enough to C# that it should be clear.

Private Sub dgvFinancialResults_DataBindingComplete Handles dgvFinancialResults.DataBindingComplete
                For Each row As DataGridViewRow in dgvFinancialResults.Rows
                    Dim invoicePricePercentChange = CSng(row.Cells("Invoice Price % Change").Value)
                    Dim netPricePercentChange = CSng(row.Cells("Net Price % Change").Value)
                    Dim tradespendPricePercentChange = CSng(row.Cells("Trade Spend % Change").Value)
                    Dim dnnsiPercentChange = CSng(row.Cells("DNNSI % Change").Value)
                    Dim cogsPercentChange = CSng(row.Cells("COGS % Change").Value)
                    Dim grossProfitPercentChange = CSng(row.Cells("Gross Profit % Change").Value)

                    If invoicePricePercentChange > Single.Epsilon Then
                        row.Cells("Invoice Price % Change").Style.ForeColor = Color.Green
                        row.Cells("Invoice Price % Change").Style.ForeColor = Color.Red
                    End If

                    If netPricePercentChange > Single.Epsilon Then
                        row.Cells("Net Price % Change").Style.ForeColor = Color.Green
                        row.Cells("Net Price % Change").Style.ForeColor = Color.Red
                    End If

                    If tradespendPricePercentChange > Single.Epsilon Then
                        row.Cells("Trade Spend % Change").Style.ForeColor = Color.Green
                        row.Cells("Trade Spend % Change").Style.ForeColor = Color.Red
                    End If

                    If dnnsiPercentChange > Single.Epsilon Then
                        row.Cells("DNNSI % Change").Style.ForeColor = Color.Green
                        row.Cells("DNNSI % Change").Style.ForeColor = Color.Red
                    End If

                    If cogsPercentChange > Single.Epsilon Then
                        row.Cells("COGS % Change").Style.ForeColor = Color.Green
                        row.Cells("COGS % Change").Style.ForeColor = Color.Red
                    End If

                    If grossProfitPercentChange > Single.Epsilon Then
                        row.Cells("Gross Profit % Change").Style.ForeColor = Color.Green
                        row.Cells("Gross Profit % Change").Style.ForeColor = Color.Red
                    End If
            Catch ex As Exception
            End Try
        End Sub

TypeError: document.getElementbyId is not a function

Case sensitive: document.getElementById (notice the capital B).

How to update a menu item shown in the ActionBar?

In Kotlin 1.2 simply call:


and the onCreateOptionsMenu function will be called again.

python: sys is not defined

You're trying to import all of those modules at once. Even if one of them fails, the rest will not import. For example:

    import datetime
    import foo
    import sys
except ImportError:

Let's say foo doesn't exist. Then only datetime will be imported.

What you can do is import the sys module at the beginning of the file, before the try/except statement:

import sys
    import numpy as np
    import pyfits as pf
    import scipy.ndimage as nd
    import pylab as pl
    import os
    import heapq
    from scipy.optimize import leastsq

except ImportError:
    print "Error: missing one of the libraries (numpy, pyfits, scipy, matplotlib)"

How to initialize log4j properly?

Simply, create under src/main/assembly folder. Depending on if you want log messages to be shown in the console or in the file you modify your file. The following is going to show your messages in the console.

# Root logger option
log4j.rootLogger=INFO, stdout

# Direct log messages to stdout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

How to work offline with TFS

Simply, change the root folder name for your solution in your local machine, it will disconnect automatically.

Dynamically create and submit form

Try with this code -
It is a totally dynamic solution:

    var form = $(document.createElement('form'));
    $(form).attr("action", "reserves.php");
    $(form).attr("method", "POST");

    var input = $("<input>").attr("type", "hidden").attr("name", "mydata").val("bla");

ASP.NET MVC JsonResult Date Format

Here's my solution in Javascript - very much like JPot's, but shorter (and possibly a tiny bit faster):

value = new Date(parseInt(value.substr(6)));

"value.substr(6)" takes out the "/Date(" part, and the parseInt function ignores the non-number characters that occur at the end.

EDIT: I have intentionally left out the radix (the 2nd argument to parseInt); see my comment below. Also, please note that ISO-8601 dates are preferred over this old format -- so this format generally shouldn't be used for new development. See the excellent Json.NET library for a great alternative that serializes dates using the ISO-8601 format.

For ISO-8601 formatted JSON dates, just pass the string into the Date constructor:

var date = new Date(jsonDate); //no ugly parsing needed; full timezone support

How to send POST request?

Your data dictionary conteines names of form input fields, you just keep on right their values to find results. form view Header configures browser to retrieve type of data you declare. With requests library it's easy to send POST:

import requests

url = ""
data = {'@number': 12524, '@type': 'issue', '@action': 'show'}
headers = {"Content-type": "application/x-www-form-urlencoded", "Accept":"text/plain"}
response =, data=data, headers=headers)


More about Request object:

Word wrapping in phpstorm

Right click on the line number area and choose:

Soft-Wrap All Files or Soft-Wrap Current File, i.e.:

enter image description here

java collections - keyset() vs entrySet() in map

To make things simple , please note that every time you do the pointer moves to the next element i.e. here if you notice carefully, then the output is perfectly fine according to the logic you have written .
This may help you in understanding better:

1st Iteration of While loop(pointer is before the 1st element):
Key: if ,value: 2 {; m.get(>2}

2nd Iteration of While loop(pointer is before the 3rd element):
Key: is ,value: 2 {; m.get(>2}

3rd Iteration of While loop(pointer is before the 5th element):
Key: be ,value: 1 {"be"; m.get("up")=>"1"}

4th Iteration of While loop(pointer is before the 7th element):
Key: me ,value: 1 {"me"; m.get("delegate")=>"1"}

Key: if ,value: 1
Key: it ,value: 2
Key: is ,value: 2
Key: to ,value: 2
Key: be ,value: 1
Key: up ,value: 1
Key: me ,value: 1
Key: delegate ,value: 1

It prints:

Key: if ,value: 2
Key: is ,value: 2
Key: be ,value: 1
Key: me ,value: 1

how to parse json using groovy

        def jsonFile = new File('File Path');
        JsonSlurper jsonSlurper = new JsonSlurper();
        def parseJson = jsonSlurper.parse(jsonFile)
        String json = JsonOutput.toJson(parseJson)
        def prettyJson = JsonOutput.prettyPrint(json)

Inner join vs Where

[For a bonus point...]

Using the JOIN syntax allows you to more easily comment out the join as its all included on one line. This can be useful if you are debugging a complex query

As everyone else says, they are functionally the same, however the JOIN is more clear of a statement of intent. It therefore may help the query optimiser either in current oracle versions in certain cases (I have no idea if it does), it may help the query optimiser in future versions of Oracle (no-one has any idea), or it may help if you change database supplier.

How to convert an integer (time) to HH:MM:SS::00 in SQL Server 2008?

    DECLARE @Hour VARCHAR(10)=CAST(@Num/3600 AS  VARCHAR(2))
    DECLARE @Minute VARCHAR(10)=CAST((@Num-@Hour*3600)/60 AS  VARCHAR(2))
    DECLARE @Time VARCHAR(13)=CASE WHEN @Hour<10 THEN '0'+@Hour ELSE @Hour END+':'+CASE WHEN @Minute<10 THEN '0'+@Minute ELSE @Minute END+':00.000'
    RETURN @Time
--SELECT dbo._ICAN_FN_IntToTime(25500)

If Else If In a Sql Server Function

No one seems to have picked that if (yes=no)>na or (no=na)>yes or (na=yes)>no, you get NULL as the result. Don't believe this is what you are after.

Here's also a more condensed form of the function, which works even if any of yes, no or na_ans is NULL.

USE [***]
/****** Object:  UserDefinedFunction [dbo].[fnActionSq]    Script Date: 02/17/2011 10:21:47 ******/
ALTER FUNCTION [dbo].[fnTally] (@SchoolId nvarchar(50))
RETURNS nvarchar(3)
return (select (
       select top 1 Result from
       (select 'Yes' Result, yes_ans union all
        select 'No', no_ans union all
        select 'N/A', na_ans) [ ]
        order by yes_ans desc, Result desc)
       from dbo.qrc_maintally
       where school_id = @SchoolId)

Changing the action of a form with JavaScript/jQuery

just to add a detail to what Tamlyn wrote, instead of
$('form').get(0).setAttribute('action', 'baz'); //this works

$('form')[0].setAttribute('action', 'baz');
works equally well

Android app unable to start activity componentinfo

The question is answered already, but I want add more information about the causes.

Android app unable to start activity componentinfo

This error often comes with appropriate logs. You can read logs and can solve this issue easily.

Here is a sample log. In which you can see clearly ClassCastException. So this issue came because TextView cannot be cast to EditText.

Caused by: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText

11-04 01:24:10.403: D/AndroidRuntime(1050): Shutting down VM
11-04 01:24:10.403: W/dalvikvm(1050): threadid=1: thread exiting with uncaught exception (group=0x41465700)
11-04 01:24:10.543: E/AndroidRuntime(1050): FATAL EXCEPTION: main
11-04 01:24:10.543: E/AndroidRuntime(1050): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.troysantry.tipcalculator/com.troysantry.tipcalculator.TipCalc}: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText
11-04 01:24:10.543: E/AndroidRuntime(1050):     at
11-04 01:24:10.543: E/AndroidRuntime(1050):     at
11-04 01:24:10.543: E/AndroidRuntime(1050):     at$600(
11-04 01:24:10.543: E/AndroidRuntime(1050):     at$H.handleMessage(
11-04 01:24:10.543: E/AndroidRuntime(1050):     at android.os.Handler.dispatchMessage(
11-04 01:24:10.543: E/AndroidRuntime(1050):     at android.os.Looper.loop(
11-04 01:24:10.543: E/AndroidRuntime(1050):     at
11-04 01:24:10.543: E/AndroidRuntime(1050):     at java.lang.reflect.Method.invokeNative(Native Method)
11-04 01:24:10.543: E/AndroidRuntime(1050):     at java.lang.reflect.Method.invoke(
11-04 01:24:10.543: E/AndroidRuntime(1050):     at$
11-04 01:24:10.543: E/AndroidRuntime(1050):     at
11-04 01:24:10.543: E/AndroidRuntime(1050):     at dalvik.system.NativeStart.main(Native Method)
11-04 01:24:10.543: E/AndroidRuntime(1050): Caused by: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText
11-04 01:24:10.543: E/AndroidRuntime(1050):     at com.troysantry.tipcalculator.TipCalc.onCreate(
11-04 01:24:10.543: E/AndroidRuntime(1050):     at
11-04 01:24:10.543: E/AndroidRuntime(1050):     at
11-04 01:24:10.543: E/AndroidRuntime(1050):     at
11-04 01:24:10.543: E/AndroidRuntime(1050):     ... 11 more
11-04 01:29:11.177: I/Process(1050): Sending signal. PID: 1050 SIG: 9
11-04 01:31:32.080: D/AndroidRuntime(1109): Shutting down VM
11-04 01:31:32.080: W/dalvikvm(1109): threadid=1: thread exiting with uncaught exception (group=0x41465700)
11-04 01:31:32.194: E/AndroidRuntime(1109): FATAL EXCEPTION: main
11-04 01:31:32.194: E/AndroidRuntime(1109): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.troysantry.tipcalculator/com.troysantry.tipcalculator.TipCalc}: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText
11-04 01:31:32.194: E/AndroidRuntime(1109):     at
11-04 01:31:32.194: E/AndroidRuntime(1109):     at
11-04 01:31:32.194: E/AndroidRuntime(1109):     at$600(
11-04 01:31:32.194: E/AndroidRuntime(1109):     at$H.handleMessage(
11-04 01:31:32.194: E/AndroidRuntime(1109):     at android.os.Handler.dispatchMessage(
11-04 01:31:32.194: E/AndroidRuntime(1109):     at android.os.Looper.loop(
11-04 01:31:32.194: E/AndroidRuntime(1109):     at
11-04 01:31:32.194: E/AndroidRuntime(1109):     at java.lang.reflect.Method.invokeNative(Native Method)
11-04 01:31:32.194: E/AndroidRuntime(1109):     at java.lang.reflect.Method.invoke(
11-04 01:31:32.194: E/AndroidRuntime(1109):     at$
11-04 01:31:32.194: E/AndroidRuntime(1109):     at
11-04 01:31:32.194: E/AndroidRuntime(1109):     at dalvik.system.NativeStart.main(Native Method)
11-04 01:31:32.194: E/AndroidRuntime(1109): Caused by: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText
11-04 01:31:32.194: E/AndroidRuntime(1109):     at com.troysantry.tipcalculator.TipCalc.onCreate(
11-04 01:31:32.194: E/AndroidRuntime(1109):     at
11-04 01:31:32.194: E/AndroidRuntime(1109):     at
11-04 01:31:32.194: E/AndroidRuntime(1109):     at
11-04 01:31:32.194: E/AndroidRuntime(1109):     ... 11 more
11-04 01:36:33.195: I/Process(1109): Sending signal. PID: 1109 SIG: 9
11-04 02:11:09.684: D/AndroidRuntime(1167): Shutting down VM
11-04 02:11:09.684: W/dalvikvm(1167): threadid=1: thread exiting with uncaught exception (group=0x41465700)
11-04 02:11:09.855: E/AndroidRuntime(1167): FATAL EXCEPTION: main
11-04 02:11:09.855: E/AndroidRuntime(1167): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.troysantry.tipcalculator/com.troysantry.tipcalculator.TipCalc}: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText
11-04 02:11:09.855: E/AndroidRuntime(1167):     at
11-04 02:11:09.855: E/AndroidRuntime(1167):     at
11-04 02:11:09.855: E/AndroidRuntime(1167):     at$600(
11-04 02:11:09.855: E/AndroidRuntime(1167):     at$H.handleMessage(
11-04 02:11:09.855: E/AndroidRuntime(1167):     at android.os.Handler.dispatchMessage(
11-04 02:11:09.855: E/AndroidRuntime(1167):     at android.os.Looper.loop(
11-04 02:11:09.855: E/AndroidRuntime(1167):     at
11-04 02:11:09.855: E/AndroidRuntime(1167):     at java.lang.reflect.Method.invokeNative(Native Method)
11-04 02:11:09.855: E/AndroidRuntime(1167):     at java.lang.reflect.Method.invoke(
11-04 02:11:09.855: E/AndroidRuntime(1167):     at$
11-04 02:11:09.855: E/AndroidRuntime(1167):     at
11-04 02:11:09.855: E/AndroidRuntime(1167):     at dalvik.system.NativeStart.main(Native Method)
11-04 02:11:09.855: E/AndroidRuntime(1167): Caused by: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText
11-04 02:11:09.855: E/AndroidRuntime(1167):     at com.troysantry.tipcalculator.TipCalc.onCreate(
11-04 02:11:09.855: E/AndroidRuntime(1167):     at
11-04 02:11:09.855: E/AndroidRuntime(1167):     at
11-04 02:11:09.855: E/AndroidRuntime(1167):     at
11-04 02:11:09.855: E/AndroidRuntime(1167):     ... 11 more

Some Common Mistakes.

1.findViewById() of non existing view

Like when you use findViewById( when button id does not exist in layout XML.

2. Wrong cast.

If you wrong cast some class, then you get this error. Like you cast RelativeLayout to LinearLayout or EditText to TextView.

3. Activity not registered in manifest.xml

If you did not register Activity in manifest.xml then this error comes.

4. findViewById() with declaration at top level

Below code is incorrect. This will create error. Because you should do findViewById() after calling setContentView(). Because an View can be there after it is created.

public class MainActivity extends Activity {

  ImageView mainImage = (ImageView) findViewById(; //incorrect way

  protected void onCreate(Bundle savedInstanceState){
    mainImage = (ImageView) findViewById(; //correct way

5. Starting abstract Activity class.

When you try to start an Activity which is abstract, you will will get this error. So just remove abstract keyword before activity class name.

6. Using kotlin but kotlin not configured.

If your activity is written in Kotlin and you have not setup kotlin in your app. then you will get error. You can follow simple steps as written in Android Link or Kotlin Link. You can check this answer too.

More information

Read about Downcast and Upcast

Read about findViewById() method of Activity class

Super keyword in Java

How to register activity in manifest

Difference between RegisterStartupScript and RegisterClientScriptBlock?

Here's an old discussion thread where I listed the main differences and the conditions in which you should use each of these methods. I think you may find it useful to go through the discussion.

To explain the differences as relevant to your posted example:

a. When you use RegisterStartupScript, it will render your script after all the elements in the page (right before the form's end tag). This enables the script to call or reference page elements without the possibility of it not finding them in the Page's DOM.

Here is the rendered source of the page when you invoke the RegisterStartupScript method:

<html xmlns="">
<head id="Head1"><title></title></head>
    <form name="form1" method="post" action="StartupScript.aspx" id="form1">
            <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="someViewstategibberish" />
        <div> <span id="lblDisplayDate">Label</span>
            <br />
            <input type="submit" name="btnPostback" value="Register Startup Script" id="btnPostback" />
            <br />
            <input type="submit" name="btnPostBack2" value="Register" id="btnPostBack2" />
            <input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="someViewstategibberish" />
        <!-- Note this part -->
        <script language='javascript'>
            var lbl = document.getElementById('lblDisplayDate');
   = 'red';
    <!-- Note this part -->

b. When you use RegisterClientScriptBlock, the script is rendered right after the Viewstate tag, but before any of the page elements. Since this is a direct script (not a function that can be called, it will immediately be executed by the browser. But the browser does not find the label in the Page's DOM at this stage and hence you should receive an "Object not found" error.

Here is the rendered source of the page when you invoke the RegisterClientScriptBlock method:

<html xmlns="">
<head id="Head1"><title></title></head>
    <form name="form1" method="post" action="StartupScript.aspx" id="form1">
            <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="someViewstategibberish" />
        <script language='javascript'>
            var lbl = document.getElementById('lblDisplayDate');
            // Error is thrown in the next line because lbl is null.
   = 'green';

Therefore, to summarize, you should call the latter method if you intend to render a function definition. You can then render the call to that function using the former method (or add a client side attribute).

Edit after comments:

For instance, the following function would work:

protected void btnPostBack2_Click(object sender, EventArgs e) 
  System.Text.StringBuilder sb = new System.Text.StringBuilder(); 
  sb.Append("<script language='javascript'>function ChangeColor() {"); 
  sb.Append("var lbl = document.getElementById('lblDisplayDate');"); 

  //Render the function definition. 
  if (!ClientScript.IsClientScriptBlockRegistered("JSScriptBlock")) 
    ClientScript.RegisterClientScriptBlock(this.GetType(), "JSScriptBlock", sb.ToString()); 

  //Render the function invocation. 
  string funcCall = "<script language='javascript'>ChangeColor();</script>"; 

  if (!ClientScript.IsStartupScriptRegistered("JSScript"))
    ClientScript.RegisterStartupScript(this.GetType(), "JSScript", funcCall); 

How to create a self-signed certificate with OpenSSL

You have the general procedure correct. The syntax for the command is below.

openssl req -new -key {private key file} -out {output file}

However, the warnings are displayed, because the browser was not able to verify the identify by validating the certificate with a known Certificate Authority (CA).

As this is a self-signed certificate there is no CA and you can safely ignore the warning and proceed. Should you want to get a real certificate that will be recognizable by anyone on the public Internet then the procedure is below.

  1. Generate a private key
  2. Use that private key to create a CSR file
  3. Submit CSR to CA (Verisign or others, etc.)
  4. Install received cert from CA on web server
  5. Add other certs to authentication chain depending on the type cert

I have more details about this in a post at Securing the Connection: Creating a Security Certificate with OpenSSL

How to call a function, PostgreSQL

I had this same issue while trying to test a very similar function that uses a SELECT statement to decide if a INSERT or an UPDATE should be done. This function was a re-write of a T-SQL stored procedure.
When I tested the function from the query window I got the error "query has no destination for result data". I finally figured out that because I used a SELECT statement inside the function that I could not test the function from the query window until I assigned the results of the SELECT to a local variable using an INTO statement. This fixed the problem.

If the original function in this thread was changed to the following it would work when called from the query window,

   v_temp integer;
SELECT 1 INTO v_temp
WHERE "userID" = $1;

Convert byte to string in Java

you can use

the character equivalent to 0x63 is 'c' but byte equivalent to it is 99

System.out.println("byte "+(char)0x63); 

Even though JRE 8 is installed on my MAC -" No Java Runtime present,requesting to install " gets displayed in terminal


For JDK 11 try this:

To handle this problem in a clean way, I suggest to use brew and jenv.

For Java 11 follow this 2 steps, first :

brew reinstall jenv 
brew reinstall openjdk@${JAVA_VERSION}
jenv add /usr/local/opt/openjdk@${JAVA_VERSION}/
jenv global ${JAVA_VERSION}

And add this at end of your shell config scripts
~/.bashrc or ~/.zshrc

export PATH="$HOME/.jenv/bin:$PATH"
eval "$(jenv init -)"
export JAVA_HOME="$HOME/.jenv/versions/`jenv version-name`"

Problem solved!

Then restart your shell and try to execute java -version

Note: If you have this problem, your current JDK version is not existent or misconfigured (or may be you have only JRE).

Script to Change Row Color when a cell changes text

I think simpler (though without a script) assuming the Status column is ColumnS.

Select ColumnS and clear formatting from it. Select entire range to be formatted and Format, Conditional formatting..., Format cells if... Custom formula is and:


with fill of choice and Done.

This is not case sensitive (change search to find for that) and will highlight a row where ColumnS contains the likes of Now complete (though also Not yet complete).

fetch from origin with deleted remote branches?

Regarding git fetch -p, its behavior changed in Git 1.9, and only Git 2.9.x/2.10 reflects that.

See commit 9e70233 (13 Jun 2016) by Jeff King (peff).
(Merged by Junio C Hamano -- gitster -- in commit 1c22105, 06 Jul 2016)

fetch: document that pruning happens before fetching

This was changed in 10a6cc8 (fetch --prune: Run prune before fetching, 2014-01-02), but it seems that nobody in that discussion realized we were advertising the "after" explicitly.

So the documentation now states:

Before fetching, remove any remote-tracking references that no longer exist on the remote

That is because:

When we have a remote-tracking branch named "frotz/nitfol" from a previous fetch, and the upstream now has a branch named "frotz", fetch would fail to remove "frotz/nitfol" with a "git fetch --prune" from the upstream. git would inform the user to use "git remote prune" to fix the problem.

Change the way "fetch --prune" works by moving the pruning operation before the fetching operation. This way, instead of warning the user of a conflict, it automatically fixes it.

how does int main() and void main() work

Neither main() or void main() are standard C. The former is allowed as it has an implicit int return value, making it the same as int main(). The purpose of main's return value is to return an exit status to the operating system.

In standard C, the only valid signatures for main are:

int main(void)


int main(int argc, char **argv)

The form you're using: int main() is an old style declaration that indicates main takes an unspecified number of arguments. Don't use it - choose one of those above.

making a paragraph in html contain a text from a file

You can use a simple HTML element <embed src="file.txt"> it loads the external resource and displays it on the screen no js needed

Bootstrap carousel multiple frames at once

I had the same problem and the solutions described here worked well. But I wanted to support window size (and layout) changes. The result is a small library that solves all the calculation. Check it out here:

To make the script work, you have to add a new <div> wrapper with the class .item-content directly into your .item <div>. Example:

<div class="carousel slide multiple" id="very-cool-carousel" data-ride="carousel">
    <div class="carousel-inner" role="listbox">
        <div class="item active">
            <div class="item-content">
                First page
        <div class="item active">
            <div class="item-content">
                Second page

Usage of this library:'div.carousel');

To change the settings:

socialbitBootstrapCarouselPageMerger.settings.spaceCalculationFactor = 0.82;


As you can see, the carousel gets updated to show more controls when you resize the window. Check out the watchWindowSizeTimeout setting to control the timeout for reacting to window size changes.

How to "perfectly" override a dict?

How can I make as "perfect" a subclass of dict as possible?

The end goal is to have a simple dict in which the keys are lowercase.

  • If I override __getitem__/__setitem__, then get/set don't work. How do I make them work? Surely I don't need to implement them individually?

  • Am I preventing pickling from working, and do I need to implement __setstate__ etc?

  • Do I need repr, update and __init__?

  • Should I just use mutablemapping (it seems one shouldn't use UserDict or DictMixin)? If so, how? The docs aren't exactly enlightening.

The accepted answer would be my first approach, but since it has some issues, and since no one has addressed the alternative, actually subclassing a dict, I'm going to do that here.

What's wrong with the accepted answer?

This seems like a rather simple request to me:

How can I make as "perfect" a subclass of dict as possible? The end goal is to have a simple dict in which the keys are lowercase.

The accepted answer doesn't actually subclass dict, and a test for this fails:

>>> isinstance(MyTransformedDict([('Test', 'test')]), dict)

Ideally, any type-checking code would be testing for the interface we expect, or an abstract base class, but if our data objects are being passed into functions that are testing for dict - and we can't "fix" those functions, this code will fail.

Other quibbles one might make:

  • The accepted answer is also missing the classmethod: fromkeys.
  • The accepted answer also has a redundant __dict__ - therefore taking up more space in memory:

    >>> = 'bar'
    >>> s.__dict__
    {'foo': 'bar', 'store': {'test': 'test'}}

Actually subclassing dict

We can reuse the dict methods through inheritance. All we need to do is create an interface layer that ensures keys are passed into the dict in lowercase form if they are strings.

If I override __getitem__/__setitem__, then get/set don't work. How do I make them work? Surely I don't need to implement them individually?

Well, implementing them each individually is the downside to this approach and the upside to using MutableMapping (see the accepted answer), but it's really not that much more work.

First, let's factor out the difference between Python 2 and 3, create a singleton (_RaiseKeyError) to make sure we know if we actually get an argument to dict.pop, and create a function to ensure our string keys are lowercase:

from itertools import chain
try:              # Python 2
    str_base = basestring
    items = 'iteritems'
except NameError: # Python 3
    str_base = str, bytes, bytearray
    items = 'items'

_RaiseKeyError = object() # singleton for no-default behavior

def ensure_lower(maybe_str):
    """dict keys can be any hashable object - only call lower if str"""
    return maybe_str.lower() if isinstance(maybe_str, str_base) else maybe_str

Now we implement - I'm using super with the full arguments so that this code works for Python 2 and 3:

class LowerDict(dict):  # dicts take a mapping or iterable as their optional first argument
    __slots__ = () # no __dict__ - that would be redundant
    @staticmethod # because this doesn't make sense as a global function.
    def _process_args(mapping=(), **kwargs):
        if hasattr(mapping, items):
            mapping = getattr(mapping, items)()
        return ((ensure_lower(k), v) for k, v in chain(mapping, getattr(kwargs, items)()))
    def __init__(self, mapping=(), **kwargs):
        super(LowerDict, self).__init__(self._process_args(mapping, **kwargs))
    def __getitem__(self, k):
        return super(LowerDict, self).__getitem__(ensure_lower(k))
    def __setitem__(self, k, v):
        return super(LowerDict, self).__setitem__(ensure_lower(k), v)
    def __delitem__(self, k):
        return super(LowerDict, self).__delitem__(ensure_lower(k))
    def get(self, k, default=None):
        return super(LowerDict, self).get(ensure_lower(k), default)
    def setdefault(self, k, default=None):
        return super(LowerDict, self).setdefault(ensure_lower(k), default)
    def pop(self, k, v=_RaiseKeyError):
        if v is _RaiseKeyError:
            return super(LowerDict, self).pop(ensure_lower(k))
        return super(LowerDict, self).pop(ensure_lower(k), v)
    def update(self, mapping=(), **kwargs):
        super(LowerDict, self).update(self._process_args(mapping, **kwargs))
    def __contains__(self, k):
        return super(LowerDict, self).__contains__(ensure_lower(k))
    def copy(self): # don't delegate w/ super - dict.copy() -> dict :(
        return type(self)(self)
    def fromkeys(cls, keys, v=None):
        return super(LowerDict, cls).fromkeys((ensure_lower(k) for k in keys), v)
    def __repr__(self):
        return '{0}({1})'.format(type(self).__name__, super(LowerDict, self).__repr__())

We use an almost boiler-plate approach for any method or special method that references a key, but otherwise, by inheritance, we get methods: len, clear, items, keys, popitem, and values for free. While this required some careful thought to get right, it is trivial to see that this works.

(Note that haskey was deprecated in Python 2, removed in Python 3.)

Here's some usage:

>>> ld = LowerDict(dict(foo='bar'))
>>> ld['FOO']
>>> ld['foo']
>>> ld.pop('FoO')
>>> ld.setdefault('Foo')
>>> ld
{'foo': None}
>>> ld.get('Bar')
>>> ld.setdefault('Bar')
>>> ld
{'bar': None, 'foo': None}
>>> ld.popitem()
('bar', None)

Am I preventing pickling from working, and do I need to implement __setstate__ etc?


And the dict subclass pickles just fine:

>>> import pickle
>>> pickle.dumps(ld)
>>> pickle.loads(pickle.dumps(ld))
{'foo': None}
>>> type(pickle.loads(pickle.dumps(ld)))
<class '__main__.LowerDict'>


Do I need repr, update and __init__?

We defined update and __init__, but you have a beautiful __repr__ by default:

>>> ld # without __repr__ defined for the class, we get this
{'foo': None}

However, it's good to write a __repr__ to improve the debugability of your code. The ideal test is eval(repr(obj)) == obj. If it's easy to do for your code, I strongly recommend it:

>>> ld = LowerDict({})
>>> eval(repr(ld)) == ld
>>> ld = LowerDict(dict(a=1, b=2, c=3))
>>> eval(repr(ld)) == ld

You see, it's exactly what we need to recreate an equivalent object - this is something that might show up in our logs or in backtraces:

>>> ld
LowerDict({'a': 1, 'c': 3, 'b': 2})


Should I just use mutablemapping (it seems one shouldn't use UserDict or DictMixin)? If so, how? The docs aren't exactly enlightening.

Yeah, these are a few more lines of code, but they're intended to be comprehensive. My first inclination would be to use the accepted answer, and if there were issues with it, I'd then look at my answer - as it's a little more complicated, and there's no ABC to help me get my interface right.

Premature optimization is going for greater complexity in search of performance. MutableMapping is simpler - so it gets an immediate edge, all else being equal. Nevertheless, to lay out all the differences, let's compare and contrast.

I should add that there was a push to put a similar dictionary into the collections module, but it was rejected. You should probably just do this instead:


It should be far more easily debugable.

Compare and contrast

There are 6 interface functions implemented with the MutableMapping (which is missing fromkeys) and 11 with the dict subclass. I don't need to implement __iter__ or __len__, but instead I have to implement get, setdefault, pop, update, copy, __contains__, and fromkeys - but these are fairly trivial, since I can use inheritance for most of those implementations.

The MutableMapping implements some things in Python that dict implements in C - so I would expect a dict subclass to be more performant in some cases.

We get a free __eq__ in both approaches - both of which assume equality only if another dict is all lowercase - but again, I think the dict subclass will compare more quickly.


  • subclassing MutableMapping is simpler with fewer opportunities for bugs, but slower, takes more memory (see redundant dict), and fails isinstance(x, dict)
  • subclassing dict is faster, uses less memory, and passes isinstance(x, dict), but it has greater complexity to implement.

Which is more perfect? That depends on your definition of perfect.

Is #pragma once a safe include guard?

Using #pragma once should work on any modern compiler, but I don't see any reason not to use a standard #ifndef include guard. It works just fine. The one caveat is that GCC didn't support #pragma once before version 3.4.

I also found that, at least on GCC, it recognizes the standard #ifndef include guard and optimizes it, so it shouldn't be much slower than #pragma once.


Try this

UPDATE `table` SET `uid` = CASE
    WHEN id = 1 THEN 2952
    WHEN id = 2 THEN 4925
    WHEN id = 3 THEN 1592
    ELSE `uid`
WHERE id  in (1,2,3)

Laravel Update Query

You could use the Laravel query builder, but this is not the best way to do it.

Check Wader's answer below for the Eloquent way - which is better as it allows you to check that there is actually a user that matches the email address, and handle the error if there isn't.

        ->where('email', $userEmail)  // find your user by their email
        ->limit(1)  // optional - to ensure only one record is updated.
        ->update(array('member_type' => $plan));  // update the record in the DB. 

If you have multiple fields to update you can simply add more values to that array at the end.

How to get column values in one comma separated value

In Sql Server you can use it.



    UserName varchar(30) NOT NULL 


INSERT INTO @UserMaster VALUES (1,'Rakesh')

INSERT INTO @UserMaster VALUES (2,'Ashish')

INSERT INTO @UserMaster VALUES (3,'Sagar')

SELECT * FROM @UserMaster


SELECT @CSV = COALESCE(@CSV + ', ', '') + UserName from @UserMaster 


How can I get the index from a JSON object with value?

In all previous solutions, you must know the name of the attribute or field. A more generic solution for any attribute is this:

let data = 
    "name": "placeHolder",
    "section": "right"
}, {
    "name": "Overview",
    "section": "left"
}, {
    "name": "ByFunction",
    "section": "left"
}, {
    "name": "Time",
    "section": "left"
}, {
    "name": "allFit",
    "section": "left"
}, {
    "name": "allbMatches",
    "section": "left"
}, {
    "name": "allOffers",
    "section": "left"
}, {
    "name": "allInterests",
    "section": "left"
}, {
    "name": "allResponses",
    "section": "left"
}, {
    "name": "divChanged",
    "section": "right"

function findByKey(key, value) {
    return (item, i) => item[key] === value

let findParams = findByKey('name', 'allOffers')
let index = data.findIndex(findParams)

C# function to return array

 static void Main()
             for (int i=0; i<GetNames().Length; i++)
                    Console.WriteLine (GetNames()[i]);

  static string[] GetNames()
         string[] ret = {"Answer", "by", "Anonymous", "Pakistani"};
         return ret;

Change border color on <select> HTML form

As Diodeus stated, IE doesn't allow anything but the default border for <select> elements. However, I know of two hacks to achieve a similar effect :

  1. Use a DIV that is placed absolutely at the same position as the dropdown and set it's borders. It will appear that the dropdown has a border.

  2. Use a Javascript solution, for instance, the one provided here.

It may however prove to be too much effort, so you should evaluate if you really require the border.

How can I create a dynamically sized array of structs?

For the test code: if you want to modify a pointer in a function, you should pass a "pointer to pointer" to the function. Corrected code is as follows:

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

typedef struct
    char *str1;
    char *str2;
} words;

void LoadData(words**, int*);

    words **x;
    int num;

    LoadData(x, &num);

    printf("%s %s\n", (*x[0]).str1, (*x[0]).str2);
    printf("%s %s\n", (*x[1]).str1, (*x[1]).str2);

void LoadData(words **x, int *num)
    *x = (words*) malloc(sizeof(words));

    (*x[0]).str1 = "johnnie\0";
    (*x[0]).str2 = "krapson\0";

    *x = (words*) realloc(*x, sizeof(words) * 2);
    (*x[1]).str1 = "bob\0";
    (*x[1]).str2 = "marley\0";

    *num = *num + 1;

Determine what attributes were changed in Rails after_save callback?

To anyone seeing this later on, as it currently (Aug. 2017) tops google: It is worth mentioning, that this behavior will be altered in Rails 5.2, and has deprecation warnings as of Rails 5.1, as ActiveModel::Dirty changed a bit.

What do I change?

If you're using attribute_changed? method in the after_*-callbacks, you'll see a warning like:

DEPRECATION WARNING: The behavior of attribute_changed? inside of after callbacks will be changing in the next version of Rails. The new return value will reflect the behavior of calling the method after save returned (e.g. the opposite of what it returns now). To maintain the current behavior, use saved_change_to_attribute? instead. (called from some_callback at /PATH_TO/app/models/user.rb:15)

As it mentions, you could fix this easily by replacing the function with saved_change_to_attribute?. So for example, name_changed? becomes saved_change_to_name?.

Likewise, if you're using the attribute_change to get the before-after values, this changes as well and throws the following:

DEPRECATION WARNING: The behavior of attribute_change inside of after callbacks will be changing in the next version of Rails. The new return value will reflect the behavior of calling the method after save returned (e.g. the opposite of what it returns now). To maintain the current behavior, use saved_change_to_attribute instead. (called from some_callback at /PATH_TO/app/models/user.rb:20)

Again, as it mentions, the method changes name to saved_change_to_attribute which returns ["old", "new"]. or use saved_changes, which returns all the changes, and these can be accessed as saved_changes['attribute'].

Nullable type as a generic parameter possible?

Multiple generic constraints can't be combined in an OR fashion (less restrictive), only in an AND fashion (more restrictive). Meaning that one method can't handle both scenarios. The generic constraints also cannot be used to make a unique signature for the method, so you'd have to use 2 separate method names.

However, you can use the generic constraints to make sure that the methods are used correctly.

In my case, I specifically wanted null to be returned, and never the default value of any possible value types. GetValueOrDefault = bad. GetValueOrNull = good.

I used the words "Null" and "Nullable" to distinguish between reference types and value types. And here is an example of a couple extension methods I wrote that compliments the FirstOrDefault method in System.Linq.Enumerable class.

    public static TSource FirstOrNull<TSource>(this IEnumerable<TSource> source)
        where TSource: class
        if (source == null) return null;
        var result = source.FirstOrDefault();   // Default for a class is null
        return result;

    public static TSource? FirstOrNullable<TSource>(this IEnumerable<TSource?> source)
        where TSource : struct
        if (source == null) return null;
        var result = source.FirstOrDefault();   // Default for a nullable is null
        return result;

Why is this jQuery click function not working?

I found the best solution for this problem by using ON with $(document).

 $(document).on('click', '#yourid', function() { alert("hello"); });

for id start with see below:

$(document).on('click', 'div[id^="start"]', function() {
alert ('hello'); });

finally after 1 week I not need to add onclick triger. I hope this will help many people

How to get distinct results in hibernate with joins and row-based limiting (paging)?

A slight improvement building on FishBoy's suggestion.

It is possible to do this kind of query in one hit, rather than in two separate stages. i.e. the single query below will page distinct results correctly, and also return entities instead of just IDs.

Simply use a DetachedCriteria with an id projection as a subquery, and then add paging values on the main Criteria object.

It will look something like this:

DetachedCriteria idsOnlyCriteria = DetachedCriteria.forClass(MyClass.class);
//add other joins and query params here

Criteria criteria = getSession().createCriteria(myClass);
criteria.add(Subqueries.propertyIn("id", idsOnlyCriteria));
return criteria.list();

How can I make an entire HTML form "readonly"?

Have all the form id's numbered and run a for loop in JS.

 for(id = 0; id<NUM_ELEMENTS; id++)
   document.getElementById(id).disabled = false; 

.gitignore file for java eclipse project

You need to add your source files with git add or the GUI equivalent so that Git will begin tracking them.

Use git status to see what Git thinks about the files in any given directory.

Can I set up HTML/Email Templates with ASP.NET?

Note that the aspx and ascx solutions require a current HttpContext, so cannot be used asynchronously (eg in threads) without a lot of work.

google console error `OR-IEH-01`

Recently I was also having this issue, then I contacted Google Support and they gave me this link to provide required info, I posted and within 24 hours my problem was fixed.


Java Regex to Validate Full Name allow only Spaces and Letters

try this regex (allowing Alphabets, Dots, Spaces):

"^[A-Za-z\s]{1,}[\.]{0,1}[A-Za-z\s]{0,}$" //regular
"^\pL+[\pL\pZ\pP]{0,}$" //unicode

This will also ensure DOT never comes at the start of the name.

HTML 5 video recording and storing a stream

RecordRTC: WebRTC audio/video recording

  • Audio recording both for Chrome and Firefox
  • Video/Gif recording for Chrome; (Firefox has a little bit issues, will be recovered soon)

Demo :

Creating .webm video from getUserMedia()

Demo :

Capturing Audio & Video in HTML5

git push rejected: error: failed to push some refs

'remote: error: denying non-fast-forward refs/heads/master (you should pull first)'

That message suggests that there is a hook on the server that is rejecting fast forward pushes. Yes, it is usually not recommended and is a good guard, but since you are the only person using it and you want to do the force push, contact the administrator of the repo to allow to do the non-fastforward push by temporarily removing the hook or giving you the permission in the hook to do so.

How to override and extend basic Django admin templates?

This site had a simple solution that worked with my Django 1.7 configuration.

FIRST: Make a symlink named admin_src in your project's template/ directory to your installed Django templates. For me on Dreamhost using a virtualenv, my "source" Django admin templates were in:


SECOND: Create an admin directory in templates/

So my project's template/ directory now looked like this:

   admin_src -> [to django source]

THIRD: In your new template/admin/ directory create a base.html file with this content:

{% extends "admin_src/base.html" %}

{% block extrahead %}
<link rel='shortcut icon' href='{{ STATIC_URL }}img/favicon-admin.ico' />
{% endblock %}

FOURTH: Add your admin favicon-admin.ico into your static root img folder.

Done. Easy.

memcpy() vs memmove()

C11 standard draft

The C11 N1570 standard draft says: "The memcpy function":

2 The memcpy function copies n characters from the object pointed to by s2 into the object pointed to by s1. If copying takes place between objects that overlap, the behavior is undefined. "The memmove function":

2 The memmove function copies n characters from the object pointed to by s2 into the object pointed to by s1. Copying takes place as if the n characters from the object pointed to by s2 are first copied into a temporary array of n characters that does not overlap the objects pointed to by s1 and s2, and then the n characters from the temporary array are copied into the object pointed to by s1

Therefore, any overlap on memcpy leads to undefined behavior, and anything can happen: bad, nothing or even good. Good is rare though :-)

memmove however clearly says that everything happens as if an intermediate buffer is used, so clearly overlaps are OK.

C++ std::copy is more forgiving however, and allows overlaps: Does std::copy handle overlapping ranges?

npm install errors with Error: ENOENT, chmod

I had the same problem, and just found a handling not mentioned here. Though I'd contribute to the community:

npm install -g myapp was not copying the bin directory. I found this to be because I did not include it in the files in my package.json

"files": [
  "bin" // this was missing

How do I use a 32-bit ODBC driver on 64-bit Server 2008 when the installer doesn't create a standard DSN?

A lot of these answers are pretty old, so I thought I would update with a solution that I think is helpful.

Our issue was similar to OP's, we upgraded 32 bit XP machines to 64 bit windows 7 and our application software that uses a 32 bit ODBC driver stopped being able to write to our database.

Turns out, there are two ODBC Data Source Managers, one for 32 bit and one for 64 bit. So I had to run the 32 bit version which is found in C:\Windows\SysWOW64\odbcad32.exe. Inside the ODBC Data Source Manager, I was able to go to the System DSN tab and Add my driver to the list using the Add button. (You can check the Drivers tab to see a list of the drivers you can add, if your driver isn't in this list then you may need to install it).

The next issue was the software that we ran was compiled to use 'Any CPU'. This would see the operating system was 64 bit, so it would look at the 64 bit ODBC Data Sources. So I had to force the program to compile as an x86 program, which then tells it to look at the 32 bit ODBC Data Sources. To set your program to x86, in Visual Studio go to your project properties and under the build tab at the top there is a platform drop down list, and choose x86. If you don't have the source code and can't compile the program as x86, you might be able to right click the program .exe and go to the compatibility tab and choose a compatibility that works for you.

Once I had the drivers added and the program pointing to the right drivers, everything worked like it use to. Hopefully this helps anyone working with older software.

Best way to move files between S3 buckets?

I know this is an old thread but for others who reach there my suggestion is to create a scheduled job to copy content from production bucket to development one.

You can use If you use .NET this article might help you

How to specify a local file within html using the file: scheme?

I had similar issue before and in my case the file was in another machine so i have mapped network drive z to the folder location where my file is then i created a context in tomcat so in my web project i could access the HTML file via context

Read properties file outside JAR file

This works for me. Load your properties file from current directory.

Attention: The method Properties#load uses ISO-8859-1 encoding.

Properties properties = new Properties();
properties.load(new FileReader(new File(".").getCanonicalPath() + File.separator + ""));
properties.forEach((k, v) -> {
            System.out.println(k + " : " + v);

Make sure, that is at the current directory . You can just write a little startup script that switches into to the right directory in before, like

#! /bin/bash
scriptdir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" 
cd $scriptdir
java -jar MyExecutable.jar
cd -

In your project just put the file in your project root, in order to make this code work from your IDE as well.