Programs & Examples On #Soundcloud

SoundCloud is a social audio storage service and community. Their api allows for deep mashups, allowing access to nearly all track meta data, and provides streaming and downloads in various formats.

Converting milliseconds to minutes and seconds with Javascript

With hours, 0-padding minutes and seconds:

var ms = 298999;
var d = new Date(1000*Math.round(ms/1000)); // round to nearest second
function pad(i) { return ('0'+i).slice(-2); }
var str = d.getUTCHours() + ':' + pad(d.getUTCMinutes()) + ':' + pad(d.getUTCSeconds());
console.log(str); // 0:04:59

How to create a stopwatch using JavaScript?

Two native solutions

  • performance.now --> Call to ... took 6.414999981643632 milliseconds.
  • console.time --> Call to ... took 5.815 milliseconds

The difference between both is precision.

For usage and explanation read on.



Performance.now (For microsecond precision use)

_x000D_
_x000D_
    var t0 = performance.now();
    doSomething();
    var t1 = performance.now();

    console.log("Call to doSomething took " + (t1 - t0) + " milliseconds.");
            
    function doSomething(){    
       for(i=0;i<1000000;i++){var x = i*i;}
    }
_x000D_
_x000D_
_x000D_

performance.now

Unlike other timing data available to JavaScript (for example Date.now), the timestamps returned by Performance.now() are not limited to one-millisecond resolution. Instead, they represent times as floating-point numbers with up to microsecond precision.

Also unlike Date.now(), the values returned by Performance.now() always increase at a constant rate, independent of the system clock (which might be adjusted manually or skewed by software like NTP). Otherwise, performance.timing.navigationStart + performance.now() will be approximately equal to Date.now().



console.time

Example: (timeEnd wrapped in setTimeout for simulation)

_x000D_
_x000D_
console.time('Search page');
  doSomething();
console.timeEnd('Search page');
 

 function doSomething(){    
       for(i=0;i<1000000;i++){var x = i*i;}
 }
_x000D_
_x000D_
_x000D_

You can change the Timer-Name for different operations.

HTML5 Canvas background image

Why don't you style it out:

<canvas id="canvas" width="800" height="600" style="background: url('./images/image.jpg')">
  Your browser does not support the canvas element.
</canvas>

Xcode : Adding a project as a build dependency

Xcode 10

  1. drag-n-drop a project into another project - is called cross-project references[About]
  2. add the added project as a build dependency - is called Explicit dependency[About]
//Xcode 10
Build Phases -> Target Dependencies -> + Add items 

//Xcode 11
Build Phases -> Dependencies -> + Add items 

In Choose items to add: dialog you will see only targets from your project and the sub-project

enter image description here

How to make a JSON call to a url?

Because the URL isn't on the same domain as your website, you need to use JSONP.

For example: (In jQuery):

$.getJSON(
    'http://soundcloud.com/oembed?url=http%3A//soundcloud.com/forss/flickermood&format=js&callback=?', 
    function(data) { ... }
);

This works by creating a <script> tag like this one:

<script src="http://soundcloud.com/oembed?url=http%3A//soundcloud.com/forss/flickermood&format=js&callback=someFunction" type="text/javascript"></script>

Their server then emits Javascript that calls someFunction with the data to retrieve.
`someFunction is an internal callback generated by jQuery that then calls your callback.

Determine if Android app is being used for the first time

There is support for just this in the support library revision 23.3.0 (in the v4 which means compability back to Android 1.6).

In your Launcher activity, first call:

AppLaunchChecker.onActivityCreate(activity);

Then call:

AppLaunchChecker.hasStartedFromLauncher(activity);

Which will return if this was the first time the app was launched.

How to remove trailing whitespaces with sed?

In the specific case of sed, the -i option that others have already mentioned is far and away the simplest and sanest one.

In the more general case, sponge, from the moreutils collection, does exactly what you want: it lets you replace a file with the result of processing it, in a way specifically designed to keep the processing step from tripping over itself by overwriting the very file it's working on. To quote the sponge man page:

sponge reads standard input and writes it out to the specified file. Unlike a shell redirect, sponge soaks up all its input before writing the output file. This allows constructing pipelines that read from and write to the same file.

https://joeyh.name/code/moreutils/

Cannot run emulator in Android Studio

I had the same error. The solution for me was change the ANDROID_HOME path. First I took a look into tools->android->sdk manager from Android Studio. In that window, we can see the path where Android Studio looks for the SDK: image

Then I opened a Windows CMD shell, executed:

echo %ANDROID_HOME%

but the path was different to the one in ANDROID STUDIO CONFIGURATION of the first step.

The solution was to change in user environment, the ANDROID_HOME, to the one of the first step: image

I finally closed the cmd shell, and opened another cmd shell to execute:

echo %ANDROID_HOME%

the path was updated, and I could run my emulator perfectly.

How to install a Mac application using Terminal

To disable inputting password:

sudo visudo

Then add a new line like below and save then:

# The user can run installer as root without inputting password
yourusername ALL=(root) NOPASSWD: /usr/sbin/installer

Then you run installer without password:

sudo installer -pkg ...

APR based Apache Tomcat Native library was not found on the java.library.path?

I resolve this (On Eclipse IDE) by delete my old server and create the same again. This error is because you don't proper terminate Tomcat server and close Eclipse.

Generate MD5 hash string with T-SQL

try this:

select SUBSTRING(sys.fn_sqlvarbasetostr(HASHBYTES('MD5',  '[email protected]' )),3,32) 

Skip a submodule during a Maven build

Maven version 3.2.1 added this feature, you can use the -pl switch (shortcut for --projects list) with ! or - (source) to exclude certain submodules.

mvn -pl '!submodule-to-exclude' install
mvn -pl -submodule-to-exclude install

Be careful in bash the character ! is a special character, so you either have to single quote it (like I did) or escape it with the backslash character.

The syntax to exclude multiple module is the same as the inclusion

mvn -pl '!submodule1,!submodule2' install
mvn -pl -submodule1,-submodule2 install

EDIT Windows does not seem to like the single quotes, but it is necessary in bash ; in Windows, use double quotes (thanks @awilkinson)

mvn -pl "!submodule1,!submodule2" install

Transparent color of Bootstrap-3 Navbar

.navbar {
   background-color: transparent;
   background: transparent;
   border-color: transparent;
}

.navbar li { color: #000 } 

http://bootply.com/106969

Uninitialized constant ActiveSupport::Dependencies::Mutex (NameError)

In case you can't upgrade to Ruby on Rails 2.3.11 (and to expand on douglasr's answer), thread must be required at the top of boot.rb. For example:

require 'thread'

# Don't change this file!
# Configure your app in config/environment.rb and config/environments/*.rb
...

Android: converting String to int

barcode often consist of large number so i think your app crashes because of the size of the string that you are trying to convert to int. you can use BigInteger

BigInteger reallyBig = new BigInteger(myString);

get everything between <tag> and </tag> with php

You can use the following:

$regex = '#<\s*?code\b[^>]*>(.*?)</code\b[^>]*>#s';
  • \b ensures that a typo (like <codeS>) is not captured.
  • The first pattern [^>]* captures the content of a tag with attributes (eg a class).
  • Finally, the flag s capture content with newlines.

See the result here : http://lumadis.be/regex/test_regex.php?id=1081

Open URL in Java to get the content

It works for me. Please check if you are using the right imports?

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;

Unable to connect to any of the specified mysql hosts. C# MySQL

If you are accessing the live database by using localhost URL then it will not work. Please deploy your service or website on IIS and create URL and then access the database by using new URL, It will work.

Undo working copy modifications of one file in Git?

For me only this one worked

git checkout -p filename

enter image description here

get original element from ng-click

Not a direct answer to this question but rather to the "issue" of $event.currentTarget apparently be set to null.

This is due to the fact that console.log shows deep mutable objects at the last state of execution, not at the state when console.log was called.

You can check this for more information: Consecutive calls to console.log produce inconsistent results

Oracle - how to remove white spaces?

you can use 'rpad' in your select query and specify the size ...

select rpad(a , 20) , rpad(b, 20) from x ;

where first parameter is your column name and second parameter is the size which you want to pad with .

How to copy directories with spaces in the name

There's no need to add space before closing quote if path doesn't contain trailing backslash, so following command should work:

robocopy "C:\Source Path" "C:\Destination Path" /option1 /option2...

But, following will not work:

robocopy "C:\Source Path\" "C:\Destination Path\" /option1 /option2...

This is due to the escaping issue that is described here:

The \ escape can cause problems with quoted directory paths that contain a trailing backslash because the closing quote " at the end of the line will be escaped \".

How do I make a delay in Java?

Using TimeUnit.SECONDS.sleep(1); or Thread.sleep(1000); Is acceptable way to do it. In both cases you have to catch InterruptedExceptionwhich makes your code Bulky.There is an Open Source java library called MgntUtils (written by me) that provides utility that already deals with InterruptedException inside. So your code would just include one line:

TimeUtils.sleepFor(1, TimeUnit.SECONDS);

See the javadoc here. You can access library from Maven Central or from Github. The article explaining about the library could be found here

Gradients in Internet Explorer 9

The code I use for all browser gradients:

background: #0A284B;
background: -webkit-gradient(linear, left top, left bottom, from(#0A284B), to(#135887));
background: -webkit-linear-gradient(#0A284B, #135887);
background: -moz-linear-gradient(top, #0A284B, #135887);
background: -ms-linear-gradient(#0A284B, #135887);
background: -o-linear-gradient(#0A284B, #135887);
background: linear-gradient(#0A284B, #135887);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#0A284B', endColorstr='#135887');
zoom: 1;

You will need to specify a height or zoom: 1 to apply hasLayout to the element for this to work in IE.


Update:

Here is a LESS Mixin (CSS) version for all you LESS users out there:

.gradient(@start, @end) {
    background: mix(@start, @end, 50%);
    filter: ~"progid:DXImageTransform.Microsoft.gradient(startColorStr="@start~", EndColorStr="@end~")";
    background: -webkit-gradient(linear, left top, left bottom, from(@start), to(@end));
    background: -webkit-linear-gradient(@start, @end);
    background: -moz-linear-gradient(top, @start, @end);
    background: -ms-linear-gradient(@start, @end);
    background: -o-linear-gradient(@start, @end);
    background: linear-gradient(@start, @end);
    zoom: 1;
}

How to run a Python script in the background even after I logout SSH?

Run nohup python bgservice.py & to get the script to ignore the hangup signal and keep running. Output will be put in nohup.out.

Ideally, you'd run your script with something like supervise so that it can be restarted if (when) it dies.

Onclick on bootstrap button

You can use 'onclick' attribute like this :

<a ... href="javascript: onclick();" ...>...</a>

Define constant variables in C++ header

C++17 inline variables

This awesome C++17 feature allow us to:

  • conveniently use just a single memory address for each constant
  • store it as a constexpr: How to declare constexpr extern?
  • do it in a single line from one header

main.cpp

#include <cassert>

#include "notmain.hpp"

int main() {
    // Both files see the same memory address.
    assert(&notmain_i == notmain_func());
    assert(notmain_i == 42);
}

notmain.hpp

#ifndef NOTMAIN_HPP
#define NOTMAIN_HPP

inline constexpr int notmain_i = 42;

const int* notmain_func();

#endif

notmain.cpp

#include "notmain.hpp"

const int* notmain_func() {
    return &notmain_i;
}

Compile and run:

g++ -c -o notmain.o -std=c++17 -Wall -Wextra -pedantic notmain.cpp
g++ -c -o main.o -std=c++17 -Wall -Wextra -pedantic main.cpp
g++ -o main -std=c++17 -Wall -Wextra -pedantic main.o notmain.o
./main

GitHub upstream.

See also: How do inline variables work?

C++ standard on inline variables

The C++ standard guarantees that the addresses will be the same. C++17 N4659 standard draft 10.1.6 "The inline specifier":

6 An inline function or variable with external linkage shall have the same address in all translation units.

cppreference https://en.cppreference.com/w/cpp/language/inline explains that if static is not given, then it has external linkage.

Inline variable implementation

We can observe how it is implemented with:

nm main.o notmain.o

which contains:

main.o:
                 U _GLOBAL_OFFSET_TABLE_
                 U _Z12notmain_funcv
0000000000000028 r _ZZ4mainE19__PRETTY_FUNCTION__
                 U __assert_fail
0000000000000000 T main
0000000000000000 u notmain_i

notmain.o:
0000000000000000 T _Z12notmain_funcv
0000000000000000 u notmain_i

and man nm says about u:

"u" The symbol is a unique global symbol. This is a GNU extension to the standard set of ELF symbol bindings. For such a symbol the dynamic linker will make sure that in the entire process there is just one symbol with this name and type in use.

so we see that there is a dedicated ELF extension for this.

C++17 standard draft on "global" const implies static

This is the quote for what was mentioned at: https://stackoverflow.com/a/12043198/895245

C++17 n4659 standard draft 6.5 "Program and linkage":

3 A name having namespace scope (6.3.6) has internal linkage if it is the name of

  • (3.1) — a variable, function or function template that is explicitly declared static; or,
  • (3.2) — a non-inline variable of non-volatile const-qualified type that is neither explicitly declared extern nor previously declared to have external linkage; or
  • (3.3) — a data member of an anonymous union.

"namespace" scope is what we colloquially often refer to as "global".

Annex C (informative) Compatibility, C.1.2 Clause 6: "basic concepts" gives the rationale why this was changed from C:

6.5 [also 10.1.7]

Change: A name of file scope that is explicitly declared const, and not explicitly declared extern, has internal linkage, while in C it would have external linkage.

Rationale: Because const objects may be used as values during translation in C++, this feature urges programmers to provide an explicit initializer for each const object. This feature allows the user to put const objects in source files that are included in more than one translation unit.

Effect on original feature: Change to semantics of well-defined feature.

Difficulty of converting: Semantic transformation.

How widely used: Seldom.

See also: Why does const imply internal linkage in C++, when it doesn't in C?

Tested in GCC 7.4.0, Ubuntu 18.04.

Provisioning Profiles menu item missing from Xcode 5

Stupid as it may sound but all "Provisioning Profiles" re-appear under "Organizer - Devices" once you connect a real device.

Android TextView padding between lines

You can use TextView.setLineSpacing(n,m) function.

How to pass an array within a query string?

You can use http_build_query to generate a URL-encoded querystring from an array in PHP. Whilst the resulting querystring will be expanded, you can decide on a unique separator you want as a parameter to the http_build_query method, so when it comes to decoding, you can check what separator was used. If it was the unique one you chose, then that would be the array querystring otherwise it would be the normal querystrings.

jQuery $.ajax(), $.post sending "OPTIONS" as REQUEST_METHOD in Firefox

Another possibility to circumvent the problem is to use a proxy script. That method is described for example here

Class type check in TypeScript

You can use the instanceof operator for this. From MDN:

The instanceof operator tests whether the prototype property of a constructor appears anywhere in the prototype chain of an object.

If you don't know what prototypes and prototype chains are I highly recommend looking it up. Also here is a JS (TS works similar in this respect) example which might clarify the concept:

_x000D_
_x000D_
    class Animal {_x000D_
        name;_x000D_
    _x000D_
        constructor(name) {_x000D_
            this.name = name;_x000D_
        }_x000D_
    }_x000D_
    _x000D_
    const animal = new Animal('fluffy');_x000D_
    _x000D_
    // true because Animal in on the prototype chain of animal_x000D_
    console.log(animal instanceof Animal); // true_x000D_
    // Proof that Animal is on the prototype chain_x000D_
    console.log(Object.getPrototypeOf(animal) === Animal.prototype); // true_x000D_
    _x000D_
    // true because Object in on the prototype chain of animal_x000D_
    console.log(animal instanceof Object); _x000D_
    // Proof that Object is on the prototype chain_x000D_
    console.log(Object.getPrototypeOf(Animal.prototype) === Object.prototype); // true_x000D_
    _x000D_
    console.log(animal instanceof Function); // false, Function not on prototype chain_x000D_
    _x000D_
    
_x000D_
_x000D_
_x000D_

The prototype chain in this example is:

animal > Animal.prototype > Object.prototype

How to know which version of Symfony I have?

Maybe the anwswers here are obsolete... in any case, for me running Symfony 4, it is easy Just type symfony -V from the command line.

enter image description here

Running a CMD or BAT in silent mode

Use Advanced BAT to EXE Converter from http://www.battoexeconverter.com

This will allow you to embed any additional binaries with your batch file in to one stand alone completely silent EXE and its freeware

How to convert number to words in java

Because you cannot have a general algorithm for every locale, no. You have to implement your own algorithm for every locale that you are supporting.

** EDIT **

Just for the heck of it, I played around until I got this class. It cannot display Long.MIN_VALUE because of bit restrictions... but I presume it could be modified and change long value types to double for decimal or even bigger numbers It can display any numbers up to 66 digits and 26 decimals using a string representation of the number. You may add more ScaleUnit for more decimals...

/**
 * This class will convert numeric values into an english representation
 * 
 * For units, see : http://www.jimloy.com/math/billion.htm
 * 
 * @author [email protected]
 */
public class NumberToWords {

    static public class ScaleUnit {
        private int exponent;
        private String[] names;
        private ScaleUnit(int exponent, String...names) {
            this.exponent = exponent;
            this.names = names;
        }
        public int getExponent() {
            return exponent;
        }
        public String getName(int index) {
            return names[index];
        }
    }

    /**
     * See http://www.wordiq.com/definition/Names_of_large_numbers
     */
    static private ScaleUnit[] SCALE_UNITS = new ScaleUnit[] {
        new ScaleUnit(63, "vigintillion", "decilliard"),
        new ScaleUnit(60, "novemdecillion", "decillion"),
        new ScaleUnit(57, "octodecillion", "nonilliard"),
        new ScaleUnit(54, "septendecillion", "nonillion"),
        new ScaleUnit(51, "sexdecillion", "octilliard"),
        new ScaleUnit(48, "quindecillion", "octillion"),
        new ScaleUnit(45, "quattuordecillion", "septilliard"),
        new ScaleUnit(42, "tredecillion", "septillion"),
        new ScaleUnit(39, "duodecillion", "sextilliard"),
        new ScaleUnit(36, "undecillion", "sextillion"),
        new ScaleUnit(33, "decillion", "quintilliard"),
        new ScaleUnit(30, "nonillion", "quintillion"),
        new ScaleUnit(27, "octillion", "quadrilliard"),
        new ScaleUnit(24, "septillion", "quadrillion"),
        new ScaleUnit(21, "sextillion", "trilliard"),
        new ScaleUnit(18, "quintillion", "trillion"),
        new ScaleUnit(15, "quadrillion", "billiard"),
        new ScaleUnit(12, "trillion", "billion"),
        new ScaleUnit(9, "billion", "milliard"),
        new ScaleUnit(6, "million", "million"),
        new ScaleUnit(3, "thousand", "thousand"),
        new ScaleUnit(2, "hundred", "hundred"),
        //new ScaleUnit(1, "ten", "ten"),
        //new ScaleUnit(0, "one", "one"),
        new ScaleUnit(-1, "tenth", "tenth"),
        new ScaleUnit(-2, "hundredth", "hundredth"),
        new ScaleUnit(-3, "thousandth", "thousandth"),
        new ScaleUnit(-4, "ten-thousandth", "ten-thousandth"),
        new ScaleUnit(-5, "hundred-thousandth", "hundred-thousandth"),
        new ScaleUnit(-6, "millionth", "millionth"),
        new ScaleUnit(-7, "ten-millionth", "ten-millionth"),
        new ScaleUnit(-8, "hundred-millionth", "hundred-millionth"),
        new ScaleUnit(-9, "billionth", "milliardth"),
        new ScaleUnit(-10, "ten-billionth", "ten-milliardth"),
        new ScaleUnit(-11, "hundred-billionth", "hundred-milliardth"),
        new ScaleUnit(-12, "trillionth", "billionth"),
        new ScaleUnit(-13, "ten-trillionth", "ten-billionth"),
        new ScaleUnit(-14, "hundred-trillionth", "hundred-billionth"),
        new ScaleUnit(-15, "quadrillionth", "billiardth"),
        new ScaleUnit(-16, "ten-quadrillionth", "ten-billiardth"),
        new ScaleUnit(-17, "hundred-quadrillionth", "hundred-billiardth"),
        new ScaleUnit(-18, "quintillionth", "trillionth"),
        new ScaleUnit(-19, "ten-quintillionth", "ten-trillionth"),
        new ScaleUnit(-20, "hundred-quintillionth", "hundred-trillionth"),
        new ScaleUnit(-21, "sextillionth", "trilliardth"),
        new ScaleUnit(-22, "ten-sextillionth", "ten-trilliardth"),
        new ScaleUnit(-23, "hundred-sextillionth", "hundred-trilliardth"),
        new ScaleUnit(-24, "septillionth","quadrillionth"),
        new ScaleUnit(-25, "ten-septillionth","ten-quadrillionth"),
        new ScaleUnit(-26, "hundred-septillionth","hundred-quadrillionth"),
    };

    static public enum Scale {
        SHORT,
        LONG;

        public String getName(int exponent) {
            for (ScaleUnit unit : SCALE_UNITS) {
                if (unit.getExponent() == exponent) {
                    return unit.getName(this.ordinal());
                }
            }
            return ""; 
        }
    }

    /**
     * Change this scale to support American and modern British value (short scale)
     * or Traditional British value (long scale)
     */
    static public Scale SCALE = Scale.SHORT; 


    static abstract public class AbstractProcessor {

        static protected final String SEPARATOR = " ";
        static protected final int NO_VALUE = -1;

        protected List<Integer> getDigits(long value) {
            ArrayList<Integer> digits = new ArrayList<Integer>();
            if (value == 0) {
                digits.add(0);
            } else {
                while (value > 0) {
                    digits.add(0, (int) value % 10);
                    value /= 10;
                }
            }
            return digits;
        }

        public String getName(long value) {
            return getName(Long.toString(value));
        }

        public String getName(double value) {
            return getName(Double.toString(value));
        }

        abstract public String getName(String value);
    }

    static public class UnitProcessor extends AbstractProcessor {

        static private final String[] TOKENS = new String[] {
            "one", "two", "three", "four", "five", "six", "seven", "eight", "nine",
            "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"
        };

        @Override
        public String getName(String value) {
            StringBuilder buffer = new StringBuilder();

            int offset = NO_VALUE;
            int number;
            if (value.length() > 3) {
                number = Integer.valueOf(value.substring(value.length() - 3), 10);
            } else {
                number = Integer.valueOf(value, 10);
            }
            number %= 100;
            if (number < 10) {
                offset = (number % 10) - 1;
                //number /= 10;
            } else if (number < 20) {
                offset = (number % 20) - 1;
                //number /= 100;
            }

            if (offset != NO_VALUE && offset < TOKENS.length) {
                buffer.append(TOKENS[offset]);
            }

            return buffer.toString();
        }

    }

    static public class TensProcessor extends AbstractProcessor {

        static private final String[] TOKENS = new String[] {
            "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"
        };

        static private final String UNION_SEPARATOR = "-";

        private UnitProcessor unitProcessor = new UnitProcessor();

        @Override
        public String getName(String value) {
            StringBuilder buffer = new StringBuilder();
            boolean tensFound = false;

            int number;
            if (value.length() > 3) {
                number = Integer.valueOf(value.substring(value.length() - 3), 10);
            } else {
                number = Integer.valueOf(value, 10);
            }
            number %= 100;   // keep only two digits
            if (number >= 20) {
                buffer.append(TOKENS[(number / 10) - 2]);
                number %= 10;
                tensFound = true;
            } else {
                number %= 20;
            }

            if (number != 0) {
                if (tensFound) {
                    buffer.append(UNION_SEPARATOR);
                }
                buffer.append(unitProcessor.getName(number));
            }

            return buffer.toString();
        }
    }

    static public class HundredProcessor extends AbstractProcessor {

        private int EXPONENT = 2;

        private UnitProcessor unitProcessor = new UnitProcessor();
        private TensProcessor tensProcessor = new TensProcessor();

        @Override
        public String getName(String value) {
            StringBuilder buffer = new StringBuilder();

            int number;
            if (value.isEmpty()) {
                number = 0;
            } else if (value.length() > 4) {
                number = Integer.valueOf(value.substring(value.length() - 4), 10);
            } else {
                number = Integer.valueOf(value, 10);
            }
            number %= 1000;  // keep at least three digits

            if (number >= 100) {
                buffer.append(unitProcessor.getName(number / 100));
                buffer.append(SEPARATOR);
                buffer.append(SCALE.getName(EXPONENT));
            }

            String tensName = tensProcessor.getName(number % 100);

            if (!tensName.isEmpty() && (number >= 100)) {
                buffer.append(SEPARATOR);
            }
            buffer.append(tensName);

            return buffer.toString();
        }
    }

    static public class CompositeBigProcessor extends AbstractProcessor {

        private HundredProcessor hundredProcessor = new HundredProcessor();
        private AbstractProcessor lowProcessor;
        private int exponent;

        public CompositeBigProcessor(int exponent) {
            if (exponent <= 3) {
                lowProcessor = hundredProcessor;
            } else {
                lowProcessor = new CompositeBigProcessor(exponent - 3);
            }
            this.exponent = exponent;
        }

        public String getToken() {
            return SCALE.getName(getPartDivider());
        }

        protected AbstractProcessor getHighProcessor() {
            return hundredProcessor;
        }

        protected AbstractProcessor getLowProcessor() {
            return lowProcessor;
        }

        public int getPartDivider() {
            return exponent;
        }

        @Override
        public String getName(String value) {
            StringBuilder buffer = new StringBuilder();

            String high, low;
            if (value.length() < getPartDivider()) {
                high = "";
                low = value;
            } else {
                int index = value.length() - getPartDivider();
                high = value.substring(0, index);
                low = value.substring(index);
            }

            String highName = getHighProcessor().getName(high);
            String lowName = getLowProcessor().getName(low);

            if (!highName.isEmpty()) {
                buffer.append(highName);
                buffer.append(SEPARATOR);
                buffer.append(getToken());

                if (!lowName.isEmpty()) {
                    buffer.append(SEPARATOR);
                }
            }

            if (!lowName.isEmpty()) {
                buffer.append(lowName);
            }

            return buffer.toString();
        }
    }

    static public class DefaultProcessor extends AbstractProcessor {

        static private String MINUS = "minus";
        static private String UNION_AND = "and";

        static private String ZERO_TOKEN = "zero";

        private AbstractProcessor processor = new CompositeBigProcessor(63);

        @Override
        public String getName(String value) {
            boolean negative = false;
            if (value.startsWith("-")) {
                negative = true;
                value = value.substring(1);
            }

            int decimals = value.indexOf(".");
            String decimalValue = null;
            if (0 <= decimals) {
                decimalValue = value.substring(decimals + 1);
                value = value.substring(0, decimals);
            }

            String name = processor.getName(value);

            if (name.isEmpty()) {
                name = ZERO_TOKEN;
            } else if (negative) {
                name = MINUS.concat(SEPARATOR).concat(name); 
            }

            if (!(null == decimalValue || decimalValue.isEmpty())) {
                name = name.concat(SEPARATOR).concat(UNION_AND).concat(SEPARATOR)
                    .concat(processor.getName(decimalValue))
                    .concat(SEPARATOR).concat(SCALE.getName(-decimalValue.length()));
            }

            return name;
        }

    }

    static public AbstractProcessor processor;


    public static void main(String...args) {

        processor = new DefaultProcessor();

        long[] values = new long[] {
            0,
            4,
            10,
            12,
            100,
            108,
            299,
            1000,
            1003,
            2040,
            45213,
            100000,
            100005,
            100010,
            202020,
            202022,
            999999,
            1000000,
            1000001,
            10000000,
            10000007,
            99999999,
            Long.MAX_VALUE,
            Long.MIN_VALUE
        };

        String[] strValues = new String[] {
            "0001.2",
            "3.141592"
        };

        for (long val : values) {
            System.out.println(val + " = " + processor.getName(val) );
        }

        for (String strVal : strValues) {
            System.out.println(strVal + " = " + processor.getName(strVal) );
        }

        // generate a very big number...
        StringBuilder bigNumber = new StringBuilder();
        for (int d=0; d<66; d++) {
            bigNumber.append( (char) ((Math.random() * 10) + '0'));
        }
        bigNumber.append(".");
        for (int d=0; d<26; d++) {
            bigNumber.append( (char) ((Math.random() * 10) + '0'));
        }

        System.out.println(bigNumber.toString() + " = " + processor.getName(bigNumber.toString()));

    }

}

and a sample output (for the random big number generator)

0 = zero
4 = four
10 = ten
12 = twelve
100 = one hundred
108 = one hundred eight
299 = two hundred ninety-nine
1000 = one thousand
1003 = one thousand three
2040 = two thousand fourty
45213 = fourty-five thousand two hundred thirteen
100000 = one hundred thousand
100005 = one hundred thousand five
100010 = one hundred thousand ten
202020 = two hundred two thousand twenty
202022 = two hundred two thousand twenty-two
999999 = nine hundred ninety-nine thousand nine hundred ninety-nine
1000000 = one million
1000001 = one million one
10000000 = ten million
10000007 = ten million seven
99999999 = ninety-nine million nine hundred ninety-nine thousand nine hundred ninety-nine
9223372036854775807 = nine quintillion two hundred twenty-three quadrillion three hundred seventy-two trillion thirty-six billion eight hundred fifty-four million seven hundred seventy-five thousand eight hundred seven
-9223372036854775808 = minus nine quintillion two hundred twenty-three quadrillion three hundred seventy-two trillion thirty-six billion eight hundred fifty-four million seven hundred seventy-five thousand eight hundred eight
0001.2 = one and two tenth
3.141592 = three and one hundred fourty-one thousand five hundred ninety-two millionth
694780458103427072928672912656674465845126458162617425283733729646.85695031739734695391404376 = six hundred ninety-four vigintillion seven hundred eighty novemdecillion four hundred fifty-eight octodecillion one hundred three septendecillion four hundred twenty-seven sexdecillion seventy-two quindecillion nine hundred twenty-eight quattuordecillion six hundred seventy-two tredecillion nine hundred twelve duodecillion six hundred fifty-six undecillion six hundred seventy-four decillion four hundred sixty-five nonillion eight hundred fourty-five octillion one hundred twenty-six septillion four hundred fifty-eight sextillion one hundred sixty-two quintillion six hundred seventeen quadrillion four hundred twenty-five trillion two hundred eighty-three billion seven hundred thirty-three million seven hundred twenty-nine thousand six hundred fourty-six and eighty-five septillion six hundred ninety-five sextillion thirty-one quintillion seven hundred thirty-nine quadrillion seven hundred thirty-four trillion six hundred ninety-five billion three hundred ninety-one million four hundred four thousand three hundred seventy-six hundred-septillionth

CSS3 scrollbar styling on a div

.scroll {
   width: 200px; height: 400px;
   overflow: auto;
}

How do I resize an image using PIL and maintain its aspect ratio?

from PIL import Image
from resizeimage import resizeimage

def resize_file(in_file, out_file, size):
    with open(in_file) as fd:
        image = resizeimage.resize_thumbnail(Image.open(fd), size)
    image.save(out_file)
    image.close()

resize_file('foo.tif', 'foo_small.jpg', (256, 256))

I use this library:

pip install python-resize-image

Warning: mysql_connect(): [2002] No such file or directory (trying to connect via unix:///tmp/mysql.sock) in

You can do it by simply aliasing the MAMP php on Apple terminal:

alias phpmamp='/Applications/MAMP/bin/php/php7.0.0/bin/php'

Example: > phpmamp - v

Now you can run something like: > phpmamp scriptname.php

Note: This will be applied only for the current terminal session.

Difference between using Throwable and Exception in a try catch

Thowable catches really everything even ThreadDeath which gets thrown by default to stop a thread from the now deprecated Thread.stop() method. So by catching Throwable you can be sure that you'll never leave the try block without at least going through your catch block, but you should be prepared to also handle OutOfMemoryError and InternalError or StackOverflowError.

Catching Throwable is most useful for outer server loops that delegate all sorts of requests to outside code but may itself never terminate to keep the service alive.

Numpy: find index of the elements within range

Other way is with:

np.vectorize(lambda x: 6 <= x <= 10)(a)

which returns:

array([False, False, False,  True,  True,  True, False, False, False])

It is sometimes useful for masking time series, vectors, etc.

Convert java.util.Date to String

It looks like you are looking for SimpleDateFormat.

Format: yyyy-MM-dd kk:mm:ss

How do you check whether a number is divisible by another number (Python)?

You can use % operator to check divisiblity of a given number

The code to check whether given no. is divisible by 3 or 5 when no. less than 1000 is given below:

n=0
while n<1000:
    if n%3==0 or n%5==0:
        print n,'is multiple of 3 or 5'
    n=n+1

What does a just-in-time (JIT) compiler do?

A just in time compiler (JIT) is a piece of software which takes receives an non executable input and returns the appropriate machine code to be executed. For example:

Intermediate representation    JIT    Native machine code for the current CPU architecture

     Java bytecode            --->        machine code
     Javascript (run with V8) --->        machine code

The consequence of this is that for a certain CPU architecture the appropriate JIT compiler must be installed.

Difference compiler, interpreter, and JIT

Although there can be exceptions in general when we want to transform source code into machine code we can use:

  1. Compiler: Takes source code and returns a executable
  2. Interpreter: Executes the program instruction by instruction. It takes an executable segment of the source code and turns that segment into machine instructions. This process is repeated until all source code is transformed into machine instructions and executed.
  3. JIT: Many different implementations of a JIT are possible, however a JIT is usually a combination of a compliler and an interpreter. The JIT first turn intermediary data (e.g. Java bytecode) which it receives into machine language via interpretation. A JIT can often sense when a certain part of the code is executed often and the will compile this part for faster execution.

How can I import Swift code to Objective-C?

If you have a project created in Swift 4 and then added Objective-C files, do it like this:

@objcMembers
public class MyModel: NSObject {
    var someFlag = false         
    func doSomething() {         
        print("doing something")
    }
}

Reference: https://useyourloaf.com/blog/objc-warnings-upgrading-to-swift-4/

Extract every nth element of a vector

To select every nth element from any starting position in the vector

nth_element <- function(vector, starting_position, n) { 
  vector[seq(starting_position, length(vector), n)] 
  }

# E.g.
vec <- 1:12

nth_element(vec, 1, 3)
# [1]  1  4  7 10

nth_element(vec, 2, 3)
# [1]  2  5  8 11

How do I generate a stream from a string?

A good combination of String extensions:

public static byte[] GetBytes(this string str)
{
    byte[] bytes = new byte[str.Length * sizeof(char)];
    System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
    return bytes;
}

public static Stream ToStream(this string str)
{
    Stream StringStream = new MemoryStream();
    StringStream.Read(str.GetBytes(), 0, str.Length);
    return StringStream;
}

How to set the matplotlib figure default size in ipython notebook?

In iPython 3.0.0, the inline backend needs to be configured in ipython_kernel_config.py. You need to manually add the c.InlineBackend.rc... line (as mentioned in Greg's answer). This will affect both the inline backend in the Qt console and the notebook.

Resource blocked due to MIME type mismatch (X-Content-Type-Options: nosniff)

i also facing this same problem in django server.So i changed DEBUG = True in settings.py file its working

flutter corner radius with transparent background

It's an old question. But for those who come across this question...

The white background behind the rounded corners is not actually the container. That is the canvas color of the app.

TO FIX: Change the canvas color of your app to Colors.transparent

Example:

return new MaterialApp(
  title: 'My App',
  theme: new ThemeData(
    primarySwatch: Colors.green,
    canvasColor: Colors.transparent, //----Change to this------------
    accentColor: Colors.blue,
  ),
  home: new HomeScreen(),
);

GridLayout and Row/Column Span Woe

Android Support V7 GridLayout library makes excess space distribution easy by accommodating the principle of weight. To make a column stretch, make sure the components inside it define a weight or a gravity. To prevent a column from stretching, ensure that one of the components in the column does not define a weight or a gravity. Remember to add dependency for this library. Add com.android.support:gridlayout-v7:25.0.1 in build.gradle.

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:columnCount="2"
app:rowCount="2">

<TextView
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:gravity="center"
    android:text="First"
    app:layout_columnWeight="1"
    app:layout_rowWeight="1" />

<TextView
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:gravity="center"
    android:text="Second"
    app:layout_columnWeight="1"
    app:layout_rowWeight="1" />

<TextView
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:gravity="center"
    android:text="Third"
    app:layout_columnWeight="1"
    app:layout_rowWeight="1" />

<TextView
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:gravity="center"        
    app:layout_columnWeight="1"
    app:layout_rowWeight="1"
    android:text="fourth"/>

</android.support.v7.widget.GridLayout>

Make var_dump look pretty

Here is my function to have a pretty var_dump. Combined with Xdebug, it helps a lot to have a better view of what we are dumping.

I improved a bit the display of Xdebug (give some space around, separator between values, wrap long variables, etc).

When you call the function, you can set a title, a background, a text color to distinguish all your var_dump in a page.

Or not ;)

/**
 * Pretty var_dump 
 * Possibility to set a title, a background-color and a text color
 */ 
function dump($data, $title="", $background="#EEEEEE", $color="#000000"){

    //=== Style  
    echo "  
    <style>
        /* Styling pre tag */
        pre {
            padding:10px 20px;
            white-space: pre-wrap;
            white-space: -moz-pre-wrap;
            white-space: -pre-wrap;
            white-space: -o-pre-wrap;
            word-wrap: break-word;
        }

        /* ===========================
        == To use with XDEBUG 
        =========================== */
        /* Source file */
        pre small:nth-child(1) {
            font-weight: bold;
            font-size: 14px;
            color: #CC0000;
        }
        pre small:nth-child(1)::after {
            content: '';
            position: relative;
            width: 100%;
            height: 20px;
            left: 0;
            display: block;
            clear: both;
        }

        /* Separator */
        pre i::after{
            content: '';
            position: relative;
            width: 100%;
            height: 15px;
            left: 0;
            display: block;
            clear: both;
            border-bottom: 1px solid grey;
        }  
    </style>
    ";

    //=== Content            
    echo "<pre style='background:$background; color:$color; padding:10px 20px; border:2px inset $color'>";
    echo    "<h2>$title</h2>";
            var_dump($data); 
    echo "</pre>";

}

HTML/Javascript Button Click Counter

    <!DOCTYPE html>
<html>
<head>
<script>
     var clicks = 0;
    function myFunction() {

        clicks += 1;
        document.getElementById("demo").innerHTML = clicks;


    }
</script>
</head>
<body>

<p>Click the button to trigger a function.</p>

<button onclick="myFunction()">Click me</button>

<p id="demo"></p>

</body>
</html>

This should work for you :) Yes var should be used

How do I sort a two-dimensional (rectangular) array in C#?

Can allso look at Array.Sort Method http://msdn.microsoft.com/en-us/library/aa311213(v=vs.71).aspx

e.g. Array.Sort(array, delegate(object[] x, object[] y){ return (x[ i ] as IComparable).CompareTo(y[ i ]);});

from http://channel9.msdn.com/forums/Coffeehouse/189171-Sorting-Two-Dimensional-Arrays-in-C/

How to extract a value from a string using regex and a shell?

You can certainly extract that part of a string and that's a great way to parse out data. Regular expression syntax varies a lot so you need to reference the help file for the regex you're using. You might try a regular expression like:

[0-9]+ *[a-zA-Z]+,([0-9]+) *[a-zA-Z]+,[0-9]+ *[a-zA-Z]+

If your regex program can do string replacement then replace the entire string with the result you want and you can easily use that result.

You didn't mention if you're using bash or some other shell. That would help get better answers when asking for help.

Are there any Open Source alternatives to Crystal Reports?

How about i-net Clear Reports (used to be i-net Crystal-Clear).

Though not free, you should also consider this low-cost, non-free, non-open-source reporting solution that can fully compete with Crystal Reports - and is Java-based.

I think it's even more cost efficient than "free ones". A small company may have to think closely about free things, but will then have to invest into manpower to find out how everything works and so on. Large companies will for sure subscribe to premium support services that cost a lot. See this article for reference

i-net Clear Reports has a very low price tag with great support for free and even better premium support via yearly subscriptions.

Disclosure: Yeah, I work for the company who built this, so I'm biased. But I honestly believe in what I just wrote.

How to convert 1 to true or 0 to false upon model fetch

Assigning Comparison to property value

JavaScript

You could assign the comparison of the property to "1"

obj["isChecked"] = (obj["isChecked"]==="1");

This only evaluates for a String value of "1" though. Other variables evaulate to false like an actual typeof number would be false. (i.e. obj["isChecked"]=1)

If you wanted to be indiscrimate about "1" or 1, you could use:

obj["isChecked"] = (obj["isChecked"]=="1");

Example Outputs

console.log(obj["isChecked"]==="1"); // true
console.log(obj["isChecked"]===1); // false
console.log(obj["isChecked"]==1); // true
console.log(obj["isChecked"]==="0"); // false
console.log(obj["isChecked"]==="Elephant"); // false

PHP

Same concept in PHP

$obj["isChecked"] = ($obj["isChecked"] == "1");

The same operator limitations as stated above for JavaScript apply.

Double Not

The 'double not' also works. It's confusing when people first read it but it works in both languages for integer/number type values. It however does not work in JavaScript for string type values as they always evaluate to true:

JavaScript

!!"1"; //true
!!"0"; //true
!!1; //true
!!0; //false
!!parseInt("0",10); // false

PHP

echo !!"1"; //true
echo !!"0"; //false
echo !!1; //true
echo !!0; //false

Using OR in SQLAlchemy

From the tutorial:

from sqlalchemy import or_
filter(or_(User.name == 'ed', User.name == 'wendy'))

How can I access a hover state in reactjs?

React components expose all the standard Javascript mouse events in their top-level interface. Of course, you can still use :hover in your CSS, and that may be adequate for some of your needs, but for the more advanced behaviors triggered by a hover you'll need to use the Javascript. So to manage hover interactions, you'll want to use onMouseEnter and onMouseLeave. You then attach them to handlers in your component like so:

<ReactComponent
    onMouseEnter={() => this.someHandler}
    onMouseLeave={() => this.someOtherHandler}
/>

You'll then use some combination of state/props to pass changed state or properties down to your child React components.

Angular2 - Http POST request parameters

angular: 
    MethodName(stringValue: any): Observable<any> {
    let params = new HttpParams();
    params = params.append('categoryName', stringValue);

    return this.http.post('yoururl', '', {
      headers: new HttpHeaders({
        'Content-Type': 'application/json'
      }),
      params: params,
      responseType: "json"
    })
  }

api:   
  [HttpPost("[action]")]
  public object Method(string categoryName)

How to set the height and the width of a textfield in Java?

package myguo;
import javax.swing.*;

public class MyGuo {

    JFrame f;
    JButton bt1 , bt2 ;
    JTextField t1,t2;
    JLabel l1,l2;

    MyGuo(){

        f=new JFrame("LOG IN FORM");
        f.setLocation(500,300);
        f.setSize(600,500);
        f.setLayout(null);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        l1=new JLabel("NAME");
        l1.setBounds(50,70,80,30);

        l2=new JLabel("PASSWORD");
        l2.setBounds(50,100,80,30);

        t1=new JTextField();
        t1.setBounds(140, 70, 200,30);

         t2=new JTextField();
        t2.setBounds(140, 110, 200,30);

        bt1 =new JButton("LOG IN");
        bt1.setBounds(150,150,80,30);

        bt2 =new JButton("CLEAR");
        bt2.setBounds(235,150,80,30);

         f.add(l1);
        f.add(l2);
         f.add(t1);
         f.add(t2);
         f.add(bt1);
         f.add(bt2);

    f.setVisible(true);

    }
    public static void main(String[] args) {
        MyGuo myGuo = new MyGuo();
}
}

Initial size for the ArrayList

If you want to add the elements with index, you could instead use an array.

    String [] test = new String[length];
    test[0] = "add";

How to set custom location for local installation of npm package?

If you want this in config, you can set npm config like so:

npm config set prefix "$(pwd)/vendor/node_modules"

or

npm config set prefix "$HOME/vendor/node_modules"

Check your config with

npm config ls -l

Or as @pje says and use the --prefix flag

mysqld_safe Directory '/var/run/mysqld' for UNIX socket file don't exists

It seems odd that this directory was not created at install - have you manually changed the path of the socket file in the my.cfg?

Have you tried simply creating this directory yourself, and restarting the service?

mkdir -p /var/run/mysqld
chown mysql:mysql /var/run/mysqld

How set the android:gravity to TextView from Java side in Android

textView.setGravity(Gravity.CENTER | Gravity.BOTTOM);

This will set gravity of your textview.

Use JAXB to create Object from XML String

To pass XML content, you need to wrap the content in a Reader, and unmarshal that instead:

JAXBContext jaxbContext = JAXBContext.newInstance(Person.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();

StringReader reader = new StringReader("xml string here");
Person person = (Person) unmarshaller.unmarshal(reader);

How to prevent buttons from submitting forms

This is an html5 error like has been said, you can still have the button as a submit (if you want to cover both javascript and non javascript users) using it like:

     <button type="submit" onclick="return false"> Register </button>

This way you will cancel the submit but still do whatever you are doing in jquery or javascript function`s and do the submit for users who dont have javascript.

using jquery $.ajax to call a PHP function

I would stick with normal approach to call the file directly, but if you really want to call a function, have a look at JSON-RPC (JSON Remote Procedure Call).

You basically send a JSON string in a specific format to the server, e.g.

{ "method": "echo", "params": ["Hello JSON-RPC"], "id": 1}

which includes the function to call and the parameters of that function.

Of course the server has to know how to handle such requests.
Here is jQuery plugin for JSON-RPC and e.g. the Zend JSON Server as server implementation in PHP.


This might be overkill for a small project or less functions. Easiest way would be karim's answer. On the other hand, JSON-RPC is a standard.

Cannot get OpenCV to compile because of undefined references?

This is a linker issue. Try:

g++ -o test_1 test_1.cpp `pkg-config opencv --cflags --libs`

This should work to compile the source. However, if you recently compiled OpenCV from source, you will meet linking issue in run-time, the library will not be found. In most cases, after compiling libraries from source, you need to do finally:

sudo ldconfig

Conditional Count on a field

I think you may be after

select 
    jobID, JobName,
    sum(case when Priority = 1 then 1 else 0 end) as priority1,
    sum(case when Priority = 2 then 1 else 0 end) as priority2,
    sum(case when Priority = 3 then 1 else 0 end) as priority3,
    sum(case when Priority = 4 then 1 else 0 end) as priority4,
    sum(case when Priority = 5 then 1 else 0 end) as priority5
from
    Jobs
group by 
    jobID, JobName

However I am uncertain if you need to the jobID and JobName in your results if so remove them and remove the group by,

How do I get the command-line for an Eclipse run configuration?

You'll find the junit launch commands in .metadata/.plugins/org.eclipse.debug.core/.launches, assuming your Eclipse works like mine does. The files are named {TestClass}.launch.

You will probably also need the .classpath file in the project directory that contains the test class.

Like the run configurations, they're XML files (even if they don't have an xml extension).

Values of disabled inputs will not be submitted

They don't get submitted, because that's what it says in the W3C specification.

17.13.2 Successful controls

A successful control is "valid" for submission. [snip]

  • Controls that are disabled cannot be successful.

In other words, the specification says that controls that are disabled are considered invalid and should not be submitted.

Call a global variable inside module

If You want to have a reference to this variable across the whole project, create somewhere d.ts file, e.g. globals.d.ts. Fill it with your global variables declarations, e.g.:

declare const BootBox: 'boot' | 'box';

Now you can reference it anywhere across the project, just like that:

const bootbox = BootBox;

Here's an example.

How can I deserialize JSON to a simple Dictionary<string,string> in ASP.NET?

I would suggest using System.Runtime.Serialization.Json that is part of .NET 4.5.

[DataContract]
public class Foo
{
   [DataMember(Name = "data")]
   public Dictionary<string,string> Data { get; set; }
}

Then use it like this:

var serializer = new DataContractJsonSerializer(typeof(List<Foo>));
var jsonParams = @"{""data"": [{""Key"":""foo"",""Value"":""bar""}] }";
var stream = new MemoryStream(Encoding.UTF8.GetBytes(jsonParams));

var obj = serializer.ReadObject(stream);
Console.WriteLine(obj);

Lombok added but getters and setters not recognized in Intellij IDEA

Go to settings->Plugins->Browse repositories and search for Lombok it will display the Lombok plugin also you will see the install option on the right side panel. Please install it. Then restart your intelliJ IDE. This has solved my issue.

How to sort an ArrayList in Java

Implement Comparable interface to Fruit.

public class Fruit implements Comparable<Fruit> {

It implements the method

@Override
    public int compareTo(Fruit fruit) {
        //write code here for compare name
    }

Then do call sort method

Collections.sort(fruitList);

How do I ignore all files in a folder with a Git repository in Sourcetree?

Right click on a file → IgnoreIgnore everything beneath.

If the Ignore option is grayed out then:

  1. Stage a file first
  2. Right click → Stop Tracking
  3. That file will appear in the pane below with a question mark → Right click on it→ Ignore

Enter image description here

Check if a string has a certain piece of text

Here you go: ES5

var test = 'Hello World';
if( test.indexOf('World') >= 0){
  // Found world
}

With ES6 best way would be to use includes function to test if the string contains the looking work.

const test = 'Hello World';
if (test.includes('World')) { 
  // Found world
}

try/catch with InputMismatchException creates infinite loop

To follow debobroto das's answer you can also put after

input.reset();
input.next(); 

I had the same problem and when I tried this. It completely fixed it.

Pass Parameter to Gulp Task

I know I am late to answer this question but I would like to add something to answer of @Ethan, the highest voted and accepted answer.

We can use yargs to get the command line parameter and with that we can also add our own alias for some parameters like follow.

var args = require('yargs')
    .alias('r', 'release')
    .alias('d', 'develop')
    .default('release', false)
    .argv;

Kindly refer this link for more details. https://github.com/yargs/yargs/blob/HEAD/docs/api.md

Following is use of alias as per given in documentation of yargs. We can also find more yargs function there and can make the command line passing experience even better.

.alias(key, alias)

Set key names as equivalent such that updates to a key will propagate to aliases and vice-versa.

Optionally .alias() can take an object that maps keys to aliases. Each key of this object should be the canonical version of the option, and each value should be a string or an array of strings.

Pythonic way to check if a file exists?

To check if a path is an existing file:

os.path.isfile(path)

Return True if path is an existing regular file. This follows symbolic links, so both islink() and isfile() can be true for the same path.

Extending from two classes

Why Not Use an Inner Class (Nesting)

class A extends B {
    private class C extends D {
        //Classes A , B , C , D accessible here 
    }
}

Disable Tensorflow debugging information

I was struggling from this for a while, tried almost all the solutions here but could not get rid of debugging info in TF 1.14, I have tried following multiple solutions:

import os
import logging
import sys

os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'  # FATAL
stderr = sys.stderr
sys.stderr = open(os.devnull, 'w')

import tensorflow as tf
tf.get_logger().setLevel(tf.compat.v1.logging.FATAL)
tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)
logging.getLogger('tensorflow').setLevel(tf.compat.v1.logging.FATAL)

sys.stderr = stderr

import absl.logging
logging.root.removeHandler(absl.logging._absl_handler)
absl.logging._warn_preinit_stderr = False

The debugging info still showed up, what finally helped was restarting my pc (actually restarting the kernel should work). So if somebody has similar problem, try restart kernel after you set your environment vars, simple but might not come in mind.

git: undo all working dir changes including new files

An alternative solution is to commit the changes, and then get rid of those commits. This does not have an immediate benefit at first, but it opens up the possibility to commit in chunks, and to create a git tag for backup.

You can do it on the current branch, like this:

git add (-A) .
git commit -m"DISCARD: Temporary local changes"
git tag archive/local-changes-2015-08-01  # optional
git revert HEAD
git reset HEAD^^

Or you can do it on detached HEAD. (assuming you start on BRANCHNAME branch):

git checkout --detach HEAD
git add (-A) .
git commit -m"DISCARD: Temporary local changes"
git tag archive/local-changes-2015-08-01  # optional
git checkout BRANCHNAME

However, what I usually do is to commit in chunks, then name some or all commits as "DISCARD: ...". Then use interactive rebase to remove the bad commits and keep the good ones.

git add -p  # Add changes in chunks.
git commit -m"DISCARD: Some temporary changes for debugging"
git add -p  # Add more stuff.
git commit -m"Docblock improvements"
git tag archive/local-changes-2015-08-01
git rebase -i (commit id)  # rebase on the commit id before the changes.
  # Remove the commits that say "DISCARD".

This is more verbose, but it allows to review exactly which changes you want to discard.

The git lol and git lola shortcuts have been very helpful with this workflow.

Android Layout Weight

weight values 0-1 share distribution of available space (after setting layout_width="0px") in proportion to the weight value. View elements with weight not specified (no weight entry) get weight 0 which means they get no expansion.

A simple alternative with no weight entries needed is to attach marquee to a view with text which tells it to expand from minimum needed for the text (wrap_content) to space available EditText: android:layout_width="wrap_content" android:ellipsize="marquee"

Perl: Use s/ (replace) and return new string

If you have Perl 5.14 or greater, you can use the /r option with the substitution operator to perform non-destructive substitution:

print "bla: ", $myvar =~ s/a/b/r, "\n";

In earlier versions you can achieve the same using a do() block with a temporary lexical variable, e.g.:

print "bla: ", do { (my $tmp = $myvar) =~ s/a/b/; $tmp }, "\n";

Control cannot fall through from one case label

You need to add a break statement:

switch (searchType)
{
case "SearchBooks":
    Selenium.Type("//*[@id='SearchBooks_TextInput']", searchText);
    Selenium.Click("//*[@id='SearchBooks_SearchBtn']");
    break;
case "SearchAuthors":
    Selenium.Type("//*[@id='SearchAuthors_TextInput']", searchText);
    Selenium.Click("//*[@id='SearchAuthors_SearchBtn']");
    break;
}

This assumes that you want to either handle the SearchBooks case or the SearchAuthors - as you had written in, in a traditional C-style switch statement the control flow would have "fallen through" from one case statement to the next meaning that all 4 lines of code get executed in the case where searchType == "SearchBooks".

The compiler error you are seeing was introduced (at least in part) to warn the programmer of this potential error.

As an alternative you could have thrown an error or returned from a method.

Generate Controller and Model

Create with Resource Method

php artisan make:controller --resource ControllerName  --model=ModelName

Use It With a path

php artisan make:controller --resource path/ControllerName  --model=ModelName

Mail multipart/alternative vs multipart/mixed

I hit this challenge today and I found these answers useful but not quite explicit enough for me.

Edit: Just found the Apache Commons Email that wraps this up nicely, meaning you don't need to know below.

If your requirement is an email with:

  1. text and html versions
  2. html version has embedded (inline) images
  3. attachments

The only structure I found that works with Gmail/Outlook/iPad is:

  • mixed
    • alternative
      • text
      • related
        • html
        • inline image
        • inline image
    • attachment
    • attachment

And the code is:

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.URLDataSource;
import javax.mail.BodyPart;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMultipart;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by StrongMan on 25/05/14.
 */
public class MailContentBuilder {

    private static final Pattern COMPILED_PATTERN_SRC_URL_SINGLE = Pattern.compile("src='([^']*)'",  Pattern.CASE_INSENSITIVE);
    private static final Pattern COMPILED_PATTERN_SRC_URL_DOUBLE = Pattern.compile("src=\"([^\"]*)\"",  Pattern.CASE_INSENSITIVE);

    /**
     * Build an email message.
     *
     * The HTML may reference the embedded image (messageHtmlInline) using the filename. Any path portion is ignored to make my life easier
     * e.g. If you pass in the image C:\Temp\dog.jpg you can use <img src="dog.jpg"/> or <img src="C:\Temp\dog.jpg"/> and both will work
     *
     * @param messageText
     * @param messageHtml
     * @param messageHtmlInline
     * @param attachments
     * @return
     * @throws MessagingException
     */
    public Multipart build(String messageText, String messageHtml, List<URL> messageHtmlInline, List<URL> attachments) throws MessagingException {
        final Multipart mpMixed = new MimeMultipart("mixed");
        {
            // alternative
            final Multipart mpMixedAlternative = newChild(mpMixed, "alternative");
            {
                // Note: MUST RENDER HTML LAST otherwise iPad mail client only renders the last image and no email
                addTextVersion(mpMixedAlternative,messageText);
                addHtmlVersion(mpMixedAlternative,messageHtml, messageHtmlInline);
            }
            // attachments
            addAttachments(mpMixed,attachments);
        }

        //msg.setText(message, "utf-8");
        //msg.setContent(message,"text/html; charset=utf-8");
        return mpMixed;
    }

    private Multipart newChild(Multipart parent, String alternative) throws MessagingException {
        MimeMultipart child =  new MimeMultipart(alternative);
        final MimeBodyPart mbp = new MimeBodyPart();
        parent.addBodyPart(mbp);
        mbp.setContent(child);
        return child;
    }

    private void addTextVersion(Multipart mpRelatedAlternative, String messageText) throws MessagingException {
        final MimeBodyPart textPart = new MimeBodyPart();
        textPart.setContent(messageText, "text/plain");
        mpRelatedAlternative.addBodyPart(textPart);
    }

    private void addHtmlVersion(Multipart parent, String messageHtml, List<URL> embeded) throws MessagingException {
        // HTML version
        final Multipart mpRelated = newChild(parent,"related");

        // Html
        final MimeBodyPart htmlPart = new MimeBodyPart();
        HashMap<String,String> cids = new HashMap<String, String>();
        htmlPart.setContent(replaceUrlWithCids(messageHtml,cids), "text/html");
        mpRelated.addBodyPart(htmlPart);

        // Inline images
        addImagesInline(mpRelated, embeded, cids);
    }

    private void addImagesInline(Multipart parent, List<URL> embeded, HashMap<String,String> cids) throws MessagingException {
        if (embeded != null)
        {
            for (URL img : embeded)
            {
                final MimeBodyPart htmlPartImg = new MimeBodyPart();
                DataSource htmlPartImgDs = new URLDataSource(img);
                htmlPartImg.setDataHandler(new DataHandler(htmlPartImgDs));
                String fileName = img.getFile();
                fileName = getFileName(fileName);
                String newFileName = cids.get(fileName);
                boolean imageNotReferencedInHtml = newFileName == null;
                if (imageNotReferencedInHtml) continue;
                // Gmail requires the cid have <> around it
                htmlPartImg.setHeader("Content-ID", "<"+newFileName+">");
                htmlPartImg.setDisposition(BodyPart.INLINE);
                parent.addBodyPart(htmlPartImg);
            }
        }
    }

    private void addAttachments(Multipart parent, List<URL> attachments) throws MessagingException {
        if (attachments != null)
        {
            for (URL attachment : attachments)
            {
                final MimeBodyPart mbpAttachment = new MimeBodyPart();
                DataSource htmlPartImgDs = new URLDataSource(attachment);
                mbpAttachment.setDataHandler(new DataHandler(htmlPartImgDs));
                String fileName = attachment.getFile();
                fileName = getFileName(fileName);
                mbpAttachment.setDisposition(BodyPart.ATTACHMENT);
                mbpAttachment.setFileName(fileName);
                parent.addBodyPart(mbpAttachment);
            }
        }
    }

    public String replaceUrlWithCids(String html, HashMap<String,String> cids)
    {
        html = replaceUrlWithCids(html, COMPILED_PATTERN_SRC_URL_SINGLE, "src='cid:@cid'", cids);
        html = replaceUrlWithCids(html, COMPILED_PATTERN_SRC_URL_DOUBLE, "src=\"cid:@cid\"", cids);
        return html;
    }

    private String replaceUrlWithCids(String html, Pattern pattern, String replacement, HashMap<String,String> cids) {
        Matcher matcherCssUrl = pattern.matcher(html);
        StringBuffer sb = new StringBuffer();
        while (matcherCssUrl.find())
        {
            String fileName = matcherCssUrl.group(1);
            // Disregarding file path, so don't clash your filenames!
            fileName = getFileName(fileName);
            // A cid must start with @ and be globally unique
            String cid = "@" + UUID.randomUUID().toString() + "_" + fileName;
            if (cids.containsKey(fileName))
                cid = cids.get(fileName);
            else
                cids.put(fileName,cid);
            matcherCssUrl.appendReplacement(sb,replacement.replace("@cid",cid));
        }
        matcherCssUrl.appendTail(sb);
        html = sb.toString();
        return html;
    }

    private String getFileName(String fileName) {
        if (fileName.contains("/"))
            fileName = fileName.substring(fileName.lastIndexOf("/")+1);
        return fileName;
    }
}

And an example of using it with from Gmail

/**
 * Created by StrongMan on 25/05/14.
 */
import com.sun.mail.smtp.SMTPTransport;

import java.net.URL;
import java.security.Security;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.URLDataSource;
import javax.mail.*;
import javax.mail.internet.*;

/**
 *
 * http://stackoverflow.com/questions/14744197/best-practices-sending-javamail-mime-multipart-emails-and-gmail
 * http://stackoverflow.com/questions/3902455/smtp-multipart-alternative-vs-multipart-mixed
 *
 *
 *
 * @author doraemon
 */
public class GoogleMail {


    private GoogleMail() {
    }

    /**
     * Send email using GMail SMTP server.
     *
     * @param username GMail username
     * @param password GMail password
     * @param recipientEmail TO recipient
     * @param title title of the message
     * @param messageText message to be sent
     * @throws AddressException if the email address parse failed
     * @throws MessagingException if the connection is dead or not in the connected state or if the message is not a MimeMessage
     */
    public static void Send(final String username, final String password, String recipientEmail, String title, String messageText, String messageHtml, List<URL> messageHtmlInline, List<URL> attachments) throws AddressException, MessagingException {
        GoogleMail.Send(username, password, recipientEmail, "", title, messageText, messageHtml, messageHtmlInline,attachments);
    }

    /**
     * Send email using GMail SMTP server.
     *
     * @param username GMail username
     * @param password GMail password
     * @param recipientEmail TO recipient
     * @param ccEmail CC recipient. Can be empty if there is no CC recipient
     * @param title title of the message
     * @param messageText message to be sent
     * @throws AddressException if the email address parse failed
     * @throws MessagingException if the connection is dead or not in the connected state or if the message is not a MimeMessage
     */
    public static void Send(final String username, final String password, String recipientEmail, String ccEmail, String title, String messageText, String messageHtml, List<URL> messageHtmlInline, List<URL> attachments) throws AddressException, MessagingException {
        Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
        final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";

        // Get a Properties object
        Properties props = System.getProperties();
        props.setProperty("mail.smtps.host", "smtp.gmail.com");
        props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
        props.setProperty("mail.smtp.socketFactory.fallback", "false");
        props.setProperty("mail.smtp.port", "465");
        props.setProperty("mail.smtp.socketFactory.port", "465");
        props.setProperty("mail.smtps.auth", "true");

        /*
        If set to false, the QUIT command is sent and the connection is immediately closed. If set
        to true (the default), causes the transport to wait for the response to the QUIT command.

        ref :   http://java.sun.com/products/javamail/javadocs/com/sun/mail/smtp/package-summary.html
                http://forum.java.sun.com/thread.jspa?threadID=5205249
                smtpsend.java - demo program from javamail
        */
        props.put("mail.smtps.quitwait", "false");

        Session session = Session.getInstance(props, null);

        // -- Create a new message --
        final MimeMessage msg = new MimeMessage(session);

        // -- Set the FROM and TO fields --
        msg.setFrom(new InternetAddress(username + "@gmail.com"));
        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipientEmail, false));

        if (ccEmail.length() > 0) {
            msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(ccEmail, false));
        }

        msg.setSubject(title);

        // mixed
        MailContentBuilder mailContentBuilder = new MailContentBuilder();
        final Multipart mpMixed = mailContentBuilder.build(messageText, messageHtml, messageHtmlInline, attachments);
        msg.setContent(mpMixed);
        msg.setSentDate(new Date());

        SMTPTransport t = (SMTPTransport)session.getTransport("smtps");

        t.connect("smtp.gmail.com", username, password);
        t.sendMessage(msg, msg.getAllRecipients());
        t.close();
    }

}

get current url in twig template?

{{ path(app.request.attributes.get('_route'),
     app.request.attributes.get('_route_params')) }}

If you want to read it into a view variable:

{% set currentPath = path(app.request.attributes.get('_route'),
                       app.request.attributes.get('_route_params')) %}

The app global view variable contains all sorts of useful shortcuts, such as app.session and app.security.token.user, that reference the services you might use in a controller.

How do I install boto?

  1. If necessary, install pip:

    sudo apt-get install python-pip

  2. Then install boto:

    pip install -U boto

Extracting extension from filename in Python

This is The Simplest Method to get both Filename & Extension in just a single line.

fName, ext = 'C:/folder name/Flower.jpeg'.split('/')[-1].split('.')

>>> print(fName)
Flower
>>> print(ext)
jpeg

Unlike other solutions, you don't need to import any package for this.

Bootstrap modal opening on page load

Use a document.ready() event around your call.

$(document).ready(function () {

    $('#memberModal').modal('show');

});

jsFiddle updated - http://jsfiddle.net/uvnggL8w/1/

Heap vs Binary Search Tree (BST)

A binary search tree uses the definition: that for every node,the node to the left of it has a less value(key) and the node to the right of it has a greater value(key).

Where as the heap,being an implementation of a binary tree uses the following definition:

If A and B are nodes, where B is the child node of A,then the value(key) of A must be larger than or equal to the value(key) of B.That is, key(A) = key(B).

http://wiki.answers.com/Q/Difference_between_binary_search_tree_and_heap_tree

I ran in the same question today for my exam and I got it right. smile ... :)

How to watch for form changes in Angular

For angular 5+ version. Putting version helps as angular makes lot of changes.

ngOnInit() {

 this.myForm = formBuilder.group({
      firstName: 'Thomas',
      lastName: 'Mann'
    })
this.formControlValueChanged() // Note if you are doing an edit/fetching data from an observer this must be called only after your form is properly initialized otherwise you will get error.
}

formControlValueChanged(): void {       
        this.myForm.valueChanges.subscribe(value => {
            console.log('value changed', value)
        })
}

Return anonymous type results?

I tend to go for this pattern:

public class DogWithBreed
{
    public Dog Dog { get; set; }
    public string BreedName  { get; set; }
}

public IQueryable<DogWithBreed> GetDogsWithBreedNames()
{
    var db = new DogDataContext(ConnectString);
    var result = from d in db.Dogs
                 join b in db.Breeds on d.BreedId equals b.BreedId
                 select new DogWithBreed()
                        {
                            Dog = d,
                            BreedName = b.BreedName
                        };
    return result;
}

It means you have an extra class, but it's quick and easy to code, easily extensible, reusable and type-safe.

How to extract .war files in java? ZIP vs JAR

If you look at the JarFile API you'll see that it's a subclass of the ZipFile class.

The jar-specific classes mostly just add jar-specific functionality, like direct support for manifest file attributes and so on.

It's OOP "in action"; since jar files are zip files, the jar classes can use zip functionality and provide additional utility.

Android sample bluetooth code to send a simple string via bluetooth

private OutputStream outputStream;
private InputStream inStream;

private void init() throws IOException {
    BluetoothAdapter blueAdapter = BluetoothAdapter.getDefaultAdapter();
    if (blueAdapter != null) {
        if (blueAdapter.isEnabled()) {
            Set<BluetoothDevice> bondedDevices = blueAdapter.getBondedDevices();

            if(bondedDevices.size() > 0) {
                Object[] devices = (Object []) bondedDevices.toArray();
                BluetoothDevice device = (BluetoothDevice) devices[position];
                ParcelUuid[] uuids = device.getUuids();
                BluetoothSocket socket = device.createRfcommSocketToServiceRecord(uuids[0].getUuid());
                socket.connect();
                outputStream = socket.getOutputStream();
                inStream = socket.getInputStream();
            }

            Log.e("error", "No appropriate paired devices.");
        } else {
            Log.e("error", "Bluetooth is disabled.");
        }
    }
}

public void write(String s) throws IOException {
    outputStream.write(s.getBytes());
}

public void run() {
    final int BUFFER_SIZE = 1024;
    byte[] buffer = new byte[BUFFER_SIZE];
    int bytes = 0;
    int b = BUFFER_SIZE;

    while (true) {
        try {
            bytes = inStream.read(buffer, bytes, BUFFER_SIZE - bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

CSS text-align: center; is not centering things

To make a inline-block element align center horizontally in its parent, add text-align:center to its parent.

AppSettings get value from .config file

This works for me:

string value = System.Configuration.ConfigurationManager.AppSettings[key];

How to access remote server with local phpMyAdmin client?

Delete complete entries of /etc/http/conf.d/phpMyAdmin.conf

And below entires in above file,

_x000D_
_x000D_
<Directory /usr/share/phpMyAdmin/>_x000D_
   AddDefaultCharset UTF-8_x000D_
_x000D_
   <IfModule mod_authz_core.c>_x000D_
     # Apache 2.4_x000D_
     <RequireAny>_x000D_
       #ADD following line:_x000D_
       Require all granted_x000D_
       Require ip 127.0.0.1_x000D_
       Require ip ::1_x000D_
     </RequireAny>_x000D_
   </IfModule>_x000D_
   <IfModule !mod_authz_core.c>_x000D_
     # Apache 2.2_x000D_
     #CHANGE following 2 lines:_x000D_
     Order Allow,Deny_x000D_
     Allow from All_x000D_
     Allow from 127.0.0.1_x000D_
     Allow from ::1_x000D_
   </IfModule>_x000D_
</Directory>
_x000D_
_x000D_
_x000D_

Then,

run below command in MySQL prompt,

GRANT ALL ON *.* to root@localhost IDENTIFIED BY 'root@<password>'

GRANT ALL ON *.* to root@'%' IDENTIFIED BY 'root@<password>'

For reference: Allow IP to Access Secured PhpMyAdmin

SQL Case Expression Syntax?

Sybase has the same case syntax as SQL Server:

Description

Supports conditional SQL expressions; can be used anywhere a value expression can be used.

Syntax

case 
     when search_condition then expression 
    [when search_condition then expression]...
    [else expression]
end

Case and values syntax

case expression
     when expression then expression 
    [when expression then expression]...
    [else expression]
end

Parameters

case

begins the case expression.

when

precedes the search condition or the expression to be compared.

search_condition

is used to set conditions for the results that are selected. Search conditions for case expressions are similar to the search conditions in a where clause. Search conditions are detailed in the Transact-SQL User’s Guide.

then

precedes the expression that specifies a result value of case.

expression

is a column name, a constant, a function, a subquery, or any combination of column names, constants, and functions connected by arithmetic or bitwise operators. For more information about expressions, see “Expressions” in.

Example

select disaster, 
       case
            when disaster = "earthquake" 
                then "stand in doorway"
            when disaster = "nuclear apocalypse" 
                then "hide in basement"
            when monster = "zombie apocalypse" 
                then "hide with Chuck Norris"
            else
                then "ask mom"
       end 
  from endoftheworld

keycloak Invalid parameter: redirect_uri

If you're seeing this problem after you've made a modification to the Keycloak context path, you'll need to make an additional change to a redirect url setting:

  1. Change <web-context>yourchange/auth</web-context> back to <web-context>auth</web-context> in standalone.xml
  2. Restart Keycloak and navigate to the login page (/auth/admin)
  3. Log in and select the "Master" realm
  4. Select "Clients" from the side menu
  5. Select the "security-admin-console" client from the list that appears
  6. Change the "Valid Redirect URIs" from /auth/admin/master/console/* to /yourchange/auth/admin/master/console/*
  7. Save and sign out. You'll again see the "Invalid redirect url" message after signing out.
  8. Now, put in your original change <web-context>yourchange/auth</web-context> in standalone.xml Restart Keycloak and navigate to the login page (which is now /yourchange/auth/admin)
  9. Log in and enjoy

Android: No Activity found to handle Intent error? How it will resolve

if (intent.resolveActivity(getPackageManager()) == null) {
    Utils.showToast(activity, no_app_available_to_complete_this_task);
} else {
    startActivityForResult(intent, 1);
}

Android Text over image

You can use a TextView and change its background to the image you want to use

Replace or delete certain characters from filenames of all files in a folder

Use PowerShell to do anything smarter for a DOS prompt. Here, I've shown how to batch rename all the files and directories in the current directory that contain spaces by replacing them with _ underscores.

Dir |
Rename-Item -NewName { $_.Name -replace " ","_" }

EDIT :
Optionally, the Where-Object command can be used to filter out ineligible objects for the successive cmdlet (command-let). The following are some examples to illustrate the flexibility it can afford you:

  • To skip any document files

    Dir |
    Where-Object { $_.Name -notmatch "\.(doc|xls|ppt)x?$" } |
    Rename-Item -NewName { $_.Name -replace " ","_" }
    
  • To process only directories (pre-3.0 version)

    Dir |
    Where-Object { $_.Mode -match "^d" } |
    Rename-Item -NewName { $_.Name -replace " ","_" }
    

    PowerShell v3.0 introduced new Dir flags. You can also use Dir -Directory there.

  • To skip any files already containing an underscore (or some other character)

    Dir |
    Where-Object { -not $_.Name.Contains("_") } |
    Rename-Item -NewName { $_.Name -replace " ","_" }
    

JavaScript global event mechanism

Does this help you:

<script type="text/javascript">
window.onerror = function() {
    alert("Error caught");
};

xxx();
</script>

I'm not sure how it handles Flash errors though...

Update: it doesn't work in Opera, but I'm hacking Dragonfly right now to see what it gets. Suggestion about hacking Dragonfly came from this question:

Mimic Window. onerror in Opera using javascript

How to create a simple proxy in C#?

Socks4 is a very simple protocol to implement. You listen for the initial connection, connect to the host/port that was requested by the client, send the success code to the client then forward the outgoing and incoming streams across sockets.

If you go with HTTP you'll have to read and possibly set/remove some HTTP headers so that's a little more work.

If I remember correctly, SSL will work across HTTP and Socks proxies. For a HTTP proxy you implement the CONNECT verb, which works much like the socks4 as described above, then the client opens the SSL connection across the proxied tcp stream.

How do you pass a function as a parameter in C?

It's not really a function, but it is an localised piece of code. Of course it doesn't pass the code just the result. It won't work if passed to an event dispatcher to be run at a later time (as the result is calculated now and not when the event occurs). But it does localise your code into one place if that is all you are trying to do.

#include <stdio.h>

int IncMultInt(int a, int b)
{
    a++;
    return a * b;
}

int main(int argc, char *argv[])

{
    int a = 5;
    int b = 7;

    printf("%d * %d = %d\n", a, b, IncMultInt(a, b));

    b = 9;

    // Create some local code with it's own local variable
    printf("%d * %d = %d\n", a, b,  ( { int _a = a+1; _a * b; } ) );

    return 0;
}

Find where java class is loaded from

Here's an example:

package foo;

public class Test
{
    public static void main(String[] args)
    {
        ClassLoader loader = Test.class.getClassLoader();
        System.out.println(loader.getResource("foo/Test.class"));
    }
}

This printed out:

file:/C:/Users/Jon/Test/foo/Test.class

overlay opaque div over youtube iframe

Hmm... what's different this time? http://jsfiddle.net/fdsaP/2/

Renders in Chrome fine. Do you need it cross-browser? It really helps being specific.

EDIT: Youtube renders the object and embed with no explicit wmode set, meaning it defaults to "window" which means it overlays everything. You need to either:


a) Host the page that contains the object/embed code yourself and add wmode="transparent" param element to object and attribute to embed if you choose to serve both elements

b) Find a way for youtube to specify those.


Display JSON Data in HTML Table

check below link to convert JSON data to standard HTML table in the simplest and fastest way.

http://crunchify.com/crunchifyjsontohtml-js-json-to-html-table-converter-script/

Eclipse C++: Symbol 'std' could not be resolved

Install C++ SDK:

Help > Install New Software > Work with: path for your eclipse version > search for C++ and install C++ sdk development tools.

Example for a path: Mars - http://download.eclipse.org/releases/mars

Extract value of attribute node via XPath

As answered above:

//Parent[@id='1']/Children/child/@name 

will only output the name attribute of the 4 child nodes belonging to the Parent specified by its predicate [@id=1]. You'll then need to change the predicate to [@id=2] to get the set of child nodes for the next Parent.

However, if you ignore the Parent node altogether and use:

//child/@name

you can select name attribute of all child nodes in one go.

name="Child_2"
name="Child_4"
name="Child_1"
name="Child_3"
name="Child_1"
name="Child_2"
name="Child_4"
name="Child_3"

WooCommerce: Finding the products in database

Update 2020

Products are located mainly in the following tables:

  • wp_posts table with post_type like product (or product_variation),

  • wp_postmeta table with post_id as relational index (the product ID).

  • wp_wc_product_meta_lookup table with product_id as relational index (the post ID) | Allow fast queries on specific product data (since WooCommerce 3.7)

  • wp_wc_order_product_lookuptable with product_id as relational index (the post ID) | Allow fast queries to retrieve products on orders (since WooCommerce 3.7)

Product types, categories, subcategories, tags, attributes and all other custom taxonomies are located in the following tables:

  • wp_terms

  • wp_termmeta

  • wp_term_taxonomy

  • wp_term_relationships - column object_id as relational index (the product ID)

  • wp_woocommerce_termmeta

  • wp_woocommerce_attribute_taxonomies (for product attributes only)

  • wp_wc_category_lookup (for product categories hierarchy only since WooCommerce 3.7)


Product types are handled by custom taxonomy product_type with the following default terms:

  • simple
  • grouped
  • variable
  • external

Some other product types for Subscriptions and Bookings plugins:

  • subscription
  • variable-subscription
  • booking

Since Woocommerce 3+ a new custom taxonomy named product_visibility handle:

  • The product visibility with the terms exclude-from-search and exclude-from-catalog
  • The feature products with the term featured
  • The stock status with the term outofstock
  • The rating system with terms from rated-1 to rated-5

Particular feature: Each product attribute is a custom taxonomy…


References:

How do I mock an open used in a with statement (using the Mock framework in Python)?

The top answer is useful but I expanded on it a bit.

If you want to set the value of your file object (the f in as f) based on the arguments passed to open() here's one way to do it:

def save_arg_return_data(*args, **kwargs):
    mm = MagicMock(spec=file)
    mm.__enter__.return_value = do_something_with_data(*args, **kwargs)
    return mm
m = MagicMock()
m.side_effect = save_arg_return_array_of_data

# if your open() call is in the file mymodule.animals 
# use mymodule.animals as name_of_called_file
open_name = '%s.open' % name_of_called_file

with patch(open_name, m, create=True):
    #do testing here

Basically, open() will return an object and with will call __enter__() on that object.

To mock properly, we must mock open() to return a mock object. That mock object should then mock the __enter__() call on it (MagicMock will do this for us) to return the mock data/file object we want (hence mm.__enter__.return_value). Doing this with 2 mocks the way above allows us to capture the arguments passed to open() and pass them to our do_something_with_data method.

I passed an entire mock file as a string to open() and my do_something_with_data looked like this:

def do_something_with_data(*args, **kwargs):
    return args[0].split("\n")

This transforms the string into a list so you can do the following as you would with a normal file:

for line in file:
    #do action

Error CS1705: "which has a higher version than referenced assembly"

Handmade dll's collection folder
If you solution has a garbage folder for dll-files from different libraries
lib, source, libs, etc.
You can get this trouble if you'll open your solution (for a firs time) in Visual Studio. And your dll's collecting folder is missed for somehow or a concrete dll-file is missed.

Visual Studio will try silently to substitute dll's reference for something on its own. If VS will succeed then a new reference will be persistent for your local solution. Not for other clones/checkouts.

I.e. your <HintPath> will be ignored and you project file (.csproj) will not be changed.
As an example of me

<Reference Include="DocumentFormat.OpenXml, Version=2.0.5022.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
  <SpecificVersion>False</SpecificVersion>
  <HintPath>..\..\..\lib\DocumentFormat.OpenXml.dll</HintPath>
</Reference>

The DocumentFormat.OpenXml will be referenced from C:\Program Files (x86)\Open XML SDK\V2.5\lib not from a solution\..\lib folder.

fast Workaround

  • check and restore you dll's collecting folder
  • from Solution Explorer do Unload Project, then Reload Project.

right Workaround is to migrate to NuGet package manager.

Comparing a variable with a string python not working when redirecting from bash script

When you read() the file, you may get a newline character '\n' in your string. Try either

if UserInput.strip() == 'List contents': 

or

if 'List contents' in UserInput: 

Also note that your second file open could also use with:

with open('/Users/.../USER_INPUT.txt', 'w+') as UserInputFile:     if UserInput.strip() == 'List contents': # or if s in f:         UserInputFile.write("ls")     else:         print "Didn't work" 

Multi value Dictionary

I know this is an old thread, but - since it's not been mentioned this works

  Dictionary<string, object> LookUp = new Dictionary<string, object>();
  LookUp.Add("bob", new { age = "23", height = "2.1m", weight = "110kg"});
  LookUp.Add("jasper", new { age = "33", height = "1.75m", weight = "90kg"});
  foreach(KeyValuePair<string, object> entry in LookUp )
  {
      object person = entry.Value;
      Console.WriteLine("Person name:" + entry.Key + " Age: "  + person.age);          
  }

Converting a factor to numeric without losing information R (as.numeric() doesn't seem to work)

First, factor consists of indices and levels. This fact is very very important when you are struggling with factor.

For example,

> z <- factor(letters[c(3, 2, 3, 4)])

# human-friendly display, but internal structure is invisible
> z
[1] c b c d
Levels: b c d

# internal structure of factor
> unclass(z)
[1] 2 1 2 3
attr(,"levels")
[1] "b" "c" "d"

here, z has 4 elements.
The index is 2, 1, 2, 3 in that order.
The level is associated with each index: 1 -> b, 2 -> c, 3 -> d.

Then, as.numeric converts simply the index part of factor into numeric.
as.character handles the index and levels, and generates character vector expressed by its level.

?as.numeric says that Factors are handled by the default method.

Android ListView Divider

The problem you're having stems from the fact that you're missing android:dividerHeight, which you need, and the fact that you're trying to specify a line weight in your drawable, which you can't do with dividers for some odd reason. Essentially to get your example to work you could do something like the following:

Create your drawable as either a rectangle or a line, either works you just can't try to set any dimensions on it, so either:

<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="line">
     <stroke android:color="#8F8F8F" android:dashWidth="1dp" android:dashGap="1dp" />
</shape>

OR:

<shape xmlns:android="http://schemas.android.com/apk/res/android"  android:shape="rectangle">
     <solid android:color="#8F8F8F"/>
</shape>

Then create a custom style (just a preference but I like to be able to reuse stuff)

<style name="dividedListStyle" parent="@android:style/Widget.ListView">
    <item name="android:cacheColorHint">@android:color/transparent</item>
    <item name="android:divider">@drawable/list_divider</item>
    <item name="android:dividerHeight">1dp</item>
</style>

Finally declare your list view using the custom style:

<ListView
     style="@style/dividedListStyle"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:id="@+id/cashItemsList">
</ListView>

I'm assuming you know how to use these snippets, if not let me know. Basically the answer to your question is that you can't set the divider thickness in the drawable, you have to leave the width undefined there and use android:dividerHeight to set it instead.

MySQL select one column DISTINCT, with corresponding other columns

You can use group by for display distinct values and also corresponding fields.

select * from tabel_name group by FirstName

Now you got output like this:

ID    FirstName     LastName
2     Bugs          Bunny
1     John          Doe


If you want to answer like

ID    FirstName     LastName
1     John          Doe
2     Bugs          Bunny

then use this query,

select * from table_name group by FirstName order by ID

Clearing NSUserDefaults

This code resets the defaults to the registration domain:

[[NSUserDefaults standardUserDefaults] setPersistentDomain:[NSDictionary dictionary] forName:[[NSBundle mainBundle] bundleIdentifier]];

In other words, it removeObjectForKey for every single key you ever registered in that app.

Credits to Ken Thomases on this Apple Developer Forums thread.

Change UITextField and UITextView Cursor / Caret Color

A more general approach would be to set the UIView's appearance's tintColor.

UIColor *myColor = [UIColor purpleColor];
[[UIView appearance] setTintColor:myColor];

Makes sense if you're using many default UI elements.

"Non-resolvable parent POM: Could not transfer artifact" when trying to refer to a parent pom from a child pom with ${parent.groupid}

Looks like you're trying to both inherit the groupId from the parent, and simultaneously specify the parent using an inherited groupId!

In the child pom, use something like this:

<modelVersion>4.0.0</modelVersion>

<parent>
  <groupId>org.felipe</groupId>
  <artifactId>tutorial_maven</artifactId>
  <version>1.0-SNAPSHOT</version>
  <relativePath>../pom.xml</relativePath>
</parent>

<artifactId>tutorial_maven_jar</artifactId>

Using properties like ${project.groupId} won't work there. If you specify the parent in this way, then you can inherit the groupId and version in the child pom. Hence, you only need to specify the artifactId in the child pom.

How to get Month Name from Calendar?

You can get it one line like this: String monthName = new DataFormatSymbols.getMonths()[cal.get(Calendar.MONTH)]

C# "internal" access modifier when doing unit testing

Adding to Eric's answer, you can also configure this in the csproj file:

<ItemGroup>
    <AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleTo">
      <_Parameter1>MyTests</_Parameter1>
    </AssemblyAttribute>
</ItemGroup>

Or if you have one test project per project to be tested, you could do something like this in your Directory.Build.props file:

<ItemGroup>
    <AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleTo">
      <_Parameter1>$(MSBuildProjectName).Test</_Parameter1>
    </AssemblyAttribute>
</ItemGroup>

See: https://stackoverflow.com/a/49978185/1678053
Example: https://github.com/gldraphael/evlog/blob/master/Directory.Build.props#L5-L12

Convert List<Object> to String[] in Java

Using Guava

List<Object> lst ...    
List<String> ls = Lists.transform(lst, Functions.toStringFunction());

What does "control reaches end of non-void function" mean?

The compiler isn't smart enough to know that <, >, and == are a "complete set". You can let it know that by removing the condition "if(val == sorted[mid])" -- it's redundant. Jut say "else return mid;"

Execute SQLite script

If you are using the windows CMD you can use this command to create a database using sqlite3

C:\sqlite3.exe DBNAME.db ".read DBSCRIPT.sql"

If you haven't a database with that name sqlite3 will create one, and if you already have one, it will run it anyways but with the "TABLENAME already exists" error, I think you can also use this command to change an already existing database (but im not sure)

Change Orientation of Bluestack : portrait/landscape mode

You could also change resolution of your bluestacks emulator. For example from 800x1280 to 1280x800

Here are instructions for how to change the screen resolution.

To change screen resolution in BlueStacks Android emulator you need to edit two registry items:

  1. Run regedit.exe

  2. Set new resolution (in decimal):

HKEY_LOCAL_MACHINE\SOFTWARE\BlueStacks\Guests\Android\FrameBuffer\0\Height

and

HKEY_LOCAL_MACHINE\SOFTWARE\BlueStacks\Guests\Android\FrameBuffer\0\Width

Kill all BlueStacks processes.

Restart BlueStacks

Android Fragment onClick button Method

The others have already said that methods in onClick are searched in activities, not fragments. Nevertheless, if you really want it, it is possible.

Basically, each view has a tag (probably null). We set the root view's tag to the fragment that inflated that view. Then, it is easy to search the view parents and retrieve the fragment containing the clicked button. Now, we find out the method name and use reflection to call the same method from the retrieved fragment. Easy!

in a class that extends Fragment:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_id, container, false);

    OnClickFragments.registerTagFragment(rootView, this); // <========== !!!!!

    return rootView;
}

public void onButtonSomething(View v) {
    Log.d("~~~","~~~ MyFragment.onButtonSomething");
    // whatever
}

all activities are derived from the same ButtonHandlingActivity:

public class PageListActivity extends ButtonHandlingActivity

ButtonHandlingActivity.java:

public class ButtonHandlingActivity extends Activity {

    public void onButtonSomething(View v) {
        OnClickFragments.invokeFragmentButtonHandlerNoExc(v);
//or, if you want to handle exceptions:
//      try {
//          OnClickFragments.invokeFragmentButtonHandler(v);
//      } catch ...
    }

}

It has to define methods for all xml onClick handlers.

com/example/customandroid/OnClickFragments.java:

package com.example.customandroid;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import android.app.Fragment;
import android.view.View;

public abstract class OnClickFragments {
    public static class FragmentHolder {
        Fragment fragment;
        public FragmentHolder(Fragment fragment) {
            this.fragment = fragment;
        }
    }
    public static Fragment getTagFragment(View view) {
        for (View v = view; v != null; v = (v.getParent() instanceof View) ? (View)v.getParent() : null) {
            Object tag = v.getTag();
            if (tag != null && tag instanceof FragmentHolder) {
                return ((FragmentHolder)tag).fragment;
            }
        }
        return null;
    }
    public static String getCallingMethodName(int callsAbove) {
        Exception e = new Exception();
        e.fillInStackTrace();
        String methodName = e.getStackTrace()[callsAbove+1].getMethodName();
        return methodName;
    }
    public static void invokeFragmentButtonHandler(View v, int callsAbove) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException {
        String methodName = getCallingMethodName(callsAbove+1);
        Fragment f = OnClickFragments.getTagFragment(v);
        Method m = f.getClass().getMethod(methodName, new Class[] { View.class });
        m.invoke(f, v);
    }
    public static void invokeFragmentButtonHandler(View v) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException {
        invokeFragmentButtonHandler(v,1);
    }
    public static void invokeFragmentButtonHandlerNoExc(View v) {
        try {
            invokeFragmentButtonHandler(v,1);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
    public static void registerTagFragment(View rootView, Fragment fragment) {
        rootView.setTag(new FragmentHolder(fragment));
    }
}

And the next adventure will be proguard obfuscation...

PS

It is of course up to you to design your application so that the data live in the Model rather than in Activities or Fragments (which are Controllers from the MVC, Model-View-Controller point of view). The View is what you define via xml, plus the custom view classes (if you define them, most people just reuse what already is). A rule of thumb: if some data definitely must survive the screen turn, they belong to Model.

TypeError: 'undefined' is not an object

I'm not sure how you could just check if something isn't undefined and at the same time get an error that it is undefined. What browser are you using?

You could check in the following way (extra = and making length a truthy evaluation)

if (typeof(sub.from) !== 'undefined' && sub.from.length) {

[update]

I see that you reset sub and thereby reset sub.from but fail to re check if sub.from exist:

for (var i = 0; i < sub.from.length; i++) {//<== assuming sub.from.exist
            mainid = sub.from[i]['id'];
            var sub = afcHelper_Submissions[mainid]; // <== re setting sub

My guess is that the error is not on the if statement but on the for(i... statement. In Firebug you can break automatically on an error and I guess it'll break on that line (not on the if statement).

Reset the Value of a Select Box

I found a little utility function a while back and I've been using it for resetting my form elements ever since (source: http://www.learningjquery.com/2007/08/clearing-form-data):

function clearForm(form) {
  // iterate over all of the inputs for the given form element
  $(':input', form).each(function() {
    var type = this.type;
    var tag = this.tagName.toLowerCase(); // normalize case
    // it's ok to reset the value attr of text inputs, 
    // password inputs, and textareas
    if (type == 'text' || type == 'password' || tag == 'textarea')
      this.value = "";
    // checkboxes and radios need to have their checked state cleared 
    // but should *not* have their 'value' changed
    else if (type == 'checkbox' || type == 'radio')
      this.checked = false;
    // select elements need to have their 'selectedIndex' property set to -1
    // (this works for both single and multiple select elements)
    else if (tag == 'select')
      this.selectedIndex = -1;
  });
};

... or as a jQuery plugin...

$.fn.clearForm = function() {
  return this.each(function() {
    var type = this.type, tag = this.tagName.toLowerCase();
    if (tag == 'form')
      return $(':input',this).clearForm();
    if (type == 'text' || type == 'password' || tag == 'textarea')
      this.value = '';
    else if (type == 'checkbox' || type == 'radio')
      this.checked = false;
    else if (tag == 'select')
      this.selectedIndex = -1;
  });
};

jQuery 'each' loop with JSON array

Brief code but full-featured

The following is a hybrid jQuery solution that formats each data "record" into an HTML element and uses the data's properties as HTML attribute values.

The jquery each runs the inner loop; I needed the regular JavaScript for on the outer loop to be able to grab the property name (instead of value) for display as the heading. According to taste it can be modified for slightly different behaviour.

This is only 5 main lines of code but wrapped onto multiple lines for display:

$.get("data.php", function(data){

    for (var propTitle in data) {

        $('<div></div>') 
            .addClass('heading')
            .insertBefore('#contentHere')
            .text(propTitle);

            $(data[propTitle]).each(function(iRec, oRec) {

                $('<div></div>')
                    .addClass(oRec.textType)
                    .attr('id', 'T'+oRec.textId)
                    .insertBefore('#contentHere')
                    .text(oRec.text);
            });
    }

});

Produces the output

(Note: I modified the JSON data text values by prepending a number to ensure I was displaying the proper records in the proper sequence - while "debugging")

<div class="heading">
    justIn
</div>
<div id="T123" class="Greeting">
    1Hello
</div>
<div id="T514" class="Question">
    1What's up?
</div>
<div id="T122" class="Order">
    1Come over here
</div>
<div class="heading">
    recent
</div>
<div id="T1255" class="Greeting">
    2Hello
</div>
<div id="T6564" class="Question">
    2What's up?
</div>
<div id="T0192" class="Order">
    2Come over here
</div>
<div class="heading">
    old
</div>
<div id="T5213" class="Greeting">
    3Hello
</div>
<div id="T9758" class="Question">
    3What's up?
</div>
<div id="T7655" class="Order">
    3Come over here
</div>
<div id="contentHere"></div>

Apply a style sheet

<style>
.heading { font-size: 24px; text-decoration:underline }
.Greeting { color: green; }
.Question { color: blue; }
.Order { color: red; }
</style>

to get a "beautiful" looking set of data

alt text

More Info
The JSON data was used in the following way:

for each category (key name the array is held under):

  • the key name is used as the section heading (e.g. justIn)

for each object held inside an array:

  • 'text' becomes the content of a div
  • 'textType' becomes the class of the div (hooked into a style sheet)
  • 'textId' becomes the id of the div
  • e.g. <div id="T122" class="Order">Come over here</div>

MySQL - UPDATE query based on SELECT Query

UPDATE
    `table1` AS `dest`,
    (
        SELECT
            *
        FROM
            `table2`
        WHERE
            `id` = x
    ) AS `src`
SET
    `dest`.`col1` = `src`.`col1`
WHERE
    `dest`.`id` = x
;

Hope this works for you.

JS file gets a net::ERR_ABORTED 404 (Not Found)

As mentionned in comments: you need a way to send your static files to the client. This can be achieved with a reverse proxy like Nginx, or simply using express.static().

Put all your "static" (css, js, images) files in a folder dedicated to it, different from where you put your "views" (html files in your case). I'll call it static for the example. Once it's done, add this line in your server code:

app.use("/static", express.static('./static/'));

This will effectively serve every file in your "static" folder via the /static route.

Querying your index.js file in the client thus becomes:

<script src="static/index.js"></script>

FPDF error: Some data has already been output, can't send PDF

For fpdf to work properly, there cannot be any output at all beside what fpdf generates. For example, this will work:

<?php
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>

While this will not (note the leading space before the opening <? tag)

 <?php
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>

Also, this will not work either (the echo will break it):

<?php
echo "About to create pdf";
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>

I'm not sure about the drupal side of things, but I know that absolutely zero non-fpdf output is a requirement for fpdf to work.


add ob_start (); at the top and at the end add ob_end_flush();

<?php
    ob_start();
    require('fpdf.php');
    $pdf = new FPDF();
    $pdf->AddPage();
    $pdf->SetFont('Arial','B',16);
    $pdf->Cell(40,10,'Hello World!');
    $pdf->Output();
    ob_end_flush(); 
?>

give me an error as below:
FPDF error: Some data has already been output, can't send PDF

to over come this error: go to fpdf.php in that,goto line number 996

function Output($name='', $dest='')

after that make changes like this:

function Output($name='', $dest='') {   
    ob_clean();     //Output PDF to so

Hi do you have a session header on the top of your page. or any includes If you have then try to add this codes on top pf your page it should works fine.

<?

while (ob_get_level())
ob_end_clean();
header("Content-Encoding: None", true);

?>

cheers :-)


In my case i had set:

ini_set('display_errors', 'on');
error_reporting(E_ALL | E_STRICT);

When i made the request to generate the report, some warnings were displayed in the browser (like the usage of deprecated functions).
Turning off the display_errors option, the report was generated successfully.

Download the Android SDK components for offline install

There is an open source offline package deployer for Windows which I wrote:

http://siddharthbarman.com/apd/

You can try this out to see if it meets your needs.

html <input type="text" /> onchange event not working

It is better to use onchange(event) with <select>. With <input> you can use below event:

- onkeyup(event)
- onkeydown(event)
- onkeypress(event)

How can I see the request headers made by curl when sending a request to the server?

curl -s -v -o/dev/null -H "Testheader: test" http://www.example.com

You could also use -I option if you want to send a HEAD request and not a GET request.

How to conditional format based on multiple specific text in Excel

Suppose your "Don't Check" list is on Sheet2 in cells A1:A100, say, and your current client IDs are in Sheet1 in Column A.

What you would do is:

  1. Select the whole data table you want conditionally formatted in Sheet1
  2. Click Conditional Formatting > New Rule > Use a Formula to determine which cells to format
  3. In the formula bar, type in =ISNUMBER(MATCH($A1,Sheet2!$A$1:$A$100,0)) and select how you want those rows formatted

And that should do the trick.

How to detect a loop in a linked list?

You may use Floyd's tortoise algorithm as suggested in above answers as well.

This algorithm can check if a singly linked list has a closed cycle. This can be achieved by iterating a list with two pointers that will move in different speed. In this way, if there is a cycle the two pointers will meet at some point in the future.

Please feel free to check out my blog post on the linked lists data structure, where I also included a code snippet with an implementation of the above-mentioned algorithm in java language.

Regards,

Andreas (@xnorcode)

How to validate domain credentials?

Here's how to determine a local user:

    public bool IsLocalUser()
    {
        return windowsIdentity.AuthenticationType == "NTLM";
    }

Edit by Ian Boyd

You should not use NTLM anymore at all. It is so old, and so bad, that Microsoft's Application Verifier (which is used to catch common programming mistakes) will throw a warning if it detects you using NTLM.

Here's a chapter from the Application Verifier documentation about why they have a test if someone is mistakenly using NTLM:

Why the NTLM Plug-in is Needed

NTLM is an outdated authentication protocol with flaws that potentially compromise the security of applications and the operating system. The most important shortcoming is the lack of server authentication, which could allow an attacker to trick users into connecting to a spoofed server. As a corollary of missing server authentication, applications using NTLM can also be vulnerable to a type of attack known as a “reflection” attack. This latter allows an attacker to hijack a user’s authentication conversation to a legitimate server and use it to authenticate the attacker to the user’s computer. NTLM’s vulnerabilities and ways of exploiting them are the target of increasing research activity in the security community.

Although Kerberos has been available for many years many applications are still written to use NTLM only. This needlessly reduces the security of applications. Kerberos cannot however replace NTLM in all scenarios – principally those where a client needs to authenticate to systems that are not joined to a domain (a home network perhaps being the most common of these). The Negotiate security package allows a backwards-compatible compromise that uses Kerberos whenever possible and only reverts to NTLM when there is no other option. Switching code to use Negotiate instead of NTLM will significantly increase the security for our customers while introducing few or no application compatibilities. Negotiate by itself is not a silver bullet – there are cases where an attacker can force downgrade to NTLM but these are significantly more difficult to exploit. However, one immediate improvement is that applications written to use Negotiate correctly are automatically immune to NTLM reflection attacks.

By way of a final word of caution against use of NTLM: in future versions of Windows it will be possible to disable the use of NTLM at the operating system. If applications have a hard dependency on NTLM they will simply fail to authenticate when NTLM is disabled.

How the Plug-in Works

The Verifier plug detects the following errors:

  • The NTLM package is directly specified in the call to AcquireCredentialsHandle (or higher level wrapper API).

  • The target name in the call to InitializeSecurityContext is NULL.

  • The target name in the call to InitializeSecurityContext is not a properly-formed SPN, UPN or NetBIOS-style domain name.

The latter two cases will force Negotiate to fall back to NTLM either directly (the first case) or indirectly (the domain controller will return a “principal not found” error in the second case causing Negotiate to fall back).

The plug-in also logs warnings when it detects downgrades to NTLM; for example, when an SPN is not found by the Domain Controller. These are only logged as warnings since they are often legitimate cases – for example, when authenticating to a system that is not domain-joined.

NTLM Stops

5000 – Application Has Explicitly Selected NTLM Package

Severity – Error

The application or subsystem explicitly selects NTLM instead of Negotiate in the call to AcquireCredentialsHandle. Even though it may be possible for the client and server to authenticate using Kerberos this is prevented by the explicit selection of NTLM.

How to Fix this Error

The fix for this error is to select the Negotiate package in place of NTLM. How this is done will depend on the particular Network subsystem being used by the client or server. Some examples are given below. You should consult the documentation on the particular library or API set that you are using.

APIs(parameter) Used by Application    Incorrect Value  Correct Value  
=====================================  ===============  ========================
AcquireCredentialsHandle (pszPackage)  “NTLM”           NEGOSSP_NAME “Negotiate”

Stash only one file out of multiple files that have changed with Git?

If you do not want to specify a message with your stashed changes, pass the filename after a double-dash.

$ git stash -- filename.ext

If it's an untracked/new file, you will have to stage it first.

This method works in git versions 2.13+

How to make a JFrame button open another JFrame class in Netbeans?

This link works with me: video

The answer posted before didn't work for me until the second click

So what I did is Directly call:

        new NewForm().setVisible(true);

        this.dispose();//to close the current jframe

Regular expression field validation in jQuery

If you wanted to search some elements based on a regex, you can use the filter function. For example, say you wanted to make sure that in all the input boxes, the user has only entered numbers, so let's find all the inputs which don't match and highlight them.

$("input:text")
    .filter(function() {
        return this.value.match(/[^\d]/);
    })
    .addClass("inputError")
;

Of course if it was just something like this, you could use the form validation plugin, but this method could be applied to any sort of elements you like. Another example to show what I mean: Find all the elements whose id matches /[a-z]+_\d+/

$("[id]").filter(function() {
    return this.id.match(/[a-z]+_\d+/);
});

How to add one day to a date?

you want after days find date this code try..

public Date getToDateAfterDays(Integer day) {
        Date nowdate = new Date();
        Calendar cal = Calendar.getInstance();
        cal.setTime(nowdate);
        cal.add(Calendar.DATE, day);
        return cal.getTime();
    }

How to make a pure css based dropdown menu?

Tested in IE7 - 9 and Firefox: http://jsfiddle.net/WCaKg/. Markup:

<ul>
    <li>&lt;li&gt;</li>

    <li>&lt;li&gt;</li>

    <li>&lt;li&gt;

        <ul>
            <li>&lt;li&gt;</li>

            <li>&lt;li&gt;</li>

            <li>&lt;li&gt;</li>

            <li>&lt;li&gt;</li>
        </ul>
    </li>

    <li>&lt;li&gt;</li>

    <li>&lt;li&gt;</li>

    <li>&lt;li&gt;</li>
</ul>

CSS:

* {
  margin: 0;
  padding: 0;
}

body {
  font: 200%/1.5 Optima, 'Lucida Grande', Lucida, 'Lucida Sans Unicode', sans-serif;
}

ul {
  width: 9em;
  list-style-type: none;
  font-size: 0.75em;
}

li {
  float: left;
  margin: 0 4px 4px 0;
  background: #60c;
  background: rgba(102, 0, 204, 0.66);
  border: 4px solid #60c;
  color: #fff;
}
li:hover {
  position: relative;
}

ul ul {
  z-index: 1;
  position: absolute;
  left: -999em;
  width: auto;
  background: #ccc;
  background: rgba(204, 204, 204, 0.33);
}

li:hover ul {
  top: 2em;
  left: 3px;
}

li li {
  margin: 0 0 3px 0;
  background: #909;
  background: rgba(153, 0, 153, 0.66);
  border: 3px solid #909;
}

java.io.FileNotFoundException: class path resource cannot be opened because it does not exist

The file location/path has to relative to your classpath locations. If resources directory is in your classpath you just need "app-context.xml" as file location.

Warning :-Presenting view controllers on detached view controllers is discouraged

To avoid getting the warning in a push navigation, you can directly use :

[self.view.window.rootViewController presentViewController:viewController animated:YES completion:nil];

And then in your modal view controller, when everything is finished, you can just call :

[self dismissViewControllerAnimated:YES completion:nil];

Python : Trying to POST form using requests

I was having problems here (i.e. sending form-data whilst uploading a file) until I used the following:

files = {'file': (filename, open(filepath, 'rb'), 'text/xml'),
         'Content-Disposition': 'form-data; name="file"; filename="' + filename + '"',
         'Content-Type': 'text/xml'}

That's the input that ended up working for me. In Chrome Dev Tools -> Network tab, I clicked the request I was interested in. In the Headers tab, there's a Form Data section, and it showed both the Content-Disposition and the Content-Type headers being set there.

I did NOT need to set headers in the actual requests.post() command for this to succeed (including them actually caused it to fail)

Can you install and run apps built on the .NET framework on a Mac?

You can use a .Net environment Visual studio, Take a look at the differences with the PC version.

A lighter editor would be Visual Code

Alternatives :

  1. Installing the Mono Project runtime . It allows you to re-compile the code and run it on a Mac, but this requires various alterations to the codebase, as the fuller .Net Framework is not available. (Also, WPF applications aren't supported here either.)

  2. Virtual machine (VMWare Fusion perhaps)

  3. Update your codebase to .Net Core, (before choosing this option take a look at this migration process)

    • .Net Core 3.1 is an open-source, free and available on Window, MacOs and Linux

    • As of September 14, a release candidate 1 of .Net Core 5.0 has been deployed on Window, MacOs and Linux.

[1] : Release candidate (RC) : releases providing early access to complete features. These releases are supported for production use when they have a go-live license

how to make a countdown timer in java

You can create a countdown timer using applet, below is the code,

   import java.applet.*;
   import java.awt.*;
   import java.awt.event.*;
   import javax.swing.*;
   import javax.swing.Timer; // not java.util.Timer
   import java.text.NumberFormat;
   import java.net.*;



/**
    * An applet that counts down from a specified time. When it reaches 00:00,
    * it optionally plays a sound and optionally moves the browser to a new page.
    * Place the mouse over the applet to pause the count; move it off to resume.
    * This class demonstrates most applet methods and features.
    **/

public class Countdown extends JApplet implements ActionListener, MouseListener
{
long remaining; // How many milliseconds remain in the countdown.
long lastUpdate; // When count was last updated
JLabel label; // Displays the count
Timer timer; // Updates the count every second
NumberFormat format; // Format minutes:seconds with leading zeros
Image image; // Image to display along with the time
AudioClip sound; // Sound to play when we reach 00:00

// Called when the applet is first loaded
public void init() {
    // Figure out how long to count for by reading the "minutes" parameter
    // defined in a <param> tag inside the <applet> tag. Convert to ms.
    String minutes = getParameter("minutes");
    if (minutes != null) remaining = Integer.parseInt(minutes) * 60000;
    else remaining = 600000; // 10 minutes by default

    // Create a JLabel to display remaining time, and set some properties.
    label = new JLabel();
    label.setHorizontalAlignment(SwingConstants.CENTER );
    label.setOpaque(true); // So label draws the background color

    // Read some parameters for this JLabel object
    String font = getParameter("font");
    String foreground = getParameter("foreground");
    String background = getParameter("background");
    String imageURL = getParameter("image");

    // Set label properties based on those parameters
    if (font != null) label.setFont(Font.decode(font));
    if (foreground != null) label.setForeground(Color.decode(foreground));
    if (background != null) label.setBackground(Color.decode(background));
    if (imageURL != null) {
        // Load the image, and save it so we can release it later
        image = getImage(getDocumentBase(), imageURL);
        // Now display the image in the JLabel.
        label.setIcon(new ImageIcon(image));
    }

    // Now add the label to the applet. Like JFrame and JDialog, JApplet
    // has a content pane that you add children to
    getContentPane().add(label, BorderLayout.CENTER);

    // Get an optional AudioClip to play when the count expires
    String soundURL = getParameter("sound");
    if (soundURL != null) sound=getAudioClip(getDocumentBase(), soundURL);

    // Obtain a NumberFormat object to convert number of minutes and
    // seconds to strings. Set it up to produce a leading 0 if necessary
    format = NumberFormat.getNumberInstance();
    format.setMinimumIntegerDigits(2); // pad with 0 if necessary

    // Specify a MouseListener to handle mouse events in the applet.
    // Note that the applet implements this interface itself
    addMouseListener(this);

    // Create a timer to call the actionPerformed() method immediately,
    // and then every 1000 milliseconds. Note we don't start the timer yet.
    timer = new Timer(1000, this);
    timer.setInitialDelay(0); // First timer is immediate.
}

// Free up any resources we hold; called when the applet is done
public void destroy() { if (image != null) image.flush(); }

// The browser calls this to start the applet running
// The resume() method is defined below.
public void start() { resume(); } // Start displaying updates

// The browser calls this to stop the applet. It may be restarted later.
// The pause() method is defined below
public void stop() { pause(); } // Stop displaying updates

// Return information about the applet
public String getAppletInfo() {
    return "Countdown applet Copyright (c) 2003 by David Flanagan";
}

// Return information about the applet parameters
public String[][] getParameterInfo() { return parameterInfo; }

// This is the parameter information. One array of strings for each
// parameter. The elements are parameter name, type, and description.
static String[][] parameterInfo = {
    {"minutes", "number", "time, in minutes, to countdown from"},
    {"font", "font", "optional font for the time display"},
    {"foreground", "color", "optional foreground color for the time"},
    {"background", "color", "optional background color"},
    {"image", "image URL", "optional image to display next to countdown"},
    {"sound", "sound URL", "optional sound to play when we reach 00:00"},
    {"newpage", "document URL", "URL to load when timer expires"},
};

// Start or resume the countdown
void resume() {
    // Restore the time we're counting down from and restart the timer.
    lastUpdate = System.currentTimeMillis();
    timer.start(); // Start the timer
}

// Pause the countdown
void pause() {
    // Subtract elapsed time from the remaining time and stop timing
    long now = System.currentTimeMillis();
    remaining -= (now - lastUpdate);
    timer.stop(); // Stop the timer
}

// Update the displayed time. This method is called from actionPerformed()
// which is itself invoked by the timer.
void updateDisplay() {
    long now = System.currentTimeMillis(); // current time in ms
    long elapsed = now - lastUpdate; // ms elapsed since last update
    remaining -= elapsed; // adjust remaining time
    lastUpdate = now; // remember this update time

    // Convert remaining milliseconds to mm:ss format and display
    if (remaining < 0) remaining = 0;
    int minutes = (int)(remaining/60000);
    int seconds = (int)((remaining)/1000);
    label.setText(format.format(minutes) + ":" + format.format(seconds));

    // If we've completed the countdown beep and display new page
    if (remaining == 0) {
        // Stop updating now.
        timer.stop();
        // If we have an alarm sound clip, play it now.
        if (sound != null) sound.play();
        // If there is a newpage URL specified, make the browser
        // load that page now.
        String newpage = getParameter("newpage");
        if (newpage != null) {
            try {
                URL url = new URL(getDocumentBase(), newpage);
                getAppletContext().showDocument(url);
            }
            catch(MalformedURLException ex) {      showStatus(ex.toString()); }
        }
    }
}

// This method implements the ActionListener interface.
// It is invoked once a second by the Timer object
// and updates the JLabel to display minutes and seconds remaining.
public void actionPerformed(ActionEvent e) { updateDisplay(); }

// The methods below implement the MouseListener interface. We use
// two of them to pause the countdown when the mouse hovers over the timer.
// Note that we also display a message in the statusline
public void mouseEntered(MouseEvent e) {
    pause(); // pause countdown
    showStatus("Paused"); // display statusline message
}
public void mouseExited(MouseEvent e) {
    resume(); // resume countdown
    showStatus(""); // clear statusline
}
// These MouseListener methods are unused.
public void mouseClicked(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
} 

Is it possible to decompile a compiled .pyc file into a .py file?

Yes, it is possible.

There is a perfect open-source Python (.PYC) decompiler, called Decompyle++ https://github.com/zrax/pycdc/

Decompyle++ aims to translate compiled Python byte-code back into valid and human-readable Python source code. While other projects have achieved this with varied success, Decompyle++ is unique in that it seeks to support byte-code from any version of Python.

Get single listView SelectedItem

None of the answers above, at least to me, show how to actually handle determining whether you have 1 item or multiple, and how to actually get the values out of your items in a generic way that doesn't depend on there actually only being one item, or multiple, so I'm throwing my hat in the ring.

This is quite easily and generically done by checking your count to see that you have at least one item, then doing a foreach loop on the .SelectedItems, casting each item as a DataRowView:

if (listView1.SelectedItems.Count > 0)
{
     foreach (DataRowView drv in listView1.SelectedItems)
     {
         string firstColumn = drv.Row[0] != null ? drv.Row[0].ToString() : String.Empty;
         string secondColumn = drv.Row[1] != null ? drv.Row[1].ToString() : String.Empty;
         // ... do something with these values before they are replaced
         // by the next run of the loop that will get the next row
     }
}

This will work, whether you have 1 item or many. It's funny that MSDN says to use ListView.SelectedListViewItemCollection to capture listView1.SelectedItems and iterate through that, but I found that this gave an error in my WPF app: The type name 'SelectedListViewItemCollection' does not exist in type 'ListView'.

How can I install a local gem?

Yup, when you do gem install, it will search the current directory first, so if your .gem file is there, it will pick it up. I found it on the gem reference, which you may find handy as well:

gem install will install the named gem. It will attempt a local installation (i.e. a .gem file in the current directory), and if that fails, it will attempt to download and install the most recent version of the gem you want.

isolating a sub-string in a string before a symbol in SQL Server 2008

This can achieve using two SQL functions- SUBSTRING and CHARINDEX

You can read strings to a variable as shown in the above answers, or can add it to a SELECT statement as below:

SELECT SUBSTRING('Net Operating Loss - 2007' ,0, CHARINDEX('-','Net Operating Loss - 2007'))

How to compare two floating point numbers in Bash?

Of course, if you don't need really floating-point arithmetic, just arithmetic on e.g. dollar values where there are always exactly two decimal digits, you might just drop the dot (effectively multiplying by 100) and compare the resulting integers.

if [[ $((10#${num1/.})) < $((10#${num2/.})) ]]; then
    ...

This obviously requires you to be sure that both values have the same number of decimal places.

How do I return JSON without using a template in Django?

from django.utils import simplejson 
from django.core import serializers 

def pagina_json(request): 
   misdatos = misdatos.objects.all()
   data = serializers.serialize('json', misdatos) 
   return HttpResponse(data, mimetype='application/json')

How to get a resource id with a known resource name?

// image from res/drawable
    int resID = getResources().getIdentifier("my_image", 
            "drawable", getPackageName());
// view
    int resID = getResources().getIdentifier("my_resource", 
            "id", getPackageName());

// string
    int resID = getResources().getIdentifier("my_string", 
            "string", getPackageName());

What's a good way to extend Error in JavaScript?

For the sake of completeness -- just because none of the previous answers mentioned this method -- if you are working with Node.js and don't have to care about browser compatibility, the desired effect is pretty easy to achieve with the built in inherits of the util module (official docs here).

For example, let's suppose you want to create a custom error class that takes an error code as the first argument and the error message as the second argument:

file custom-error.js:

'use strict';

var util = require('util');

function CustomError(code, message) {
  Error.captureStackTrace(this, CustomError);
  this.name = CustomError.name;
  this.code = code;
  this.message = message;
}

util.inherits(CustomError, Error);

module.exports = CustomError;

Now you can instantiate and pass/throw your CustomError:

var CustomError = require('./path/to/custom-error');

// pass as the first argument to your callback
callback(new CustomError(404, 'Not found!'));

// or, if you are working with try/catch, throw it
throw new CustomError(500, 'Server Error!');

Note that, with this snippet, the stack trace will have the correct file name and line, and the error instance will have the correct name!

This happens due to the usage of the captureStackTrace method, which creates a stack property on the target object (in this case, the CustomError being instantiated). For more details about how it works, check the documentation here.

How can I convince IE to simply display application/json rather than offer to download it?

If you are okay with just having IE open the JSON into a notepad, you can change your system's default program for .json files to Notepad.

To do this, create or find a .json file, right mouse click, and select "Open With" or "Choose Default Program."

This might come in handy if you by chance want to use Internet Explorer but your IT company wont let you edit your registry. Otherwise, I recommend the above answers.

jquery - Check for file extension before uploading

The following code allows to upload gif, png, jpg, jpeg and bmp files.

var extension = $('#your_file_id').val().split('.').pop().toLowerCase();

if($.inArray(extension, ['gif','png','jpg','jpeg','bmp']) == -1) {
    alert('Sorry, invalid extension.');
    return false;
}

How to verify an XPath expression in Chrome Developers tool or Firefox's Firebug?

By using Chrome or Opera

without any plugins, without writing any single XPath syntax character

  1. right click the required element, then "inspect"
  2. right click on highlighted element tag, choose Copy ? Copy XPath.

;)

Enter image description here

What is the difference between Builder Design pattern and Factory Design pattern?

+-------------------------------------------------------------------+---------------------------------------------------+
|                              Builder                              |                      Factory                      |
+-------------------------------------------------------------------+---------------------------------------------------+
| Return only single instance to handle complex object construction | Retrun various instances on multiple constructors |
| No interface required                                             | Interface driven                                  |
| Inner classes is involved (to avoid telescopic constructors)      | Subclasses are involved                           |
+-------------------------------------------------------------------+---------------------------------------------------+  

Telescoping Constructor Pattern

Analogy:

  • Factory: Consider a restaurant. The creation of "today's meal" is a factory pattern, because you tell the kitchen "get me today's meal" and the kitchen (factory) decides what object to generate, based on hidden criteria.
  • Builder: The builder appears if you order a custom pizza. In this case, the waiter tells the chef (builder) "I need a pizza; add cheese, onions and bacon to it!" Thus, the builder exposes the attributes the generated object should have, but hides how to set them.

Courtesy

OpenCV TypeError: Expected cv::UMat for argument 'src' - What is this?

The following can be used from numpy:

import numpy as np 
image = np.array(image)

Creating a folder if it does not exists - "Item already exists"

Alternative syntax using the -Not operator and depending on your preference for readability:

if( -Not (Test-Path -Path $TARGETDIR ) )
{
    New-Item -ItemType directory -Path $TARGETDIR
}

Classpath including JAR within a JAR

After some research I have found method that doesn't require maven or any 3rd party extension/program.

You can use "Class-Path" in your manifest file.

For example:

Create manifest file MANIFEST.MF

Manifest-Version: 1.0
Created-By: Bundle
Class-Path: ./custom_lib.jar
Main-Class: YourMainClass

Compile all your classes and run jar cfm Testing.jar MANIFEST.MF *.class custom_lib.jar

c stands for create archive f indicates that you want to specify file v is for verbose input m means that we will pass custom manifest file

Be sure that you included lib in jar package. You should be able to run jar in the normal way.

based on: http://www.ibm.com/developerworks/library/j-5things6/

all other information you need about the class-path do you find here

How to update Ruby with Homebrew?

To upgrade Ruby with rbenv: Per the rbenv README

  • Update first: brew upgrade rbenv ruby-build
  • See list of Ruby versions: versions available: rbenv install -l
  • Install: rbenv install <selected version>

How to include !important in jquery

I solved this problem with:

inputObj.css('cssText', inputObj.attr('style')+'padding-left: ' + (width + 5) + 'px !IMPORTANT;');

So no inline-Style is lost, an the last overrides the first

C++ templates that accept only certain types

I suggest using Boost's static assert feature in concert with is_base_of from the Boost Type Traits library:

template<typename T>
class ObservableList {
    BOOST_STATIC_ASSERT((is_base_of<List, T>::value)); //Yes, the double parentheses are needed, otherwise the comma will be seen as macro argument separator
    ...
};

In some other, simpler cases, you can simply forward-declare a global template, but only define (explicitly or partially specialise) it for the valid types:

template<typename T> class my_template;     // Declare, but don't define

// int is a valid type
template<> class my_template<int> {
    ...
};

// All pointer types are valid
template<typename T> class my_template<T*> {
    ...
};

// All other types are invalid, and will cause linker error messages.

[Minor EDIT 6/12/2013: Using a declared-but-not-defined template will result in linker, not compiler, error messages.]

Video format or MIME type is not supported

In my case, this error:

Video format or MIME type is not supported.

Was due to the CSP in my .htaccess that did not allow the content to be loaded. You can check this by opening the browser's console and refreshing the page.

Once I added the domain that was hosting the video in the media-src part of that CSP, the console was clean and the video was loaded properly. Example:

Content-Security-Policy: default-src 'none'; media-src https://myvideohost.domain; script-src 'self'; style-src 'unsafe-inline' 'self'

How do you do block comments in YAML?

Not trying to be smart about it, but if you use Sublime Text for your editor, the steps are:

  1. Select the block
  2. cmd+/ on Mac or ctrl+/ on Linux & Windows
  3. Profit

I'd imagine that other editors have similar functionality too. Which one are you using? I'd be happy to do some digging.

SQL Server 2008: how do I grant privileges to a username?

Like the following. It will make the user database owner.

EXEC sp_addrolemember N'db_owner', N'USerNAme'

Setting the filter to an OpenFileDialog to allow the typical image formats?

Just a necrocomment for using string.Join and LINQ.

ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
dlgOpenMockImage.Filter = string.Format("{0}| All image files ({1})|{1}|All files|*", 
    string.Join("|", codecs.Select(codec => 
    string.Format("{0} ({1})|{1}", codec.CodecName, codec.FilenameExtension)).ToArray()),
    string.Join(";", codecs.Select(codec => codec.FilenameExtension).ToArray()));

How to get the values of a ConfigurationSection of type NameValueSectionHandler

Here are some examples from this blog mentioned earlier:

<configuration>    
   <Database>    
      <add key="ConnectionString" value="data source=.;initial catalog=NorthWind;integrated security=SSPI"/>    
   </Database>    
</configuration>  

get values:

 NameValueCollection db = (NameValueCollection)ConfigurationSettings.GetConfig("Database");         
    labelConnection2.Text = db["ConnectionString"];

-

Another example:

<Locations 
   ImportDirectory="C:\Import\Inbox"
   ProcessedDirectory ="C:\Import\Processed"
   RejectedDirectory ="C:\Import\Rejected"
/>

get value:

Hashtable loc = (Hashtable)ConfigurationSettings.GetConfig("Locations"); 

labelImport2.Text = loc["ImportDirectory"].ToString();
labelProcessed2.Text = loc["ProcessedDirectory"].ToString();

Foreach loop in C++ equivalent of C#

string[] strarr = {"ram","mohan","sita"};

#include <string>
std::string strarr = { "ram", "mohan", "sita" };

or

const char* strarr[] = { "ram", "mohan", "sita" };

foreach(string str in strarr) { listbox.items.add(str); }

for (int i = 0; i < sizeof strarr / sizeof *strarr; ++i)
    listbox.items.add(strarr[i]);

Note: you can also put the strings into a std::vector rather than an array:

std::vector<std::string> strvec;
strvec.push_back("ram");
strvec.push_back("mohan");
strvec.push_back("sita");

for (std::vector<std::string>::const_iterator i = strvec.begin(); i != strvec.end(); ++i)
    listbox.items.add(*i);

Most pythonic way to delete a file which may not exist

This is another solution:

if os.path.isfile(os.path.join(path, filename)):
    os.remove(os.path.join(path, filename))

Strange "java.lang.NoClassDefFoundError" in Eclipse

Doing Project->Clean… in Eclipse solved this problem for me.

Cast object to interface in TypeScript

Here's another way to force a type-cast even between incompatible types and interfaces where TS compiler normally complains:

export function forceCast<T>(input: any): T {

  // ... do runtime checks here

  // @ts-ignore <-- forces TS compiler to compile this as-is
  return input;
}

Then you can use it to force cast objects to a certain type:

import { forceCast } from './forceCast';

const randomObject: any = {};
const typedObject = forceCast<IToDoDto>(randomObject);

Note that I left out the part you are supposed to do runtime checks before casting for the sake of reducing complexity. What I do in my project is compiling all my .d.ts interface files into JSON schemas and using ajv to validate in runtime.

Can't install any package with node npm

If anyone is specifically getting Unexpected token <, and your package.json is fine, check your npm-shrinkwrap.json file! I had unresolved merge issues in mine, and fixing that resolved everything.

How to determine whether a substring is in a different string

with in: substring in string:

>>> substring = "please help me out"
>>> string = "please help me out so that I could solve this"
>>> substring in string
True

How do I get the width and height of a HTML5 canvas?

It might be worth looking at a tutorial: MDN Canvas Tutorial

You can get the width and height of a canvas element simply by accessing those properties of the element. For example:

var canvas = document.getElementById('mycanvas');
var width = canvas.width;
var height = canvas.height;

If the width and height attributes are not present in the canvas element, the default 300x150 size will be returned. To dynamically get the correct width and height use the following code:

const canvasW = canvas.getBoundingClientRect().width;
const canvasH = canvas.getBoundingClientRect().height;

Or using the shorter object destructuring syntax:

const { width, height } = canvas.getBoundingClientRect();

The context is an object you get from the canvas to allow you to draw into it. You can think of the context as the API to the canvas, that provides you with the commands that enable you to draw on the canvas element.

How to move div vertically down using CSS

I don't see any mention of flexbox in here, so I will illustrate:

HTML

 <div class="wrapper">
   <div class="main">top</div>
   <div class="footer">bottom</div>
 </div>

CSS

 .wrapper {
   display: flex;
   flex-direction: column;
   min-height: 100vh;
  }
 .main {
   flex: 1;
 }
 .footer {
  flex: 0;
 }

How can I get list of values from dict?

There should be one - and preferably only one - obvious way to do it.

Therefore list(dictionary.values()) is the one way.

Yet, considering Python3, what is quicker?

[*L] vs. [].extend(L) vs. list(L)

small_ds = {x: str(x+42) for x in range(10)}
small_df = {x: float(x+42) for x in range(10)}

print('Small Dict(str)')
%timeit [*small_ds.values()]
%timeit [].extend(small_ds.values())
%timeit list(small_ds.values())

print('Small Dict(float)')
%timeit [*small_df.values()]
%timeit [].extend(small_df.values())
%timeit list(small_df.values())

big_ds = {x: str(x+42) for x in range(1000000)}
big_df = {x: float(x+42) for x in range(1000000)}

print('Big Dict(str)')
%timeit [*big_ds.values()]
%timeit [].extend(big_ds.values())
%timeit list(big_ds.values())

print('Big Dict(float)')
%timeit [*big_df.values()]
%timeit [].extend(big_df.values())
%timeit list(big_df.values())
Small Dict(str)
256 ns ± 3.37 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
338 ns ± 0.807 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
336 ns ± 1.9 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

Small Dict(float)
268 ns ± 0.297 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
343 ns ± 15.2 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
336 ns ± 0.68 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

Big Dict(str)
17.5 ms ± 142 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
16.5 ms ± 338 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
16.2 ms ± 19.7 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

Big Dict(float)
13.2 ms ± 41 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
13.1 ms ± 919 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
12.8 ms ± 578 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

Done on Intel(R) Core(TM) i7-8650U CPU @ 1.90GHz.

# Name                    Version                   Build
ipython                   7.5.0            py37h24bf2e0_0

The result

  1. For small dictionaries * operator is quicker
  2. For big dictionaries where it matters list() is maybe slightly quicker

Insert an item into sorted list in Python

Hint 1: You might want to study the Python code in the bisect module.

Hint 2: Slicing can be used for list insertion:

>>> s = ['a', 'b', 'd', 'e']
>>> s[2:2] = ['c']
>>> s
['a', 'b', 'c', 'd', 'e']

How to find integer array size in java

The length of an array is available as

int l = array.length;

The size of a List is availabe as

int s = list.size();

How are Anonymous inner classes used in Java?

Yes, anonymous inner classes is definitely one of the advantages of Java.

With an anonymous inner class you have access to final and member variables of the surrounding class, and that comes in handy in listeners etc.

But a major advantage is that the inner class code, which is (at least should be) tightly coupled to the surrounding class/method/block, has a specific context (the surrounding class, method, and block).

Changing background color of selected cell?

SWIFT 4, XCODE 9, IOS 11

After some testing this WILL remove the background color when deselected or cell is tapped a second time when table view Selection is set to "Multiple Selection". Also works when table view Style is set to "Grouped".

extension ViewController: UITableViewDelegate {
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if let cell = tableView.cellForRow(at: indexPath) {
            cell.contentView.backgroundColor = UIColor.darkGray
        }
    }
}

Note: In order for this to work as you see below, your cell's Selection property can be set to anything BUT None.

How it looks with different options

Style: Plain, Selection: Single Selection

Single Selection

Style: Plain, Selection: Multiple Selection

Multiple Selection

Style: Grouped, Selection: Multiple Selection

Grouped Multiple Selection

Bonus - Animation

For a smoother color transition, try some animation:

extension ViewController: UITableViewDelegate {
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if let cell = tableView.cellForRow(at: indexPath) {
            UIView.animate(withDuration: 0.3, animations: {
                cell.contentView.backgroundColor = UIColor.darkGray
            })
        }
    }
}

Animated color transition

Bonus - Text and Image Changing

You may notice the icon and text color also changing when cell is selected. This happens automatically when you set the UIImage and UILabel Highlighted properties

UIImage

  1. Supply two colored images:

Two colored images

  1. Set the Highlighted image property:

Highlighted property

UILabel

Just supply a color for the Highlighted property:

Highlighted Color

check if a number already exist in a list in python

You could probably use a set object instead. Just add numbers to the set. They inherently do not replicate.

Finding blocking/locking queries in MS SQL (mssql)

I found this query which helped me find my locked table and query causing the issue.

SELECT  L.request_session_id AS SPID, 
        DB_NAME(L.resource_database_id) AS DatabaseName,
        O.Name AS LockedObjectName, 
        P.object_id AS LockedObjectId, 
        L.resource_type AS LockedResource, 
        L.request_mode AS LockType,
        ST.text AS SqlStatementText,        
        ES.login_name AS LoginName,
        ES.host_name AS HostName,
        TST.is_user_transaction as IsUserTransaction,
        AT.name as TransactionName,
        CN.auth_scheme as AuthenticationMethod
FROM    sys.dm_tran_locks L
        JOIN sys.partitions P ON P.hobt_id = L.resource_associated_entity_id
        JOIN sys.objects O ON O.object_id = P.object_id
        JOIN sys.dm_exec_sessions ES ON ES.session_id = L.request_session_id
        JOIN sys.dm_tran_session_transactions TST ON ES.session_id = TST.session_id
        JOIN sys.dm_tran_active_transactions AT ON TST.transaction_id = AT.transaction_id
        JOIN sys.dm_exec_connections CN ON CN.session_id = ES.session_id
        CROSS APPLY sys.dm_exec_sql_text(CN.most_recent_sql_handle) AS ST
WHERE   resource_database_id = db_id()
ORDER BY L.request_session_id

How to convert integer into date object python?

This question is already answered, but for the benefit of others looking at this question I'd like to add the following suggestion: Instead of doing the slicing yourself as suggested above you might also use strptime() which is (IMHO) easier to read and perhaps the preferred way to do this conversion.

import datetime
s = "20120213"
s_datetime = datetime.datetime.strptime(s, '%Y%m%d')

How to upload image in CodeIgniter?

Below code for an uploading a single file at a time. This is correct and perfect to upload a single file. Read all commented instructions and follow the code. Definitely, it is worked.

public function upload_file() {
    ***// Upload folder location***
    $config['upload_path'] = './public/upload/';

    ***// Allowed file type***
    $config['allowed_types'] = 'jpg|jpeg|png|pdf';

    ***// Max size, i will set 2MB***
    $config['max_size'] = '2024';

    $config['max_width'] = '1024';
    $config['max_height'] = '768';

    ***// load upload library***            
    $this->load->library('upload', $config);

    ***// do_upload is the method, to send the particular image and file on that 
       // particular 
       // location that is detail in $config['upload_path']. 
       // In bracks will set name upload, here you need to set input name attribute 
       // value.***

    if($this->upload->do_upload('upload')) {
       $data = $this->upload->data();
       $post['upload'] = $data['file_name'];
    } else {
      $error = array('error' => $this->upload->display_errors());
    }
 }

In Java, how can I determine if a char array contains a particular character?

From NumberKeyListener source code. This method they use to check if char is contained in defined array of accepted characters:

protected static boolean ok(char[] accept, char c) {
    for (int i = accept.length - 1; i >= 0; i--) {
        if (accept[i] == c) {
            return true;
        }
    }

    return false;
}

It is similar to @ÓscarLópez solution. Might be a bit faster cause of absence of foreach iterator.

How to check string length with JavaScript

The quick and dirty way would be to simple bind to the keyup event.

_x000D_
_x000D_
$('#mytxt').keyup(function(){_x000D_
    $('#divlen').text('you typed ' + this.value.length + ' characters');_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<input type=text id=mytxt >_x000D_
<div id=divlen></div>
_x000D_
_x000D_
_x000D_

But better would be to bind a reusable function to several events. For example also to the change(), so you can also anticipate text changes such as pastes (with the context menu, shortcuts would also be caught by the keyup )

How to restore to a different database in sql server?

You can create a new db then use the "Restore Wizard" enabling the Overwrite option or;

View the content;

RESTORE FILELISTONLY FROM DISK='c:\your.bak'

note the logical names of the .mdf & .ldf from the results, then;

RESTORE DATABASE MyTempCopy FROM DISK='c:\your.bak'
WITH 
   MOVE 'LogicalNameForTheMDF' TO 'c:\MyTempCopy.mdf',
   MOVE 'LogicalNameForTheLDF' TO 'c:\MyTempCopy_log.ldf'

To create the database MyTempCopy with the contents of your.bak.

Example (restores a backup of a db called 'creditline' to 'MyTempCopy';

RESTORE FILELISTONLY FROM DISK='e:\mssql\backup\creditline.bak'

>LogicalName
>--------------
>CreditLine
>CreditLine_log

RESTORE DATABASE MyTempCopy FROM DISK='e:\mssql\backup\creditline.bak'
WITH 
   MOVE 'CreditLine' TO 'e:\mssql\MyTempCopy.mdf',
   MOVE 'CreditLine_log' TO 'e:\mssql\MyTempCopy_log.ldf'

>RESTORE DATABASE successfully processed 186 pages in 0.010 seconds (144.970 MB/sec).

Find first element by predicate

Already answered by @AjaxLeung, but in comments and hard to find.
For check only

lst.stream()
    .filter(x -> x > 5)
    .findFirst()
    .isPresent()

is simplified to

lst.stream()
    .anyMatch(x -> x > 5)

Error retrieving parent for item: No resource found that matches the given name 'android:TextAppearance.Material.Widget.Button.Borderless.Colored'

Solution for me (Android Studio) :

1) Use shortcut Ctrl+Shift+Alt+S or File -> Project Structure

2) and increase the level of SDK "Compile SDK Version".

How to increase timeout for a single test case in mocha

(since I ran into this today)

Be careful when using ES2015 fat arrow syntax:

This will fail :

it('accesses the network', done => {

  this.timeout(500); // will not work

  // *this* binding refers to parent function scope in fat arrow functions!
  // i.e. the *this* object of the describe function

  done();
});

EDIT: Why it fails:

As @atoth mentions in the comments, fat arrow functions do not have their own this binding. Therefore, it's not possible for the it function to bind to this of the callback and provide a timeout function.

Bottom line: Don't use arrow functions for functions that need an increased timeout.

The type or namespace name 'Entity' does not exist in the namespace 'System.Data'

I found the root cause is when you install the nuget packages through the UI the scripts won't run sometimes. So I'd recommend open Output view while you do that. If you don't see the license agreement window when installing Nuget, there is a better change your IDE isn't doing the job right. So that's why a restart, cleanup and rebuild helps!

PS: That adding anything under System.Data.Entity.* helps because, that triggers the Nuget installer to work properly. But this I found a quite unreliable way.

So just watch the output window, you MUST see something like a successful nuget installation message at the end. Most the time when there an issue, Nuget installer won't even kick off. That's when your restart of IDE is going to help.

When things go well, Nuget package manager and IDE (I used Installer term above) would do the change, compile the solution and keep you happy! But when its not give a little help by restarting IDE and watching that Output window!

How do I set the figure title and axes labels font size in Matplotlib?

7 (best solution)

 from numpy import*
 import matplotlib.pyplot as plt
 X = linspace(-pi, pi, 1000)

class Crtaj:

    def nacrtaj(self,x,y):
         self.x=x
         self.y=y
         return plt.plot (x,y,"om")

def oznaci(self):
    return plt.xlabel("x-os"), plt.ylabel("y-os"), plt.grid(b=True)

6 (slightly worse solution)

from numpy import*
M = array([[3,2,3],[1,2,6]])
class AriSred(object):
    def __init__(self,m):
    self.m=m
    
def srednja(self):
    redovi = len(M)
    stupci = len (M[0])
    lista=[]
    a=0
    suma=0
    while a<stupci:
        for i in range (0,redovi):
            suma=suma+ M[i,a]
        lista.append(suma)
        a=a+1
        suma=0
    b=array(lista) 
    b=b/redovi
    return b



OBJ = AriSred(M)
sr = OBJ.srednja()