Programs & Examples On #Didfailwitherror

How to make an HTTP request + basic auth in Swift

swift 4:

let username = "username"
let password = "password"
let loginString = "\(username):\(password)"

guard let loginData = loginString.data(using: String.Encoding.utf8) else {
    return
}
let base64LoginString = loginData.base64EncodedString()

request.httpMethod = "GET"
request.setValue("Basic \(base64LoginString)", forHTTPHeaderField: "Authorization")

Sending an HTTP POST request on iOS

The following code describes a simple example using POST method.(How one can pass data by POST method)

Here, I describe how one can use of POST method.

1. Set post string with actual username and password.

NSString *post = [NSString stringWithFormat:@"Username=%@&Password=%@",@"username",@"password"]; 

2. Encode the post string using NSASCIIStringEncoding and also the post string you need to send in NSData format.

NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]; 

You need to send the actual length of your data. Calculate the length of the post string.

NSString *postLength = [NSString stringWithFormat:@"%d",[postData length]]; 

3. Create a Urlrequest with all the properties like HTTP method, http header field with length of the post string. Create URLRequest object and initialize it.

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; 

Set the Url for which your going to send the data to that request.

[request setURL:[NSURL URLWithString:@"http://www.abcde.com/xyz/login.aspx"]]; 

Now, set HTTP method (POST or GET). Write this lines as it is in your code.

[request setHTTPMethod:@"POST"]; 

Set HTTP header field with length of the post data.

[request setValue:postLength forHTTPHeaderField:@"Content-Length"]; 

Also set the Encoded value for HTTP header Field.

[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];

Set the HTTPBody of the urlrequest with postData.

[request setHTTPBody:postData];

4. Now, create URLConnection object. Initialize it with the URLRequest.

NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self]; 

It returns the initialized url connection and begins to load the data for the url request. You can check that whether you URL connection is done properly or not using just if/else statement as below.

if(conn) {
    NSLog(@"Connection Successful");
} else {
    NSLog(@"Connection could not be made");
}

5. To receive the data from the HTTP request , you can use the delegate methods provided by the URLConnection Class Reference. Delegate methods are as below.

// This method is used to receive the data which we get using post method.
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data

// This method receives the error report in case of connection is not made to server. 
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error 

// This method is used to process the data after connection has made successfully.
- (void)connectionDidFinishLoading:(NSURLConnection *)connection

Also Refer This and This documentation for POST method.

And here is best example with source code of HTTPPost Method.

How to send json data in the Http request using NSURLRequest

You can try this code for send json string

NSData *jsonData = [NSJSONSerialization dataWithJSONObject:ARRAY_CONTAIN_JSON_STRING options:NSJSONWritin*emphasized text*gPrettyPrinted error:NULL];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSString *WS_test = [NSString stringWithFormat:@"www.test.com?xyz.php&param=%@",jsonString];

ADB server version (36) doesn't match this client (39) {Not using Genymotion}

You have two versions of ADB

$ /usr/local/bin/adb version
Android Debug Bridge version 1.0.36
Revision 0e9850346394-android

and

$ /Users/user/Library/Android/sdk/platform-tools/adb version
Android Debug Bridge version 1.0.39
Revision 3db08f2c6889-android

You could see which one your PATH is pointing to (echo $PATH) but I fixed it with a adb stop-server on one version and a adb start-server on the other.

How to fix Python indentation

I would reach for autopep8 to do this:

$ # see what changes it would make
$ autopep8 path/to/file.py --select=E101,E121 --diff

$ # make these changes
$ autopep8 path/to/file.py --select=E101,E121 --in-place

Note: E101 and E121 are pep8 indentation (I think you can simply pass --select=E1 to fix all indentation related issues - those starting with E1).

You can apply this to your entire project using recursive flag:

$ autopep8 package_dir --recursive --select=E101,E121 --in-place

See also Tool to convert Python code to be PEP8 compliant.

Display text on MouseOver for image in html

You can use CSS hover
Link to jsfiddle here: http://jsfiddle.net/ANKwQ/5/

HTML:

<a><img src='https://encrypted-tbn2.google.com/images?q=tbn:ANd9GcQB3a3aouZcIPEF0di4r9uK4c0r9FlFnCasg_P8ISk8tZytippZRQ'></a>
<div>text</div>
?

CSS:

div {
    display: none;
    border:1px solid #000;
    height:30px;
    width:290px;
    margin-left:10px;
}

a:hover + div {
    display: block;
}?

Determine Pixel Length of String in Javascript/jQuery?

If you use Snap.svg, the following works:

var tPaper = Snap(300, 300);
var tLabelText = tPaper.text(100, 100, "label text");
var tWidth = tLabelText.getBBox().width;  // the width of the text in pixels.
tLabelText.attr({ x : 150 - (tWidth/2)});   // now it's centered in x

How to split a string by spaces in a Windows batch file?

If someone need to split a string with any delimiter and store values in separate variables, here is the script I built,

FOR /F "tokens=1,2 delims=x" %i in ("1920x1080") do (
  set w=%i
  set h=%j
)
echo %w%
echo %h%

Explanation: 'tokens' defines what elements you need to pass to the body of FOR, with token delimited by character 'x'. So after delimiting, the first and second token are passed to the body. In the body %i refers to first token and %j refers to second token. We can take %k to refer to 3rd token and so on..

Please also type HELP FOR in cmd to get a detailed explanation.

How do I change the background color of the ActionBar of an ActionBarActivity using XML?

Behavior of Actionbar can also be changed in APIs < 11

See the Android Official Documentation for reference

I am building an app with minSdkVersion = "9" and targetSdkVersion = "21" I changed the color of action bar and it works fine with API level 9

Here is an xml

res/values/themes.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- the theme applied to the application or activity -->
    <style name="CustomActionBarTheme"
           parent="@style/Theme.AppCompat.Light.DarkActionBar">
        <item name="android:actionBarStyle">@style/MyActionBar</item>

        <!-- Support library compatibility -->
        <item name="actionBarStyle">@style/MyActionBar</item>
    </style>

    <!-- ActionBar styles -->
    <style name="MyActionBar"
           parent="@style/Widget.AppCompat.Light.ActionBar.Solid.Inverse">
        <item name="android:background">@color/actionbar_background</item>

        <!-- Support library compatibility -->
        <item name="background">@color/actionbar_background</item>
    </style>
</resources>

and set the color of actionbar you want

res/values/colors.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="actionbar_background">#fff</color> //write the color you want here
</resources>

Actionbar color can also be defined in .class file, the snippet is

ActionBar bar = getActionBar();
bar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#0000ff")));

but this will not work with the API < 11, so styling the actionbar in xml is only way for API < 11

C/C++ line number

C++20 offers a new way to achieve this by using std::source_location. This is currently accessible in gcc an clang as std::experimental::source_location with #include <experimental/source_location>.

The problem with macros like __LINE__ is that if you want to create for example a logging function that outputs the current line number along with a message, you always have to pass __LINE__ as a function argument, because it is expanded at the call site. Something like this:

void log(const std::string msg) {
    std::cout << __LINE__ << " " << msg << std::endl;
}

Will always output the line of the function declaration and not the line where log was actually called from. On the other hand, with std::source_location you can write something like this:

#include <experimental/source_location>
using std::experimental::source_location;

void log(const std::string msg, const source_location loc = source_location::current())
{
    std::cout << loc.line() << " " << msg << std::endl;
}

Here, loc is initialized with the line number pointing to the location where log was called. You can try it online here.

get enum name from enum value

This is my take on it:

public enum LoginState { 
    LOGGED_IN(1), LOGGED_OUT(0), IN_TRANSACTION(-1);

    private int code;

    LoginState(int code) {
        this.code = code;
    }

    public int getCode() {
        return code;
    }

    public static LoginState getLoginStateFromCode(int code){
        for(LoginState e : LoginState.values()){
            if(code == e.code) return e;
        }
        return LoginState.LOGGED_OUT; //or null
    }
};

And I have used it with System Preferences in Android like so:

LoginState getLoginState(int i) {
    return LoginState.getLoginStateFromCode(
                prefs().getInt(SPK_IS_LOGIN, LoginState.LOGGED_OUT.getCode())
            );
}

public static void setLoginState(LoginState newLoginState) {
    editor().putInt(SPK_IS_LOGIN, newLoginState.getCode());
    editor().commit();
}

where pref and editor are SharedPreferences and a SharedPreferences.Editor

error CS0234: The type or namespace name 'Script' does not exist in the namespace 'System.Web'

I had the same. Script been underlined. I added a reference to System.Web.Extensions. Thereafter the Script was no longer underlined. Hope this helps someone.

How to Set Opacity (Alpha) for View in Android

I just found your question while having the similar problem with a TextView. I was able to solve it, by extending TextView and overriding onSetAlpha. Maybe you could try something similar with your button:

import android.content.Context;
import android.util.AttributeSet;
import android.widget.TextView;

public class AlphaTextView extends TextView {

  public AlphaTextView(Context context) {
    super(context);
  }

  public AlphaTextView(Context context, AttributeSet attrs) {
    super(context, attrs);
  }

  public AlphaTextView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
  }

  @Override
  public boolean onSetAlpha(int alpha) {
    setTextColor(getTextColors().withAlpha(alpha));
    setHintTextColor(getHintTextColors().withAlpha(alpha));
    setLinkTextColor(getLinkTextColors().withAlpha(alpha));
    return true;
  }
}

Check if a key is down?

In addition to using keyup and keydown listeners to track when is key goes down and back up, there are actually some properties that tell you if certain keys are down.

window.onmousemove = function (e) {
  if (!e) e = window.event;
  if (e.shiftKey) {/*shift is down*/}
  if (e.altKey) {/*alt is down*/}
  if (e.ctrlKey) {/*ctrl is down*/}
  if (e.metaKey) {/*cmd is down*/}
}

This are available on all browser generated event objects, such as those from keydown, keyup, and keypress, so you don't have to use mousemove.

I tried generating my own event objects with document.createEvent('KeyboardEvent') and document.createEvent('KeyboardEvent') and looking for e.shiftKey and such, but I had no luck.

I'm using Chrome 17 on Mac

Tomcat 7: How to set initial heap size correctly?

It works even without using 'export' keyword. This is what i have in my setenv.sh (/usr/share/tomcat7/bin/setenv.sh) and it works.

OS : 14.04.1-Ubuntu Server version: Apache Tomcat/7.0.52 (Ubuntu) Server built: Jun 30 2016 01:59:37 Server number: 7.0.52.0

JAVA_OPTS="-Dorg.apache.catalina.security.SecurityListener.UMASK=`umask` -server -Xms6G -Xmx6G -Xmn1400m -XX:HeapDumpPath=/Some/logs/ -XX:+HeapDumpOnOutOfMemoryError -XX:+UseConcMarkSweepGC -XX:+UseParNewGC -XX:SurvivorRatio=8 -XX:+UseCompressedOops -Dcom.sun.management.jmxremote.port=8181 -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false"
JAVA_OPTS="$JAVA_OPTS -Dserver.name=$HOSTNAME"

JQuery: Change value of hidden input field

If you're doing this in Drupal and use the Form API to change the #type from text to 'hidden' in hook_form_alter (for example), be advised that the output HTML will have different (or omitted) DIV wrappers, IDs and class names.

C# : 'is' keyword and checking for Not

The way you have it is fine but you could create a set of extension methods to make "a more elegant way to check for the 'NOT' instance."

public static bool Is<T>(this object myObject)
{
    return (myObject is T);
}

public static bool IsNot<T>(this object myObject)
{
    return !(myObject is T);
}

Then you could write:

if (child.IsNot<IContainer>())
{
    // child is not an IContainer
}

Hide "NFC Tag type not supported" error on Samsung Galaxy devices

Before Android 4.4

What you are trying to do is simply not possible from an app (at least not on a non-rooted/non-modified device). The message "NFC tag type not supported" is displayed by the Android system (or more specifically the NFC system service) before and instead of dispatching the tag to your app. This means that the NFC system service filters MIFARE Classic tags and never notifies any app about them. Consequently, your app can't detect MIFARE Classic tags or circumvent that popup message.

On a rooted device, you may be able to bypass the message using either

  1. Xposed to modify the behavior of the NFC service, or
  2. the CSC (Consumer Software Customization) feature configuration files on the system partition (see /system/csc/. The NFC system service disables the popup and dispatches MIFARE Classic tags to apps if the CSC feature <CscFeature_NFC_EnableSecurityPromptPopup> is set to any value but "mifareclassic" or "all". For instance, you could use:

    <CscFeature_NFC_EnableSecurityPromptPopup>NONE</CscFeature_NFC_EnableSecurityPromptPopup>
    

    You could add this entry to, for instance, the file "/system/csc/others.xml" (within the section <FeatureSet> ... </FeatureSet> that already exists in that file).

Since, you asked for the Galaxy S6 (the question that you linked) as well: I have tested this method on the S4 when it came out. I have not verified if this still works in the latest firmware or on other devices (e.g. the S6).

Since Android 4.4

This is pure guessing, but according to this (link no longer available), it seems that some apps (e.g. NXP TagInfo) are capable of detecting MIFARE Classic tags on affected Samsung devices since Android 4.4. This might mean that foreground apps are capable of bypassing that popup using the reader-mode API (see NfcAdapter.enableReaderMode) possibly in combination with NfcAdapter.FLAG_READER_SKIP_NDEF_CHECK.

Dynamic function name in javascript?

I struggled a lot with this issue. @Albin solution worked like a charm while developing, but it did not work when I changed it to production. After some debugging I realized how to achieve what I needed. I'm using ES6 with CRA (create-react-app), which means it's bundled by Webpack.

Lets say you have a file that exports the functions you need:

myFunctions.js

export function setItem(params) {
  // ...
}

export function setUser(params) {
  // ...
}

export function setPost(params) {
  // ...
}

export function setReply(params) {
  // ...
}

And you need to dynamically call these functions elsewhere:

myApiCalls.js

import * as myFunctions from 'path_to/myFunctions';
/* note that myFunctions is imported as an array,
 * which means its elements can be easily accessed
 * using an index. You can console.log(myFunctions).
 */

function accessMyFunctions(res) {
  // lets say it receives an API response
  if (res.status === 200 && res.data) {
    const { data } = res;
    // I want to read all properties in data object and 
    // call a function based on properties names.
    for (const key in data) {
      if (data.hasOwnProperty(key)) {
        // you can skip some properties that are usually embedded in
        // a normal response
        if (key !== 'success' && key !== 'msg') {
          // I'm using a function to capitalize the key, which is
          // used to dynamically create the function's name I need.
          // Note that it does not create the function, it's just a
          // way to access the desired index on myFunctions array.
          const name = `set${capitalizeFirstLetter(key)}`;
          // surround it with try/catch, otherwise all unexpected properties in
          // data object will break your code.
          try {
            // finally, use it.
            myFunctions[name](data[key]);
          } catch (error) {
            console.log(name, 'does not exist');
            console.log(error);
          }
        }
      }
    }
  }
}

Pandas Replace NaN with blank/empty string

If you are reading the dataframe from a file (say CSV or Excel) then use :

  • df.read_csv(path , na_filter=False)
  • df.read_excel(path , na_filter=False)

This will automatically consider the empty fields as empty strings ''


If you already have the dataframe

  • df = df.replace(np.nan, '', regex=True)
  • df = df.fillna('')

Angular2 router (@angular/router), how to set default route?

I just faced the same issue, I managed to make it work on my machine, however the change I did is not the same way it is mentioned in the documentation so it could be an issue of angular version routing module, mine is Angular 7

It only worked when I changed the lazy module main route entry path with same path as configured at the app-routes.ts

routes = [{path:'', redirectTo: '\home\default', pathMatch: 'full'},
           {path: '', 
           children: [{
             path:'home',
             loadChildren :'lazy module path'      
           }]

         }];

 routes configured at HomeModule
 const routes = [{path: 'home', redirectTo: 'default', pathMatch: 'full'},
             {path: 'default', component: MyPageComponent},
            ]

 instead of 
 const routes = [{path: '', redirectTo: 'default', pathMatch: 'full'},
                   {path: 'default', component: MyPageComponent},
                ]

Detect if a NumPy array contains at least one non-numeric value?

This should be faster than iterating and will work regardless of shape.

numpy.isnan(myarray).any()

Edit: 30x faster:

import timeit
s = 'import numpy;a = numpy.arange(10000.).reshape((100,100));a[10,10]=numpy.nan'
ms = [
    'numpy.isnan(a).any()',
    'any(numpy.isnan(x) for x in a.flatten())']
for m in ms:
    print "  %.2f s" % timeit.Timer(m, s).timeit(1000), m

Results:

  0.11 s numpy.isnan(a).any()
  3.75 s any(numpy.isnan(x) for x in a.flatten())

Bonus: it works fine for non-array NumPy types:

>>> a = numpy.float64(42.)
>>> numpy.isnan(a).any()
False
>>> a = numpy.float64(numpy.nan)
>>> numpy.isnan(a).any()
True

Random number between 0 and 1 in python

I want a random number between 0 and 1, like 0.3452

random.random() is what you are looking for:

From python docs: random.random() Return the next random floating point number in the range [0.0, 1.0).


And, btw, Why your try didn't work?:

Your try was: random.randrange(0, 1)

From python docs: random.randrange() Return a randomly selected element from range(start, stop, step). This is equivalent to choice(range(start, stop, step)), but doesn’t actually build a range object.

So, what you are doing here, with random.randrange(a,b) is choosing a random element from range(a,b); in your case, from range(0,1), but, guess what!: the only element in range(0,1), is 0, so, the only element you can choose from range(0,1), is 0; that's why you were always getting 0 back.

Batch file include external file for variables

Let's not forget good old parameters. When starting your *.bat or *.cmd file you can add up to nine parameters after the command file name:

call myscript.bat \\path\to\my\file.ext type
call myscript.bat \\path\to\my\file.ext "Del /F"

Example script

The myscript.bat could be something like this:

@Echo Off
Echo The path of this scriptfile %~0
Echo The name of this scriptfile %~n0
Echo The extension of this scriptfile %~x0
Echo.
If "%~2"=="" (
   Echo Parameter missing, quitting.
   GoTo :EOF
)
If Not Exist "%~1" (
   Echo File does not exist, quitting.
   GoTo :EOF
)
Echo Going to %~2 this file: %~1
%~2 "%~1"
If %errorlevel%  NEQ 0 (
   Echo Failed to %~2 the %~1.
)
@Echo On

Example output

c:\>c:\bats\myscript.bat \\server\path\x.txt type
The path of this scriptfile c:\bats\myscript.bat
The name of this scriptfile myscript
The extension of this scriptfile .bat

Going to type this file: \\server\path\x.txt
This is the content of the file:
Some alphabets: ABCDEFG abcdefg
Some numbers: 1234567890

c:\>c:\bats\myscript.bat \\server\path\x.txt "del /f "
The path of this scriptfile c:\bats\myscript.bat
The name of this scriptfile myscript
The extension of this scriptfile .bat

Going to del /f  this file: \\server\path\x.txt

c:\>

How do I make an Android EditView 'Done' button and hide the keyboard when clicked?

I have to point that out as a lot of people can struggle into that without knowing the problem.

If you want the kb to hide when clicking Done, and you set android:imeOptions="actionDone" & android:maxLines="1" without setting your EditText inputType it will NOT work as the default inputType for the EditText is not "text" as a lot of people think.

so, setting only inputType will give you the results you desire whatever what you are setting it to like "text", "number", ...etc.

How to select all instances of a variable and edit variable name in Sublime

It's mentioned by @watsonic that in Sublime Text 3 on Mac OS, starting with an empty selection, simply ^?G (AltF3 on Windows) does the trick, instead of ?D + ^?G in Sublime Text 2.

What does "The APR based Apache Tomcat Native library was not found" mean?

I just went through this and configured it with the following:

Ubuntu 16.04

Tomcat 8.5.9

Apache2.4.25

APR 1.5.2

Tomcat-native 1.2.10

Java 8

These are the steps i used based on the older posts here:

Install package

sudo apt-get update
sudo apt-get install libtcnative-1

Verify these packages are installed

sudo apt-get install make 
sudo apt-get install gcc
sudo apt-get install openssl

Install package

sudo apt-get install libssl-dev

Install and compile Apache APR

cd /opt/tomcat/bin
sudo wget http://apache.mirror.anlx.net//apr/apr-1.5.2.tar.gz
sudo tar -xzvf apr-1.5.2.tar.gz
cd apr-1.5.2
sudo ./configure
sudo make
sudo make install

verify installation

cd /usr/local/apr/lib/
ls 

you should see the compiled file as

libapr-1.la

Download and install Tomcat Native source package

cd /opt/tomcat/bin
sudo wget https://archive.apache.org/dist/tomcat/tomcat-connectors/native/1.2.10/source/tomcat-native-1.2.10-src.tar.gz
sudo tar -xzvf tomcat-native-1.2.10-src.tar.gz
cd tomcat-native-1.2.10-src/native

verify JAVA_HOME

sudo pico ~/.bashrc
export JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64
source ~/.bashrc
sudo ./configure --with-apr=/usr/local/apr --with-java-home=$JAVA_HOME
sudo make
sudo make install

Edit the /opt/tomcat/bin/setenv.sh file with following line:

sudo pico /opt/tomcat/bin/setenv.sh
export LD_LIBRARY_PATH='$LD_LIBRARY_PATH:/usr/local/apr/lib'

restart tomcat

sudo service tomcat restart

Can we define min-margin and max-margin, max-padding and min-padding in css?

I ran across this looking for a way to do a max-margin for responsive design. I need a 5% margin for mobile/tablet devices up to 48 pixels wide. Berd gave me the answer by using media queries.

My answer: 48 * 2 = 96 total max margin 96 is 10% of total width. 10 * 96 = (960) 100% of vw where 48px is the first time I want it to overwrite the % .

So my media queries to control my margins become:

@media (max-width: 959px) {
    .content {
        margin: 30px 5% 48px;
    }
}
@media (min-width: 960px) {
    .content {
        display:block;
        margin: 30px 48px 48px;
    }
}

HTML text input field with currency symbol

Since you can't do ::before with content: '$' on inputs and adding an absolutely positioned element adds extra html - I like do to a background SVG inline css.

It goes something like this:

input {
    width: 85px;
    background-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' version='1.1' height='16px' width='85px'><text x='2' y='13' fill='gray' font-size='12' font-family='arial'>$</text></svg>");
    padding-left: 12px;
}

It outputs the following:

svg dollar sign background css

Note: the code must all be on a single line. Support is pretty good in modern browsers, but be sure to test.

What is the difference between a HashMap and a TreeMap?

Along with sorted key store one another difference is with TreeMap, developer can give (String.CASE_INSENSITIVE_ORDER) with String keys, so then the comparator ignores case of key while performing comparison of keys on map access. This is not possible to give such option with HashMap - it is always case sensitive comparisons in HashMap.

What does this thread join code mean?

Simply put:
t1.join() returns after t1 is completed.
It doesn't do anything to thread t1, except wait for it to finish.
Naturally, code following t1.join() will be executed only after t1.join() returns.

Finding all possible combinations of numbers to reach a given sum

PHP Version, as inspired by Keith Beller's C# version.

bala's PHP version did not work for me, because I did not need to group numbers. I wanted a simpler implementation with one target value, and a pool of numbers. This function will also prune any duplicate entries.

/**
 * Calculates a subset sum: finds out which combinations of numbers
 * from the numbers array can be added together to come to the target
 * number.
 * 
 * Returns an indexed array with arrays of number combinations.
 * 
 * Example: 
 * 
 * <pre>
 * $matches = subset_sum(array(5,10,7,3,20), 25);
 * </pre>
 * 
 * Returns:
 * 
 * <pre>
 * Array
 * (
 *   [0] => Array
 *   (
 *       [0] => 3
 *       [1] => 5
 *       [2] => 7
 *       [3] => 10
 *   )
 *   [1] => Array
 *   (
 *       [0] => 5
 *       [1] => 20
 *   )
 * )
 * </pre>
 * 
 * @param number[] $numbers
 * @param number $target
 * @param array $part
 * @return array[number[]]
 */
function subset_sum($numbers, $target, $part=null)
{
    // we assume that an empty $part variable means this
    // is the top level call.
    $toplevel = false;
    if($part === null) {
        $toplevel = true;
        $part = array();
    }

    $s = 0;
    foreach($part as $x) 
    {
        $s = $s + $x;
    }

    // we have found a match!
    if($s == $target) 
    {
        sort($part); // ensure the numbers are always sorted
        return array(implode('|', $part));
    }

    // gone too far, break off
    if($s >= $target) 
    {
        return null;
    }

    $matches = array();
    $totalNumbers = count($numbers);

    for($i=0; $i < $totalNumbers; $i++) 
    {
        $remaining = array();
        $n = $numbers[$i];

        for($j = $i+1; $j < $totalNumbers; $j++) 
        {
            $remaining[] = $numbers[$j];
        }

        $part_rec = $part;
        $part_rec[] = $n;

        $result = subset_sum($remaining, $target, $part_rec);
        if($result) 
        {
            $matches = array_merge($matches, $result);
        }
    }

    if(!$toplevel) 
    {
        return $matches;
    }

    // this is the top level function call: we have to
    // prepare the final result value by stripping any
    // duplicate results.
    $matches = array_unique($matches);
    $result = array();
    foreach($matches as $entry) 
    {
        $result[] = explode('|', $entry);
    }

    return $result;
}

Timing Delays in VBA

Your code only creates a time without a date. If your assumption is correct that when it runs the application.wait the time actually already reached that time it will wait for 24 hours exactly. I also worry a bit about calling now() multiple times (could be different?) I would change the code to

 application.wait DateAdd("s", 1, Now)

Programmatically saving image to Django ImageField

Super easy if model hasn't been created yet:

First, copy your image file to the upload path (assumed = 'path/' in following snippet).

Second, use something like:

class Layout(models.Model):
    image = models.ImageField('img', upload_to='path/')

layout = Layout()
layout.image = "path/image.png"
layout.save()

tested and working in django 1.4, it might work also for an existing model.

What's the difference between abstraction and encapsulation?

My opinion of abstraction is not in the sense of hiding implementation or background details!

Abstraction gives us the benefit to deal with a representation of the real world which is easier to handle, has the ability to be reused, could be combined with other components of our more or less complex program package. So we have to find out how we pick a complete peace of the real world, which is complete enough to represent the sense of our algorithm and data. The implementation of the interface may hide the details but this is not part of the work we have to do for abstracting something.

For me most important thing for abstraction is:

  1. reduction of complexity
  2. reduction of size/quantity
  3. splitting of non related domains to clear and independent components

All this has for me nothing to do with hiding background details!

If you think of sorting some data, abstraction can result in:

  1. a sorting algorithm, which is independent of the data representation
  2. a compare function, which is independent of data and sort algorithm
  3. a generic data representation, which is independent of the used algorithms

All these has nothing to do with hiding information.

How can I limit ngFor repeat to some number of items in Angular?

 <div *ngFor="let item of list;trackBy: trackByFunc" >
   {{item.value}}
 </div>

In your ts file

 trackByFunc(index, item){
    return item ? item.id : undefined;
  }

How to extract text from a PDF?

For image extraction, pdfimages is a free command line tool for Linux or Windows (win32):

pdfimages: Extract and Save Images From A Portable Document Format ( PDF ) File

pull access denied repository does not exist or may require docker login

If the repository is private you have to assign permissions to download it. You have two options, with the docker login command, or put in ~/.docker/docker.config the file generated once you login.

Restarting cron after changing crontab file?

Try this: service crond restart, Hence it's crond not cron.

shift a std_logic_vector of n bit to right or left

I would not suggest to use sll or srl with std_logic_vector.

During simulation sll gave me 'U' value for those bits, where I expected 0's.

Use shift_left(), shift_right() functions.

For example:

OP1 : in std_logic_vector(7 downto 0); signal accum: std_logic_vector(7 downto 0);

accum <= std_logic_vector(shift_left(unsigned(accum), to_integer(unsigned(OP1)))); accum <= std_logic_vector(shift_right(unsigned(accum), to_integer(unsigned(OP1))));

Fatal Error: Allowed Memory Size of 134217728 Bytes Exhausted (CodeIgniter + XML-RPC)

Change the memory limit in the php.ini file and restart Apache. After the restart, run the phpinfo(); function from any PHP file for a memory_limit change confirmation.

memory_limit = -1

Memory limit -1 means there is no memory limit set. It's now at the maximum.

Combining multiple commits before pushing in Git

You can do this with git rebase -i, passing in the revision that you want to use as the 'root':

git rebase -i origin/master

will open an editor window showing all of the commits you have made after the last commit in origin/master. You can reject commits, squash commits into a single commit, or edit previous commits.

There are a few resources that can probably explain this in a better way, and show some other examples:

http://book.git-scm.com/4_interactive_rebasing.html

and

http://gitready.com/advanced/2009/02/10/squashing-commits-with-rebase.html

are the first two good pages I could find.

Add element to a JSON file?

One possible issue I see is you set your JSON unconventionally within an array/list object. I would recommend using JSON in its most accepted form, i.e.:

test_json = { "a": 1, "b": 2}

Once you do this, adding a json element only involves the following line:

test_json["c"] = 3

This will result in:

{'a': 1, 'b': 2, 'c': 3}

Afterwards, you can add that json back into an array or a list of that is desired.

Display milliseconds in Excel

I've discovered in Excel 2007, if the results are a Table from an embedded query, the ss.000 does not work. I can paste the query results (from SQL Server Management Studio), and format the time just fine. But when I embed the query as a Data Connection in Excel, the format always gives .000 as the milliseconds.

What do the return values of Comparable.compareTo mean in Java?

take example if we want to compare "a" and "b", i.e ("a" == this)

  1. negative int if a < b
  2. if a == b
  3. Positive int if a > b

How to get next/previous record in MySQL?

This is universal solution for conditions wiht more same results.

<?php
$your_name1_finded="somethnig searched"; //$your_name1_finded must be finded in previous select

$result = db_query("SELECT your_name1 FROM your_table WHERE your_name=your_condition ORDER BY your_name1, your_name2"); //Get all our ids

$i=0;
while($row = db_fetch_assoc($result)) { //Loop through our rows
    $i++;
    $current_row[$i]=$row['your_name1'];// field with results
    if($row['your_name1'] == $your_name1_finded) {//If we haven't hit our current row yet
        $yid=$i;
    }
}
//buttons
if ($current_row[$yid-1]) $out_button.= "<a  class='button' href='/$your_url/".$current_row[$yid-1]."'>BUTTON_PREVIOUS</a>";
if ($current_row[$yid+1]) $out_button.= "<a  class='button' href='/$your_url/".$current_row[$yid+1]."'>BUTTON_NEXT</a>";

echo $out_button;//display buttons
?>

See line breaks and carriage returns in editor

To disagree with the official answer:

:set list will not show ^M characters (CRs). Supplying the -b option to vi/vim will work. Or, once vim is loaded, type :e ++ff=unix.

Newline in string attribute

<TextBlock Text="Stuff on line1&#x0a;Stuff on line 2"/>

You can use any hexadecimally encoded value to represent a literal. In this case, I used the line feed (char 10). If you want to do "classic" vbCrLf, then you can use &#x0d;&#x0a;

By the way, note the syntax: It's the ampersand, a pound, the letter x, then the hex value of the character you want, and then finally a semi-colon.

ALSO: For completeness, you can bind to a text that already has the line feeds embedded in it like a constant in your code behind, or a variable constructed at runtime.

Unix: How to delete files listed in a file

Here's another looping example. This one also contains an 'if-statement' as an example of checking to see if the entry is a 'file' (or a 'directory' for example):

for f in $(cat 1.txt); do if [ -f $f ]; then rm $f; fi; done

Trigger validation of all fields in Angular Form submit

You can use Angular-Validator to do what you want. It's stupid simple to use.

It will:

  • Only validate the fields on $dirty or on submit
  • Prevent the form from being submitted if it is invalid
  • Show custom error message after the field is $dirty or the form is submitted

See the demo

Example

<form angular-validator 
       angular-validator-submit="myFunction(myBeautifulForm)"
       name="myBeautifulForm">
       <!-- form fields here -->
    <button type="submit">Submit</button>
</form>

If the field does not pass the validator then the user will not be able to submit the form.

Check out angular-validator use cases and examples for more information.

Disclaimer: I am the author of Angular-Validator

Convert date formats in bash

Just with bash:

convert_date () {
    local months=( JAN FEB MAR APR MAY JUN JUL AUG SEP OCT NOV DEC )
    local i
    for (( i=0; i<11; i++ )); do
        [[ $2 = ${months[$i]} ]] && break
    done
    printf "%4d%02d%02d\n" $3 $(( i+1 )) $1
}

And invoke it like this

d=$( convert_date 27 JUN 2011 )

Or if the "old" date string is stored in a variable

d_old="27 JUN 2011"
d=$( convert_date $d_old )  # not quoted

Best way to pretty print a hash

Using Pry you just need to add the following code to your ~/.pryrc:

require "awesome_print"
AwesomePrint.pry!

SyntaxError: missing ) after argument list

For me, once there was a mistake in spelling of function

For e.g. instead of

$(document).ready(function(){

});

I wrote

$(document).ready(funciton(){

});

So keep that also in check

Add to Array jQuery

For JavaScript arrays, you use Both push() and concat() function.

var array = [1, 2, 3];
array.push(4, 5);         //use push for appending a single array.




var array1 = [1, 2, 3];
var array2 = [4, 5, 6];

var array3 = array1.concat(array2);   //It is better use concat for appending more then one array.

How to check if a file exists in a folder?

This woked for me.

file_browse_path=C:\Users\Gunjan\Desktop\New folder\100x25Barcode.prn
  String path = @"" + file_browse_path.Text;

  if (!File.Exists(path))
             {
      MessageBox.Show("File not exits. Please enter valid path for the file.");
                return;
             }

MVC Razor view nested foreach's model

You can simply use EditorTemplates to do that, you need to create a directory named "EditorTemplates" in your controller's view folder and place a seperate view for each of your nested entities (named as entity class name)

Main view :

@model ViewModels.MyViewModels.Theme

@Html.LabelFor(Model.Theme.name)
@Html.EditorFor(Model.Theme.Categories)

Category view (/MyController/EditorTemplates/Category.cshtml) :

@model ViewModels.MyViewModels.Category

@Html.LabelFor(Model.Name)
@Html.EditorFor(Model.Products)

Product view (/MyController/EditorTemplates/Product.cshtml) :

@model ViewModels.MyViewModels.Product

@Html.LabelFor(Model.Name)
@Html.EditorFor(Model.Orders)

and so on

this way Html.EditorFor helper will generate element's names in an ordered manner and therefore you won't have any further problem for retrieving the posted Theme entity as a whole

How to reference Microsoft.Office.Interop.Excel dll?

If you have VS 2013 Express and you cant find Microsoft.Office namespace, try this ('Microsoft Excel 12.0 Object Library' if you want to use Office 2007)

enter image description here

'setInterval' vs 'setTimeout'

setTimeout(expression, timeout); runs the code/function once after the timeout.

setInterval(expression, timeout); runs the code/function in intervals, with the length of the timeout between them.

Example:

var intervalID = setInterval(alert, 1000); // Will alert every second.
// clearInterval(intervalID); // Will clear the timer.

setTimeout(alert, 1000); // Will alert once, after a second.

Javascript - Replace html using innerHTML

You should chain the replace() together instead of assigning the result and replacing again.

var strMessage1 = document.getElementById("element1") ;
strMessage1.innerHTML = strMessage1.innerHTML
                        .replace(/aaaaaa./g,'<a href=\"http://www.google.com/')
                        .replace(/.bbbbbb/g,'/world\">Helloworld</a>');

See DEMO.

Check if Key Exists in NameValueCollection

If the collection size is small you could go with the solution provided by rich.okelly. However, a large collection means that the generation of the dictionary may be noticeably slower than just searching the keys collection.

Also, if your usage scenario is searching for keys in different points in time, where the NameValueCollection may have been modified, generating the dictionary each time may, again, be slower than just searching the keys collection.

Select the top N values by group

I prefer @Ista solution, cause needs no extra package and is simple.
A modification of the data.table solution also solve my problem, and is more general.
My data.frame is

> str(df)
'data.frame':   579 obs. of  11 variables:
 $ trees     : num  2000 5000 1000 2000 1000 1000 2000 5000 5000 1000 ...
 $ interDepth: num  2 3 5 2 3 4 4 2 3 5 ...
 $ minObs    : num  6 4 1 4 10 6 10 10 6 6 ...
 $ shrinkage : num  0.01 0.001 0.01 0.005 0.01 0.01 0.001 0.005 0.005 0.001     ...
 $ G1        : num  0 2 2 2 2 2 8 8 8 8 ...
 $ G2        : logi  FALSE FALSE FALSE FALSE FALSE FALSE ...
 $ qx        : num  0.44 0.43 0.419 0.439 0.43 ...
 $ efet      : num  43.1 40.6 39.9 39.2 38.6 ...
 $ prec      : num  0.606 0.593 0.587 0.582 0.574 0.578 0.576 0.579 0.588 0.585 ...
 $ sens      : num  0.575 0.57 0.573 0.575 0.587 0.574 0.576 0.566 0.542 0.545 ...
 $ acu       : num  0.631 0.645 0.647 0.648 0.655 0.647 0.619 0.611 0.591 0.594 ...

The data.table solution needs order on i to do the job:

> require(data.table)
> dt1 <- data.table(df)
> dt2 = dt1[order(-efet, G1, G2), head(.SD, 3), by = .(G1, G2)]
> dt2
    G1    G2 trees interDepth minObs shrinkage        qx   efet  prec  sens   acu
 1:  0 FALSE  2000          2      6     0.010 0.4395953 43.066 0.606 0.575 0.631
 2:  0 FALSE  2000          5      1     0.005 0.4294718 37.554 0.583 0.548 0.607
 3:  0 FALSE  5000          2      6     0.005 0.4395753 36.981 0.575 0.559 0.616
 4:  2 FALSE  5000          3      4     0.001 0.4296346 40.624 0.593 0.570 0.645
 5:  2 FALSE  1000          5      1     0.010 0.4186802 39.915 0.587 0.573 0.647
 6:  2 FALSE  2000          2      4     0.005 0.4390503 39.164 0.582 0.575 0.648
 7:  8 FALSE  2000          4     10     0.001 0.4511349 38.240 0.576 0.576 0.619
 8:  8 FALSE  5000          2     10     0.005 0.4469665 38.064 0.579 0.566 0.611
 9:  8 FALSE  5000          3      6     0.005 0.4426952 37.888 0.588 0.542 0.591
10:  2  TRUE  5000          3      4     0.001 0.3812878 21.057 0.510 0.479 0.615
11:  2  TRUE  2000          3     10     0.005 0.3790536 20.127 0.507 0.470 0.608
12:  2  TRUE  1000          5      4     0.001 0.3690911 18.981 0.500 0.475 0.611
13:  8  TRUE  5000          6     10     0.010 0.2865042 16.870 0.497 0.435 0.635
14:  0  TRUE  2000          6      4     0.010 0.3192862  9.779 0.460 0.433 0.621  

By some reason, it does not order the way pointed (probably because ordering by the groups). So, another ordering is done.

> dt2[order(G1, G2)]
    G1    G2 trees interDepth minObs shrinkage        qx   efet  prec  sens   acu
 1:  0 FALSE  2000          2      6     0.010 0.4395953 43.066 0.606 0.575 0.631
 2:  0 FALSE  2000          5      1     0.005 0.4294718 37.554 0.583 0.548 0.607
 3:  0 FALSE  5000          2      6     0.005 0.4395753 36.981 0.575 0.559 0.616
 4:  0  TRUE  2000          6      4     0.010 0.3192862  9.779 0.460 0.433 0.621
 5:  2 FALSE  5000          3      4     0.001 0.4296346 40.624 0.593 0.570 0.645
 6:  2 FALSE  1000          5      1     0.010 0.4186802 39.915 0.587 0.573 0.647
 7:  2 FALSE  2000          2      4     0.005 0.4390503 39.164 0.582 0.575 0.648
 8:  2  TRUE  5000          3      4     0.001 0.3812878 21.057 0.510 0.479 0.615
 9:  2  TRUE  2000          3     10     0.005 0.3790536 20.127 0.507 0.470 0.608
10:  2  TRUE  1000          5      4     0.001 0.3690911 18.981 0.500 0.475 0.611
11:  8 FALSE  2000          4     10     0.001 0.4511349 38.240 0.576 0.576 0.619
12:  8 FALSE  5000          2     10     0.005 0.4469665 38.064 0.579 0.566 0.611
13:  8 FALSE  5000          3      6     0.005 0.4426952 37.888 0.588 0.542 0.591
14:  8  TRUE  5000          6     10     0.010 0.2865042 16.870 0.497 0.435 0.635

The entity cannot be constructed in a LINQ to Entities query

You cannot (and should not be able to) project onto a mapped entity. You can, however, project onto an anonymous type or onto a DTO:

public class ProductDTO
{
    public string Name { get; set; }
    // Other field you may need from the Product entity
}

And your method will return a List of DTO's.

public List<ProductDTO> GetProducts(int categoryID)
{
    return (from p in db.Products
            where p.CategoryID == categoryID
            select new ProductDTO { Name = p.Name }).ToList();
}

Creating a chart in Excel that ignores #N/A or blank cells

Best way is use Empty

Dim i as Integer
For i = 1 to 1000
    If CPT_DB.Cells(i, 1) > 100 Then
       CPT_DB.Cells(i, 2) = CPT_DB.Cells(i, 1)
    Else
       CPT_DB.Cells(i, 2) = Empty //**********************
    End If
Next i

How do I install a color theme for IntelliJ IDEA 7.0.x

Take a look here: Third Party Add-ons

You may have to extract the jar using a zip application. Hopefully inside you'll find a collection of XML files.


IntelliJ IDEA Plugins

AWS CLI S3 A client error (403) occurred when calling the HeadObject operation: Forbidden

Trying to solve this problem myself, I discovered that there is no HeadBucket permission. It looks like there is, because that's what the error message tells you, but actually the HEAD operation requires the ListBucket permission. I also discovered that my IAM policy and my bucket policy were conflicting. Make sure you check both.

return in for loop or outside loop

Now someone told me that this is not very good programming because I use the return statement inside a loop and this would cause garbage collection to malfunction.

That's incorrect, and suggests you should treat other advice from that person with a degree of skepticism.

The mantra of "only have one return statement" (or more generally, only one exit point) is important in languages where you have to manage all resources yourself - that way you can make sure you put all your cleanup code in one place.

It's much less useful in Java: as soon as you know that you should return (and what the return value should be), just return. That way it's simpler to read - you don't have to take in any of the rest of the method to work out what else is going to happen (other than finally blocks).

Representing Directory & File Structure in Markdown Syntax

I'd suggest using wasabi then you can either use the markdown-ish feel like this

root/ # entry comments can be inline after a '#'
      # or on their own line, also after a '#'

  readme.md # a child of, 'root/', it's indented
            # under its parent.

  usage.md  # indented syntax is nice for small projects
            # and short comments.

  src/          # directories MUST be identified with a '/'
    fileOne.txt # files don't need any notation
    fileTwo*    # '*' can identify executables
    fileThree@  # '@' can identify symlinks

and throw that exact syntax at the js library for this

wasabi example

Where to find free public Web Services?

https://www.programmableweb.com/ -- Great collection of all category API's across web. It not only show cases the API's , but also Developers who use those API's in their applications and code samples, rating of the API and much more. They have more than apis they also have sdk and libraries too.

SQL selecting rows by most recent date with two unique columns

You can use a GROUP BY to group items by type and id. Then you can use the MAX() Aggregate function to get the most recent service month. The below returns a result set with ChargeId, ChargeType, and MostRecentServiceMonth

SELECT
  CHARGEID,
  CHARGETYPE,
  MAX(SERVICEMONTH) AS "MostRecentServiceMonth"
FROM INVOICE
GROUP BY CHARGEID, CHARGETYPE

Update ViewPager dynamically?

This might be of help to someone - in my case when inserting a new page the view pager was asking for the position of an existing fragment twice, but not asking for the position of the new item, causing incorrect behaviour and data not displaying.

  1. Copy the source for for FragmentStatePagerAdapter (seems to have not been updated in ages).

  2. Override notifyDataSetChanged()

    @Override
    public void notifyDataSetChanged() {
        mFragments.clear();
        super.notifyDataSetChanged();
    }
    
  3. Add a sanity check to destroyItem() to prevent crashes:

    if (position < mFragments.size()) {
        mFragments.set(position, null);
    }
    

javascript toISOString() ignores timezone offset

moment.js FTW!!!

Just convert your date to a moment and manipulate it however you please:

var d = new Date(twDate);
var m = moment(d).format();
console.log(m);
// example output:
// 2016-01-08T00:00:00-06:00

http://momentjs.com/docs/

How do I get a YouTube video thumbnail from the YouTube API?

A simple PHP function I created for the YouTube thumbnail and the types are

  • default
  • hqdefault
  • mqdefault
  • sddefault
  • maxresdefault

 

function get_youtube_thumb($link,$type){

    $video_id = explode("?v=", $link);

    if (empty($video_id[1])){
        $video_id = explode("/v/", $link);
        $video_id = explode("&", $video_id[1]);
        $video_id = $video_id[0];
    }
    $thumb_link = "";

    if($type == 'default'   || $type == 'hqdefault' ||
       $type == 'mqdefault' || $type == 'sddefault' ||
       $type == 'maxresdefault'){

        $thumb_link = 'http://img.youtube.com/vi/'.$video_id.'/'.$type.'.jpg';

    }elseif($type == "id"){
        $thumb_link = $video_id;
    }
    return $thumb_link;}

AngularJS ui-router login authentication

The solutions posted so far are needlessly complicated, in my opinion. There's a simpler way. The documentation of ui-router says listen to $locationChangeSuccess and use $urlRouter.sync() to check a state transition, halt it, or resume it. But even that actually doesn't work.

However, here are two simple alternatives. Pick one:

Solution 1: listening on $locationChangeSuccess

You can listen to $locationChangeSuccess and you can perform some logic, even asynchronous logic there. Based on that logic, you can let the function return undefined, which will cause the state transition to continue as normal, or you can do $state.go('logInPage'), if the user needs to be authenticated. Here's an example:

angular.module('App', ['ui.router'])

// In the run phase of your Angular application  
.run(function($rootScope, user, $state) {

  // Listen to '$locationChangeSuccess', not '$stateChangeStart'
  $rootScope.$on('$locationChangeSuccess', function() {
    user
      .logIn()
      .catch(function() {
        // log-in promise failed. Redirect to log-in page.
        $state.go('logInPage')
      })
  })
})

Keep in mind that this doesn't actually prevent the target state from loading, but it does redirect to the log-in page if the user is unauthorized. That's okay since real protection is on the server, anyway.

Solution 2: using state resolve

In this solution, you use ui-router resolve feature.

You basically reject the promise in resolve if the user is not authenticated and then redirect them to the log-in page.

Here's how it goes:

angular.module('App', ['ui.router'])

.config(
  function($stateProvider) {
    $stateProvider
      .state('logInPage', {
        url: '/logInPage',
        templateUrl: 'sections/logInPage.html',
        controller: 'logInPageCtrl',
      })
      .state('myProtectedContent', {
        url: '/myProtectedContent',
        templateUrl: 'sections/myProtectedContent.html',
        controller: 'myProtectedContentCtrl',
        resolve: { authenticate: authenticate }
      })
      .state('alsoProtectedContent', {
        url: '/alsoProtectedContent',
        templateUrl: 'sections/alsoProtectedContent.html',
        controller: 'alsoProtectedContentCtrl',
        resolve: { authenticate: authenticate }
      })

    function authenticate($q, user, $state, $timeout) {
      if (user.isAuthenticated()) {
        // Resolve the promise successfully
        return $q.when()
      } else {
        // The next bit of code is asynchronously tricky.

        $timeout(function() {
          // This code runs after the authentication promise has been rejected.
          // Go to the log-in page
          $state.go('logInPage')
        })

        // Reject the authentication promise to prevent the state from loading
        return $q.reject()
      }
    }
  }
)

Unlike the first solution, this solution actually prevents the target state from loading.

How to backup MySQL database in PHP?

Take a look here! It is a native solution written in php. You won't need to exec mysqldump, or cope with incomplete scripts. This is a full mysqldump clone, without dependencies, output compression and sane defaults.

Out of the box, mysqldump-php supports backing up table structures, the data itself, views, triggers and events.

MySQLDump-PHP is the only library that supports:

  • output binary blobs as hex.
  • resolves view dependencies (using Stand-In tables).
  • output compared against original mysqldump. Linked to travis-ci testing system (testing from php 5.3 to 7.1 & hhvm)
  • dumps stored procedures.
  • dumps events.
  • does extended-insert and/or complete-insert.
  • supports virtual columns from MySQL 5.7.

You can install it using composer, or just download the php file, and it is as easy as doing:

use Ifsnop\Mysqldump as IMysqldump;

try {
    $dump = new IMysqldump\Mysqldump('database', 'username', 'password');
    $dump->start('storage/work/dump.sql');
} catch (\Exception $e) {
    echo 'mysqldump-php error: ' . $e->getMessage();
}

All the options are explained at the github page, but more or less are auto-explicative:

$dumpSettingsDefault = array(
    'include-tables' => array(),
    'exclude-tables' => array(),
    'compress' => Mysqldump::NONE,
    'init_commands' => array(),
    'no-data' => array(),
    'reset-auto-increment' => false,
    'add-drop-database' => false,
    'add-drop-table' => false,
    'add-drop-trigger' => true,
    'add-locks' => true,
    'complete-insert' => false,
    'databases' => false,
    'default-character-set' => Mysqldump::UTF8,
    'disable-keys' => true,
    'extended-insert' => true,
    'events' => false,
    'hex-blob' => true, /* faster than escaped content */
    'net_buffer_length' => self::MAXLINESIZE,
    'no-autocommit' => true,
    'no-create-info' => false,
    'lock-tables' => true,
    'routines' => false,
    'single-transaction' => true,
    'skip-triggers' => false,
    'skip-tz-utc' => false,
    'skip-comments' => false,
    'skip-dump-date' => false,
    'skip-definer' => false,
    'where' => '',
    /* deprecated */
    'disable-foreign-keys-check' => true
);

How to use an existing database with an Android application

NOTE: Before trying this code, please find this line in the below code:

private static String DB_NAME ="YourDbName"; // Database name

DB_NAME here is the name of your database. It is assumed that you have a copy of the database in the assets folder, so for example, if your database name is ordersDB, then the value of DB_NAME will be ordersDB,

private static String DB_NAME ="ordersDB";

Keep the database in assets folder and then follow the below:

DataHelper class:

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DataBaseHelper extends SQLiteOpenHelper {

    private static String TAG = "DataBaseHelper"; // Tag just for the LogCat window
    private static String DB_NAME ="YourDbName"; // Database name
    private static int DB_VERSION = 1; // Database version
    private final File DB_FILE;
    private SQLiteDatabase mDataBase;
    private final Context mContext;

    public DataBaseHelper(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
        DB_FILE = context.getDatabasePath(DB_NAME);
        this.mContext = context;
    }

    public void createDataBase() throws IOException {
        // If the database does not exist, copy it from the assets.
        boolean mDataBaseExist = checkDataBase();
        if(!mDataBaseExist) {
            this.getReadableDatabase();
            this.close();
            try {
                // Copy the database from assests
                copyDataBase();
                Log.e(TAG, "createDatabase database created");
            } catch (IOException mIOException) {
                throw new Error("ErrorCopyingDataBase");
            }
        }
    }

    // Check that the database file exists in databases folder
    private boolean checkDataBase() {
        return DB_FILE.exists();
    }

    // Copy the database from assets
    private void copyDataBase() throws IOException {
        InputStream mInput = mContext.getAssets().open(DB_NAME);
        OutputStream mOutput = new FileOutputStream(DB_FILE);
        byte[] mBuffer = new byte[1024];
        int mLength;
        while ((mLength = mInput.read(mBuffer)) > 0) {
            mOutput.write(mBuffer, 0, mLength);
        }
        mOutput.flush();
        mOutput.close();
        mInput.close();
    }

    // Open the database, so we can query it
    public boolean openDataBase() throws SQLException {
        // Log.v("DB_PATH", DB_FILE.getAbsolutePath());
        mDataBase = SQLiteDatabase.openDatabase(DB_FILE, null, SQLiteDatabase.CREATE_IF_NECESSARY);
        // mDataBase = SQLiteDatabase.openDatabase(DB_FILE, null, SQLiteDatabase.NO_LOCALIZED_COLLATORS);
        return mDataBase != null;
    }

    @Override
    public synchronized void close() {
        if(mDataBase != null) {
            mDataBase.close();
        }
        super.close();
    }

}

Write a DataAdapter class like:

import java.io.IOException;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

public class TestAdapter {

    protected static final String TAG = "DataAdapter";

    private final Context mContext;
    private SQLiteDatabase mDb;
    private DataBaseHelper mDbHelper;

    public TestAdapter(Context context) {
        this.mContext = context;
        mDbHelper = new DataBaseHelper(mContext);
    }

    public TestAdapter createDatabase() throws SQLException {
        try {
            mDbHelper.createDataBase();
        } catch (IOException mIOException) {
            Log.e(TAG, mIOException.toString() + "  UnableToCreateDatabase");
            throw new Error("UnableToCreateDatabase");
        }
        return this;
    }

    public TestAdapter open() throws SQLException {
        try {
            mDbHelper.openDataBase();
            mDbHelper.close();
            mDb = mDbHelper.getReadableDatabase();
        } catch (SQLException mSQLException) {
            Log.e(TAG, "open >>"+ mSQLException.toString());
            throw mSQLException;
        }
        return this;
    }

    public void close() {
        mDbHelper.close();
    }

     public Cursor getTestData() {
         try {
             String sql ="SELECT * FROM myTable";
             Cursor mCur = mDb.rawQuery(sql, null);
             if (mCur != null) {
                mCur.moveToNext();
             }
             return mCur;
         } catch (SQLException mSQLException) {
             Log.e(TAG, "getTestData >>"+ mSQLException.toString());
             throw mSQLException;
         }
     }
}

Now you can use it like:

TestAdapter mDbHelper = new TestAdapter(urContext);
mDbHelper.createDatabase();
mDbHelper.open();

Cursor testdata = mDbHelper.getTestData();

mDbHelper.close();

EDIT: Thanks to JDx

For Android 4.1 (Jelly Bean), change:

DB_PATH = "/data/data/" + context.getPackageName() + "/databases/";

to:

DB_PATH = context.getApplicationInfo().dataDir + "/databases/";

in the DataHelper class, this code will work on Jelly Bean 4.2 multi-users.

EDIT: Instead of using hardcoded path, we can use

DB_PATH = context.getDatabasePath(DB_NAME).getAbsolutePath();

which will give us the full path to the database file and works on all Android versions

PHP code is not being executed, instead code shows on the page

This just happened to me again, along with the server downloading html files, rather than processing. I had not use the webserver apache for some time on the computer and meanwhile Ubuntu updated like two more versions from originally installed LTS. Now it is

$ cat /etc/issue
Ubuntu 16.04 LTS

So the php worked after like so:

$ sudo apt-get install lamp-server^
$ sudo a2enmod php7.0
$ sudo service apache2 restart 

The webserver was now parsing the php. Maybe now got to update some webs since php7.0 now running where as it was before running php5. Oh well.

Comparing two arrays & get the values which are not common

Your results will not be helpful unless the arrays are first sorted. To sort an array, run it through Sort-Object.

$x = @(5,1,4,2,3)
$y = @(2,4,6,1,3,5)

Compare-Object -ReferenceObject ($x | Sort-Object) -DifferenceObject ($y | Sort-Object)

AngularJs ReferenceError: angular is not defined

If you've downloaded the angular.js file from Google, you need to make sure that Everyone has Read access to it, or it will not be loaded by your HTML file. By default, it seems to download with No access permissions, so you'll also be getting a message such as:

GET http://localhost/myApp/js/angular.js

This maddened me for about half an hour!

Python - TypeError: 'int' object is not iterable

If the case is:

n=int(input())

Instead of -> for i in n: -> gives error- 'int' object is not iterable

Use -> for i in range(0,n): -> works fine..!

What does the following Oracle error mean: invalid column index

Using Spring's SimpleJdbcTemplate, I got it when I tried to do this:

String sqlString = "select pwy_code from approver where university_id = '123'";
List<Map<String, Object>> rows = getSimpleJdbcTemplate().queryForList(sqlString, uniId);
  • I had an argument to queryForList that didn't correspond to a question mark in the SQL. The first line should have been:

    String sqlString = "select pwy_code from approver where university_id = ?";
    

How to convert a list into data table

you can use this extension method and call it like this.

DataTable dt =   YourList.ToDataTable();

public static DataTable ToDataTable<T>(this List<T> iList)
        {
            DataTable dataTable = new DataTable();
            PropertyDescriptorCollection propertyDescriptorCollection =
                TypeDescriptor.GetProperties(typeof(T));
            for (int i = 0; i < propertyDescriptorCollection.Count; i++)
            {
                PropertyDescriptor propertyDescriptor = propertyDescriptorCollection[i];
                Type type = propertyDescriptor.PropertyType;

                if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
                    type = Nullable.GetUnderlyingType(type);


                dataTable.Columns.Add(propertyDescriptor.Name, type);
            }
            object[] values = new object[propertyDescriptorCollection.Count];
            foreach (T iListItem in iList)
            {
                for (int i = 0; i < values.Length; i++)
                {
                    values[i] = propertyDescriptorCollection[i].GetValue(iListItem);
                }
                dataTable.Rows.Add(values);
            }
            return dataTable;
        }

nginx - client_max_body_size has no effect

Someone correct me if this is bad, but I like to lock everything down as much as possible, and if you've only got one target for uploads (as it usually the case), then just target your changes to that one file. This works for me on the Ubuntu nginx-extras mainline 1.7+ package:

location = /upload.php {
    client_max_body_size 102M;
    fastcgi_param PHP_VALUE "upload_max_filesize=102M \n post_max_size=102M";
    (...)
}

Disable/turn off inherited CSS3 transitions

Another way to remove all transitions is with the unset keyword:

a.tags {
    transition: unset;
}

In the case of transition, unset is equivalent to initial, since transition is not an inherited property:

a.tags {
    transition: initial;
}

A reader who knows about unset and initial can tell that these solutions are correct immediately, without having to think about the specific syntax of transition.

How to measure elapsed time in Python?

Here's a pretty well documented and fully type hinted decorator I use as a general utility:

from functools import wraps
from time import perf_counter
from typing import Any, Callable, Optional, TypeVar, cast

F = TypeVar("F", bound=Callable[..., Any])


def timer(prefix: Optional[str] = None, precision: int = 6) -> Callable[[F], F]:
    """Use as a decorator to time the execution of any function.

    Args:
        prefix: String to print before the time taken.
            Default is the name of the function.
        precision: How many decimals to include in the seconds value.

    Examples:
        >>> @timer()
        ... def foo(x):
        ...     return x
        >>> foo(123)
        foo: 0.000...s
        123
        >>> @timer("Time taken: ", 2)
        ... def foo(x):
        ...     return x
        >>> foo(123)
        Time taken: 0.00s
        123

    """
    def decorator(func: F) -> F:
        @wraps(func)
        def wrapper(*args: Any, **kwargs: Any) -> Any:
            nonlocal prefix
            prefix = prefix if prefix is not None else f"{func.__name__}: "
            start = perf_counter()
            result = func(*args, **kwargs)
            end = perf_counter()
            print(f"{prefix}{end - start:.{precision}f}s")
            return result
        return cast(F, wrapper)
    return decorator

Example usage:

from timer import timer


@timer(precision=9)
def takes_long(x: int) -> bool:
    return x in (i for i in range(x + 1))


result = takes_long(10**8)
print(result)

Output:

takes_long: 4.942629056s
True

The doctests can be checked with:

$ python3 -m doctest --verbose -o=ELLIPSIS timer.py

And the type hints with:

$ mypy timer.py

Add a string of text into an input field when user clicks a button

Example for you to work from

HTML:

<input type="text" value="This is some text" id="text" style="width: 150px;" />
<br />
<input type="button" value="Click Me" id="button" />?

jQuery:

<script type="text/javascript">
$(function () {
    $('#button').on('click', function () {
        var text = $('#text');
        text.val(text.val() + ' after clicking');    
    });
});
<script>

Javascript

<script type="text/javascript">
document.getElementById("button").addEventListener('click', function () {
    var text = document.getElementById('text');
    text.value += ' after clicking';
});
</script>

Working jQuery example: http://jsfiddle.net/geMtZ/ ?

Sort array of objects by object fields

A simple alternative that allows you to determine dynamically the field on which the sorting is based:

$order_by = 'name';
usort($your_data, function ($a, $b) use ($order_by)
{
    return strcmp($a->{$order_by}, $b->{$order_by});
});

This is based on the Closure class, which allows anonymous functions. It is available since PHP 5.3.

How do I set a conditional breakpoint in gdb, when char* x points to a string whose value equals "hello"?

Since GDB 7.5 you can use these native Convenience Functions:

$_memeq(buf1, buf2, length)
$_regex(str, regex)
$_streq(str1, str2)
$_strlen(str)

Seems quite less problematic than having to execute a "foreign" strcmp() on the process' stack each time the breakpoint is hit. This is especially true for debugging multithreaded processes.

Note your GDB needs to be compiled with Python support, which is not an issue with current linux distros. To be sure, you can check it by running show configuration inside GDB and searching for --with-python. This little oneliner does the trick, too:

$ gdb -n -quiet -batch -ex 'show configuration' | grep 'with-python'
             --with-python=/usr (relocatable)

For your demo case, the usage would be

break <where> if $_streq(x, "hello")

or, if your breakpoint already exists and you just want to add the condition to it

condition <breakpoint number> $_streq(x, "hello")

$_streq only matches the whole string, so if you want something more cunning you should use $_regex, which supports the Python regular expression syntax.

Mark error in form using Bootstrap

(UPDATED with examples for Bootstrap v4, v3 and v3)

Examples of forms with validation classes for the past few major versions of Bootstrap.

Bootstrap v4

See the live version on codepen

bootstrap v4 form validation

<div class="container">
  <form>
    <div class="form-group row">
      <label for="inputEmail" class="col-sm-2 col-form-label text-success">Email</label>
      <div class="col-sm-7">
        <input type="email" class="form-control is-valid" id="inputEmail" placeholder="Email">
      </div>
    </div>

    <div class="form-group row">
      <label for="inputPassword" class="col-sm-2 col-form-label text-danger">Password</label>
      <div class="col-sm-7">
        <input type="password" class="form-control is-invalid" id="inputPassword" placeholder="Password">
      </div>
      <div class="col-sm-3">
        <small id="passwordHelp" class="text-danger">
          Must be 8-20 characters long.
        </small>      
      </div>
    </div>
  </form>
</div>

Bootstrap v3

See the live version on codepen

bootstrap v3 form validation

<form role="form">
  <div class="form-group has-warning">
    <label class="control-label" for="inputWarning">Input with warning</label>
    <input type="text" class="form-control" id="inputWarning">
    <span class="help-block">Something may have gone wrong</span>
  </div>
  <div class="form-group has-error">
    <label class="control-label" for="inputError">Input with error</label>
    <input type="text" class="form-control" id="inputError">
    <span class="help-block">Please correct the error</span>
  </div>
  <div class="form-group has-info">
    <label class="control-label" for="inputError">Input with info</label>
    <input type="text" class="form-control" id="inputError">
    <span class="help-block">Username is taken</span>
  </div>
  <div class="form-group has-success">
    <label class="control-label" for="inputSuccess">Input with success</label>
    <input type="text" class="form-control" id="inputSuccess" />
    <span class="help-block">Woohoo!</span>
  </div>
</form>

Bootstrap v2

See the live version on jsfiddle

bootstrap v2 form validation

The .error, .success, .warning and .info classes are appended to the .control-group. This is standard Bootstrap markup and styling in v2. Just follow that and you're in good shape. Of course you can go beyond with your own styles to add a popup or "inline flash" if you prefer, but if you follow Bootstrap convention and hang those validation classes on the .control-group it will stay consistent and easy to manage (at least since you'll continue to have the benefit of Bootstrap docs and examples)

  <form class="form-horizontal">
    <div class="control-group warning">
      <label class="control-label" for="inputWarning">Input with warning</label>
      <div class="controls">
        <input type="text" id="inputWarning">
        <span class="help-inline">Something may have gone wrong</span>
      </div>
    </div>
    <div class="control-group error">
      <label class="control-label" for="inputError">Input with error</label>
      <div class="controls">
        <input type="text" id="inputError">
        <span class="help-inline">Please correct the error</span>
      </div>
    </div>
    <div class="control-group info">
      <label class="control-label" for="inputInfo">Input with info</label>
      <div class="controls">
        <input type="text" id="inputInfo">
        <span class="help-inline">Username is taken</span>
      </div>
    </div>
    <div class="control-group success">
      <label class="control-label" for="inputSuccess">Input with success</label>
      <div class="controls">
        <input type="text" id="inputSuccess">
        <span class="help-inline">Woohoo!</span>
      </div>
    </div>
  </form>

Import CSV to mysql table

To load data from text file or csv file the command is

load data local infile 'file-name.csv'
into table table-name
fields terminated by '' enclosed by '' lines terminated by '\n' (column-name);

In above command, in my case there is only one column to be loaded so there is no "terminated by" and "enclosed by" so I kept it empty else programmer can enter the separating character . for e.g . ,(comma) or " or ; or any thing.

**for people who are using mysql version 5 and above **

Before loading the file into mysql must ensure that below tow line are added in side etc/mysql/my.cnf

to edit my.cnf command is

sudo vi /etc/mysql/my.cnf

[mysqld]  
local-infile

[mysql]  
local-infile  

did you register the component correctly? For recursive components, make sure to provide the "name" option

This is WRONG:

import {
    Tabs,
    Tabpane
  } from 'iview'

This is CORRECT:

import Iview from "iview";
const { Tabs, Tabpane} = Iview;

Convert Java String to sql.Timestamp

Here's the intended way to convert a String to a Date:

String timestamp = "2011-10-02-18.48.05.123";
DateFormat df = new SimpleDateFormat("yyyy-MM-dd-kk.mm.ss.SSS");
Date parsedDate = df.parse(timestamp);

Admittedly, it only has millisecond resolution, but in all services slower than Twitter, that's all you'll need, especially since most machines don't even track down to the actual nanoseconds.

Environment variable substitution in sed

In addition to Norman Ramsey's answer, I'd like to add that you can double-quote the entire string (which may make the statement more readable and less error prone).

So if you want to search for 'foo' and replace it with the content of $BAR, you can enclose the sed command in double-quotes.

sed 's/foo/$BAR/g'
sed "s/foo/$BAR/g"

In the first, $BAR will not expand correctly while in the second $BAR will expand correctly.

How to send HTML email using linux command line

Command Line

Create a file named tmp.html with the following contents:

<b>my bold message</b>

Next, paste the following into the command line (parentheses and all):

(
  echo To: [email protected]
  echo From: [email protected]
  echo "Content-Type: text/html; "
  echo Subject: a logfile
  echo
  cat tmp.html
) | sendmail -t

The mail will be dispatched including a bold message due to the <b> element.

Shell Script

As a script, save the following as email.sh:

ARG_EMAIL_TO="[email protected]"
ARG_EMAIL_FROM="Your Name <[email protected]>"
ARG_EMAIL_SUBJECT="Subject Line"

(
  echo "To: ${ARG_EMAIL_TO}"
  echo "From: ${ARG_EMAIL_FROM}"
  echo "Subject: ${ARG_EMAIL_SUBJECT}"
  echo "Mime-Version: 1.0"
  echo "Content-Type: text/html; charset='utf-8'"
  echo
  cat contents.html
) | sendmail -t

Create a file named contents.html in the same directory as the email.sh script that resembles:

<html><head><title>Subject Line</title></head>
<body>
  <p style='color:red'>HTML Content</p>
</body>
</html>

Run email.sh. When the email arrives, the HTML Content text will appear red.

Related

How to correctly close a feature branch in Mercurial?

It is strange, that no one yet has suggested the most robust way of closing a feature branches... You can just combine merge commit with --close-branch flag (i.e. commit modified files and close the branch simultaneously):

hg up feature-x
hg merge default
hg ci -m "Merge feature-x and close branch" --close-branch
hg branch default -f

So, that is all. No one extra head on revgraph. No extra commit.

Better way to convert an int to a boolean

int i = 0;
bool b = Convert.ToBoolean(i);

HTML/Javascript change div content

Get the id of the div whose content you want to change then assign the text as below:

  var myDiv = document.getElementById("divId");
  myDiv.innerHTML = "Content To Show";

Auto-redirect to another HTML page

<meta http-equiv="refresh" content="5; url=http://example.com/">

How to push both value and key into PHP array

Exactly what Pekka said...

Alternatively, you can probably use array_merge like this if you wanted:

array_merge($_GET, array($rule[0] => $rule[1]));

But I'd prefer Pekka's method probably as it is much simpler.

Using bind variables with dynamic SELECT INTO clause in PL/SQL

No you can't use bind variables that way. In your second example :into_bind in v_query_str is just a placeholder for value of variable v_num_of_employees. Your select into statement will turn into something like:

SELECT COUNT(*) INTO  FROM emp_...

because the value of v_num_of_employees is null at EXECUTE IMMEDIATE.

Your first example presents the correct way to bind the return value to a variable.

Edit

The original poster has edited the second code block that I'm referring in my answer to use OUT parameter mode for v_num_of_employees instead of the default IN mode. This modification makes the both examples functionally equivalent.

android:layout_height 50% of the screen size

This kind of worked for me. Though FAB doesn't float independently, but now it isn't getting pushed down.

Observe the weights given inside the LinearLayout

<LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:id="@+id/andsanddkasd">

            <android.support.v7.widget.RecyclerView
                android:id="@+id/sharedResourcesRecyclerView"
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_weight="4"
                />

            <android.support.design.widget.FloatingActionButton
                android:id="@+id/fab"
                android:layout_width="wrap_content"
                android:layout_height="0dp"
                android:layout_gravity="bottom|right"
                android:src="@android:drawable/ic_input_add"
                android:layout_weight="1"/>

        </LinearLayout>

Hope this helps :)

Embed Youtube video inside an Android app

Pretty simple: Just put it inside a static method.

startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(linkYouTube)));

setting request headers in selenium

You can do it with PhantomJSDriver.

PhantomJSDriver pd = ((PhantomJSDriver) ((WebDriverFacade) getDriver()).getProxiedDriver());
pd.executePhantomJS(
            "this.onResourceRequested = function(request, net) {" +
            "   net.setHeader('header-name', 'header-value')" +
            "};");

Using the request object, you can filter also so the header won't be set for every request.

Pass correct "this" context to setTimeout callback?

There are ready-made shortcuts (syntactic sugar) to the function wrapper @CMS answered with. (Below assuming that the context you want is this.tip.)


ECMAScript 2015 (all common browsers and smartphones, Node.js 5.0.0+)

For virtually all javascript development (in 2020) you can use fat arrow functions, which are part of the ECMAScript 2015 (Harmony/ES6/ES2015) specification.

An arrow function expression (also known as fat arrow function) has a shorter syntax compared to function expressions and lexically binds the this value [...].

(param1, param2, ...rest) => { statements }

In your case, try this:

if (this.options.destroyOnHide) {
    setTimeout(() => { this.tip.destroy(); }, 1000);
}

ECMAScript 5 (older browsers and smartphones, Node.js) and Prototype.js

If you target browser compatible with ECMA-262, 5th edition (ECMAScript 5) or Node.js, which (in 2020) means all common browsers as well as older browsers, you could use Function.prototype.bind. You can optionally pass any function arguments to create partial functions.

fun.bind(thisArg[, arg1[, arg2[, ...]]])

Again, in your case, try this:

if (this.options.destroyOnHide) {
    setTimeout(this.tip.destroy.bind(this.tip), 1000);
}

The same functionality has also been implemented in Prototype (any other libraries?).

Function.prototype.bind can be implemented like this if you want custom backwards compatibility (but please observe the notes).


jQuery

If you are already using jQuery 1.4+, there's a ready-made function for explicitly setting the this context of a function.

jQuery.proxy(): Takes a function and returns a new one that will always have a particular context.

$.proxy(function, context[, additionalArguments])

In your case, try this:

if (this.options.destroyOnHide) {
    setTimeout($.proxy(this.tip.destroy, this.tip), 1000);
}

Underscore.js, lodash

It's available in Underscore.js, as well as lodash, as _.bind(...)1,2

bind Bind a function to an object, meaning that whenever the function is called, the value of this will be the object. Optionally, bind arguments to the function to pre-fill them, also known as partial application.

_.bind(function, object, [*arguments])

In your case, try this:

if (this.options.destroyOnHide) {
    setTimeout(_.bind(this.tip.destroy, this.tip), 1000);
}

PHP: How to use array_filter() to filter array keys?

Here is a more flexible solution using a closure:

$my_array = array("foo" => 1, "hello" => "world");
$allowed = array("foo", "bar");
$result = array_flip(array_filter(array_flip($my_array), function ($key) use ($allowed)
{
    return in_array($key, $allowed);
}));
var_dump($result);

Outputs:

array(1) {
  'foo' =>
  int(1)
}

So in the function, you can do other specific tests.

Detecting locked tables (locked by LOCK TABLE)

You could also get all relevant details from performance_schema:

SELECT
OBJECT_SCHEMA
,OBJECT_NAME
,GROUP_CONCAT(DISTINCT EXTERNAL_LOCK)
FROM performance_schema.table_handles 
WHERE EXTERNAL_LOCK IS NOT NULL

GROUP BY
OBJECT_SCHEMA
,OBJECT_NAME

This works similar as

show open tables WHERE In_use > 0

How to pass query parameters with a routerLink

<a [routerLink]="['../']" [queryParams]="{name: 'ferret'}" [fragment]="nose">Ferret Nose</a>
foo://example.com:8042/over/there?name=ferret#nose
\_/   \______________/\_________/ \_________/ \__/
 |           |            |            |        |
scheme    authority      path        query   fragment

For more info - https://angular.io/guide/router#query-parameters-and-fragments

AngularJS : When to use service instead of factory

There is nothing a Factory cannot do or does better in comparison with a Service. And vice verse. Factory just seems to be more popular. The reason for that is its convenience in handling private/public members. Service would be more clumsy in this regard. When coding a Service you tend to make your object members public via “this” keyword and may suddenly find out that those public members are not visible to private methods (ie inner functions).

var Service = function(){

  //public
  this.age = 13;

  //private
  function getAge(){

    return this.age; //private does not see public

  }

  console.log("age: " + getAge());

};

var s = new Service(); //prints 'age: undefined'

Angular uses the “new” keyword to create a service for you, so the instance Angular passes to the controller will have the same drawback. Of course you may overcome the problem by using this/that:

var Service = function(){

  var that = this;

  //public
  this.age = 13;

  //private
  function getAge(){

    return that.age;

  }

  console.log("age: " + getAge());

};

var s = new Service();// prints 'age: 13'  

But with a large Service constant this\that-ing would make the code poorly readable. Moreover, the Service prototypes will not see private members – only public will be available to them:

var Service = function(){

  var name = "George";

};

Service.prototype.getName = function(){

  return this.name; //will not see a private member

};

var s = new Service();
console.log("name: " + s.getName());//prints 'name: undefined'

Summing it up, using Factory is more convenient. As Factory does not have these drawbacks. I would recommend using it by default.

SQL Server stored procedure Nullable parameter

You can/should set your parameter to value to DBNull.Value;

if (variable == "")
{
     cmd.Parameters.Add("@Param", SqlDbType.VarChar, 500).Value = DBNull.Value;
}
else
{
     cmd.Parameters.Add("@Param", SqlDbType.VarChar, 500).Value = variable;
}

Or you can leave your server side set to null and not pass the param at all.

SSL error SSL3_GET_SERVER_CERTIFICATE:certificate verify failed

Have you tried using the stream_context_set_option() method ?

$context = stream_context_create();
$result = stream_context_set_option($context, 'ssl', 'local_cert', '/etc/ssl/certs/cacert.pem');
$fp = fsockopen($host, $port, $errno, $errstr, 20, $context);

In addition, try file_get_contents() for the pem file, to make sure you have permissions to access it, and make sure the host name matches the certificate.

Ruby: What is the easiest way to remove the first element from an array?

You can use:

a.slice!(0)

slice! generalizes to any index or range.

When to use RabbitMQ over Kafka?

If you have complex routing needs and want a built-in GUI to monitor the broker, then RabbitMQ might be best for your application. Otherwise, if you’re looking for a message broker to handle high throughput and provide access to stream history, Kafka is the likely the better choice.

How do I do multiple CASE WHEN conditions using SQL Server 2008?

Combining all conditions

select  a.* from tbl_Company a

where  a.Company_ID NOT IN (1,2)  

AND (   
        (0 = 
            CASE WHEN (@Fromdate = '' or @Todate='')
                THEN 0 
                ELSE 1  
            END
        )      -- if 0=0 true , if 0=1 fails (filter only when the fromdate and todate is present)
                OR
        (a.Created_Date between @Fromdate and @Todate )                 
    )

increase the java heap size permanently?

what platform are you running?..
if its unix, maybe adding

alias java='java -Xmx1g'  

to .bashrc (or similar) work

edit: Changing XmX to Xmx

Notification not showing in Oreo

If you can't get the push notification in 26+ SDK version?

your solution is here:

public static void showNotification(Context context, String title, String messageBody) {

        boolean isLoggedIn = SessionManager.getInstance().isLoggedIn();
        Log.e(TAG, "User logged in state: " + isLoggedIn);

        Intent intent = null;
        if (isLoggedIn) {
            //goto notification screen
            intent = new Intent(context, MainActivity.class);
            intent.putExtra(Extras.EXTRA_JUMP_TO, DrawerItems.ITEM_NOTIFICATION);
        } else {
            //goto login screen
            intent = new Intent(context, LandingActivity.class);
        }

        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0 /* Request code */, intent, PendingIntent.FLAG_ONE_SHOT);

        //Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        //Bitmap largeIcon = BitmapFactory.decodeResource(getResources(), R.drawable.ic_app_notification_icon);

        String channel_id = createNotificationChannel(context);

        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context, channel_id)
                .setContentTitle(title)
                .setContentText(messageBody)
                .setStyle(new NotificationCompat.BigTextStyle().bigText(messageBody))
                /*.setLargeIcon(largeIcon)*/
                .setSmallIcon(R.drawable.app_logo_color) //needs white icon with transparent BG (For all platforms)
                .setColor(ContextCompat.getColor(context, R.color.colorPrimaryDark))
                .setVibrate(new long[]{1000, 1000})
                .setSound(Settings.System.DEFAULT_NOTIFICATION_URI)
                .setContentIntent(pendingIntent)
                .setPriority(Notification.PRIORITY_HIGH)
                .setAutoCancel(true);

        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify((int) ((new Date(System.currentTimeMillis()).getTime() / 1000L) % Integer.MAX_VALUE) /* ID of notification */, notificationBuilder.build());
    }

public static String createNotificationChannel(Context context) {

        // NotificationChannels are required for Notifications on O (API 26) and above.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

            // The id of the channel.
            String channelId = "Channel_id";

            // The user-visible name of the channel.
            CharSequence channelName = "Application_name";
            // The user-visible description of the channel.
            String channelDescription = "Application_name Alert";
            int channelImportance = NotificationManager.IMPORTANCE_DEFAULT;
            boolean channelEnableVibrate = true;
//            int channelLockscreenVisibility = Notification.;

            // Initializes NotificationChannel.
            NotificationChannel notificationChannel = new NotificationChannel(channelId, channelName, channelImportance);
            notificationChannel.setDescription(channelDescription);
            notificationChannel.enableVibration(channelEnableVibrate);
//            notificationChannel.setLockscreenVisibility(channelLockscreenVisibility);

            // Adds NotificationChannel to system. Attempting to create an existing notification
            // channel with its original values performs no operation, so it's safe to perform the
            // below sequence.
            NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
            assert notificationManager != null;
            notificationManager.createNotificationChannel(notificationChannel);

            return channelId;
        } else {
            // Returns null for pre-O (26) devices.
            return null;
        }
    }

NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context, channel_id)

-> Here you will get push notification using channel_id in your device which is consist 26+ SDK version.

-> Because, the NotificationCompat.Builder(context) is deprecated method now you will use an updated version which is having two parameters one is context, other is channel_id.

-> NotificationCompat.Builder(context, channel_id) updated method. try it.

-> In 26+ SDK version of device you will create channel_id every time.

Java: Insert multiple rows into MySQL with PreparedStatement

You can create a batch by PreparedStatement#addBatch() and execute it by PreparedStatement#executeBatch().

Here's a kickoff example:

public void save(List<Entity> entities) throws SQLException {
    try (
        Connection connection = database.getConnection();
        PreparedStatement statement = connection.prepareStatement(SQL_INSERT);
    ) {
        int i = 0;

        for (Entity entity : entities) {
            statement.setString(1, entity.getSomeProperty());
            // ...

            statement.addBatch();
            i++;

            if (i % 1000 == 0 || i == entities.size()) {
                statement.executeBatch(); // Execute every 1000 items.
            }
        }
    }
}

It's executed every 1000 items because some JDBC drivers and/or DBs may have a limitation on batch length.

See also:

What is the maximum length of data I can put in a BLOB column in MySQL?

May or may not be accurate, but according to this site: http://www.htmlite.com/mysql003.php.

BLOB A string with a maximum length of 65535 characters.

The MySQL manual says:

The maximum size of a BLOB or TEXT object is determined by its type, but the largest value you actually can transmit between the client and server is determined by the amount of available memory and the size of the communications buffers

I think the first site gets their answers from interpreting the MySQL manual, per http://dev.mysql.com/doc/refman/5.0/en/storage-requirements.html

How to get Real IP from Visitor?

This is my function.

benefits :

  • Work if $_SERVER was not available.
  • Filter private and/or reserved IPs;
  • Process all forwarded IPs in X_FORWARDED_FOR
  • Compatible with CloudFlare
  • Can set a default if no valid IP found!
  • Short & Simple !

/**
 * Get real user ip
 *
 * Usage sample:
 * GetRealUserIp();
 * GetRealUserIp('ERROR',FILTER_FLAG_NO_RES_RANGE);
 * 
 * @param string $default default return value if no valid ip found
 * @param int    $filter_options filter options. default is FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE
 *
 * @return string real user ip
 */

function GetRealUserIp($default = NULL, $filter_options = 12582912) {
    $HTTP_X_FORWARDED_FOR = isset($_SERVER)? $_SERVER["HTTP_X_FORWARDED_FOR"]:getenv('HTTP_X_FORWARDED_FOR');
    $HTTP_CLIENT_IP = isset($_SERVER)?$_SERVER["HTTP_CLIENT_IP"]:getenv('HTTP_CLIENT_IP');
    $HTTP_CF_CONNECTING_IP = isset($_SERVER)?$_SERVER["HTTP_CF_CONNECTING_IP"]:getenv('HTTP_CF_CONNECTING_IP');
    $REMOTE_ADDR = isset($_SERVER)?$_SERVER["REMOTE_ADDR"]:getenv('REMOTE_ADDR');

    $all_ips = explode(",", "$HTTP_X_FORWARDED_FOR,$HTTP_CLIENT_IP,$HTTP_CF_CONNECTING_IP,$REMOTE_ADDR");
    foreach ($all_ips as $ip) {
        if ($ip = filter_var($ip, FILTER_VALIDATE_IP, $filter_options))
            break;
    }
    return $ip?$ip:$default;
}

how to bind datatable to datagridview in c#

foreach (DictionaryEntry entry in Hashtable)
{
    datagridviewTZ.Rows.Add(entry.Key.ToString(), entry.Value.ToString());
}

How to convert date to string and to date again?

tl;dr

How to convert date to string and to date again?

LocalDate.now().toString()

2017-01-23

…and…

LocalDate.parse( "2017-01-23" )

java.time

The Question uses troublesome old date-time classes bundled with the earliest versions of Java. Those classes are now legacy, supplanted by the java.time classes built into Java 8, Java 9, and later.

Determining today’s date requires a time zone. For any given moment the date varies around the globe by zone.

If not supplied by you, your JVM’s current default time zone is applied. That default can change at any moment during runtime, and so is unreliable. I suggest you always specify your desired/expected time zone.

ZoneId z = ZoneId.of( "America/Montreal" ) ;
LocalDate ld = LocalDate.now( z ) ;

ISO 8601

Your desired format of YYYY-MM-DD happens to comply with the ISO 8601 standard.

That standard happens to be used by default by the java.time classes when parsing/generating strings. So you can simply call LocalDate::parse and LocalDate::toString without specifying a formatting pattern.

String s = ld.toString() ;

To parse:

LocalDate ld = LocalDate.parse( s ) ;

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

php: check if an array has duplicates

Keep it simple, silly! ;)

Simple OR logic...

function checkDuplicatesInArray($array){
    $duplicates=FALSE;
    foreach($array as $k=>$i){
        if(!isset($value_{$i})){
            $value_{$i}=TRUE;
        }
        else{
            $duplicates|=TRUE;          
        }
    }
    return ($duplicates);
}

Regards!

1030 Got error 28 from storage engine

Check your /backup to see if you can delete an older not needed backup.

Should you use rgba(0, 0, 0, 0) or rgba(255, 255, 255, 0) for transparency in CSS?

I would recommend using rgba(255,255,255,0) because broken (newest) safari thinks that if you are using transparent or rgba(0,0,0,0) in linear-gradent you really mean gray, For more info please head to - What happens in Safari with the transparent color?

Replace the single quote (') character from a string

Do you mean like this?

>>> mystring = "This isn't the right place to have \"'\" (single quotes)"
>>> mystring
'This isn\'t the right place to have "\'" (single quotes)'
>>> newstring = mystring.replace("'", "")
>>> newstring
'This isnt the right place to have "" (single quotes)'

Difference between app.use and app.get in express.js

app.use() is intended for binding middleware to your application. The path is a "mount" or "prefix" path and limits the middleware to only apply to any paths requested that begin with it. It can even be used to embed another application:

// subapp.js
var express = require('express');
var app = modules.exports = express();
// ...
// server.js
var express = require('express');
var app = express();

app.use('/subapp', require('./subapp'));

// ...

By specifying / as a "mount" path, app.use() will respond to any path that starts with /, which are all of them and regardless of HTTP verb used:

  • GET /
  • PUT /foo
  • POST /foo/bar
  • etc.

app.get(), on the other hand, is part of Express' application routing and is intended for matching and handling a specific route when requested with the GET HTTP verb:

  • GET /

And, the equivalent routing for your example of app.use() would actually be:

app.all(/^\/.*/, function (req, res) {
    res.send('Hello');
});

(Update: Attempting to better demonstrate the differences.)

The routing methods, including app.get(), are convenience methods that help you align responses to requests more precisely. They also add in support for features like parameters and next('route').

Within each app.get() is a call to app.use(), so you can certainly do all of this with app.use() directly. But, doing so will often require (probably unnecessarily) reimplementing various amounts of boilerplate code.

Examples:

  • For simple, static routes:

    app.get('/', function (req, res) {
      // ...
    });
    

    vs.

    app.use('/', function (req, res, next) {
      if (req.method !== 'GET' || req.url !== '/')
        return next();
    
      // ...
    });
    
  • With multiple handlers for the same route:

    app.get('/', authorize('ADMIN'), function (req, res) {
      // ...
    });
    

    vs.

    const authorizeAdmin = authorize('ADMIN');
    
    app.use('/', function (req, res, next) {
      if (req.method !== 'GET' || req.url !== '/')
        return next();
    
      authorizeAdmin(req, res, function (err) {
        if (err) return next(err);
    
        // ...
      });
    });
    
  • With parameters:

    app.get('/item/:id', function (req, res) {
      let id = req.params.id;
      // ...
    });
    

    vs.

    const pathToRegExp = require('path-to-regexp');
    
    function prepareParams(matches, pathKeys, previousParams) {
      var params = previousParams || {};
    
      // TODO: support repeating keys...
      matches.slice(1).forEach(function (segment, index) {
        let { name } = pathKeys[index];
        params[name] = segment;
      });
    
      return params;
    }
    
    const itemIdKeys = [];
    const itemIdPattern = pathToRegExp('/item/:id', itemIdKeys);
    
    app.use('/', function (req, res, next) {
      if (req.method !== 'GET') return next();
    
      var urlMatch = itemIdPattern.exec(req.url);
      if (!urlMatch) return next();
    
      if (itemIdKeys && itemIdKeys.length)
        req.params = prepareParams(urlMatch, itemIdKeys, req.params);
    
      let id = req.params.id;
      // ...
    });
    

Note: Express' implementation of these features are contained in its Router, Layer, and Route.

Authenticate Jenkins CI for Github private repository

An alternative to the answer from sergey_mo is to create multiple ssh keys on the jenkins server.

(Though as the first commenter to sergey_mo's answer said, this may end up being more painful than managing a single key-pair.)

JavaScript Editor Plugin for Eclipse

Think that JavaScriptDevelopmentTools might do it. Although, I have eclipse indigo, and I'm pretty sure it does that kind of thing automatically.

How to make div background color transparent in CSS

    /*Fully Opaque*/
    .class-name {
      opacity:1.0;
    }

    /*Translucent*/
    .class-name {
      opacity:0.5;
    }

    /*Transparent*/
    .class-name {
      opacity:0;
    }

    /*or you can use a transparent rgba value like this*/
    .class-name{
      background-color: rgba(255, 242, 0, 0.7);
      }

    /*Note - Opacity value can be anything between 0 to 1;
    Eg(0.1,0.8)etc */

How can I stage and commit all files, including newly added files, using a single command?

I have in my config two aliases:

alias.foo=commit -a -m 'none'
alias.coa=commit -a -m

if I am too lazy I just commit all changes with

git foo

and just to do a quick commit

git coa "my changes are..."

coa stands for "commit all"

How to execute shell command in Javascript

This depends entirely on the JavaScript environment. Please elaborate.

For example, in Windows Scripting, you do things like:

var shell = WScript.CreateObject("WScript.Shell");
shell.Run("command here");

python: how to identify if a variable is an array or a scalar

Combining @jamylak and @jpaddison3's answers together, if you need to be robust against numpy arrays as the input and handle them in the same way as lists, you should use

import numpy as np
isinstance(P, (list, tuple, np.ndarray))

This is robust against subclasses of list, tuple and numpy arrays.

And if you want to be robust against all other subclasses of sequence as well (not just list and tuple), use

import collections
import numpy as np
isinstance(P, (collections.Sequence, np.ndarray))

Why should you do things this way with isinstance and not compare type(P) with a target value? Here is an example, where we make and study the behaviour of NewList, a trivial subclass of list.

>>> class NewList(list):
...     isThisAList = '???'
... 
>>> x = NewList([0,1])
>>> y = list([0,1])
>>> print x
[0, 1]
>>> print y
[0, 1]
>>> x==y
True
>>> type(x)
<class '__main__.NewList'>
>>> type(x) is list
False
>>> type(y) is list
True
>>> type(x).__name__
'NewList'
>>> isinstance(x, list)
True

Despite x and y comparing as equal, handling them by type would result in different behaviour. However, since x is an instance of a subclass of list, using isinstance(x,list) gives the desired behaviour and treats x and y in the same manner.

How to convert milliseconds into a readable date?

No, you'll need to do it manually.

_x000D_
_x000D_
function prettyDate(date) {_x000D_
  var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',_x000D_
                'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];_x000D_
_x000D_
  return months[date.getUTCMonth()] + ' ' + date.getUTCDate() + ', ' + date.getUTCFullYear();_x000D_
}_x000D_
_x000D_
console.log(prettyDate(new Date(1324339200000)));
_x000D_
_x000D_
_x000D_

retrieve links from web page using python and BeautifulSoup

This script does what your looking for, But also resolves the relative links to absolute links.

import urllib
import lxml.html
import urlparse

def get_dom(url):
    connection = urllib.urlopen(url)
    return lxml.html.fromstring(connection.read())

def get_links(url):
    return resolve_links((link for link in get_dom(url).xpath('//a/@href')))

def guess_root(links):
    for link in links:
        if link.startswith('http'):
            parsed_link = urlparse.urlparse(link)
            scheme = parsed_link.scheme + '://'
            netloc = parsed_link.netloc
            return scheme + netloc

def resolve_links(links):
    root = guess_root(links)
    for link in links:
        if not link.startswith('http'):
            link = urlparse.urljoin(root, link)
        yield link  

for link in get_links('http://www.google.com'):
    print link

How to Troubleshoot Intermittent SQL Timeout Errors

I suggest you have a deep look at the super cool SQL Server's Dynamic Management Views feature:

Dynamic management views and functions return server state information that can be used to monitor the health of a server instance, diagnose problems, and tune performance.

This article is a good start with DMVs, although it was written for SQL 2005 (DMVs feature first appearance): Troubleshooting Performance Problems in SQL Server 2005, especially the 'blocking' chapters.

__FILE__ macro shows full path

If you ended up on this page looking for a way to remove absolute source path that is pointing to ugly build location from the binary that you are shipping, below might suit your needs.

Although this doesn't produce exactly the answer that the author has expressed his wish for since it assumes the use of CMake, it gets pretty close. It's a pity this wasn't mentioned earlier by anyone as it would have saved me loads of time.

OPTION(CMAKE_USE_RELATIVE_PATHS "If true, cmake will use relative paths" ON)

Setting above variable to ON will generate build command in the format:

cd /ugly/absolute/path/to/project/build/src && 
    gcc <.. other flags ..> -c ../../src/path/to/source.c

As a result, __FILE__ macro will resolve to ../../src/path/to/source.c

CMake documentation

Beware of the warning on the documentation page though:

Use relative paths (May not work!).

It is not guaranteed to work in all cases, but worked in mine - CMake 3.13 + gcc 4.5

Server.UrlEncode vs. HttpUtility.UrlEncode

I had significant headaches with these methods before, I recommend you avoid any variant of UrlEncode, and instead use Uri.EscapeDataString - at least that one has a comprehensible behavior.

Let's see...

HttpUtility.UrlEncode(" ") == "+" //breaks ASP.NET when used in paths, non-
                                  //standard, undocumented.
Uri.EscapeUriString("a?b=e") == "a?b=e" // makes sense, but rarely what you
                                        // want, since you still need to
                                        // escape special characters yourself

But my personal favorite has got to be HttpUtility.UrlPathEncode - this thing is really incomprehensible. It encodes:

  • " " ==> "%20"
  • "100% true" ==> "100%%20true" (ok, your url is broken now)
  • "test A.aspx#anchor B" ==> "test%20A.aspx#anchor%20B"
  • "test A.aspx?hmm#anchor B" ==> "test%20A.aspx?hmm#anchor B" (note the difference with the previous escape sequence!)

It also has the lovelily specific MSDN documentation "Encodes the path portion of a URL string for reliable HTTP transmission from the Web server to a client." - without actually explaining what it does. You are less likely to shoot yourself in the foot with an Uzi...

In short, stick to Uri.EscapeDataString.

Fastest way to ping a network range and return responsive hosts?

You should use NMAP:

nmap -T5 -sP 192.168.0.0-255

Where/how can I download (and install) the Microsoft.Jet.OLEDB.4.0 for Windows 8, 64 bit?

Make sure to target x86 on your project in Visual Studio. This should fix your trouble.

Decode Hex String in Python 3

Something like:

>>> bytes.fromhex('4a4b4c').decode('utf-8')
'JKL'

Just put the actual encoding you are using.

Reading Excel files from C#

Koogra is an open-source component written in C# that reads and writes Excel files.

how to make window.open pop up Modal?

Modal Window using ExtJS approach.

In Main Window

<html>
<link rel="stylesheet" href="ext.css" type="text/css">
<head>    
<script type="text/javascript" src="ext-all.js"></script>

function openModalDialog() {
    Ext.onReady(function() {
        Ext.create('Ext.window.Window', {
        title: 'Hello',
        height: Ext.getBody().getViewSize().height*0.8,
        width: Ext.getBody().getViewSize().width*0.8,
        minWidth:'730',
        minHeight:'450',
        layout: 'fit',
        itemId : 'popUpWin',        
        modal:true,
        shadow:false,
        resizable:true,
        constrainHeader:true,
        items: [{
            xtype: 'box',
            autoEl: {
                     tag: 'iframe',
                     src: '2.html',
                     frameBorder:'0'
            }
        }]
        }).show();
  });
}
function closeExtWin(isSubmit) {
     Ext.ComponentQuery.query('#popUpWin')[0].close();
     if (isSubmit) {
          document.forms[0].userAction.value = "refresh";
          document.forms[0].submit();
    }
}
</head>
<body>
   <form action="abc.jsp">
   <a href="javascript:openModalDialog()"> Click to open dialog </a>
   </form>
</body>
</html>

In popupWindow 2.html

<html>
<head>
<script type="text\javascript">
function doSubmit(action) {
     if (action == 'save') {
         window.parent.closeExtWin(true);
     } else {
         window.parent.closeExtWin(false);
     }   
}
</script>
</head>
<body>
    <a href="javascript:doSubmit('save');" title="Save">Save</a>
    <a href="javascript:doSubmit('cancel');" title="Cancel">Cancel</a>
</body>
</html>

How do I change TextView Value inside Java Code?

First we need to find a Button:

Button mButton = (Button) findViewById(R.id.my_button);

After that, you must implement View.OnClickListener and there you should find the TextView and execute the method setText:

mButton.setOnClickListener(new View.OnClickListener {
    public void onClick(View v) {
        final TextView mTextView = (TextView) findViewById(R.id.my_text_view);
        mTextView.setText("Some Text");
    }
});

nodejs get file name from absolute path?

So Nodejs comes with the default global variable called '__fileName' that holds the current file being executed My advice is to pass the __fileName to a service from any file , so that the retrieval of the fileName is made dynamic

Below, I make use of the fileName string and then split it based on the path.sep. Note path.sep avoids issues with posix file seperators and windows file seperators (issues with '/' and '\'). It is much cleaner. Getting the substring and getting only the last seperated name and subtracting it with the actulal length by 3 speaks for itself.

You can write a service like this (Note this is in typescript , but you can very well write it in js )

export class AppLoggingConstants {

    constructor(){

    }
      // Here make sure the fileName param is actually '__fileName'
    getDefaultMedata(fileName: string, methodName: string) {
        const appName = APP_NAME;
        const actualFileName = fileName.substring(fileName.lastIndexOf(path.sep)+1, fileName.length - 3);
        //const actualFileName = fileName;
     return appName+ ' -- '+actualFileName;
    }


}

export const AppLoggingConstantsInstance = new AppLoggingConstants();

How to set top position using jquery

You could also do

   var x = $('#element').height();   // or any changing value

   $('selector').css({'top' : x + 'px'});

OR

You can use directly

$('#element').css( "height" )

The difference between .css( "height" ) and .height() is that the latter returns a unit-less pixel value (for example, 400) while the former returns a value with units intact (for example, 400px). The .height() method is recommended when an element's height needs to be used in a mathematical calculation. jquery doc

Execute multiple command lines with the same process using .NET

You could also tell MySQL to execute the commands in the given file, like so:

mysql --user=root --password=sa casemanager < CaseManager.sql

How to sort an object array by date property?

Adding absolute will give better results

var datesArray =[
      {"some":"data1","date": "2018-06-30T13:40:31.493Z"},
      {"some":"data2","date": "2018-07-04T13:40:31.493Z"},
      {"some":"data3","date": "2018-06-27T13:40:54.394Z"}
   ]

var sortedJsObjects = datesArray.sort(function(a,b){ 
    return Math.abs(new Date(a.date) - new Date(b.date)) 
});

What is a software framework?

A framework provides functionalities/solution to the particular problem area.
Definition from wiki:

A software framework, in computer programming, is an abstraction in which common code providing generic functionality can be selectively overridden or specialized by user code providing specific functionality. Frameworks are a special case of software libraries in that they are reusable abstractions of code wrapped in a well-defined Application programming interface (API), yet they contain some key distinguishing features that separate them from normal libraries.

Change the "From:" address in Unix "mail"

Here are some options:

  • If you have privelige enough, configure sendmail to do rewrites with the generics table

  • Write the entire header yourself (or mail it to yourself, save the entire message with all headers, and re-edit, and send it with rmail from the command line

  • Send directly with sendmail, use the "-f" command line flag and don't include your "From:" line in your message

These aren't all exactly the same, but I'll leave it to you look into it further.

On my portable, I have sendmail authenticating as a client to an outgoing mail server and I use generics to make returning mail come to another account. It works like a charm. I aggregate incoming mail with fetchmail.

Best XML parser for Java

I have found dom4j to be the tool for working with XML. Especially compared to Xerces.

Using Python's list index() method on a list of tuples or objects?

Inspired by this question, I found this quite elegant:

>>> tuple_list = [("pineapple", 5), ("cherry", 7), ("kumquat", 3), ("plum", 11)]
>>> next(i for i, t in enumerate(tuple_list) if t[1] == 7)
1
>>> next(i for i, t in enumerate(tuple_list) if t[0] == "kumquat")
2

Using ExcelDataReader to read Excel data starting from a particular cell

public static DataTable ConvertExcelToDataTable(string filePath, bool isXlsx = false)
{
    System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
    //open file and returns as Stream
        using (var stream = File.Open(filePath, FileMode.Open, FileAccess.Read))
        {
                using (var reader = ExcelReaderFactory.CreateReader(stream))
                {

                    var conf = new ExcelDataSetConfiguration
                    {
                        ConfigureDataTable = _ => new ExcelDataTableConfiguration
                        {
                            UseHeaderRow = true
                        }
                    };

                    var dataSet = reader.AsDataSet(conf);

                    // Now you can get data from each sheet by its index or its "name"
                    var dataTable = dataSet.Tables[0];

                    Console.WriteLine("Total no of rows  " + dataTable.Rows.Count);
                    Console.WriteLine("Total no of Columns  " + dataTable.Columns.Count);

                    return dataTable;

                }

        }
   
}

MySQL update CASE WHEN/THEN/ELSE

If id is sequential starting at 1, the simplest (and quickest) would be:

UPDATE `table` 
SET uid = ELT(id, 2952, 4925, 1592) 
WHERE id IN (1,2,3)

As ELT() returns the Nth element of the list of strings: str1 if N = 1, str2 if N = 2, and so on. Returns NULL if N is less than 1 or greater than the number of arguments.

Clearly, the above code only works if id is 1, 2, or 3. If id was 10, 20, or 30, either of the following would work:

UPDATE `table` 
SET uid = CASE id 
WHEN 10 THEN 2952 
WHEN 20 THEN 4925 
WHEN 30 THEN 1592 END CASE 
WHERE id IN (10, 20, 30)

or the simpler:

UPDATE `table` 
SET uid = ELT(FIELD(id, 10, 20, 30), 2952, 4925, 1592) 
WHERE id IN (10, 20, 30)

As FIELD() returns the index (position) of str in the str1, str2, str3, ... list. Returns 0 if str is not found.

How good is Java's UUID.randomUUID?

The original generation scheme for UUIDs was to concatenate the UUID version with the MAC address of the computer that is generating the UUID, and with the number of 100-nanosecond intervals since the adoption of the Gregorian calendar in the West. By representing a single point in space (the computer) and time (the number of intervals), the chance of a collision in values is effectively nil.

Java Generics With a Class & an Interface - Together

You can't do it with "anonymous" type parameters (ie, wildcards that use ?), but you can do it with "named" type parameters. Simply declare the type parameter at method or class level.

import java.util.List;
interface A{}
interface B{}
public class Test<E extends B & A, T extends List<E>> {
    T t;
}

Using an integer as a key in an associative array in JavaScript

Try using an Object, not an Array:

var test = new Object(); test[2300] = 'Some string';

How to switch Python versions in Terminal?

pyenv is a 3rd party version manager which is super commonly used (18k stars, 1.6k forks) and exactly what I looked for when I came to this question.

Install pyenv.

Usage

$ pyenv install --list
Available versions:
  2.1.3
  [...]
  3.8.1
  3.9-dev
  activepython-2.7.14
  activepython-3.5.4
  activepython-3.6.0
  anaconda-1.4.0
  [... a lot more; including anaconda, miniconda, activepython, ironpython, pypy, stackless, ....]

$ pyenv install 3.8.1
Downloading Python-3.8.1.tar.xz...
-> https://www.python.org/ftp/python/3.8.1/Python-3.8.1.tar.xz
Installing Python-3.8.1...
Installed Python-3.8.1 to /home/moose/.pyenv/versions/3.8.1

$ pyenv versions
* system (set by /home/moose/.pyenv/version)
  2.7.16
  3.5.7
  3.6.9
  3.7.4
  3.8-dev

$ python --version
Python 2.7.17
$ pip --version
pip 19.3.1 from /home/moose/.local/lib/python3.6/site-packages/pip (python 3.6)

$ mkdir pyenv-experiment && echo "3.8.1" > "pyenv-experiment/.python-version"
$ cd pyenv-experiment

$ python --version
Python 3.8.1
$ pip --version
pip 19.2.3 from /home/moose/.pyenv/versions/3.8.1/lib/python3.8/site-packages/pip (python 3.8)

How to assign the output of a command to a Makefile variable

In the below example, I have stored the Makefile folder path to LOCAL_PKG_DIR and then use LOCAL_PKG_DIR variable in targets.

Makefile:

LOCAL_PKG_DIR := $(shell eval pwd)

.PHONY: print
print:
    @echo $(LOCAL_PKG_DIR)

Terminal output:

$ make print
/home/amrit/folder

Creating lowpass filter in SciPy - understanding methods and units

A few comments:

  • The Nyquist frequency is half the sampling rate.
  • You are working with regularly sampled data, so you want a digital filter, not an analog filter. This means you should not use analog=True in the call to butter, and you should use scipy.signal.freqz (not freqs) to generate the frequency response.
  • One goal of those short utility functions is to allow you to leave all your frequencies expressed in Hz. You shouldn't have to convert to rad/sec. As long as you express your frequencies with consistent units, the scaling in the utility functions takes care of the normalization for you.

Here's my modified version of your script, followed by the plot that it generates.

import numpy as np
from scipy.signal import butter, lfilter, freqz
import matplotlib.pyplot as plt


def butter_lowpass(cutoff, fs, order=5):
    nyq = 0.5 * fs
    normal_cutoff = cutoff / nyq
    b, a = butter(order, normal_cutoff, btype='low', analog=False)
    return b, a

def butter_lowpass_filter(data, cutoff, fs, order=5):
    b, a = butter_lowpass(cutoff, fs, order=order)
    y = lfilter(b, a, data)
    return y


# Filter requirements.
order = 6
fs = 30.0       # sample rate, Hz
cutoff = 3.667  # desired cutoff frequency of the filter, Hz

# Get the filter coefficients so we can check its frequency response.
b, a = butter_lowpass(cutoff, fs, order)

# Plot the frequency response.
w, h = freqz(b, a, worN=8000)
plt.subplot(2, 1, 1)
plt.plot(0.5*fs*w/np.pi, np.abs(h), 'b')
plt.plot(cutoff, 0.5*np.sqrt(2), 'ko')
plt.axvline(cutoff, color='k')
plt.xlim(0, 0.5*fs)
plt.title("Lowpass Filter Frequency Response")
plt.xlabel('Frequency [Hz]')
plt.grid()


# Demonstrate the use of the filter.
# First make some data to be filtered.
T = 5.0         # seconds
n = int(T * fs) # total number of samples
t = np.linspace(0, T, n, endpoint=False)
# "Noisy" data.  We want to recover the 1.2 Hz signal from this.
data = np.sin(1.2*2*np.pi*t) + 1.5*np.cos(9*2*np.pi*t) + 0.5*np.sin(12.0*2*np.pi*t)

# Filter the data, and plot both the original and filtered signals.
y = butter_lowpass_filter(data, cutoff, fs, order)

plt.subplot(2, 1, 2)
plt.plot(t, data, 'b-', label='data')
plt.plot(t, y, 'g-', linewidth=2, label='filtered data')
plt.xlabel('Time [sec]')
plt.grid()
plt.legend()

plt.subplots_adjust(hspace=0.35)
plt.show()

lowpass example

How to fire AJAX request Periodically?

Yes, you could use either the JavaScript setTimeout() method or setInterval() method to invoke the code that you would like to run. Here's how you might do it with setTimeout:

function executeQuery() {
  $.ajax({
    url: 'url/path/here',
    success: function(data) {
      // do something with the return value here if you like
    }
  });
  setTimeout(executeQuery, 5000); // you could choose not to continue on failure...
}

$(document).ready(function() {
  // run the first time; all subsequent calls will take care of themselves
  setTimeout(executeQuery, 5000);
});

Grep for beginning and end of line?

It looks like you were on the right track... The ^ character matches beginning-of-line, and $ matches end-of-line. Jonathan's pattern will work for you... just wanted to give you the explanation behind it

MySQL 1062 - Duplicate entry '0' for key 'PRIMARY'

Set AUTO_INCREMENT to PRIMARY KEY

How to get all the AD groups for a particular user?

Here is the code that worked for me:

public ArrayList GetBBGroups(WindowsIdentity identity)
{
    ArrayList groups = new ArrayList();

    try
    {
        String userName = identity.Name;
        int pos = userName.IndexOf(@"\");
        if (pos > 0) userName = userName.Substring(pos + 1);

        PrincipalContext domain = new PrincipalContext(ContextType.Domain, "riomc.com");
        UserPrincipal user = UserPrincipal.FindByIdentity(domain, IdentityType.SamAccountName, userName);

        DirectoryEntry de = new DirectoryEntry("LDAP://RIOMC.com");
        DirectorySearcher search = new DirectorySearcher(de);
        search.Filter = "(&(objectClass=group)(member=" + user.DistinguishedName + "))";
        search.PropertiesToLoad.Add("samaccountname");
        search.PropertiesToLoad.Add("cn");

        String name;
        SearchResultCollection results = search.FindAll();
        foreach (SearchResult result in results)
        {
            name = (String)result.Properties["samaccountname"][0];
            if (String.IsNullOrEmpty(name))
            {
                name = (String)result.Properties["cn"][0];
            }
            GetGroupsRecursive(groups, de, name);
        }
    }
    catch
    {
        // return an empty list...
    }

    return groups;
}

public void GetGroupsRecursive(ArrayList groups, DirectoryEntry de, String dn)
{
    DirectorySearcher search = new DirectorySearcher(de);
    search.Filter = "(&(objectClass=group)(|(samaccountname=" + dn + ")(cn=" + dn + ")))";
    search.PropertiesToLoad.Add("memberof");

    String group, name;
    SearchResult result = search.FindOne();
    if (result == null) return;

    group = @"RIOMC\" + dn;
    if (!groups.Contains(group))
    {
        groups.Add(group);
    }
    if (result.Properties["memberof"].Count == 0) return;
    int equalsIndex, commaIndex;
    foreach (String dn1 in result.Properties["memberof"])
    {
        equalsIndex = dn1.IndexOf("=", 1);
        if (equalsIndex > 0)
        {
            commaIndex = dn1.IndexOf(",", equalsIndex + 1);
            name = dn1.Substring(equalsIndex + 1, commaIndex - equalsIndex - 1);
            GetGroupsRecursive(groups, de, name);
        }
    }
}

I measured it's performance in a loop of 200 runs against the code that uses the AttributeValuesMultiString recursive method; and it worked 1.3 times faster. It might be so because of our AD settings. Both snippets gave the same result though.

PHP mail function doesn't complete sending of e-mail

If you're stuck with an app hosted on Hostgator, this is what solved my problem. Thanks a lot to the guy who posted the detailed solution. In case the link goes offline one day, there you have the summary:

  • Look for the sendmail path in your server. A simple way to check it, is to temporarily write the following code in a page which only you will access, to read the generated info: <?php phpinfo(); ?>. Open this page, and look for sendmail path. (Then, don't forget to remove this code!)
  • Problem and fix: if your sendmail path is saying only -t -i, then edit your server's php.ini and add the following line: sendmail_path = /usr/sbin/sendmail -t -i;

But, after being able to send mail with PHP mail() function, I learned that it sends not authenticated email, what created another issue. The emails were all falling in my Hotmail's junk mail box, and some emails were never delivered, which I guess is related to the fact that they are not authenticated. That's why I decided to switch from mail() to PHPMailer with SMTP, after all.

printing all contents of array in C#

this is the easiest way that you could print the String by using array!!!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace arraypracticeforstring
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] arr = new string[3] { "Snehal", "Janki", "Thakkar" };

            foreach (string item in arr)
            {
                Console.WriteLine(item.ToString());
            }
            Console.ReadLine();
        }
    }
}

#pragma mark in Swift?

I think Extensions is a better way instead of #pragma mark.

The Code before using Extensions:

class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
    ...

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        ...
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        ...
    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        ...
    }
}

The code after using Extensions:

class ViewController: UIViewController {
    ...
}

extension ViewController: UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        ...
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        ...
    }
}

extension ViewController: UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
       ...
    }
}

How to cancel an $http request in AngularJS?

If you want to cancel pending requests on stateChangeStart with ui-router, you can use something like this:

// in service

                var deferred = $q.defer();
                var scope = this;
                $http.get(URL, {timeout : deferred.promise, cancel : deferred}).success(function(data){
                    //do something
                    deferred.resolve(dataUsage);
                }).error(function(){
                    deferred.reject();
                });
                return deferred.promise;

// in UIrouter config

$rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {
    //To cancel pending request when change state
       angular.forEach($http.pendingRequests, function(request) {
          if (request.cancel && request.timeout) {
             request.cancel.resolve();
          }
       });
    });

Hide Utility Class Constructor : Utility classes should not have a public or default constructor

I don't know Sonar, but I suspect it's looking for a private constructor:

private FilePathHelper() {
    // No-op; won't be called
}

Otherwise the Java compiler will provide a public parameterless constructor, which you really don't want.

(You should also make the class final, although other classes wouldn't be able to extend it anyway due to it only having a private constructor.)

splitting a number into the integer and decimal parts

We can use a not famous built-in function; divmod:

>>> s = 1234.5678
>>> i, d = divmod(s, 1)
>>> i
1234.0
>>> d
0.5678000000000338

DNS caching in linux

You have here available an example of DNS Caching in Debian using dnsmasq.

Configuration summary:

/etc/default/dnsmasq

# Ensure you add this line
DNSMASQ_OPTS="-r /etc/resolv.dnsmasq"

/etc/resolv.dnsmasq

# Your preferred servers
nameserver 1.1.1.1
nameserver 8.8.8.8
nameserver 2001:4860:4860::8888

/etc/resolv.conf

nameserver 127.0.0.1

Then just restart dnsmasq.

Benchmark test using DNS 1.1.1.1:

for i in {1..100}; do time dig slashdot.org @1.1.1.1; done 2>&1 | grep ^real | sed -e s/.*m// | awk '{sum += $1} END {print sum / NR}'

Benchmark test using you local cached DNS:

for i in {1..100}; do time dig slashdot.org; done 2>&1 | grep ^real | sed -e s/.*m// | awk '{sum += $1} END {print sum / NR}'

How to focus on a form input text field on page load using jQuery?

Sorry for bumping an old question. I found this via google.

Its also worth noting that its possible to use more than one selector, thus you can target any form element, and not just one specific type.

eg.

$('#myform input,#myform textarea').first().focus();

This will focus the first input or textarea it finds, and of course you can add other selectors into the mix as well. Handy if you can't be certain of a specific element type being first, or if you want something a bit general/reusable.

Getting time elapsed in Objective-C

NSDate *start = [NSDate date];
// do stuff...
NSTimeInterval timeInterval = [start timeIntervalSinceNow];

timeInterval is the difference between start and now, in seconds, with sub-millisecond precision.

Button Width Match Parent

Container(
  width: double.infinity,
  child: RaisedButton(...),
),

HTML5 Pre-resize images before uploading

If you don't want to reinvent the wheel you may try plupload.com

How do I pass a variable by reference?

I found the other answers rather long and complicated, so I created this simple diagram to explain the way Python treats variables and parameters. enter image description here

Blur effect on a div element

Try using this library: https://github.com/jakiestfu/Blur.js-II

That should do it for ya.

jQuery Scroll To bottom of the page

function scrollToBottom() {
     $("#mContainer").animate({ scrollTop: $("#mContainer")[0].scrollHeight }, 1000);
}

This is the solution work from me and you find, I'm sure

How to Multi-thread an Operation Within a Loop in Python

Edit 2018-02-06: revision based on this comment

Edit: forgot to mention that this works on Python 2.7.x

There's multiprocesing.pool, and the following sample illustrates how to use one of them:

from multiprocessing.pool import ThreadPool as Pool
# from multiprocessing import Pool

pool_size = 5  # your "parallelness"

# define worker function before a Pool is instantiated
def worker(item):
    try:
        api.my_operation(item)
    except:
        print('error with item')

pool = Pool(pool_size)

for item in items:
    pool.apply_async(worker, (item,))

pool.close()
pool.join()

Now if you indeed identify that your process is CPU bound as @abarnert mentioned, change ThreadPool to the process pool implementation (commented under ThreadPool import). You can find more details here: http://docs.python.org/2/library/multiprocessing.html#using-a-pool-of-workers

How to Calculate Execution Time of a Code Snippet in C++

It is better to run the inner loop several times with the performance timing only once and average by dividing inner loop repetitions than to run the whole thing (loop + performance timing) several times and average. This will reduce the overhead of the performance timing code vs your actual profiled section.

Wrap your timer calls for the appropriate system. For Windows, QueryPerformanceCounter is pretty fast and "safe" to use.

You can use "rdtsc" on any modern X86 PC as well but there may be issues on some multicore machines (core hopping may change timer) or if you have speed-step of some sort turned on.

Find Oracle JDBC driver in Maven repository

Some Oracle Products support publishing maven artifacts to a local repository. The products have a plugin/maven directory which contains descriptions where to find those artifacts and where to store them. There is a Plugin from Oracle which will actually do the upload.

See: http://docs.oracle.com/middleware/1212/core/MAVEN/config_maven.htm

One of the products which may ship OJDBC in this way is the WLS, it uses however quite strange coordinates:

<groupId>com.oracle.weblogic</groupId>
<artifactId>ojdbc6</artifactId>
<version>12.1.2-0-0</version>

Unable instantiate android.gms.maps.MapFragment

I've this issue i just update Google Play services and make sure that you are adding the google-play-service-lib project as dependency, it's working now without any code change but i still getting "The Google Play services resources were not found. Check your project configuration to ensure that the resources are included." but this only happens when you have setMyLocationEnabled(true), anyone knows why?

How can I change the font size using seaborn FacetGrid?

For the legend, you can use this

plt.setp(g._legend.get_title(), fontsize=20)

Where g is your facetgrid object returned after you call the function making it.

Difference Between Select and SelectMany

enter image description here

var players = db.SoccerTeams.Where(c => c.Country == "Spain")
                            .SelectMany(c => c.players);

foreach(var player in players)
{
    Console.WriteLine(player.LastName);
}
  1. De Gea
  2. Alba
  3. Costa
  4. Villa
  5. Busquets

...

Generate an integer sequence in MySQL

The simplest way to do this is:

SET @seq := 0;
SELECT @seq := FLOOR(@seq + 1) AS sequence, yt.*
FROM your_table yt;

or in one query:

SELECT @seq := FLOOR(@seq + 1) AS sequence, yt.*
FROM (SELECT @seq := 0) s, your_table yt;

The FLOOR() function is used here to get an INTEGER in place of a FLOAT. Sometimes it is needed.

My answer was inspired by David Poor answer. Thanks David!

How to construct a relative path in Java from two absolute paths (or URLs)?

At the time of writing (June 2010), this was the only solution that passed my test cases. I can't guarantee that this solution is bug-free, but it does pass the included test cases. The method and tests I've written depend on the FilenameUtils class from Apache commons IO.

The solution was tested with Java 1.4. If you're using Java 1.5 (or higher) you should consider replacing StringBuffer with StringBuilder (if you're still using Java 1.4 you should consider a change of employer instead).

import java.io.File;
import java.util.regex.Pattern;

import org.apache.commons.io.FilenameUtils;

public class ResourceUtils {

    /**
     * Get the relative path from one file to another, specifying the directory separator. 
     * If one of the provided resources does not exist, it is assumed to be a file unless it ends with '/' or
     * '\'.
     * 
     * @param targetPath targetPath is calculated to this file
     * @param basePath basePath is calculated from this file
     * @param pathSeparator directory separator. The platform default is not assumed so that we can test Unix behaviour when running on Windows (for example)
     * @return
     */
    public static String getRelativePath(String targetPath, String basePath, String pathSeparator) {

        // Normalize the paths
        String normalizedTargetPath = FilenameUtils.normalizeNoEndSeparator(targetPath);
        String normalizedBasePath = FilenameUtils.normalizeNoEndSeparator(basePath);

        // Undo the changes to the separators made by normalization
        if (pathSeparator.equals("/")) {
            normalizedTargetPath = FilenameUtils.separatorsToUnix(normalizedTargetPath);
            normalizedBasePath = FilenameUtils.separatorsToUnix(normalizedBasePath);

        } else if (pathSeparator.equals("\\")) {
            normalizedTargetPath = FilenameUtils.separatorsToWindows(normalizedTargetPath);
            normalizedBasePath = FilenameUtils.separatorsToWindows(normalizedBasePath);

        } else {
            throw new IllegalArgumentException("Unrecognised dir separator '" + pathSeparator + "'");
        }

        String[] base = normalizedBasePath.split(Pattern.quote(pathSeparator));
        String[] target = normalizedTargetPath.split(Pattern.quote(pathSeparator));

        // First get all the common elements. Store them as a string,
        // and also count how many of them there are.
        StringBuffer common = new StringBuffer();

        int commonIndex = 0;
        while (commonIndex < target.length && commonIndex < base.length
                && target[commonIndex].equals(base[commonIndex])) {
            common.append(target[commonIndex] + pathSeparator);
            commonIndex++;
        }

        if (commonIndex == 0) {
            // No single common path element. This most
            // likely indicates differing drive letters, like C: and D:.
            // These paths cannot be relativized.
            throw new PathResolutionException("No common path element found for '" + normalizedTargetPath + "' and '" + normalizedBasePath
                    + "'");
        }   

        // The number of directories we have to backtrack depends on whether the base is a file or a dir
        // For example, the relative path from
        //
        // /foo/bar/baz/gg/ff to /foo/bar/baz
        // 
        // ".." if ff is a file
        // "../.." if ff is a directory
        //
        // The following is a heuristic to figure out if the base refers to a file or dir. It's not perfect, because
        // the resource referred to by this path may not actually exist, but it's the best I can do
        boolean baseIsFile = true;

        File baseResource = new File(normalizedBasePath);

        if (baseResource.exists()) {
            baseIsFile = baseResource.isFile();

        } else if (basePath.endsWith(pathSeparator)) {
            baseIsFile = false;
        }

        StringBuffer relative = new StringBuffer();

        if (base.length != commonIndex) {
            int numDirsUp = baseIsFile ? base.length - commonIndex - 1 : base.length - commonIndex;

            for (int i = 0; i < numDirsUp; i++) {
                relative.append(".." + pathSeparator);
            }
        }
        relative.append(normalizedTargetPath.substring(common.length()));
        return relative.toString();
    }


    static class PathResolutionException extends RuntimeException {
        PathResolutionException(String msg) {
            super(msg);
        }
    }    
}

The test cases that this passes are

public void testGetRelativePathsUnix() {
    assertEquals("stuff/xyz.dat", ResourceUtils.getRelativePath("/var/data/stuff/xyz.dat", "/var/data/", "/"));
    assertEquals("../../b/c", ResourceUtils.getRelativePath("/a/b/c", "/a/x/y/", "/"));
    assertEquals("../../b/c", ResourceUtils.getRelativePath("/m/n/o/a/b/c", "/m/n/o/a/x/y/", "/"));
}

public void testGetRelativePathFileToFile() {
    String target = "C:\\Windows\\Boot\\Fonts\\chs_boot.ttf";
    String base = "C:\\Windows\\Speech\\Common\\sapisvr.exe";

    String relPath = ResourceUtils.getRelativePath(target, base, "\\");
    assertEquals("..\\..\\Boot\\Fonts\\chs_boot.ttf", relPath);
}

public void testGetRelativePathDirectoryToFile() {
    String target = "C:\\Windows\\Boot\\Fonts\\chs_boot.ttf";
    String base = "C:\\Windows\\Speech\\Common\\";

    String relPath = ResourceUtils.getRelativePath(target, base, "\\");
    assertEquals("..\\..\\Boot\\Fonts\\chs_boot.ttf", relPath);
}

public void testGetRelativePathFileToDirectory() {
    String target = "C:\\Windows\\Boot\\Fonts";
    String base = "C:\\Windows\\Speech\\Common\\foo.txt";

    String relPath = ResourceUtils.getRelativePath(target, base, "\\");
    assertEquals("..\\..\\Boot\\Fonts", relPath);
}

public void testGetRelativePathDirectoryToDirectory() {
    String target = "C:\\Windows\\Boot\\";
    String base = "C:\\Windows\\Speech\\Common\\";
    String expected = "..\\..\\Boot";

    String relPath = ResourceUtils.getRelativePath(target, base, "\\");
    assertEquals(expected, relPath);
}

public void testGetRelativePathDifferentDriveLetters() {
    String target = "D:\\sources\\recovery\\RecEnv.exe";
    String base = "C:\\Java\\workspace\\AcceptanceTests\\Standard test data\\geo\\";

    try {
        ResourceUtils.getRelativePath(target, base, "\\");
        fail();

    } catch (PathResolutionException ex) {
        // expected exception
    }
}

Spring Boot Remove Whitelabel Error Page

I had a similar issue WhiteLabel Error message on my Angular SPA whenever I did a refresh.

The fix was to create a controller that implements ErrorController but instead of returning a String, I had to return a ModelAndView object that forwards to /

@CrossOrigin
@RestController
public class IndexController implements ErrorController {
    
    private static final String PATH = "/error";
    
    @RequestMapping(value = PATH)
    public ModelAndView saveLeadQuery() {           
        return new ModelAndView("forward:/");
    }

    @Override
    public String getErrorPath() {
        return PATH;
    }
}

Use Awk to extract substring

Or just use cut:

echo aaa0.bbb.ccc | cut -d'.' -f1

jQuery append and remove dynamic table row

Change ID to class :

$("#customFields").append('<tr valign="top"><th scope="row"><label for="customFieldName">Custom Field</label></th><td><input type="text" class="code" id="customFieldName" name="customFieldName[]" value="" placeholder="Input Name" /> &nbsp; <input type="text" class="code" id="customFieldValue" name="customFieldValue[]" value="" placeholder="Input Value" /> &nbsp; <a href="javascript:void(0);" class="remCF">Remove</a></td></tr>');

$(".remCF").on('click',function(){
            $(this).parent().parent().remove();
        });

http://jsfiddle.net/7BHDm/1/

R * not meaningful for factors ERROR

new[,2] is a factor, not a numeric vector. Transform it first

new$MY_NEW_COLUMN <-as.numeric(as.character(new[,2])) * 5

node.js, socket.io with SSL

If your server certificated file is not trusted, (for example, you may generate the keystore by yourself with keytool command in java), you should add the extra option rejectUnauthorized

var socket = io.connect('https://localhost', {rejectUnauthorized: false});

Update a submodule to the latest commit

A few of the other answers recommend merging/committing within the submodule's directory, which IMO can become a little messy.

Assuming the remote server is named origin and we want the master branch of the submodule(s), I tend to use:

git submodule foreach "git fetch && git reset --hard origin/master"

Note: This will perform a hard reset on each submodule -- if you don't want this, you can change --hard to --soft.

Python: Is there an equivalent of mid, right, and left from BASIC?

Thanks Andy W

I found that the mid() did not quite work as I expected and I modified as follows:

def mid(s, offset, amount):
    return s[offset-1:offset+amount-1]

I performed the following test:

print('[1]23', mid('123', 1, 1))
print('1[2]3', mid('123', 2, 1))
print('12[3]', mid('123', 3, 1))
print('[12]3', mid('123', 1, 2))
print('1[23]', mid('123', 2, 2))

Which resulted in:

[1]23 1
1[2]3 2
12[3] 3
[12]3 12
1[23] 23

Which was what I was expecting. The original mid() code produces this:

[1]23 2
1[2]3 3
12[3] 
[12]3 23
1[23] 3

But the left() and right() functions work fine. Thank you.

Creating a LinkedList class from scratch

Linked List Program with following functionalities

1 Insert At Start
2 Insert At End
3 Insert At any Position
4 Delete At any Position
5 Display 
6 Get Size
7 Empty Status
8 Replace data at given postion
9 Search Element by position
10 Delete a Node by Given Data
11 Search Element Iteratively
12 Search Element Recursively




 package com.elegant.ds.linkedlist.practice;

import java.util.Scanner;

class Node {

    Node link = null;
    int data = 0;

    public Node() {
        link = null;
        data = 0;
    }

    public Node(int data, Node link) {
        this.data = data;
        this.link = null;
    }

    public Node getLink() {
        return link;
    }

    public void setLink(Node link) {
        this.link = link;
    }

    public int getData() {
        return data;
    }

    public void setData(int data) {
        this.data = data;
    }

}

class SinglyLinkedListImpl {

    Node start = null;
    Node end = null;
    int size = 0;

    public SinglyLinkedListImpl() {
        start = null;
        end = null;
        size = 0;
    }

    public void insertAtStart(int data) {
        Node nptr = new Node(data, null);
        if (start == null) {
            start = nptr;
            end = start;
        } else {
            nptr.setLink(start);
            start = nptr;
        }
        size++;
    }

    public void insertAtEnd(int data) {
        Node nptr = new Node(data, null);
        if (start == null) {
            start = nptr;
            end = nptr;
        } else {
            end.setLink(nptr);
            end = nptr;
        }
        size++;
    }

    public void insertAtPosition(int position, int data) {
        Node nptr = new Node(data, null);
        Node ptr = start;
        position = position - 1;
        for (int i = 1; i < size; i++) {
            if (i == position) {
                Node temp = ptr.getLink();
                ptr.setLink(nptr);
                nptr.setLink(temp);
                break;
            }
            ptr = ptr.getLink();
        }
        size++;
    }

    public void repleaceDataAtPosition(int position, int data) {
        if (start == null) {
            System.out.println("Empty!");
            return;
        }

        Node ptr = start;
        for (int i = 1; i < size; i++) {
            if (i == position) {
                ptr.setData(data);
            }
            ptr = ptr.getLink();
        }
    }

    public void deleteAtPosition(int position) {
        if (start == null) {
            System.out.println("Empty!");
            return;
        }

        if (position == size) {
            Node startPtr = start;
            Node endPtr = start;
            while (startPtr != null) {
                endPtr = startPtr;
                startPtr = startPtr.getLink();
            }
            end = endPtr;
            end.setLink(null);
            size--;
            return;
        }

        Node ptr = start;
        position = position - 1;
        for (int i = 1; i < size; i++) {

            if (i == position) {
                Node temp = ptr.getLink();
                temp = temp.getLink();
                ptr.setLink(temp);
                break;
            }
            ptr = ptr.getLink();
        }
        size--;
    }

    public void deleteNodeByGivenData(int data) {
        if (start == null) {
            System.out.println("Empty!");
            return;
        }

        if (start.getData() == data && start.getLink() == null) {
            start = null;
            end = null;
            size--;
            return;
        }

        if (start.getData() == data && start.getLink() != null) {
            start = start.getLink();
            size--;
            return;
        }

        if (end.getData() == data) {
            Node startPtr = start;
            Node endPtr = start;

            startPtr = startPtr.getLink();
            while (startPtr.getLink() != null) {
                endPtr = startPtr;
                startPtr = startPtr.getLink();
            }
            end = endPtr;
            end.setLink(null);
            size--;
            return;
        }

        Node startPtr = start;
        Node prevLink = startPtr;
        startPtr = startPtr.getLink();
        while (startPtr.getData() != data && startPtr.getLink() != null) {
            prevLink = startPtr;
            startPtr = startPtr.getLink();
        }
        if (startPtr.getData() == data) {
            Node temp = prevLink.getLink();
            temp = temp.getLink();
            prevLink.setLink(temp);
            size--;
            return;
        }

        System.out.println(data + " not found!");
    }

    public void disply() {
        if (start == null) {
            System.out.println("Empty!");
            return;
        }

        if (start.getLink() == null) {
            System.out.println(start.getData());
            return;
        }

        Node ptr = start;
        System.out.print(ptr.getData() + "->");
        ptr = start.getLink();
        while (ptr.getLink() != null) {
            System.out.print(ptr.getData() + "->");
            ptr = ptr.getLink();
        }
        System.out.println(ptr.getData() + "\n");
    }

    public void searchElementByPosition(int position) {
        if (position == 1) {
            System.out.println("Element at " + position + " is : " + start.getData());
            return;
        }

        if (position == size) {
            System.out.println("Element at " + position + " is : " + end.getData());
            return;
        }

        Node ptr = start;
        for (int i = 1; i < size; i++) {
            if (i == position) {
                System.out.println("Element at " + position + " is : " + ptr.getData());
                break;
            }
            ptr = ptr.getLink();
        }
    }

    public void searchElementIteratively(int data) {

        if (isEmpty()) {
            System.out.println("Empty!");
            return;
        }

        if (start.getData() == data) {
            System.out.println(data + " found at " + 1 + " position");
            return;
        }

        if (start.getLink() != null && end.getData() == data) {
            System.out.println(data + " found at " + size + " position");
            return;
        }

        Node startPtr = start;
        int position = 0;
        while (startPtr.getLink() != null) {
            ++position;
            if (startPtr.getData() == data) {
                break;
            }
            startPtr = startPtr.getLink();
        }
        if (startPtr.getData() == data) {
            System.out.println(data + " found at " + position);
            return;
        }

        System.out.println(data + " No found!");
    }

    public void searchElementRecursively(Node start, int data, int count) {

        if (isEmpty()) {
            System.out.println("Empty!");
            return;
        }
        if (start.getData() == data) {
            System.out.println(data + " found at " + (++count));
            return;
        }
        if (start.getLink() == null) {
            System.out.println(data + " not found!");
            return;
        }
        searchElementRecursively(start.getLink(), data, ++count);
    }

    public int getSize() {
        return size;
    }

    public boolean isEmpty() {
        return start == null;
    }
}

public class SinglyLinkedList {

    @SuppressWarnings("resource")
    public static void main(String[] args) {
        SinglyLinkedListImpl listImpl = new SinglyLinkedListImpl();
        System.out.println("Singly Linked list : ");
        boolean yes = true;
        do {
            System.out.println("1 Insert At Start :");
            System.out.println("2 Insert At End :");
            System.out.println("3 Insert At any Position :");
            System.out.println("4 Delete At any Position :");
            System.out.println("5 Display :");
            System.out.println("6 Get Size");
            System.out.println("7 Empty Status");
            System.out.println("8 Replace data at given postion");
            System.out.println("9 Search Element by position ");
            System.out.println("10 Delete a Node by Given Data");
            System.out.println("11 Search Element Iteratively");
            System.out.println("12 Search Element Recursively");
            System.out.println("13 Exit :");
            Scanner scanner = new Scanner(System.in);
            int choice = scanner.nextInt();
            switch (choice) {
            case 1:
                listImpl.insertAtStart(scanner.nextInt());
                break;

            case 2:
                listImpl.insertAtEnd(scanner.nextInt());
                break;

            case 3:
                int position = scanner.nextInt();
                if (position <= 1 || position > listImpl.getSize()) {
                    System.out.println("invalid position!");
                } else {
                    listImpl.insertAtPosition(position, scanner.nextInt());
                }
                break;

            case 4:
                int deletePosition = scanner.nextInt();
                if (deletePosition <= 1 || deletePosition > listImpl.getSize()) {
                    System.out.println("invalid position!");
                } else {
                    listImpl.deleteAtPosition(deletePosition);
                }
                break;

            case 5:
                listImpl.disply();
                break;

            case 6:
                System.out.println(listImpl.getSize());
                break;

            case 7:
                System.out.println(listImpl.isEmpty());
                break;

            case 8:
                int replacePosition = scanner.nextInt();
                if (replacePosition < 1 || replacePosition > listImpl.getSize()) {
                    System.out.println("Invalid position!");
                } else {
                    listImpl.repleaceDataAtPosition(replacePosition, scanner.nextInt());
                }
                break;

            case 9:
                int searchPosition = scanner.nextInt();
                if (searchPosition < 1 || searchPosition > listImpl.getSize()) {
                    System.out.println("Invalid position!");
                } else {
                    listImpl.searchElementByPosition(searchPosition);
                }
                break;

            case 10:
                listImpl.deleteNodeByGivenData(scanner.nextInt());
                break;

            case 11:
                listImpl.searchElementIteratively(scanner.nextInt());
                break;

            case 12:
                listImpl.searchElementRecursively(listImpl.start, scanner.nextInt(), 0);
                break;

            default:
                System.out.println("invalid choice");
                break;
            }
        } while (yes);
    }
}

It will help you in linked list.

How do I link to part of a page? (hash?)

Just append a hash with an ID of an element to the URL. E.g.

<div id="about"></div>

and

http://mysite.com/#about

So the link would look like:

<a href="http://mysite.com/#about">About</a>

or just

<a href="#about">About</a>

How do I combine a background-image and CSS3 gradient on the same element?

I always use the following code to make it work. There are some notes:

  1. If you place image URL before gradient, this image will be displayed above the gradient as expected.

_x000D_
_x000D_
.background-gradient {_x000D_
  background: url('http://trungk18.github.io/img/trungk18.png') no-repeat, -moz-linear-gradient(135deg, #6ec575 0, #3b8686 100%);_x000D_
  background: url('http://trungk18.github.io/img/trungk18.png') no-repeat, -webkit-gradient(135deg, #6ec575 0, #3b8686 100%);_x000D_
  background: url('http://trungk18.github.io/img/trungk18.png') no-repeat, -webkit-linear-gradient(135deg, #6ec575 0, #3b8686 100%);_x000D_
  background: url('http://trungk18.github.io/img/trungk18.png') no-repeat, -o-linear-gradient(135deg, #6ec575 0, #3b8686 100%);_x000D_
  background: url('http://trungk18.github.io/img/trungk18.png') no-repeat, -ms-linear-gradient(135deg, #6ec575 0, #3b8686 100%);_x000D_
  background: url('http://trungk18.github.io/img/trungk18.png') no-repeat, linear-gradient(135deg, #6ec575 0, #3b8686 100%);_x000D_
  height: 500px;_x000D_
  width: 500px;_x000D_
}
_x000D_
<div class="background-gradient"></div>
_x000D_
_x000D_
_x000D_

  1. If you place gradient before image URL, this image will be displayed under the gradient.

_x000D_
_x000D_
.background-gradient {_x000D_
  background: -moz-linear-gradient(135deg, #6ec575 0, #3b8686 100%), url('http://trungk18.github.io/img/trungk18.png') no-repeat;_x000D_
  background: -webkit-gradient(135deg, #6ec575 0, #3b8686 100%), url('http://trungk18.github.io/img/trungk18.png') no-repeat;_x000D_
  background: -webkit-linear-gradient(135deg, #6ec575 0, #3b8686 100%), url('http://trungk18.github.io/img/trungk18.png') no-repeat;_x000D_
  background: -o-linear-gradient(135deg, #6ec575 0, #3b8686 100%), url('http://trungk18.github.io/img/trungk18.png') no-repeat;_x000D_
  background: -ms-linear-gradient(135deg, #6ec575 0, #3b8686 100%), url('http://trungk18.github.io/img/trungk18.png') no-repeat;_x000D_
  background: linear-gradient(135deg, #6ec575 0, #3b8686 100%), url('http://trungk18.github.io/img/trungk18.png') no-repeat;_x000D_
  width: 500px;_x000D_
  height: 500px;_x000D_
}
_x000D_
<div class="background-gradient"></div>
_x000D_
_x000D_
_x000D_

This technique is just the same as we have multiple background images as describe here

How can I avoid Java code in JSP files, using JSP 2?

If somebody is really against programming in more languages than one, I suggest GWT. Theoretically, you can avoid all the JavaScript and HTML elements, because Google Toolkit transforms all the client and shared code to JavaScript. You won't have problem with them, so you have a webservice without coding in any other languages. You can even use some default CSS from somewhere as it is given by extensions (smartGWT or Vaadin). You don't need to learn dozens of annotations.

Of course, if you want, you can hack yourself into the depths of the code and inject JavaScript and enrich your HTML page, but really you can avoid it if you want, and the result will be good as it was written in any other frameworks. I it's say worth a try, and the basic GWT is well-documented.

And of course many fellow programmers hereby described or recommended several other solutions. GWT is for people who really don't want to deal with the web part or to minimize it.

PHP compare two arrays and get the matched values not the difference

I think the better answer for this questions is

array_diff() 

because it Compares array against one or more other arrays and returns the values in array that are not present in any of the other arrays.

Whereas

array_intersect() returns an array containing all the values of array that are present in all the arguments. Note that keys are preserved.

Binary Search Tree - Java Implementation


Here is the complete Implementation of Binary Search Tree In Java insert,search,countNodes,traversal,delete,empty,maximum & minimum node,find parent node,print all leaf node, get level,get height, get depth,print left view, mirror view


import java.util.NoSuchElementException;
import java.util.Scanner;

import org.junit.experimental.max.MaxCore;

class BSTNode {

    BSTNode left = null;
    BSTNode rigth = null;
    int data = 0;

    public BSTNode() {
        super();
    }

    public BSTNode(int data) {
        this.left = null;
        this.rigth = null;
        this.data = data;
    }

    @Override
    public String toString() {
        return "BSTNode [left=" + left + ", rigth=" + rigth + ", data=" + data + "]";
    }

}


class BinarySearchTree {

    BSTNode root = null;

    public BinarySearchTree() {

    }

    public void insert(int data) {
        BSTNode node = new BSTNode(data);
        if (root == null) {
            root = node;
            return;
        }

        BSTNode currentNode = root;
        BSTNode parentNode = null;

        while (true) {
            parentNode = currentNode;
            if (currentNode.data == data)
                throw new IllegalArgumentException("Duplicates nodes note allowed in Binary Search Tree");

            if (currentNode.data > data) {
                currentNode = currentNode.left;
                if (currentNode == null) {
                    parentNode.left = node;
                    return;
                }
            } else {
                currentNode = currentNode.rigth;
                if (currentNode == null) {
                    parentNode.rigth = node;
                    return;
                }
            }
        }
    }

    public int countNodes() {
        return countNodes(root);
    }

    private int countNodes(BSTNode node) {
        if (node == null) {
            return 0;
        } else {
            int count = 1;
            count += countNodes(node.left);
            count += countNodes(node.rigth);
            return count;
        }
    }

    public boolean searchNode(int data) {
        if (empty())
            return empty();
        return searchNode(data, root);
    }

    public boolean searchNode(int data, BSTNode node) {
        if (node != null) {
            if (node.data == data)
                return true;
            else if (node.data > data)
                return searchNode(data, node.left);
            else if (node.data < data)
                return searchNode(data, node.rigth);
        }
        return false;
    }

    public boolean delete(int data) {
        if (empty())
            throw new NoSuchElementException("Tree is Empty");

        BSTNode currentNode = root;
        BSTNode parentNode = root;
        boolean isLeftChild = false;

        while (currentNode.data != data) {
            parentNode = currentNode;
            if (currentNode.data > data) {
                isLeftChild = true;
                currentNode = currentNode.left;
            } else if (currentNode.data < data) {
                isLeftChild = false;
                currentNode = currentNode.rigth;
            }
            if (currentNode == null)
                return false;
        }

        // CASE 1: node with no child
        if (currentNode.left == null && currentNode.rigth == null) {
            if (currentNode == root)
                root = null;
            if (isLeftChild)
                parentNode.left = null;
            else
                parentNode.rigth = null;
        }

        // CASE 2: if node with only one child
        else if (currentNode.left != null && currentNode.rigth == null) {
            if (root == currentNode) {
                root = currentNode.left;
            }
            if (isLeftChild)
                parentNode.left = currentNode.left;
            else
                parentNode.rigth = currentNode.left;
        } else if (currentNode.rigth != null && currentNode.left == null) {
            if (root == currentNode)
                root = currentNode.rigth;
            if (isLeftChild)
                parentNode.left = currentNode.rigth;
            else
                parentNode.rigth = currentNode.rigth;
        }

        // CASE 3: node with two child
        else if (currentNode.left != null && currentNode.rigth != null) {

            // Now we have to find minimum element in rigth sub tree
            // that is called successor
            BSTNode successor = getSuccessor(currentNode);
            if (currentNode == root)
                root = successor;
            if (isLeftChild)
                parentNode.left = successor;
            else
                parentNode.rigth = successor;
            successor.left = currentNode.left;
        }

        return true;
    }

    private BSTNode getSuccessor(BSTNode deleteNode) {

        BSTNode successor = null;
        BSTNode parentSuccessor = null;
        BSTNode currentNode = deleteNode.left;

        while (currentNode != null) {
            parentSuccessor = successor;
            successor = currentNode;
            currentNode = currentNode.left;
        }

        if (successor != deleteNode.rigth) {
            parentSuccessor.left = successor.left;
            successor.rigth = deleteNode.rigth;
        }

        return successor;
    }

    public int nodeWithMinimumValue() {
        return nodeWithMinimumValue(root);
    }

    private int nodeWithMinimumValue(BSTNode node) {
        if (node.left != null)
            return nodeWithMinimumValue(node.left);
        return node.data;
    }

    public int nodewithMaximumValue() {
        return nodewithMaximumValue(root);
    }

    private int nodewithMaximumValue(BSTNode node) {
        if (node.rigth != null)
            return nodewithMaximumValue(node.rigth);
        return node.data;
    }

    public int parent(int data) {
        return parent(root, data);
    }

    private int parent(BSTNode node, int data) {
        if (empty())
            throw new IllegalArgumentException("Empty");
        if (root.data == data)
            throw new IllegalArgumentException("No Parent node found");

        BSTNode parent = null;
        BSTNode current = node;

        while (current.data != data) {
            parent = current;
            if (current.data > data)
                current = current.left;
            else
                current = current.rigth;
            if (current == null)
                throw new IllegalArgumentException(data + " is not a node in tree");
        }
        return parent.data;
    }

    public int sibling(int data) {
        return sibling(root, data);
    }

    private int sibling(BSTNode node, int data) {
        if (empty())
            throw new IllegalArgumentException("Empty");
        if (root.data == data)
            throw new IllegalArgumentException("No Parent node found");

        BSTNode cureent = node;
        BSTNode parent = null;
        boolean isLeft = false;

        while (cureent.data != data) {
            parent = cureent;
            if (cureent.data > data) {
                cureent = cureent.left;
                isLeft = true;
            } else {
                cureent = cureent.rigth;
                isLeft = false;
            }
            if (cureent == null)
                throw new IllegalArgumentException("No Parent node found");
        }
        if (isLeft) {
            if (parent.rigth != null) {
                return parent.rigth.data;
            } else
                throw new IllegalArgumentException("No Sibling is there");
        } else {
            if (parent.left != null)
                return parent.left.data;
            else
                throw new IllegalArgumentException("No Sibling is there");
        }
    }

    public void leafNodes() {
        if (empty())
            throw new IllegalArgumentException("Empty");
        leafNode(root);
    }

    private void leafNode(BSTNode node) {
        if (node == null)
            return;
        if (node.rigth == null && node.left == null)
            System.out.print(node.data + " ");
        leafNode(node.left);
        leafNode(node.rigth);
    }

    public int level(int data) {
        if (empty())
            throw new IllegalArgumentException("Empty");
        return level(root, data, 1);
    }

    private int level(BSTNode node, int data, int level) {
        if (node == null)
            return 0;
        if (node.data == data)
            return level;
        int result = level(node.left, data, level + 1);
        if (result != 0)
            return result;
        result = level(node.rigth, data, level + 1);
        return result;
    }

    public int depth() {
        return depth(root);
    }

    private int depth(BSTNode node) {
        if (node == null)
            return 0;
        else
            return 1 + Math.max(depth(node.left), depth(node.rigth));
    }

    public int height() {
        return height(root);
    }

    private int height(BSTNode node) {
        if (node == null)
            return 0;
        else
            return 1 + Math.max(height(node.left), height(node.rigth));
    }

    public void leftView() {
        leftView(root);
    }

    private void leftView(BSTNode node) {
        if (node == null)
            return;
        int height = height(node);

        for (int i = 1; i <= height; i++) {
            printLeftView(node, i);
        }
    }

    private boolean printLeftView(BSTNode node, int level) {
        if (node == null)
            return false;

        if (level == 1) {
            System.out.print(node.data + " ");
            return true;
        } else {
            boolean left = printLeftView(node.left, level - 1);
            if (left)
                return true;
            else
                return printLeftView(node.rigth, level - 1);
        }
    }

    public void mirroeView() {
        BSTNode node = mirroeView(root);
        preorder(node);
        System.out.println();
        inorder(node);
        System.out.println();
        postorder(node);
        System.out.println();
    }

    private BSTNode mirroeView(BSTNode node) {
        if (node == null || (node.left == null && node.rigth == null))
            return node;

        BSTNode temp = node.left;
        node.left = node.rigth;
        node.rigth = temp;

        mirroeView(node.left);
        mirroeView(node.rigth);
        return node;
    }

    public void preorder() {
        preorder(root);
    }

    private void preorder(BSTNode node) {
        if (node != null) {
            System.out.print(node.data + " ");
            preorder(node.left);
            preorder(node.rigth);
        }
    }

    public void inorder() {
        inorder(root);
    }

    private void inorder(BSTNode node) {
        if (node != null) {
            inorder(node.left);
            System.out.print(node.data + " ");
            inorder(node.rigth);
        }
    }

    public void postorder() {
        postorder(root);
    }

    private void postorder(BSTNode node) {
        if (node != null) {
            postorder(node.left);
            postorder(node.rigth);
            System.out.print(node.data + " ");
        }
    }

    public boolean empty() {
        return root == null;
    }

}

public class BinarySearchTreeTest {
    public static void main(String[] l) {
        System.out.println("Weleome to Binary Search Tree");
        Scanner scanner = new Scanner(System.in);
        boolean yes = true;
        BinarySearchTree tree = new BinarySearchTree();
        do {
            System.out.println("\n1. Insert");
            System.out.println("2. Search Node");
            System.out.println("3. Count Node");
            System.out.println("4. Empty Status");
            System.out.println("5. Delete Node");
            System.out.println("6. Node with Minimum Value");
            System.out.println("7. Node with Maximum Value");
            System.out.println("8. Find Parent node");
            System.out.println("9. Count no of links");
            System.out.println("10. Get the sibling of any node");
            System.out.println("11. Print all the leaf node");
            System.out.println("12. Get the level of node");
            System.out.println("13. Depth of the tree");
            System.out.println("14. Height of Binary Tree");
            System.out.println("15. Left View");
            System.out.println("16. Mirror Image of Binary Tree");
            System.out.println("Enter Your Choice :: ");
            int choice = scanner.nextInt();
            switch (choice) {
            case 1:
                try {
                    System.out.println("Enter Value");
                    tree.insert(scanner.nextInt());
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                break;

            case 2:
                System.out.println("Enter the node");
                System.out.println(tree.searchNode(scanner.nextInt()));
                break;

            case 3:
                System.out.println(tree.countNodes());
                break;

            case 4:
                System.out.println(tree.empty());
                break;

            case 5:
                try {
                    System.out.println("Enter the node");
                    System.out.println(tree.delete(scanner.nextInt()));
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }

            case 6:
                try {
                    System.out.println(tree.nodeWithMinimumValue());
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                break;

            case 7:
                try {
                    System.out.println(tree.nodewithMaximumValue());
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                break;

            case 8:
                try {
                    System.out.println("Enter the node");
                    System.out.println(tree.parent(scanner.nextInt()));
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                break;

            case 9:
                try {
                    System.out.println(tree.countNodes() - 1);
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                break;

            case 10:
                try {
                    System.out.println("Enter the node");
                    System.out.println(tree.sibling(scanner.nextInt()));
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                break;

            case 11:
                try {
                    tree.leafNodes();
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }

            case 12:
                try {
                    System.out.println("Enter the node");
                    System.out.println("Level is : " + tree.level(scanner.nextInt()));
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                break;

            case 13:
                try {
                    System.out.println(tree.depth());
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                break;

            case 14:
                try {
                    System.out.println(tree.height());
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                break;

            case 15:
                try {
                    tree.leftView();
                    System.out.println();
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                break;

            case 16:
                try {
                    tree.mirroeView();
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                break;

            default:
                break;
            }
            tree.preorder();
            System.out.println();
            tree.inorder();
            System.out.println();
            tree.postorder();
        } while (yes);
        scanner.close();
    }
}

how to pass variable from shell script to sqlplus

You appear to have a heredoc containing a single SQL*Plus command, though it doesn't look right as noted in the comments. You can either pass a value in the heredoc:

sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql BUILDING
exit;
EOF

or if BUILDING is $2 in your script:

sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql $2
exit;
EOF

If your file.sql had an exit at the end then it would be even simpler as you wouldn't need the heredoc:

sqlplus -S user/pass@localhost @/opt/D2RQ/file.sql $2

In your SQL you can then refer to the position parameters using substitution variables:

...
}',SEM_Models('&1'),NULL,
...

The &1 will be replaced with the first value passed to the SQL script, BUILDING; because that is a string it still needs to be enclosed in quotes. You might want to set verify off to stop if showing you the substitutions in the output.


You can pass multiple values, and refer to them sequentially just as you would positional parameters in a shell script - the first passed parameter is &1, the second is &2, etc. You can use substitution variables anywhere in the SQL script, so they can be used as column aliases with no problem - you just have to be careful adding an extra parameter that you either add it to the end of the list (which makes the numbering out of order in the script, potentially) or adjust everything to match:

sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql total_count BUILDING
exit;
EOF

or:

sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql total_count $2
exit;
EOF

If total_count is being passed to your shell script then just use its positional parameter, $4 or whatever. And your SQL would then be:

SELECT COUNT(*) as &1
FROM TABLE(SEM_MATCH(
'{
        ?s rdf:type :ProcessSpec .
        ?s ?p ?o
}',SEM_Models('&2'),NULL,
SEM_ALIASES(SEM_ALIAS('','http://VISION/DataSource/SEMANTIC_CACHE#')),NULL));

If you pass a lot of values you may find it clearer to use the positional parameters to define named parameters, so any ordering issues are all dealt with at the start of the script, where they are easier to maintain:

define MY_ALIAS = &1
define MY_MODEL = &2

SELECT COUNT(*) as &MY_ALIAS
FROM TABLE(SEM_MATCH(
'{
        ?s rdf:type :ProcessSpec .
        ?s ?p ?o
}',SEM_Models('&MY_MODEL'),NULL,
SEM_ALIASES(SEM_ALIAS('','http://VISION/DataSource/SEMANTIC_CACHE#')),NULL));

From your separate question, maybe you just wanted:

SELECT COUNT(*) as &1
FROM TABLE(SEM_MATCH(
'{
        ?s rdf:type :ProcessSpec .
        ?s ?p ?o
}',SEM_Models('&1'),NULL,
SEM_ALIASES(SEM_ALIAS('','http://VISION/DataSource/SEMANTIC_CACHE#')),NULL));

... so the alias will be the same value you're querying on (the value in $2, or BUILDING in the original part of the answer). You can refer to a substitution variable as many times as you want.

That might not be easy to use if you're running it multiple times, as it will appear as a header above the count value in each bit of output. Maybe this would be more parsable later:

select '&1' as QUERIED_VALUE, COUNT(*) as TOTAL_COUNT

If you set pages 0 and set heading off, your repeated calls might appear in a neat list. You might also need to set tab off and possibly use rpad('&1', 20) or similar to make that column always the same width. Or get the results as CSV with:

select '&1' ||','|| COUNT(*)

Depends what you're using the results for...

Passing a variable from one php include file to another: global vs. not

Here is a pitfall to avoid. In case you need to access your variable $name within a function, you need to say "global $name;" at the beginning of that function. You need to repeat this for each function in the same file.

include('front.inc');
global $name;

function foo() {
  echo $name;
}

function bar() {
  echo $name;
}

foo();
bar();

will only show errors. The correct way to do that would be:

include('front.inc');

function foo() {
  global $name;
  echo $name;
}

function bar() {
  global $name;
  echo $name;
}

foo();
bar();

Angular @ViewChild() error: Expected 2 arguments, but got 1

Angular 8

In Angular 8, ViewChild has another param

@ViewChild('nameInput', {static: false}) component : Component

You can read more about it here and here

Angular 9 & Angular 10

In Angular 9 default value is static: false, so doesn't need to provide param unless you want to use {static: true}

Java: Instanceof and Generics

Old post, but a simple way to do generic instanceOf checking.

public static <T> boolean isInstanceOf(Class<T> clazz, Class<T> targetClass) {
    return clazz.isInstance(targetClass);
}