Programs & Examples On #Mobile browser

A mobile browser is a web browser designed for use on a mobile device such as a mobile phone or PDA.

Overflow-x:hidden doesn't prevent content from overflowing in mobile browsers

try

html, body {
  overflow-x:hidden 
} 

instead of just

body {
  overflow-x:hidden 
}

forcing web-site to show in landscape mode only

@Golmaal really answered this, I'm just being a bit more verbose.

<style type="text/css">
    #warning-message { display: none; }
    @media only screen and (orientation:portrait){
        #wrapper { display:none; }
        #warning-message { display:block; }
    }
    @media only screen and (orientation:landscape){
        #warning-message { display:none; }
    }
</style>

....

<div id="wrapper">
    <!-- your html for your website -->
</div>
<div id="warning-message">
    this website is only viewable in landscape mode
</div>

You have no control over the user moving the orientation however you can at least message them. This example will hide the wrapper if in portrait mode and show the warning message and then hide the warning message in landscape mode and show the portrait.

I don't think this answer is any better than @Golmaal , only a compliment to it. If you like this answer, make sure to give @Golmaal the credit.

Update

I've been working with Cordova a lot recently and it turns out you CAN control it when you have access to the native features.

Another Update

So after releasing Cordova it is really terrible in the end. It is better to use something like React Native if you want JavaScript. It is really amazing and I know it isn't pure web but the pure web experience on mobile kind of failed.

How to hide a mobile browser's address bar?

In my case problem was in css and html layout. Layout was something like html - body - root - ... html and body was overflow: hidden, and root was position: fixed, height: 100vh.

Whith this layout browser tabs on mobile doesnt hide. For solve this I delete overflow: hidden from html and body and delete position: fixed, height: 100vh from root.

Detecting a mobile browser

//true / false
function isMobile()
{
   return (/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ); 
}

also you can follow this tutorial to detect a specific mobile. Click here.

c#: getter/setter

You can also use a lambda expression

public string Type
{
    get => _type;
    set => _type = value;
}

Twitter bootstrap scrollable table

Figured I would post on here since I could not get any of the above to work with Bootstrap 4. I found this online and worked perfectly for me...

table
{
    width: 100%;
    display: block;
    border:solid black 1px;
}

thead
{
    display: inline-block;
    width: 100%;
    height: 20px;
}

tbody
{
    height: 200px;
    display: inline-block;
    width: 100%;
    overflow: auto;
}

th, td
{
    width: 100px;
    border:solid 1px black;
    text-align:center;
}

I have also attached the working jsfindle.

https://jsfiddle.net/jgngg28t/

Hope it helps someone else.

How do I call a JavaScript function on page load?

For detect loaded html (from server) inserted into DOM use MutationObserver or detect moment in your loadContent function when data are ready to use

_x000D_
_x000D_
let ignoreFirstChange = 0;_x000D_
let observer = (new MutationObserver((m, ob)=>_x000D_
{_x000D_
  if(ignoreFirstChange++ > 0) console.log('Element added on', new Date());_x000D_
}_x000D_
)).observe(content, {childList: true, subtree:true });_x000D_
_x000D_
_x000D_
// TEST: simulate element loading_x000D_
let tmp=1;_x000D_
function loadContent(name) {  _x000D_
  setTimeout(()=>{_x000D_
    console.log(`Element ${name} loaded`)_x000D_
    content.innerHTML += `<div>My name is ${name}</div>`; _x000D_
  },1500*tmp++)_x000D_
}; _x000D_
_x000D_
loadContent('Senna');_x000D_
loadContent('Anna');_x000D_
loadContent('John');
_x000D_
<div id="content"><div>
_x000D_
_x000D_
_x000D_

mongodb, replicates and error: { "$err" : "not master and slaveOk=false", "code" : 13435 }

I got here searching for the same error, but from Node.js native driver. The answer for me was combination of answers by campeterson and Prabhat.

The issue is that readPreference setting defaults to primary, which then somehow leads to the confusing slaveOk error. My problem is that I just wan to read from my replica set from any node. I don't even connect to it as to replicaset. I just connect to any node to read from it.

Setting readPreference to primaryPreferred (or better to the ReadPreference.PRIMARY_PREFERRED constant) solved it for me. Just pass it as an option to MongoClient.connect() or to client.db() or to any find(), aggregate() or other function.

const { MongoClient, ReadPreference } = require('mongodb');
const client = await MongoClient.connect(MONGODB_CONNECTIONSTRING, { readPreference: ReadPreference.PRIMARY_PREFERRED });

What is {this.props.children} and when you should use it?

What even is ‘children’?

The React docs say that you can use props.children on components that represent ‘generic boxes’ and that don’t know their children ahead of time. For me, that didn’t really clear things up. I’m sure for some, that definition makes perfect sense but it didn’t for me.

My simple explanation of what this.props.children does is that it is used to display whatever you include between the opening and closing tags when invoking a component.

A simple example:

Here’s an example of a stateless function that is used to create a component. Again, since this is a function, there is no this keyword so just use props.children

const Picture = (props) => {
  return (
    <div>
      <img src={props.src}/>
      {props.children}
    </div>
  )
}

This component contains an <img> that is receiving some props and then it is displaying {props.children}.

Whenever this component is invoked {props.children} will also be displayed and this is just a reference to what is between the opening and closing tags of the component.

//App.js
render () {
  return (
    <div className='container'>
      <Picture key={picture.id} src={picture.src}>
          //what is placed here is passed as props.children  
      </Picture>
    </div>
  )
}

Instead of invoking the component with a self-closing tag <Picture /> if you invoke it will full opening and closing tags <Picture> </Picture> you can then place more code between it.

This de-couples the <Picture> component from its content and makes it more reusable.

Reference: A quick intro to React’s props.children

How to block until an event is fired in c#

A very easy kind of event you can wait for is the ManualResetEvent, and even better, the ManualResetEventSlim.

They have a WaitOne() method that does exactly that. You can wait forever, or set a timeout, or a "cancellation token" which is a way for you to decide to stop waiting for the event (if you want to cancel your work, or your app is asked to exit).

You fire them calling Set().

Here is the doc.

Java generics - why is "extends T" allowed but not "implements T"?

In fact, when using generic on interface, the keyword is also extends. Here is the code example:

There are 2 classes that implements the Greeting interface:

interface Greeting {
    void sayHello();
}

class Dog implements Greeting {
    @Override
    public void sayHello() {
        System.out.println("Greeting from Dog: Hello ");
    }
}

class Cat implements Greeting {
    @Override
    public void sayHello() {
        System.out.println("Greeting from Cat: Hello ");
    }
}

And the test code:

@Test
public void testGeneric() {
    Collection<? extends Greeting> animals;

    List<Dog> dogs = Arrays.asList(new Dog(), new Dog(), new Dog());
    List<Cat> cats = Arrays.asList(new Cat(), new Cat(), new Cat());

    animals = dogs;
    for(Greeting g: animals) g.sayHello();

    animals = cats;
    for(Greeting g: animals) g.sayHello();
}

How to make a variadic macro (variable number of arguments)

#define DEBUG

#ifdef DEBUG
  #define PRINT print
#else
  #define PRINT(...) ((void)0) //strip out PRINT instructions from code
#endif 

void print(const char *fmt, ...) {

    va_list args;
    va_start(args, fmt);
    vsprintf(str, fmt, args);
        va_end(args);

        printf("%s\n", str);

}

int main() {
   PRINT("[%s %d, %d] Hello World", "March", 26, 2009);
   return 0;
}

If the compiler does not understand variadic macros, you can also strip out PRINT with either of the following:

#define PRINT //

or

#define PRINT if(0)print

The first comments out the PRINT instructions, the second prevents PRINT instruction because of a NULL if condition. If optimization is set, the compiler should strip out never executed instructions like: if(0) print("hello world"); or ((void)0);

(Built-in) way in JavaScript to check if a string is a valid number

Save yourself the headache of trying to find a "built-in" solution.

There isn't a good answer, and the hugely upvoted answer in this thread is wrong.

npm install is-number

In JavaScript, it's not always as straightforward as it should be to reliably check if a value is a number. It's common for devs to use +, -, or Number() to cast a string value to a number (for example, when values are returned from user input, regex matches, parsers, etc). But there are many non-intuitive edge cases that yield unexpected results:

console.log(+[]); //=> 0
console.log(+''); //=> 0
console.log(+'   '); //=> 0
console.log(typeof NaN); //=> 'number'

The number of method references in a .dex file cannot exceed 64k API 17

Do this, it works:

defaultConfig {
    applicationId "com.example.maps"
    minSdkVersion 15
    targetSdkVersion 24
    versionCode 1
    versionName "1.0"
    multiDexEnabled true
}

Finding the layers and layer sizes for each Docker image

It's indeed doable to query the manifest or blob info from docker registry server without pulling the image to local disk.

You can refer to the Registry v2 API to fetch the manifest of image.

GET /v2/<name>/manifests/<reference>

Note, you have to handle different manifest version. For v2 you can directly get the size of layer and digest of blob. For v1 manifest, you can HEAD the blob download url to get the actual layer size.

There is a simple script for handling above cases that will be continuously maintained.

intellij incorrectly saying no beans of type found for autowired repository

Add Spring annotation @Repository over the repository class.

I know it should work without this annotation. But if you add this, IntelliJ will not show error.

@Repository
public interface YourRepository ...
...

If you use Spring Data with extending Repository class it will be conflict pagkages. Then you must indicate explicity pagkages.

import org.springframework.data.repository.Repository;
...

@org.springframework.stereotype.Repository
public interface YourRepository extends Repository<YourClass, Long> {
    ...
}

And next you can autowired your repository without errors.

@Autowired
YourRepository yourRepository;

It probably is not a good solution (I guess you are trying to register repositorium twice). But work for me and don't show errors.

Maybe in the new version of IntelliJ can be fixed: https://youtrack.jetbrains.com/issue/IDEA-137023

how to create 100% vertical line in css

100% height refers to the height of the parent container. In order for your div to go full height of the body you have to set this:

html, body {height: 100%; min-height: 100%}

Hope it helps.

Set variable with multiple values and use IN

Use a Temp Table or a Table variable, e.g.

select 'A' as [value]
into #tmp
union
select 'B'
union 
select 'C'

and then

SELECT   
blah 
FROM    foo 
WHERE   myField IN (select [value] from #tmp) 

or

SELECT   
f.blah 
FROM foo f INNER JOIN #tmp t ON f.myField = t.[value]

Disable button in jQuery

There are two things here, and the highest voted answer is technically correct as per the OPs question.

Briefly summarized as:

$("some sort of selector").prop("disabled", true | false);

However should you be using jQuery UI (I know the OP wasn't but some people arriving here might be) then while this will disable the buttons click event it wont make the button appear disabled as per the UI styling.

If you are using a jQuery UI styled button then it should be enabled / disabled via:

$("some sort of selector").button("enable" | "disable");

http://api.jqueryui.com/button/#method-disable

Wrapping text inside input type="text" element HTML/CSS

To create a text input in which the value under the hood is a single line string but is presented to the user in a word-wrapped format you can use the contenteditable attribute on a <div> or other element:

_x000D_
_x000D_
const el = document.querySelector('div[contenteditable]');_x000D_
_x000D_
// Get value from element on input events_x000D_
el.addEventListener('input', () => console.log(el.textContent));_x000D_
_x000D_
// Set some value_x000D_
el.textContent = 'Lorem ipsum curae magna venenatis mattis, purus luctus cubilia quisque in et, leo enim aliquam consequat.'
_x000D_
div[contenteditable] {_x000D_
  border: 1px solid black;_x000D_
  width: 200px;_x000D_
}
_x000D_
<div contenteditable></div>
_x000D_
_x000D_
_x000D_

How to use php serialize() and unserialize()

Most storage mediums can store string types. They can not directly store a PHP data structure such as an array or object, and they shouldn't, as that would couple the data storage medium with PHP.

Instead, serialize() allows you to store one of these structs as a string. It can be de-serialised from its string representation with unserialize().

If you are familiar with json_encode() and json_decode() (and JSON in general), the concept is similar.

Exception: Unexpected end of ZLIB input stream

You have to call close() on the GZIPOutputStream before you attempt to read it. The final bytes of the file will only be written when the file is actually closed. (This is irrespective of any explicit buffering in the output stack. The stream only knows to compress and write the last bytes when you tell it to close. A flush() probably won't help ... though calling finish() instead of close() should work. Look at the javadocs.)

Here's the correct code (in Java);

package test;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class GZipTest {

    public static void main(String[] args) throws
                FileNotFoundException, IOException {
        String name = "/tmp/test";
        GZIPOutputStream gz = new GZIPOutputStream(new FileOutputStream(name));
        gz.write(10);
        gz.close();       // Remove this to reproduce the reported bug
        System.out.println(new GZIPInputStream(new FileInputStream(name)).read());
    }
}

(I've not implemented resource management or exception handling / reporting properly as they are not relevant to the purpose of this code. Don't treat this as an example of "good code".)

The network path was not found

I recently had the same issue. It's more likely that your application can not connect to database server due to the network issues.

In my case I was connected to wrong WiFi.

Spring boot: Unable to start embedded Tomcat servlet container

For me, the problem was in XML migrations. I deleted all tables and sequences and it works on next bootRun

Using an authorization header with Fetch in React Native

I had this identical problem, I was using django-rest-knox for authentication tokens. It turns out that nothing was wrong with my fetch method which looked like this:

...
    let headers = {"Content-Type": "application/json"};
    if (token) {
      headers["Authorization"] = `Token ${token}`;
    }
    return fetch("/api/instruments/", {headers,})
      .then(res => {
...

I was running apache.

What solved this problem for me was changing WSGIPassAuthorization to 'On' in wsgi.conf.

I had a Django app deployed on AWS EC2, and I used Elastic Beanstalk to manage my application, so in the django.config, I did this:

container_commands:
  01wsgipass:
    command: 'echo "WSGIPassAuthorization On" >> ../wsgi.conf'

window.location.href not working

Please check you are using // not \\ by-mistake , like below

Wrong:"http:\\stackoverflow.com"

Right:"http://stackoverflow.com"

Using a global variable with a thread

You just need to declare a as a global in thread2, so that you aren't modifying an a that is local to that function.

def thread2(threadname):
    global a
    while True:
        a += 1
        time.sleep(1)

In thread1, you don't need to do anything special, as long as you don't try to modify the value of a (which would create a local variable that shadows the global one; use global a if you need to)>

def thread1(threadname):
    #global a       # Optional if you treat a as read-only
    while a < 10:
        print a

How to change Android usb connect mode to charge only?

The HTC devices have the PCSII.apk which allow them to select usb connect mode. For your device, you can set it manually:

Use SQLite Editor to open /data/data/com.android.providers.setting/databases/settings.db

open table secure

turn settings starting with mount_ums_ to 0, then restart devices.

UPDATE: If it still doesn't work, try turning on debug mode.

Convert iterator to pointer?

Use vector::front, it should be the most portable solution. I've used this when I'm interfacing with a fixed API that wants a char ptr. Example:

void funcThatTakesCharPtr(char* start, size_t size);

...

void myFunc(vector<char>& myVec)
{
    // Get a pointer to the front element of my vector:
    char* myDataPtr = &(myVec.front());

    // Pass that pointer to my external API:
    funcThatTakesCharPtr(myDataPtr, myVec.size());
}

How to resize a custom view programmatically?

if you are overriding onMeasure, don't forget to update the new sizes

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    setMeasuredDimension(newWidth, newHeight);
}

Get a CSS value with JavaScript

Use the following. It helped me.

document.getElementById('image_1').offsetTop

See also Get Styles.

SQL Server Profiler - How to filter trace to only display events from one database?

Under Trace properties > Events Selection tab > select show all columns. Now under column filters, you should see the database name. Enter the database name for the Like section and you should see traces only for that database.

Get selected key/value of a combo box using jQuery

This works:

<select name="foo" id="foo">
<option value="1">a</option>
<option value="2">b</option>
<option value="3">c</option>
</select>
<input type="button" id="button" value="Button" />

$('#button').click(function() {
    alert($('#foo option:selected').text());
    alert($('#foo option:selected').val());
});

Checking Bash exit status of several commands efficiently

I've developed an almost flawless try & catch implementation in bash, that allows you to write code like:

try 
    echo 'Hello'
    false
    echo 'This will not be displayed'

catch 
    echo "Error in $__EXCEPTION_SOURCE__ at line: $__EXCEPTION_LINE__!"

You can even nest the try-catch blocks inside themselves!

try {
    echo 'Hello'

    try {
        echo 'Nested Hello'
        false
        echo 'This will not execute'
    } catch {
        echo "Nested Caught (@ $__EXCEPTION_LINE__)"
    }

    false
    echo 'This will not execute too'

} catch {
    echo "Error in $__EXCEPTION_SOURCE__ at line: $__EXCEPTION_LINE__!"
}

The code is a part of my bash boilerplate/framework. It further extends the idea of try & catch with things like error handling with backtrace and exceptions (plus some other nice features).

Here's the code that's responsible just for try & catch:

set -o pipefail
shopt -s expand_aliases
declare -ig __oo__insideTryCatch=0

# if try-catch is nested, then set +e before so the parent handler doesn't catch us
alias try="[[ \$__oo__insideTryCatch -gt 0 ]] && set +e;
           __oo__insideTryCatch+=1; ( set -e;
           trap \"Exception.Capture \${LINENO}; \" ERR;"
alias catch=" ); Exception.Extract \$? || "

Exception.Capture() {
    local script="${BASH_SOURCE[1]#./}"

    if [[ ! -f /tmp/stored_exception_source ]]; then
        echo "$script" > /tmp/stored_exception_source
    fi
    if [[ ! -f /tmp/stored_exception_line ]]; then
        echo "$1" > /tmp/stored_exception_line
    fi
    return 0
}

Exception.Extract() {
    if [[ $__oo__insideTryCatch -gt 1 ]]
    then
        set -e
    fi

    __oo__insideTryCatch+=-1

    __EXCEPTION_CATCH__=( $(Exception.GetLastException) )

    local retVal=$1
    if [[ $retVal -gt 0 ]]
    then
        # BACKWARDS COMPATIBILE WAY:
        # export __EXCEPTION_SOURCE__="${__EXCEPTION_CATCH__[(${#__EXCEPTION_CATCH__[@]}-1)]}"
        # export __EXCEPTION_LINE__="${__EXCEPTION_CATCH__[(${#__EXCEPTION_CATCH__[@]}-2)]}"
        export __EXCEPTION_SOURCE__="${__EXCEPTION_CATCH__[-1]}"
        export __EXCEPTION_LINE__="${__EXCEPTION_CATCH__[-2]}"
        export __EXCEPTION__="${__EXCEPTION_CATCH__[@]:0:(${#__EXCEPTION_CATCH__[@]} - 2)}"
        return 1 # so that we may continue with a "catch"
    fi
}

Exception.GetLastException() {
    if [[ -f /tmp/stored_exception ]] && [[ -f /tmp/stored_exception_line ]] && [[ -f /tmp/stored_exception_source ]]
    then
        cat /tmp/stored_exception
        cat /tmp/stored_exception_line
        cat /tmp/stored_exception_source
    else
        echo -e " \n${BASH_LINENO[1]}\n${BASH_SOURCE[2]#./}"
    fi

    rm -f /tmp/stored_exception /tmp/stored_exception_line /tmp/stored_exception_source
    return 0
}

Feel free to use, fork and contribute - it's on GitHub.

How to add "on delete cascade" constraints?

Usage:

select replace_foreign_key('user_rates_posts', 'post_id', 'ON DELETE CASCADE');

Function:

CREATE OR REPLACE FUNCTION 
    replace_foreign_key(f_table VARCHAR, f_column VARCHAR, new_options VARCHAR) 
RETURNS VARCHAR
AS $$
DECLARE constraint_name varchar;
DECLARE reftable varchar;
DECLARE refcolumn varchar;
BEGIN

SELECT tc.constraint_name, ccu.table_name AS foreign_table_name, ccu.column_name AS foreign_column_name 
FROM 
    information_schema.table_constraints AS tc 
    JOIN information_schema.key_column_usage AS kcu
      ON tc.constraint_name = kcu.constraint_name
    JOIN information_schema.constraint_column_usage AS ccu
      ON ccu.constraint_name = tc.constraint_name
WHERE constraint_type = 'FOREIGN KEY' 
   AND tc.table_name= f_table AND kcu.column_name= f_column
INTO constraint_name, reftable, refcolumn;

EXECUTE 'alter table ' || f_table || ' drop constraint ' || constraint_name || 
', ADD CONSTRAINT ' || constraint_name || ' FOREIGN KEY (' || f_column || ') ' ||
' REFERENCES ' || reftable || '(' || refcolumn || ') ' || new_options || ';';

RETURN 'Constraint replaced: ' || constraint_name || ' (' || f_table || '.' || f_column ||
 ' -> ' || reftable || '.' || refcolumn || '); New options: ' || new_options;

END;
$$ LANGUAGE plpgsql;

Be aware: this function won't copy attributes of initial foreign key. It only takes foreign table name / column name, drops current key and replaces with new one.

Set HTML element's style property in javascript

The DOM element style "property" is a readonly collection of all the style attributes defined on the element. (The collection property is readonly, not necessarily the items within the collection.)

You would be better off using the className "property" on the elements.

Bash Shell Script - Check for a flag and grab its value

Use $# to grab the number of arguments, if it is unequal to 2 there are not enough arguments provided:

if [ $# -ne 2 ]; then
   usage;
fi

Next, check if $1 equals -t, otherwise an unknown flag was used:

if [ "$1" != "-t" ]; then
  usage;
fi

Finally store $2 in FLAG:

FLAG=$2

Note: usage() is some function showing the syntax. For example:

function usage {
   cat << EOF
Usage: script.sh -t <application>

Performs some activity
EOF
   exit 1
}

Extract month and year from a zoo::yearmon object

The lubridate package is amazing for this kind of thing:

> require(lubridate)
> month(date1)
[1] 3
> year(date1)
[1] 2012

How to parse a string in JavaScript?

as amber and sinan have noted above, the javascritp '.split' method will work just fine. Just pass it the string separator(-) and the string that you intend to split('123-abc-itchy-knee') and it will do the rest.

    var coolVar = '123-abc-itchy-knee';
    var coolVarParts = coolVar.split('-'); // this is an array containing the items

    var1=coolVarParts[0]; //this will retrieve 123

To access each item from the array just use the respective index(indices start at zero).

How do I rename all folders and files to lowercase on Linux?

None of the solutions here worked for me because I was on a system that didn't have access to the perl rename script, plus some of the files included spaces. However, I found a variant that works:

find . -depth -exec sh -c '
    t=${0%/*}/$(printf %s "${0##*/}" | tr "[:upper:]" "[:lower:]");
    [ "$t" = "$0" ] || mv -i "$0" "$t"
' {} \;

Credit goes to "Gilles 'SO- stop being evil'", see this answer on the similar question "change entire directory tree to lower-case names" on the Unix & Linux StackExchange.

Update one MySQL table with values from another

It depends what is a use of those tables, but you might consider putting trigger on original table on insert and update. When insert or update is done, update the second table based on only one item from the original table. It will be quicker.

WhatsApp API (java/python)

This is the developers page of the Open WhatsApp official page: http://openwhatsapp.org/develop/

You can find a lot of information there about Yowsup.

Or, you can just go the the library's link (which I copied from the Open WhatsApp page anyway): https://github.com/tgalal/yowsup

Enjoy!

How to include *.so library in Android Studio?

I have solved a similar problem using external native lib dependencies that are packaged inside of jar files. Sometimes these architecture dependend libraries are packaged alltogether inside one jar, sometimes they are split up into several jar files. so i wrote some buildscript to scan the jar dependencies for native libs and sort them into the correct android lib folders. Additionally this also provides a way to download dependencies that not found in maven repos which is currently usefull to get JNA working on android because not all native jars are published in public maven repos.

android {
    compileSdkVersion 23
    buildToolsVersion '24.0.0'

    lintOptions {
        abortOnError false
    }


    defaultConfig {
        applicationId "myappid"
        minSdkVersion 17
        targetSdkVersion 23
        versionCode 1
        versionName "1.0.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

    sourceSets {
        main {
            jniLibs.srcDirs = ["src/main/jniLibs", "$buildDir/native-libs"]
        }
    }
}

def urlFile = { url, name ->
    File file = new File("$buildDir/download/${name}.jar")
    file.parentFile.mkdirs()
    if (!file.exists()) {
        new URL(url).withInputStream { downloadStream ->
            file.withOutputStream { fileOut ->
                fileOut << downloadStream
            }
        }
    }
    files(file.absolutePath)
}
dependencies {
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.3.0'
    compile 'com.android.support:design:23.3.0'
    compile 'net.java.dev.jna:jna:4.2.0'
    compile urlFile('https://github.com/java-native-access/jna/blob/4.2.2/lib/native/android-arm.jar?raw=true', 'jna-android-arm')
    compile urlFile('https://github.com/java-native-access/jna/blob/4.2.2/lib/native/android-armv7.jar?raw=true', 'jna-android-armv7')
    compile urlFile('https://github.com/java-native-access/jna/blob/4.2.2/lib/native/android-aarch64.jar?raw=true', 'jna-android-aarch64')
    compile urlFile('https://github.com/java-native-access/jna/blob/4.2.2/lib/native/android-x86.jar?raw=true', 'jna-android-x86')
    compile urlFile('https://github.com/java-native-access/jna/blob/4.2.2/lib/native/android-x86-64.jar?raw=true', 'jna-android-x86_64')
    compile urlFile('https://github.com/java-native-access/jna/blob/4.2.2/lib/native/android-mips.jar?raw=true', 'jna-android-mips')
    compile urlFile('https://github.com/java-native-access/jna/blob/4.2.2/lib/native/android-mips64.jar?raw=true', 'jna-android-mips64')
}
def safeCopy = { src, dst ->
    File fdst = new File(dst)
    fdst.parentFile.mkdirs()
    fdst.bytes = new File(src).bytes

}

def archFromName = { name ->
    switch (name) {
        case ~/.*android-(x86-64|x86_64|amd64).*/:
            return "x86_64"
        case ~/.*android-(i386|i686|x86).*/:
            return "x86"
        case ~/.*android-(arm64|aarch64).*/:
            return "arm64-v8a"
        case ~/.*android-(armhf|armv7|arm-v7|armeabi-v7).*/:
            return "armeabi-v7a"
        case ~/.*android-(arm).*/:
            return "armeabi"
        case ~/.*android-(mips).*/:
            return "mips"
        case ~/.*android-(mips64).*/:
            return "mips64"
        default:
            return null
    }
}

task extractNatives << {
    project.configurations.compile.each { dep ->
        println "Scanning ${dep.name} for native libs"
        if (!dep.name.endsWith(".jar"))
            return
        zipTree(dep).visit { zDetail ->
            if (!zDetail.name.endsWith(".so"))
                return
            print "\tFound ${zDetail.name}"
            String arch = archFromName(zDetail.toString())
            if(arch != null){
                println " -> $arch"
                safeCopy(zDetail.file.absolutePath,
                        "$buildDir/native-libs/$arch/${zDetail.file.name}")
            } else {
                println " -> No valid arch"
            }
        }
    }
}

preBuild.dependsOn(['extractNatives'])

Adding a public key to ~/.ssh/authorized_keys does not log me in automatically

I have the home directory in a non-standard location and in sshd logs I have the following line, even if all permissions were just fine (see the other answers):

Could not open authorized keys '/data/home/user1/.ssh/authorized_keys': Permission denied

I have found a solution here: Trouble with ssh public key authentication to RHEL 6.5

In my particular case:

  • Added a new line in /etc/selinux/targeted/contexts/files/file_contexts.homedirs:

  • This is the original line for regular home directories:

    /home/[^/]*/\.ssh(/.*)? unconfined_u:object_r:ssh_home_t:s0

  • This is my new line:

    /data/home/[^/]*/\.ssh(/.*)? unconfined_u:object_r:ssh_home_t:s0

  • Followed by a restorecon -r /data/ and a sshd restart.

Accept function as parameter in PHP

Just code it like this:

function example($anon) {
  $anon();
}

example(function(){
  // some codes here
});

it would be great if you could invent something like this (inspired by Laravel Illuminate):

Object::method("param_1", function($param){
  $param->something();
});

"Fatal error: Cannot redeclare <function>"

Another possible reason for getting that error is that your function has the same name as another PHP built-in function. For example,

function checkdate($date){
   $now=strtotime(date('Y-m-d H:i:s'));
   $tenYearsAgo=strtotime("-10 years", $now);
   $dateToCheck=strtotime($date);
   return ($tenYearsAgo > $dateToCheck) ? false : true;
}
echo checkdate('2016-05-12');

where the checkdate function already exists in PHP.

Most efficient way to find mode in numpy array

if you want to find mode as int Value here is the easiest way I was trying to find out mode of Array using Scipy Stats but the problem is that output of the code look like:

ModeResult(mode=array(2), count=array([[1, 2, 2, 2, 1, 2]])) , I only want the Integer output so if you want the same just try this

import numpy as np
from scipy import stats
numbers = list(map(int, input().split())) 
print(int(stats.mode(numbers)[0]))

Last line is enough to print Mode Value in Python: print(int(stats.mode(numbers)[0]))

Styling text input caret

Here are some vendors you might me looking for

::-webkit-input-placeholder {color: tomato}
::-moz-placeholder          {color: tomato;} /* Firefox 19+ */
:-moz-placeholder           {color: tomato;} /* Firefox 18- */
:-ms-input-placeholder      {color: tomato;}

You can also style different states, such as focus

:focus::-webkit-input-placeholder {color: transparent}
:focus::-moz-placeholder          {color: transparent}
:focus:-moz-placeholder           {color: transparent}
:focus:-ms-input-placeholder      {color: transparent}

You can also do certain transitions on it, like

::-VENDOR-input-placeholder       {text-indent: 0px;   transition: text-indent 0.3s ease;}
:focus::-VENDOR-input-placeholder  {text-indent: 500px; transition: text-indent 0.3s ease;}

How to display a gif fullscreen for a webpage background?

This should do what you're looking for.

CSS:

html, body {
    height: 100%;
    margin: 0;
}

.gif-container {
  background: url("image.gif") center;
  background-size: cover;

  height: 100%;
}

HTML:

<div class="gif-container"></div>

Re-assign host access permission to MySQL user

Similar issue where I was getting permissions failed. On my setup, I SSH in only. So What I did to correct the issue was

sudo MySQL
SELECT User, Host FROM mysql.user WHERE Host <> '%';
MariaDB [(none)]> SELECT User, Host FROM mysql.user WHERE Host <> '%';
+-------+-------------+
| User  | Host        |
+-------+-------------+
| root  | 169.254.0.% |
| foo   | 192.168.0.% |
| bar   | 192.168.0.% |
+-------+-------------+
4 rows in set (0.00 sec)

I need these users moved to 'localhost'. So I issued the following:

UPDATE mysql.user SET host = 'localhost' WHERE user = 'foo';
UPDATE mysql.user SET host = 'localhost' WHERE user = 'bar';

Run SELECT User, Host FROM mysql.user WHERE Host <> '%'; again and we see:

MariaDB [(none)]> SELECT User, Host FROM mysql.user WHERE Host <> '%';
+-------+-------------+
| User  | Host        |
+-------+-------------+
| root  | 169.254.0.% |
| foo   | localhost   |
| bar   | localhost   |
+-------+-------------+
4 rows in set (0.00 sec)

And then I was able to work normally again. Hope that helps someone.

$ mysql -u foo -p
Enter password:
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 74
Server version: 10.1.23-MariaDB-9+deb9u1 Raspbian 9.0

Copyright (c) 2000, 2017, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]>

Convert boolean to int in Java

Lets play trick with Boolean.compare(boolean, boolean). Default behavior of function: if both values are equal than it returns 0 otherwise -1.

public int valueOf(Boolean flag) {
   return Boolean.compare(flag, Boolean.TRUE) + 1;
}

Explanation: As we know default return of Boolean.compare is -1 in case of mis-match so +1 make return value to 0 for False and 1 for True

Installing Android Studio, does not point to a valid JVM installation error

My problem was different to any of the above as far as I can tell. I had a working version 1.1 of Android Studio and upgraded to 1.2 Then I got the JAVA_HOME error when starting 1.2

The problem was that my JAVA_HOME was set to "C:\Program Files\Java\jdk1.8.0_20" with quotation marks included. I haven't put them there to quote the string, the quotation marks were in the Variable Value field. It appears that 1.1 is happy with the quotes being there but 1.2 is not.

Removing quotes removed the error and 1.2 now opens fine

Why is my xlabel cut off in my matplotlib plot?

In case you want to store it to a file, you solve it using bbox_inches="tight" argument:

plt.savefig('myfile.png', bbox_inches = "tight")

How to unpackage and repackage a WAR file

I am sure there is ANT tags to do it but have used this 7zip hack in .bat script. I use http://www.7-zip.org/ command line tool. All the times I use this for changing jdbc url within j2ee context.xml file.

mkdir .\temp-install
c:\apps\commands\7za.exe x -y mywebapp.war META-INF/context.xml -otemp-install\mywebapp
..here I have small tool to replace text in xml file..
c:\apps\commands\7za.exe u -y -tzip mywebapp.war ./temp-install/mywebapp/*
rmdir /Q /S .\temp-install

You could extract entire .war file (its zip after all), delete files, replace files, add files, modify files and repackage to .war archive file. But changing one file in a large .war archive this might be best extracting specific file and then update original archive.

Stop and Start a service via batch or cmd file?

We'd like to think that "net stop " will stop the service. Sadly, reality isn't that black and white. If the service takes a long time to stop, the command will return before the service has stopped. You won't know, though, unless you check errorlevel.

The solution seems to be to loop round looking for the state of the service until it is stopped, with a pause each time round the loop.

But then again...

I'm seeing the first service take a long time to stop, then the "net stop" for a subsequent service just appears to do nothing. Look at the service in the services manager, and its state is still "Started" - no change to "Stopping". Yet I can stop this second service manually using the SCM, and it stops in 3 or 4 seconds.

How to know if a Fragment is Visible?

Try this if you have only one Fragment

if (getSupportFragmentManager().getBackStackEntryCount() == 0) {
                    //TODO: Your Code Here
                }

SQL Server: UPDATE a table by using ORDER BY

Edit

Following solution could have problems with clustered indexes involved as mentioned here. Thanks to Martin for pointing this out.

The answer is kept to educate those (like me) who don't know all side-effects or ins and outs of SQL Server.


Expanding on the answer gaven by Quassnoi in your link, following works

DECLARE @Test TABLE (Number INTEGER, AText VARCHAR(2), ID INTEGER)
DECLARE @Number INT

INSERT INTO @Test VALUES (1, 'A', 1)
INSERT INTO @Test VALUES (2, 'B', 2)
INSERT INTO @Test VALUES (1, 'E', 5)
INSERT INTO @Test VALUES (3, 'C', 3)
INSERT INTO @Test VALUES (2, 'D', 4)

SET @Number = 0

;WITH q AS (
    SELECT  TOP 1000000 *
    FROM    @Test
    ORDER BY
            ID
)            
UPDATE  q
SET     @Number = Number = @Number + 1

MySql Table Insert if not exist otherwise update

Jai is correct that you should use INSERT ... ON DUPLICATE KEY UPDATE.

Note that you do not need to include datenum in the update clause since it's the unique key, so it should not change. You do need to include all of the other columns from your table. You can use the VALUES() function to make sure the proper values are used when updating the other columns.

Here is your update re-written using the proper INSERT ... ON DUPLICATE KEY UPDATE syntax for MySQL:

INSERT INTO AggregatedData (datenum,Timestamp)
VALUES ("734152.979166667","2010-01-14 23:30:00.000")
ON DUPLICATE KEY UPDATE 
  Timestamp=VALUES(Timestamp)

How to get access to raw resources that I put in res folder?

InputStream in = getResources().openRawResource(resourceName);

This will work correctly. Before that you have to create the xml file / text file in raw resource. Then it will be accessible.

Edit
Some times com.andriod.R will be imported if there is any error in layout file or image names. So You have to import package correctly, then only the raw file will be accessible.

How to use Elasticsearch with MongoDB?

Using river can present issues when your operation scales up. River will use a ton of memory when under heavy operation. I recommend implementing your own elasticsearch models, or if you're using mongoose you can build your elasticsearch models right into that or use mongoosastic which essentially does this for you.

Another disadvantage to Mongodb River is that you'll be stuck using mongodb 2.4.x branch, and ElasticSearch 0.90.x. You'll start to find that you're missing out on a lot of really nice features, and the mongodb river project just doesn't produce a usable product fast enough to keep stable. That said Mongodb River is definitely not something I'd go into production with. It's posed more problems than its worth. It will randomly drop write under heavy load, it will consume lots of memory, and there's no setting to cap that. Additionally, river doesn't update in realtime, it reads oplogs from mongodb, and this can delay updates for as long as 5 minutes in my experience.

We recently had to rewrite a large portion of our project, because its a weekly occurrence that something goes wrong with ElasticSearch. We had even gone as far as to hire a Dev Ops consultant, who also agrees that its best to move away from River.

UPDATE: Elasticsearch-mongodb-river now supports ES v1.4.0 and mongodb v2.6.x. However, you'll still likely run into performance problems on heavy insert/update operations as this plugin will try to read mongodb's oplogs to sync. If there are a lot of operations since the lock(or latch rather) unlocks, you'll notice extremely high memory usage on your elasticsearch server. If you plan on having a large operation, river is not a good option. The developers of ElasticSearch still recommend you to manage your own indexes by communicating directly with their API using the client library for your language, rather than using river. This isn't really the purpose of river. Twitter-river is a great example of how river should be used. Its essentially a great way to source data from outside sources, but not very reliable for high traffic or internal use.

Also consider that mongodb-river falls behind in version, as its not maintained by ElasticSearch Organization, its maintained by a thirdparty. Development was stuck on v0.90 branch for a long time after the release of v1.0, and when a version for v1.0 was released it wasn't stable until elasticsearch released v1.3.0. Mongodb versions also fall behind. You may find yourself in a tight spot when you're looking to move to a later version of each, especially with ElasticSearch under such heavy development, with many very anticipated features on the way. Staying up on the latest ElasticSearch has been very important as we rely heavily on constantly improving our search functionality as its a core part of our product.

All in all you'll likely get a better product if you do it yourself. Its not that difficult. Its just another database to manage in your code, and it can easily be dropped in to your existing models without major refactoring.

Sorting std::map using value

U can consider using boost::bimap that might gave you a feeling that map is sorted by key and by values simultaneously (this is not what really happens, though)

memcpy() vs memmove()

As already pointed out in other answers, memmove is more sophisticated than memcpy such that it accounts for memory overlaps. The result of memmove is defined as if the src was copied into a buffer and then buffer copied into dst. This does NOT mean that the actual implementation uses any buffer, but probably does some pointer arithmetic.

How to extract the first two characters of a string in shell scripting?

colrm — remove columns from a file

To leave first two chars, just remove columns starting from 3

cat file | colrm 3

How can I remove space (margin) above HTML header?

Just for completeness, changing overflow to auto/hidden should do the trick too.

_x000D_
_x000D_
body {_x000D_
  margin: 0px;_x000D_
  padding: 0px;_x000D_
}_x000D_
_x000D_
header {_x000D_
  margin: 0px;_x000D_
  padding: 0px;_x000D_
  height: 20em;_x000D_
  background-color: #C0C0C0;_x000D_
  overflow: auto;_x000D_
}
_x000D_
<header>_x000D_
  <h1>OQ Online Judge</h1>_x000D_
_x000D_
  <form action="<?php echo base_url();?>/index.php/base/si" method="post">_x000D_
    <label for="email1">E-mail :</label>_x000D_
    <input type="text" name="email" id="email1">_x000D_
    <label for="password1">Password :</label>_x000D_
    <input type="password" name="password" id="password1">_x000D_
    <input type="submit" name="submit" value="Login">_x000D_
  </form>_x000D_
</header>
_x000D_
_x000D_
_x000D_

PowerShell To Set Folder Permissions

Specifying inheritance in the FileSystemAccessRule() constructor fixes this, as demonstrated by the modified code below (notice the two new constuctor parameters inserted between "FullControl" and "Allow").

$Acl = Get-Acl "\\R9N2WRN\Share"

$Ar = New-Object System.Security.AccessControl.FileSystemAccessRule("user", "FullControl", "ContainerInherit,ObjectInherit", "None", "Allow")

$Acl.SetAccessRule($Ar)
Set-Acl "\\R9N2WRN\Share" $Acl

According to this topic

"when you create a FileSystemAccessRule the way you have, the InheritanceFlags property is set to None. In the GUI, this corresponds to an ACE with the Apply To box set to "This Folder Only", and that type of entry has to be viewed through the Advanced settings."

I have tested the modification and it works, but of course credit is due to the MVP posting the answer in that topic.

Php header location redirect not working

Try adding

ob_start();

at the top of the code i.e. before the include statement.

How to install a specific version of a package with pip?

Use ==:

pip install django_modeltranslation==0.4.0-beta2

make image( not background img) in div repeat?

Not with CSS you can't. You need to use JS. A quick example copying the img to the background:

var $el = document.getElementById( 'rightflower' )
  , $img = $el.getElementsByTagName( 'img' )[0]
  , src  = $img.src

$el.innerHTML = "";
$el.style.background = "url( " + src + " ) repeat-y;"

Or you can actually repeat the image, but how many times?

var $el = document.getElementById( 'rightflower' )
  , str = ""
  , imgHTML = $el.innerHTML
  , i, i2;
for( i=0,i2=10; i<i2; i++ ){
    str += imgHTML;
}
$el.innerHTML = str;

Is there a way to only install the mysql client (Linux)?

there are two ways to install mysql client on centOS.

1. First method (download rpm package)

download rpm package from mysql website https://downloads.mysql.com/archives/community/ enter image description here

if you download this rpm package like picture, it's filename like mysql-community-client-8.0.21-1.el8.x86_64.rpm.

then execute sudo rpm -ivh --nodeps --force mysql-community-client-8.0.21-1.el8.x86_64.rpm can install the rpm package the parameters -ivh means install, print output, don't verify and check.

if raise error, maybe version conflict, you can execute rpm -pa | grep mysql to find conflicting package, then execute rpm -e --nodeps <package name> to remove them, and install once more.

finnaly, you can execute which mysql, it's success if print /usr/bin/mysql.

2.Second method (Set repo of yum)

Please refer to this official website:

MySQL Yum Repository

A Quick Guide to Using the MySQL Yum Repository

Declare multiple module.exports in Node.js

If the files are written using ES6 export, you can write:

module.exports = {
  ...require('./foo'),
  ...require('./bar'),
};

How to create custom view programmatically in swift having controls text field, button etc

view = MyCustomView(frame: CGRectZero)

In this line you are trying to set empty rect for your custom view. That's why you cant see your view in simulator.

Looping from 1 to infinity in Python

def to_infinity():
    index = 0
    while True:
        yield index
        index += 1

for i in to_infinity():
    if i > 10:
        break

@import vs #import - iOS 7

It seems that since XCode 7.x a lot of warnings are coming out when enabling clang module with CLANG_ENABLE_MODULES

Take a look at Lots of warnings when building with Xcode 7 with 3rd party libraries

jQuery: what is the best way to restrict "number"-only input for textboxes? (allow decimal points)

There's a nice jquery plugin called Jquery Mask Plugin that designed to make masks on form fields and html elements, but you can also used it to simply define what kind of data could be typed inside of a field:

$('.numeric-input').mask('0#');

Now only numbers will be allowed inside your form field.

text-align: right on <select> or <option>

You could try using the "dir" attribute, but I'm not sure that would produce the desired effect?

<select dir="rtl">
    <option>Foo</option>    
    <option>bar</option>
    <option>to the right</option>
</select>

Demo here: http://jsfiddle.net/fparent/YSJU7/

How to change plot background color?

simpler answer:

ax = plt.axes()
ax.set_facecolor('silver')

What is bootstrapping?

Alex, it's pretty much what your computer does when it boots up. ('Booting' a computer actually comes from the word bootstrapping)

Initially, the small program in your BIOS runs. That contains enough machine code to load and run a larger, more complex program.

That second program is probably something like NTLDR (in Windows) or LILO (in Linux), which then executes and is able to load, then run, the rest of the operating system.

c# Image resizing to different size while preserving aspect ratio

I'm going to add my code here too. This code will allow you resize an image with or without the aspect ratio being enforced or to resize with padding. This is a modified version of egrunin's code.

using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;

namespace ConsoleApplication1
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var path = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName;
            ResizeImage(path, "large.jpg", path, "new.jpg", 100, 100, true, true);
        }

        /// <summary>Resizes an image to a new width and height.</summary>
        /// <param name="originalPath">The folder which holds the original image.</param>
        /// <param name="originalFileName">The file name of the original image.</param>
        /// <param name="newPath">The folder which will hold the resized image.</param>
        /// <param name="newFileName">The file name of the resized image.</param>
        /// <param name="maximumWidth">When resizing the image, this is the maximum width to resize the image to.</param>
        /// <param name="maximumHeight">When resizing the image, this is the maximum height to resize the image to.</param>
        /// <param name="enforceRatio">Indicates whether to keep the width/height ratio aspect or not. If set to false, images with an unequal width and height will be distorted and padding is disregarded. If set to true, the width/height ratio aspect is maintained and distortion does not occur.</param>
        /// <param name="addPadding">Indicates whether fill the smaller dimension of the image with a white background. If set to true, the white padding fills the smaller dimension until it reach the specified max width or height. This is used for maintaining a 1:1 ratio if the max width and height are the same.</param>
        private static void ResizeImage(string originalPath, string originalFileName, string newPath, string newFileName, int maximumWidth, int maximumHeight, bool enforceRatio, bool addPadding)
        {
            var image = Image.FromFile(originalPath + "\\" + originalFileName);
            var imageEncoders = ImageCodecInfo.GetImageEncoders();
            EncoderParameters encoderParameters = new EncoderParameters(1);
            encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, 100L);
            var canvasWidth = maximumWidth;
            var canvasHeight = maximumHeight;
            var newImageWidth = maximumWidth;
            var newImageHeight = maximumHeight;
            var xPosition = 0;
            var yPosition = 0;


            if (enforceRatio)
            {
                var ratioX = maximumWidth / (double)image.Width;
                var ratioY = maximumHeight / (double)image.Height;
                var ratio = ratioX < ratioY ? ratioX : ratioY;
                newImageHeight = (int)(image.Height * ratio);
                newImageWidth = (int)(image.Width * ratio);

                if (addPadding)
                {
                    xPosition = (int)((maximumWidth - (image.Width * ratio)) / 2);
                    yPosition = (int)((maximumHeight - (image.Height * ratio)) / 2);
                }
                else
                {
                    canvasWidth = newImageWidth;
                    canvasHeight = newImageHeight;                  
                }
            }

            var thumbnail = new Bitmap(canvasWidth, canvasHeight);
            var graphic = Graphics.FromImage(thumbnail);

            if (enforceRatio && addPadding)
            {
                graphic.Clear(Color.White);
            }

            graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
            graphic.SmoothingMode = SmoothingMode.HighQuality;
            graphic.PixelOffsetMode = PixelOffsetMode.HighQuality;
            graphic.CompositingQuality = CompositingQuality.HighQuality;
            graphic.DrawImage(image, xPosition, yPosition, newImageWidth, newImageHeight);

            thumbnail.Save(newPath + "\\" + newFileName, imageEncoders[1], encoderParameters);
        }
    }
}

Why is "except: pass" a bad programming practice?

Since it hasn't been mentioned yet, it's better style to use contextlib.suppress:

with suppress(FileNotFoundError):
    os.remove('somefile.tmp')

In this example, somefile.tmp will be non-existent after this block of code executes without raising any exceptions (other than FileNotFoundError, which is suppressed).

force line break in html table cell

Try using

<table  border="1" cellspacing="0" cellpadding="0" class="template-table" 
style="table-layout: fixed; width: 100%"> 

as table style along with

<td style="word-break:break-word">long text</td>

for td it works for normal/real scenario text with words, not for random typed letters without gaps

How to retrieve the last autoincremented ID from a SQLite table?

I've had issues with using SELECT last_insert_rowid() in a multithreaded environment. If another thread inserts into another table that has an autoinc, last_insert_rowid will return the autoinc value from the new table.

Here's where they state that in the doco:

If a separate thread performs a new INSERT on the same database connection while the sqlite3_last_insert_rowid() function is running and thus changes the last insert rowid, then the value returned by sqlite3_last_insert_rowid() is unpredictable and might not equal either the old or the new last insert rowid.

That's from sqlite.org doco

How to make a variable accessible outside a function?

Your variable declarations and their scope are correct. The problem you are facing is that the first AJAX request may take a little bit time to finish. Therefore, the second URL will be filled with the value of sID before the its content has been set. You have to remember that AJAX request are normally asynchronous, i.e. the code execution goes on while the data is being fetched in the background.

You have to nest the requests:

$.getJSON("https://prod.api.pvp.net/api/lol/eune/v1.1/summoner/by-name/"+input+"?api_key=API_KEY_HERE"  , function(name){   obj = name;   // sID is only now available!   sID = obj.id;   console.log(sID); }); 


Clean up your code!

  • Put the second request into a function
  • and let it accept sID as a parameter, so you don't have to declare it globally anymore! (Global variables are almost always evil!)
  • Remove sID and obj variables - name.id is sufficient unless you really need the other variables outside the function.


$.getJSON("https://prod.api.pvp.net/api/lol/eune/v1.1/summoner/by-name/"+input+"?api_key=API_KEY_HERE"  , function(name){   // We don't need sID or obj here - name.id is sufficient   console.log(name.id);    doSecondRequest(name.id); });  /// TODO Choose a better name function doSecondRequest(sID) {   $.getJSON("https://prod.api.pvp.net/api/lol/eune/v1.2/stats/by-summoner/" + sID + "/summary?api_key=API_KEY_HERE", function(stats){         console.log(stats);   }); } 

Hapy New Year :)

Drop all the tables, stored procedures, triggers, constraints and all the dependencies in one sql statement

Here I found new query to delete all sp,functions and triggers

declare @procName varchar(500)
declare cur cursor 

for select [name] from sys.objects where type = 'p'
open cur
fetch next from cur into @procName
while @@fetch_status = 0
begin
    exec('drop procedure ' + @procName)
    fetch next from cur into @procName
end
close cur
deallocate cur

Store text file content line by line into array

I would recommend using an ArrayList, which handles dynamic sizing, whereas an array will require a defined size up front, which you may not know. You can always turn the list back into an array.

BufferedReader in = new BufferedReader(new FileReader("path/of/text"));
String str;

List<String> list = new ArrayList<String>();
while((str = in.readLine()) != null){
    list.add(str);
}

String[] stringArr = list.toArray(new String[0]);

Installing Bower on Ubuntu

Hi another solution to this problem is to simply add the node nodejs binary folder to your PATH using the following command:

ln -s /usr/bin/nodejs /usr/bin/node

See NPM GitHub for better explanation

Grep for beginning and end of line?

Many answers provided for this question. Just wanted to add one more which uses bashism-

#! /bin/bash
while read -r || [[ -n "$REPLY" ]]; do
[[ "$REPLY" =~ ^(-rwx|drwx).*[[:digit:]]+$ ]] && echo "Got one -> $REPLY"
done <"$1"

@kurumi answer for bash, which uses case is also correct but it will not read last line of file if there is no newline sequence at the end(Just save the file without pressing 'Enter/Return' at the last line).

Redirect using AngularJS

Don't forget to inject $location into controller.

Rails 4: before_filter vs. before_action

before_filter/before_action: means anything to be executed before any action executes.

Both are same. they are just alias for each other as their behavior is same.

Flask at first run: Do not use the development server in a production environment

The official tutorial discusses deploying an app to production. One option is to use Waitress, a production WSGI server. Other servers include Gunicorn and uWSGI.

When running publicly rather than in development, you should not use the built-in development server (flask run). The development server is provided by Werkzeug for convenience, but is not designed to be particularly efficient, stable, or secure.

Instead, use a production WSGI server. For example, to use Waitress, first install it in the virtual environment:

$ pip install waitress

You need to tell Waitress about your application, but it doesn’t use FLASK_APP like flask run does. You need to tell it to import and call the application factory to get an application object.

$ waitress-serve --call 'flaskr:create_app'
Serving on http://0.0.0.0:8080

Or you can use waitress.serve() in the code instead of using the CLI command.

from flask import Flask

app = Flask(__name__)

@app.route("/")
def index():
    return "<h1>Hello!</h1>"

if __name__ == "__main__":
    from waitress import serve
    serve(app, host="0.0.0.0", port=8080)
$ python hello.py

Understanding the grid classes ( col-sm-# and col-lg-# ) in Bootstrap 3

Here you have a very good tutorial, that explains, how to use the new grid classes in Bootstrap 3.

It also covers mixins etc.

How can I generate a list of consecutive numbers?

Just to give you another example, although range(value) is by far the best way to do this, this might help you later on something else.

list = []
calc = 0

while int(calc) < 9:
    list.append(calc)
    calc = int(calc) + 1

print list
[0, 1, 2, 3, 4, 5, 6, 7, 8]

BeautifulSoup getting href

You can use find_all in the following way to find every a element that has an href attribute, and print each one:

from BeautifulSoup import BeautifulSoup

html = '''<a href="some_url">next</a>
<span class="class"><a href="another_url">later</a></span>'''

soup = BeautifulSoup(html)

for a in soup.find_all('a', href=True):
    print "Found the URL:", a['href']

The output would be:

Found the URL: some_url
Found the URL: another_url

Note that if you're using an older version of BeautifulSoup (before version 4) the name of this method is findAll. In version 4, BeautifulSoup's method names were changed to be PEP 8 compliant, so you should use find_all instead.


If you want all tags with an href, you can omit the name parameter:

href_tags = soup.find_all(href=True)

Using <style> tags in the <body> with other HTML

As others have already mentioned, HTML 4 requires the <style> tag to be placed in the <head> section (even though most browsers allow <style> tags within the body).

However, HTML 5 includes the scoped attribute (see update below), which allows you to create style sheets that are scoped within the parent element of the <style> tag. This also enables you to place <style> tags within the <body> element:

<!DOCTYPE html>
<html>
<head></head>
<body>

<div id="scoped-content">
    <style type="text/css" scoped>
        h1 { color: red; } 
    </style>

    <h1>Hello</h1>
</div>

    <h1>
      World
    </h1>

</body>
</html>

If you render the above code in an HTML-5 enabled browser that supports scoped, you will see the limited scope of the style sheet.

There's just one major caveat...

At the time I'm writing this answer (May, 2013) almost no mainstream browser currently supports the scoped attribute. (Although apparently developer builds of Chromium support it.)

HOWEVER, there is an interesting implication of the scoped attribute that pertains to this question. It means that future browsers are mandated via the standard to allow <style> elements within the <body> (as long as the <style> elements are scoped.)

So, given that:

  • Almost every existing browser currently ignores the scoped attribute
  • Almost every existing browser currently allows <style> tags within the <body>
  • Future implementations will be required to allow (scoped) <style> tags within the <body>

...then there is literally no harm * in placing <style> tags within the body, as long as you future proof them with a scoped attribute. The only problem is that current browsers won't actually limit the scope of the stylesheet - they'll apply it to the whole document. But the point is that, for all practical purposes, you can include <style> tags within the <body> provided that you:

  • Future-proof your HTML by including the scoped attribute
  • Understand that as of now, the stylesheet within the <body> will not actually be scoped (because no mainstream browser support exists yet)


* except of course, for pissing off HTML validators...


Finally, regarding the common (but subjective) claim that embedding CSS within HTML is poor practice, it should be noted that the whole point of the scoped attribute is to accommodate typical modern development frameworks that allow developers to import chunks of HTML as modules or syndicated content. It is very convenient to have embedded CSS that only applies to a particular chunk of HTML, in order to develop encapsulated, modular components with specific stylings.


Update as of Feb 2019, according to the Mozilla documentation, the scoped attribute is deprecated. Chrome stopped supporting it in version 36 (2014) and Firefox in version 62 (2018). In both cases, the feature had to be explicitly enabled by the user in the browsers' settings. No other major browser ever supported it.

DATEDIFF function in Oracle

In Oracle, you can simply subtract two dates and get the difference in days. Also note that unlike SQL Server or MySQL, in Oracle you cannot perform a select statement without a from clause. One way around this is to use the builtin dummy table, dual:

SELECT TO_DATE('2000-01-02', 'YYYY-MM-DD') -  
       TO_DATE('2000-01-01', 'YYYY-MM-DD') AS DateDiff
FROM   dual

Returning value that was passed into a method

Even more useful, if you have multiple parameters you can access any/all of them with:

_mock.Setup(x => x.DoSomething(It.IsAny<string>(),It.IsAny<string>(),It.IsAny<string>())
     .Returns((string a, string b, string c) => string.Concat(a,b,c));

You always need to reference all the arguments, to match the method's signature, even if you're only going to use one of them.

jQuery's .click - pass parameters to user function

You need to use an anonymous function like this:

$('.leadtoscore').click(function() {
  add_event('shot')
});

You can call it like you have in the example, just a function name without parameters, like this:

$('.leadtoscore').click(add_event);

But the add_event method won't get 'shot' as it's parameter, but rather whatever click passes to it's callback, which is the event object itself...so it's not applicable in this case, but works for many others. If you need to pass parameters, use an anonymous function...or, there's one other option, use .bind() and pass data, like this:

$('.leadtoscore').bind('click', { param: 'shot' }, add_event);

And access it in add_event, like this:

function add_event(event) {
  //event.data.param == "shot", use as needed
}

Get data from fs.readFile

Use the built in promisify library (Node 8+) to make these old callback functions more elegant.

const fs = require('fs');
const util = require('util');

const readFile = util.promisify(fs.readFile);

async function doStuff() {
  try {
    const content = await readFile(filePath, 'utf8');
    console.log(content);
  } catch (e) {
    console.error(e);
  }
}

What does operator "dot" (.) mean?

There is a whole page in the MATLAB documentation dedicated to this topic: Array vs. Matrix Operations. The gist of it is below:

MATLAB® has two different types of arithmetic operations: array operations and matrix operations. You can use these arithmetic operations to perform numeric computations, for example, adding two numbers, raising the elements of an array to a given power, or multiplying two matrices.

Matrix operations follow the rules of linear algebra. By contrast, array operations execute element by element operations and support multidimensional arrays. The period character (.) distinguishes the array operations from the matrix operations. However, since the matrix and array operations are the same for addition and subtraction, the character pairs .+ and .- are unnecessary.

Use of for_each on map elements

From what I remembered, C++ map can return you an iterator of keys using map.begin(), you can use that iterator to loop over all the keys until it reach map.end(), and get the corresponding value: C++ map

Adding a Button to a WPF DataGrid

First create a DataGridTemplateColumn to contain the button:

<DataGridTemplateColumn>
  <DataGridTemplateColumn.CellTemplate> 
    <DataTemplate> 
      <Button Click="ShowHideDetails">Details</Button> 
    </DataTemplate> 
  </DataGridTemplateColumn.CellTemplate> 
</DataGridTemplateColumn>

When the button is clicked, update the containing DataGridRow's DetailsVisibility:

void ShowHideDetails(object sender, RoutedEventArgs e)
{
    for (var vis = sender as Visual; vis != null; vis = VisualTreeHelper.GetParent(vis) as Visual)
    if (vis is DataGridRow)
    {
        var row = (DataGridRow)vis;
        row.DetailsVisibility = 
        row.DetailsVisibility == Visibility.Visible ? Visibility.Collapsed : Visibility.Visible;
        break;
    }
}

Select row on click react-table

Another mechanism for dynamic styling is to define it in the JSX for your component. For example, the following could be used to selectively style the current step in the React tic-tac-toe tutorial (one of the suggested extra credit enhancements:

  return (
    <li key={move}>
      <button style={{fontWeight:(move === this.state.stepNumber ? 'bold' : '')}} onClick={() => this.jumpTo(move)}>{desc}</button>
    </li>
  );

Granted, a cleaner approach would be to add/remove a 'selected' CSS class but this direct approach might be helpful in some cases.

Cursor inside cursor

You could also sidestep nested cursor issues, general cursor issues, and global variable issues by avoiding the cursors entirely.

declare @rowid int
declare @rowid2 int
declare @id int
declare @type varchar(10)
declare @rows int
declare @rows2 int
declare @outer table (rowid int identity(1,1), id int, type varchar(100))
declare @inner table (rowid int  identity(1,1), clientid int, whatever int)

insert into @outer (id, type) 
Select id, type from sometable

select @rows = count(1) from @outer
while (@rows > 0)
Begin
    select top 1 @rowid = rowid, @id  = id, @type = type
    from @outer
    insert into @innner (clientid, whatever ) 
    select clientid whatever from contacts where contactid = @id
    select @rows2 = count(1) from @inner
    while (@rows2 > 0)
    Begin
        select top 1 /* stuff you want into some variables */
        /* Other statements you want to execute */
        delete from @inner where rowid = @rowid2
        select @rows2 = count(1) from @inner
    End  
    delete from @outer where rowid = @rowid
    select @rows = count(1) from @outer
End

How can I see the entire HTTP request that's being sent by my Python application?

If you're using Python 2.x, try installing a urllib2 opener. That should print out your headers, although you may have to combine that with other openers you're using to hit the HTTPS.

import urllib2
urllib2.install_opener(urllib2.build_opener(urllib2.HTTPHandler(debuglevel=1)))
urllib2.urlopen(url)

JavaScript backslash (\) in variables is causing an error

The jsfiddle link to where i tried out your query http://jsfiddle.net/A8Dnv/1/ its working fine @Imrul as mentioned you are using C# on server side and you dont mind that either: http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.escape.aspx

How to grant all privileges to root user in MySQL 8.0

1) This worked for me. First, create a new user. Example: User foo with password bar

> mysql> CREATE USER 'foo'@'localhost' IDENTIFIED WITH mysql_native_password BY 'bar';

2) Replace the below code with a username with 'foo'.

> mysql> GRANT ALL PRIVILEGES ON database_name.* TO'foo'@'localhost';

Note: database_name is the database that you want to have privileges, . means all on all

3) Login as user foo

mysql> mysql -u foo -p

Password: bar

4) Make sure your initial connection from Sequelize is set to foo with pw bar.

What is the meaning of <> in mysql query?

<> is equal to != i.e, both are used to represent the NOT EQUAL operation. For instance, email <> '' and email != '' are same.

CSS text-overflow: ellipsis; not working?

So if you reach this question because you're having trouble trying to get the ellipsis working inside a display: flex container, try adding min-width: 0 to the outmost container that's overflowing its parent even though you already set a overflow: hidden to it and see how that works for you.

More details and a working example on this codepen by aj-foster. Totally did the trick in my case.

Android Studio doesn't recognize my device

In my case it was due to already running and hanged adb.exe on another user under my PC. I had two users on my PC, the second user had the adb.exe process hanged even when I tried to end the process. It worked with me after (End Process Tree) from the Task Manager.

Hope this will help someone with multiple users :)

Ahmad

Check if object is a jQuery object

The best way to check the instance of an object is through instanceof operator or with the method isPrototypeOf() which inspects if the prototype of an object is in another object's prototype chain.

obj instanceof jQuery;
jQuery.prototype.isPrototypeOf(obj);

But sometimes it might fail in the case of multiple jQuery instances on a document. As @Georgiy Ivankin mentioned:

if I have $ in my current namespace pointing to jQuery2 and I have an object from outer namespace (where $ is jQuery1) then I have no way to use instanceof for checking if that object is a jQuery object

One way to overcome that problem is by aliasing the jQuery object in a closure or IIFE

//aliases jQuery as $
(function($, undefined) {
    /*... your code */

    console.log(obj instanceof $);
    console.log($.prototype.isPrototypeOf(obj));

    /*... your code */
}(jQuery1));
//imports jQuery1

Other way to overcome that problem is by inquiring the jquery property in obj

'jquery' in obj

However, if you try to perform that checking with primitive values, it will throw an error, so you can modify the previous checking by ensuring obj to be an Object

'jquery' in Object(obj)

Although the previous way is not the safest (you can create the 'jquery' property in an object), we can improve the validation by working with both approaches:

if (obj instanceof jQuery || 'jquery' in Object(obj)) { }

The problem here is that any object can define a property jquery as own, so a better approach would be to ask in the prototype, and ensure that the object is not null or undefined

if (obj && (obj instanceof jQuery || obj.constructor.prototype.jquery)) { }

Due to coercion, the if statement will make short circuit by evaluating the && operator when obj is any of the falsy values (null, undefined, false, 0, ""), and then proceeds to perform the other validations.

Finally we can write an utility function:

function isjQuery(obj) {
  return (obj && (obj instanceof jQuery || obj.constructor.prototype.jquery));
}

Let's take a look at: Logical Operators and truthy / falsy

How to set top-left alignment for UILabel for iOS application?

I found a solution using AutoLayout in StoryBoard.

1) Set no of lines to 0 and text alignment to Left.

enter image description here

2) Set height constraint.

enter image description here

3) The height Constraint should be in Relation - Less Than or Equal

enter image description here

4)

   override func viewWillLayoutSubviews() {
        sampleLabel.sizeToFit()
    }

I got the result as follows :

enter image description here

Why should I use var instead of a type?

As the others have said, there is no difference in the compiled code (IL) when you use either of the following:

var x1 = new object();
object x2 = new object;

I suppose Resharper warns you because it is [in my opinion] easier to read the first example than the second. Besides, what's the need to repeat the name of the type twice?

Consider the following and you'll get what I mean:

KeyValuePair<string, KeyValuePair<string, int>> y1 = new KeyValuePair<string, KeyValuePair<string, int>>("key", new KeyValuePair<string, int>("subkey", 5));

It's way easier to read this instead:

var y2 = new KeyValuePair<string, KeyValuePair<string, int>>("key", new KeyValuePair<string, int>("subkey", 5));

Hiding axis text in matplotlib plots

If you want to hide just the axis text keeping the grid lines:

frame1 = plt.gca()
frame1.axes.xaxis.set_ticklabels([])
frame1.axes.yaxis.set_ticklabels([])

Doing set_visible(False) or set_ticks([]) will also hide the grid lines.

Save a subplot in matplotlib

Applying the full_extent() function in an answer by @Joe 3 years later from here, you can get exactly what the OP was looking for. Alternatively, you can use Axes.get_tightbbox() which gives a little tighter bounding box

import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
from matplotlib.transforms import Bbox

def full_extent(ax, pad=0.0):
    """Get the full extent of an axes, including axes labels, tick labels, and
    titles."""
    # For text objects, we need to draw the figure first, otherwise the extents
    # are undefined.
    ax.figure.canvas.draw()
    items = ax.get_xticklabels() + ax.get_yticklabels() 
#    items += [ax, ax.title, ax.xaxis.label, ax.yaxis.label]
    items += [ax, ax.title]
    bbox = Bbox.union([item.get_window_extent() for item in items])

    return bbox.expanded(1.0 + pad, 1.0 + pad)

# Make an example plot with two subplots...
fig = plt.figure()
ax1 = fig.add_subplot(2,1,1)
ax1.plot(range(10), 'b-')

ax2 = fig.add_subplot(2,1,2)
ax2.plot(range(20), 'r^')

# Save the full figure...
fig.savefig('full_figure.png')

# Save just the portion _inside_ the second axis's boundaries
extent = full_extent(ax2).transformed(fig.dpi_scale_trans.inverted())
# Alternatively,
# extent = ax.get_tightbbox(fig.canvas.renderer).transformed(fig.dpi_scale_trans.inverted())
fig.savefig('ax2_figure.png', bbox_inches=extent)

I'd post a pic but I lack the reputation points

sys.path different in Jupyter and Python - how to import own modules in Jupyter?

Here is what I do on my projects in jupyter notebook,

import sys
sys.path.append("../") # go to parent dir
from customFunctions import *

Then, to affect changes in customFunctions.py,

%load_ext autoreload
%autoreload 2

JPA EntityManager: Why use persist() over merge()?

JPA is indisputably a great simplification in the domain of enterprise applications built on the Java platform. As a developer who had to cope up with the intricacies of the old entity beans in J2EE I see the inclusion of JPA among the Java EE specifications as a big leap forward. However, while delving deeper into the JPA details I find things that are not so easy. In this article I deal with comparison of the EntityManager’s merge and persist methods whose overlapping behavior may cause confusion not only to a newbie. Furthermore I propose a generalization that sees both methods as special cases of a more general method combine.

Persisting entities

In contrast to the merge method the persist method is pretty straightforward and intuitive. The most common scenario of the persist method's usage can be summed up as follows:

"A newly created instance of the entity class is passed to the persist method. After this method returns, the entity is managed and planned for insertion into the database. It may happen at or before the transaction commits or when the flush method is called. If the entity references another entity through a relationship marked with the PERSIST cascade strategy this procedure is applied to it also."

enter image description here

The specification goes more into details, however, remembering them is not crucial as these details cover more or less exotic situations only.

Merging entities

In comparison to persist, the description of the merge's behavior is not so simple. There is no main scenario, as it is in the case of persist, and a programmer must remember all scenarios in order to write a correct code. It seems to me that the JPA designers wanted to have some method whose primary concern would be handling detached entities (as the opposite to the persist method that deals with newly created entities primarily.) The merge method's major task is to transfer the state from an unmanaged entity (passed as the argument) to its managed counterpart within the persistence context. This task, however, divides further into several scenarios which worsen the intelligibility of the overall method's behavior.

Instead of repeating paragraphs from the JPA specification I have prepared a flow diagram that schematically depicts the behaviour of the merge method:

enter image description here

So, when should I use persist and when merge?

persist

  • You want the method always creates a new entity and never updates an entity. Otherwise, the method throws an exception as a consequence of primary key uniqueness violation.
  • Batch processes, handling entities in a stateful manner (see Gateway pattern).
  • Performance optimization

merge

  • You want the method either inserts or updates an entity in the database.
  • You want to handle entities in a stateless manner (data transfer objects in services)
  • You want to insert a new entity that may have a reference to another entity that may but may not be created yet (relationship must be marked MERGE). For example, inserting a new photo with a reference to either a new or a preexisting album.

Remove last item from array

2019 ECMA5 Solution:

const new_arr = arr.reduce((d, i, idx, l) => idx < l.length - 1 ? [...d, i] : d, [])

Non destructive, generic, one-liner and only requires a copy & paste at the end of your array.

Values of disabled inputs will not be submitted

Yes, all browsers should not submit the disabled inputs, as they are read-only.

More information (section 17.12.1)

Attribute definitions

disabled [CI] When set for a form control, this Boolean attribute disables the control for user input. When set, the disabled attribute has the following effects on an element:

  • Disabled controls do not receive focus.
  • Disabled controls are skipped in tabbing navigation.
  • Disabled controls cannot be successful.

The following elements support the disabled attribute: BUTTON, INPUT, OPTGROUP, OPTION, SELECT, and TEXTAREA.

This attribute is inherited but local declarations override the inherited value.

How disabled elements are rendered depends on the user agent. For example, some user agents "gray out" disabled menu items, button labels, etc.

In this example, the INPUT element is disabled. Therefore, it cannot receive user input nor will its value be submitted with the form.

<INPUT disabled name="fred" value="stone">

Note. The only way to modify dynamically the value of the disabled attribute is through a script.

Pandas DataFrame to List of Dictionaries

As an extension to John Galt's answer -

For the following DataFrame,

   customer  item1   item2   item3
0         1  apple    milk  tomato
1         2  water  orange  potato
2         3  juice   mango   chips

If you want to get a list of dictionaries including the index values, you can do something like,

df.to_dict('index')

Which outputs a dictionary of dictionaries where keys of the parent dictionary are index values. In this particular case,

{0: {'customer': 1, 'item1': 'apple', 'item2': 'milk', 'item3': 'tomato'},
 1: {'customer': 2, 'item1': 'water', 'item2': 'orange', 'item3': 'potato'},
 2: {'customer': 3, 'item1': 'juice', 'item2': 'mango', 'item3': 'chips'}}

How can I determine the type of an HTML element in JavaScript?

nodeName is the attribute you are looking for. For example:

var elt = document.getElementById('foo');
console.log(elt.nodeName);

Note that nodeName returns the element name capitalized and without the angle brackets, which means that if you want to check if an element is an <div> element you could do it as follows:

elt.nodeName == "DIV"

While this would not give you the expected results:

elt.nodeName == "<div>"

Difference between modes a, a+, w, w+, and r+ in built-in open function?

I hit upon this trying to figure out why you would use mode 'w+' versus 'w'. In the end, I just did some testing. I don't see much purpose for mode 'w+', as in both cases, the file is truncated to begin with. However, with the 'w+', you could read after writing by seeking back. If you tried any reading with 'w', it would raise an IOError. Reading without using seek with mode 'w+' isn't going to yield anything, since the file pointer will be after where you have written.

How to call JavaScript function instead of href in HTML

That syntax should work OK, but you can try this alternative.

<a href="javascript:void(0);" onclick="ShowOld(2367,146986,2);">

or

<a href="javascript:ShowOld(2367, 146986, 2);">

UPDATED ANSWER FOR STRING VALUES

If you are passing strings, use single quotes for your function's parameters

<a href="javascript:ShowOld('foo', 146986, 'bar');">

AngularJS + JQuery : How to get dynamic content working in angularjs

You need to call $compile on the HTML string before inserting it into the DOM so that angular gets a chance to perform the binding.

In your fiddle, it would look something like this.

$("#dynamicContent").html(
  $compile(
    "<button ng-click='count = count + 1' ng-init='count=0'>Increment</button><span>count: {{count}} </span>"
  )(scope)
);

Obviously, $compile must be injected into your controller for this to work.

Read more in the $compile documentation.

jQuery not working with IE 11

Adding the "x_ua_compatible" tag to the page didn't work for me. Instead I added it as an HTTP Respone Header via IIS and that worked fine.

In IIS Manager select the site then open HTTP Response Headers and click Add:

enter image description here

The site didn't need restarting, but I did need to Ctrl+F5 to force the page to reload.

How to use passive FTP mode in Windows command prompt?

According to this Egnyte article, Passive FTP is supported from Windows 8.1 onwards.

The Registry key:

"HKEY_CURRENT_USER\Software\Microsoft\FTP\Use PASV"

should be set with the value: yes

If you don't like poking around in the Registry, do the following:

  1. Press WinKey+R to open the Run dialog.
  2. Type inetcpl.cpl and press Enter. The Internet Options dialog will open.
  3. Click on the Advanced tab.
  4. Make your way down to the Browsing secction of the tree view, and ensure the Use Passive FTP item is set to on.
  5. Click on the OK button.

Every time you use ftp.exe, remember to pass the

quote pasv

command immediately after logging in to a remote host.

PS: Grant ftp.exe access to private networks if your Firewall complains.

Adding an onclick function to go to url in JavaScript?

HTML

<input type="button" value="My Button" 
onclick="location.href = 'https://myurl'" />

MVC

<input type="button" value="My Button" 
onclick="location.href='@Url.Action("MyAction", "MyController", new { id = 1 })'" />

Compare 2 JSON objects

Simply parsing the JSON and comparing the two objects is not enough because it wouldn't be the exact same object references (but might be the same values).

You need to do a deep equals.

From http://threebit.net/mail-archive/rails-spinoffs/msg06156.html - which seems the use jQuery.

Object.extend(Object, {
   deepEquals: function(o1, o2) {
     var k1 = Object.keys(o1).sort();
     var k2 = Object.keys(o2).sort();
     if (k1.length != k2.length) return false;
     return k1.zip(k2, function(keyPair) {
       if(typeof o1[keyPair[0]] == typeof o2[keyPair[1]] == "object"){
         return deepEquals(o1[keyPair[0]], o2[keyPair[1]])
       } else {
         return o1[keyPair[0]] == o2[keyPair[1]];
       }
     }).all();
   }
});

Usage:

var anObj = JSON.parse(jsonString1);
var anotherObj= JSON.parse(jsonString2);

if (Object.deepEquals(anObj, anotherObj))
   ...

What online brokers offer APIs?

As of this posting it looks like TradeKing is working on an API. Not sure what the future of it is though.

How to specify Memory & CPU limit in docker compose version 3

Docker Compose does not support the deploy key. It's only respected when you use your version 3 YAML file in a Docker Stack.

This message is printed when you add the deploy key to you docker-compose.yml file and then run docker-compose up -d

WARNING: Some services (database) use the 'deploy' key, which will be ignored. Compose does not support 'deploy' configuration - use docker stack deploy to deploy to a swarm.

The documentation (https://docs.docker.com/compose/compose-file/#deploy) says:

Specify configuration related to the deployment and running of services. This only takes effect when deploying to a swarm with docker stack deploy, and is ignored by docker-compose up and docker-compose run.

cannot resolve symbol javafx.application in IntelliJ Idea IDE

In IntelliJ Idea,

Check the following things are configured properly,

Step 1:

File -> Setting -> Plugins -> search javafx and make sure its enabled.

Step 2: Project Structure (Ctrl+Shift+Alt+s)

Platform Settings -> SDKs -> 1.8 -> Make sure Classpath should have "jre\lib\ext\jfxrt.jar"

Step 3:

Project Settings -> Project -> Project SDK - should be selected 1.8

Project Settings -> Project -> Project language level - configured as 8

Ubuntu: If not found jfxrt.jar in your SDKs then install sudo apt-get install openjfx

How to mention C:\Program Files in batchfile

use this as somethink

"C:/Program Files (x86)/Nox/bin/nox_adb" install -r app.apk

where

"path_to_executable" commands_argument

How to define several include path in Makefile

You need to use -I with each directory. But you can still delimit the directories with whitespace if you use (GNU) make's foreach:

INC=$(DIR1) $(DIR2) ...
INC_PARAMS=$(foreach d, $(INC), -I$d)

jQuery: Selecting by class and input type

You have to use (for checkboxes) :checkbox and the .name attribute to select by class.

For example:

$("input.aclass:checkbox")

The :checkbox selector:

Matches all input elements of type checkbox. Using this psuedo-selector like $(':checkbox') is equivalent to $('*:checkbox') which is a slow selector. It's recommended to do $('input:checkbox').

You should read jQuery documentation to know about selectors.

LIKE vs CONTAINS on SQL Server

Having run both queries on a SQL Server 2012 instance, I can confirm the first query was fastest in my case.

The query with the LIKE keyword showed a clustered index scan.

The CONTAINS also had a clustered index scan with additional operators for the full text match and a merge join.

Plan

How to embed images in email

Generally I handle this by setting up an HTML formatted SMTP message, with IMG tags pointing to a content server. Just make sure you have both text and HTML versions since some email clients cannot support HTML emails.

JPA: JOIN in JPQL

Join on one-to-many relation in JPQL looks as follows:

select b.fname, b.lname from Users b JOIN b.groups c where c.groupName = :groupName 

When several properties are specified in select clause, result is returned as Object[]:

Object[] temp = (Object[]) em.createNamedQuery("...")
    .setParameter("groupName", groupName)
    .getSingleResult(); 
String fname = (String) temp[0];
String lname = (String) temp[1];

By the way, why your entities are named in plural form, it's confusing. If you want to have table names in plural, you may use @Table to specify the table name for the entity explicitly, so it doesn't interfere with reserved words:

@Entity @Table(name = "Users")     
public class User implements Serializable { ... } 

Add item to array in VBScript

Based on Charles Clayton's answer, but slightly simplified...

' add item to array
Sub ArrayAdd(arr, val)
    ReDim Preserve arr(UBound(arr) + 1)
    arr(UBound(arr)) = val
End Sub

Used like so

a = Array()
AddItem(a, 5)
AddItem(a, "foo")

In plain English, what does "git reset" do?

Remember that in git you have:

  • the HEAD pointer, which tells you what commit you're working on
  • the working tree, which represents the state of the files on your system
  • the staging area (also called the index), which "stages" changes so that they can later be committed together

Please include detailed explanations about:

--hard, --soft and --merge;

In increasing order of dangerous-ness:

  • --soft moves HEAD but doesn't touch the staging area or the working tree.
  • --mixed moves HEAD and updates the staging area, but not the working tree.
  • --merge moves HEAD, resets the staging area, and tries to move all the changes in your working tree into the new working tree.
  • --hard moves HEAD and adjusts your staging area and working tree to the new HEAD, throwing away everything.

concrete use cases and workflows;

  • Use --soft when you want to move to another commit and patch things up without "losing your place". It's pretty rare that you need this.

--

# git reset --soft example
touch foo                            // Add a file, make some changes.
git add foo                          // 
git commit -m "bad commit message"   // Commit... D'oh, that was a mistake!
git reset --soft HEAD^               // Go back one commit and fix things.
git commit -m "good commit"          // There, now it's right.

--

  • Use --mixed (which is the default) when you want to see what things look like at another commit, but you don't want to lose any changes you already have.

  • Use --merge when you want to move to a new spot but incorporate the changes you already have into that the working tree.

  • Use --hard to wipe everything out and start a fresh slate at the new commit.

React passing parameter via onclick event using ES6 syntax

TL;DR:

Don't bind function (nor use arrow functions) inside render method. See official recommendations.

https://reactjs.org/docs/faq-functions.html


So, there's an accepted answer and a couple more that points the same. And also there are some comments preventing people from using bind within the render method, and also avoiding arrow functions there for the same reason (those functions will be created once again and again on each render). But there's no example, so I'm writing one.

Basically, you have to bind your functions in the constructor.

class Actions extends Component {

    static propTypes = {
        entity_id: PropTypes.number,
        contact_id: PropTypes.number,
        onReplace: PropTypes.func.isRequired,
        onTransfer: PropTypes.func.isRequired
    }

    constructor() {
        super();
        this.onReplace = this.onReplace.bind(this);
        this.onTransfer = this.onTransfer.bind(this);
    }

    onReplace() {
        this.props.onReplace(this.props.entity_id, this.props.contact_id);
    }

    onTransfer() {
        this.props.onTransfer(this.props.entity_id, this.props.contact_id);
    }

    render() {
        return (
            <div className="actions">
                <button className="btn btn-circle btn-icon-only btn-default"
                    onClick={this.onReplace}
                    title="Replace">
                        <i className="fa fa-refresh"></i>
                </button>
                <button className="btn btn-circle btn-icon-only btn-default"
                    onClick={this.onTransfer}
                    title="Transfer">
                    <i className="fa fa-share"></i>
                </button>                                 
            </div>
        )
    }
}

export default Actions

Key lines are:

constructor

this.onReplace = this.onReplace.bind(this);

method

onReplace() {
    this.props.onReplace(this.props.entity_id, this.props.contact_id);
}

render

onClick={this.onReplace}

In Visual Studio Code How do I merge between two local branches?

You can do it without using plugins.

In the latest version of vscode that I'm using (1.17.0) you can simply open the branch that you want (from the bottom left menu) then press ctrl+shift+p and type Git: Merge branch and then choose the other branch that you want to merge from (to the current one)

How to use Google fonts in React.js?

Google fonts in React.js?

Open your stylesheet i.e, app.css, style.css (what name you have), it doesn't matter, just open stylesheet and paste this code

@import url('https://fonts.googleapis.com/css?family=Josefin+Sans');

and don't forget to change URL of your font that you want, else working fine

and use this as :

body {
  font-family: 'Josefin Sans', cursive;
}

How do I increase the scrollback buffer in a running screen session?

For posterity, this answer is incorrect as noted by Steven Lu. Leaving original text however.

Original answer:

To those arriving via web search (several years later)...

When using screen, your scrollback buffer is a combination of both the screen scrollback buffer as the two previous answers have noted, as well as your putty scrollback buffer.

Be sure that you are increasing BOTH the putty scrollback buffer as well as the screen scrollback buffer, else your putty window itself won't let you scroll back to see your screen's scrollback history (overcome by scrolling within screen with ctrl+a->ctrl+u)

You can change your putty scrollback limit under the "Window" category in the settings. Exiting and reopening a putty session to your screen won't close your screen (assuming you just close the putty window and don't type exit), as the OP asked for.

Hope that helps identify why increasing the screen's scrollback buffer doesn't solve someone's problem.

What is the correct wget command syntax for HTTPS with username and password?

You could try the same address with HTTP instead of HTTPS. Be aware that this does use HTTP instead of HTTPS and only some sites might support this method.

Example address: https://cdimage.debian.org/debian-cd/current/amd64/iso-cd/debian-10.3.0-amd64-netinst.iso

wget http://cdimage.debian.org/debian-cd/current/amd64/iso-cd/debian-10.3.0-amd64-netinst.iso

*notice the http:// instead of https://.

This is probably not recommended though :)

If you can, try use curl.


EDIT:

FYI an example with username (and prompt for password) would be:

curl --user $USERNAME -O http://cdimage.debian.org/debian-cd/current/amd64/iso-cd/debian-10.3.0-amd64-netinst.iso

Where -O is

 -O, --remote-name
              Write output to a local file named like the remote file we get. (Only the file part of the remote file is used, the path is cut off.)

Difference between frontend, backend, and middleware in web development

Here is one breakdown:

Front-end tier -> User Interface layer usually consisting of a mix of HTML, Javascript, CSS, Flash, and various server-side code like ASP.Net, classic ASP, PHP, etc. Think of this as being closest to the user in terms of code.

Middleware, middle-tier -> One tier back, generally referred to as the "plumbing" part of a system. Java and C# are common languages for writing this part that could be viewed as the glue between the UI and the data and can be webservices or WCF components or other SOA components possibly.

Back-end tier -> Databases and other data stores are generally at this level. Oracle, MS-SQL, MySQL, SAP, and various off-the-shelf pieces of software come to mind for this piece of software that is the final processing of the data.

Overlap can exist between any of these as you could have everything poured into one layer like an ASP.Net website that uses the built-in AJAX functionality that generates Javascript while the code behind may contain database commands making the code behind contain both middle and back-end tiers. Alternatively, one could use VBScript to act as all the layers using ADO objects and merging all three tiers into one.

Similarly, taking middleware and either front or back-end can be combined in some cases.

Bottlenecks generally have a few different levels to them:

1) Database or back-end processing -> This can vary from payroll or sales or other tasks where the throughput to the database is bogging things down.

2) Middleware bottlenecks -> This would be where some web service may be hitting capacity but the front and back ends have bandwidth to handle more traffic. Alternatively, there may be some server that is part of a system that isn't quite the UI part or the raw data that can be a bottleneck using something like Biztalk or MSMQ.

3) Front-end bottlenecks -> This could client or server-side issues. For example, if you took a low-end PC and had it load a web page that consisted of a lot of data being downloaded, the client could be where the bottleneck is. Similarly, the server could be queuing up requests if it is getting hammered with requests like what Amazon.com or other high-traffic websites may get at times.

Some of this is subject to interpretation, so it isn't perfect by any means and YMMV.


EDIT: Something to consider is that some systems can have multiple front-ends or back-ends. For example, a content management system will likely have a way for site visitors to view the content that is a front-end but what about how content editors are able to change the data on the site? The ability to pull up this data could be seen as front-end since it is a UI component or it could be seen as a back-end since it is used by internal users rather than the general public viewing the site. Thus, there is something to be said for context here.

The operation couldn’t be completed. (com.facebook.sdk error 2.) ios6

I solve my problem by passing nil permission while login.

[FBSession openActiveSessionWithReadPermissions:nil
                                       allowLoginUI:YES
                                  completionHandler:

Make Iframe to fit 100% of container's remaining height

You can do this with html/css like this:

<body>
    <div style="width:100%; height:30px; background-color:#cccccc;">Banner</div>
    <iframe src="http: //www.google.com.tw" style="position:fixed;top:30px;bottom:0px;width:100%;"></iframe>
</body>

Redirect output of mongo query to a csv file

Just weighing in here with a nice solution I have been using. This is similar to Lucky Soni's solution above in that it supports aggregation, but doesn't require hard coding of the field names.

cursor = db.<collection_name>.<my_query_with_aggregation>;

headerPrinted = false;
while (cursor.hasNext()) {
    item = cursor.next();
    
    if (!headerPrinted) {
        print(Object.keys(item).join(','));
        headerPrinted = true;
    }

    line = Object
        .keys(item)
        .map(function(prop) {
            return '"' + item[prop] + '"';
        })
        .join(',');
    print(line);
}

Save this as a .js file, in this case we'll call it example.js and run it with the mongo command line like so:

mongo <database_name> example.js --quiet > example.csv

I can't access http://localhost/phpmyadmin/

Just change - $cfg['Servers'][$i]['host'] = 'localhost'; in config.inc.ph. i.e. from existing to localhost if you installed it locally

How can I check if a scrollbar is visible?

This expands on @Reigel's answer. It will return an answer for horizontal or vertical scrollbars.

(function($) {
    $.fn.hasScrollBar = function() {
        var e = this.get(0);
        return {
            vertical: e.scrollHeight > e.clientHeight,
            horizontal: e.scrollWidth > e.clientWidth
        };
    }
})(jQuery);

Example:

element.hasScrollBar()             // Returns { vertical: true/false, horizontal: true/false }
element.hasScrollBar().vertical    // Returns true/false
element.hasScrollBar().horizontal  // Returns true/false

delete word after or around cursor in VIM

Normal mode:

daw : delete the word under the cursor    
caw : delete the word under the cursor and put you in insert mode 

Writing html form data to a txt file without the use of a webserver

i made a little change to this code to save entry of a radio button but unable to save the text which appears in text box after selecting the radio button.

the code is below:-

    <!DOCTYPE html>
<html>
<head>
<style>
form * {
  display: block;
  margin: 10px;
}
</style>
<script language="Javascript" >
function download(filename, text) {
  var pom = document.createElement('a');
  pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + 

encodeURIComponent(text));
  pom.setAttribute('download', filename);

  pom.style.display = 'none';
  document.body.appendChild(pom);

  pom.click();

  document.body.removeChild(pom);
}
</script>
</head>
<body>

<form onsubmit="download(this['name'].value, this['text'].value)">
  <input type="text" name="name" value="test.txt">
  <textarea rows=3 cols=50 name="text">PLEASE WRITE ANSWER HERE. </textarea>
<input type="radio" name="radio" value="Option 1" onclick="getElementById('problem').value=this.value;"> Option 1<br>
<input type="radio" name="radio" value="Option 2" onclick="getElementById('problem').value=this.value;"> Option 2<br>
<form onsubmit="download(this['name'].value, this['text'].value)">
<input type="text" name="problem" id="problem">
  <input type="submit" value="SAVE">
</form>
</body>
</html>

Unable to access JSON property with "-" dash

jsonObj.profile-id is a subtraction expression (i.e. jsonObj.profile - id).

To access a key that contains characters that cannot appear in an identifier, use brackets:

jsonObj["profile-id"]

How to remove part of a string before a ":" in javascript?

There is no need for jQuery here, regular JavaScript will do:

var str = "Abc: Lorem ipsum sit amet";
str = str.substring(str.indexOf(":") + 1);

Or, the .split() and .pop() version:

var str = "Abc: Lorem ipsum sit amet";
str = str.split(":").pop();

Or, the regex version (several variants of this):

var str = "Abc: Lorem ipsum sit amet";
str = /:(.+)/.exec(str)[1];

python: how to get information about a function?

In python: help(my_list.append) for example, will give you the docstring of the function.

>>> my_list = []
>>> help(my_list.append)

    Help on built-in function append:

    append(...)
        L.append(object) -- append object to end

Global variables in Java

Lots of good answers, but I want to give this example as it's considered the more proper way to access variables of a class by another class: using getters and setters.

The reason why you use getters and setters this way instead of just making the variable public is as follows. Lets say your var is going to be a global parameter that you NEVER want someone to change during the execution of your program (in the case when you are developing code with a team), something like maybe the URL for a website. In theory this could change and may be used many times in your program, so you want to use a global var to be able to update it all at once. But you do not want someone else to go in and change this var (possibly without realizing how important it is). In that case you simply do not include a setter method, and only include the getter method.

public class Global{
    private static int var = 5;

    public static int getVar(){
        return Global.var;
    }

    //If you do not want to change the var ever then do not include this
    public static void setVar(int var){
        Global.var = var;
    }
}

how to make a full screen div, and prevent size to be changed by content?

#fullDiv {
    height: 100%;
    width: 100%;
    left: 0;
    top: 0;
    overflow: hidden;
    position: fixed;
}

How is CountDownLatch used in Java Multithreading?

As mentioned in JavaDoc (https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/CountDownLatch.html), CountDownLatch is a synchronization aid, introduced in Java 5. Here the synchronization does not mean restricting access to a critical section. But rather sequencing actions of different threads. The type of synchronization achieved through CountDownLatch is similar to that of Join. Assume that there is a thread "M" which needs to wait for other worker threads "T1", "T2", "T3" to complete its tasks Prior to Java 1.5, the way this can be done is, M running the following code

    T1.join();
    T2.join();
    T3.join();

The above code makes sure that thread M resumes its work after T1, T2, T3 completes its work. T1, T2, T3 can complete their work in any order. The same can be achieved through CountDownLatch, where T1,T2, T3 and thread M share same CountDownLatch object.
"M" requests : countDownLatch.await();
where as "T1","T2","T3" does countDownLatch.countdown();

One disadvantage with the join method is that M has to know about T1, T2, T3. If there is a new worker thread T4 added later, then M has to be aware of it too. This can be avoided with CountDownLatch. After implementation the sequence of action would be [T1,T2,T3](the order of T1,T2,T3 could be anyway) -> [M]

How to get number of rows using SqlDataReader in C#

There are only two options:

  • Find out by reading all rows (and then you might as well store them)

  • run a specialized SELECT COUNT(*) query beforehand.

Going twice through the DataReader loop is really expensive, you would have to re-execute the query.

And (thanks to Pete OHanlon) the second option is only concurrency-safe when you use a transaction with a Snapshot isolation level.

Since you want to end up storing all rows in memory anyway the only sensible option is to read all rows in a flexible storage (List<> or DataTable) and then copy the data to any format you want. The in-memory operation will always be much more efficient.

How to run iPhone emulator WITHOUT starting Xcode?

From Terminal you have to run:

open -a Simulator

How to set the color of "placeholder" text?

#Try this:

input[type="text"],textarea[type="text"]::-webkit-input-placeholder {
    color:#f51;
}
input[type="text"],textarea[type="text"]:-moz-placeholder {
    color:#f51;
}
input[type="text"],textarea[type="text"]::-moz-placeholder {
    color:#f51;
}
input[type="text"],textarea[type="text"]:-ms-input-placeholder {
    color:#f51;
}

##Works very well for me.

Create a mocked list by mockito

OK, this is a bad thing to be doing. Don't mock a list; instead, mock the individual objects inside the list. See Mockito: mocking an arraylist that will be looped in a for loop for how to do this.

Also, why are you using PowerMock? You don't seem to be doing anything that requires PowerMock.

But the real cause of your problem is that you are using when on two different objects, before you complete the stubbing. When you call when, and provide the method call that you are trying to stub, then the very next thing you do in either Mockito OR PowerMock is to specify what happens when that method is called - that is, to do the thenReturn part. Each call to when must be followed by one and only one call to thenReturn, before you do any more calls to when. You made two calls to when without calling thenReturn - that's your error.

What is the purpose of the "final" keyword in C++11 for functions?

Final cannot be applied to non-virtual functions.

error: only virtual member functions can be marked 'final'

It wouldn't be very meaningful to be able to mark a non-virtual method as 'final'. Given

struct A { void foo(); };
struct B : public A { void foo(); };
A * a = new B;
a -> foo(); // this will call A :: foo anyway, regardless of whether there is a B::foo

a->foo() will always call A::foo.

But, if A::foo was virtual, then B::foo would override it. This might be undesirable, and hence it would make sense to make the virtual function final.

The question is though, why allow final on virtual functions. If you have a deep hierarchy:

struct A            { virtual void foo(); };
struct B : public A { virtual void foo(); };
struct C : public B { virtual void foo() final; };
struct D : public C { /* cannot override foo */ };

Then the final puts a 'floor' on how much overriding can be done. Other classes can extend A and B and override their foo, but it a class extends C then it is not allowed.

So it probably doesn't make sense to make the 'top-level' foo final, but it might make sense lower down.

(I think though, there is room to extend the words final and override to non-virtual members. They would have a different meaning though.)

How to Extract Year from DATE in POSTGRESQL

Try

select date_part('year', your_column) from your_table;

or

select extract(year from your_column) from your_table;

Should each and every table have a primary key?

It is a good practice to have a PK on every table, but it's not a MUST. Most probably you will need a unique index, and/or a clustered index (which is PK or not) depending on your need.

Check out the Primary Keys and Clustered Indexes sections on Books Online (for SQL Server)

"PRIMARY KEY constraints identify the column or set of columns that have values that uniquely identify a row in a table. No two rows in a table can have the same primary key value. You cannot enter NULL for any column in a primary key. We recommend using a small, integer column as a primary key. Each table should have a primary key. A column or combination of columns that qualify as a primary key value is referred to as a candidate key."

But then check this out also: http://www.aisintl.com/case/primary_and_foreign_key.html

RSpec: how to test if a method was called?

The below should work

describe "#foo"
  it "should call 'bar' with appropriate arguments" do
     subject.stub(:bar)
     subject.foo
     expect(subject).to have_received(:bar).with("Invalid number of arguments")
  end
end

Documentation: https://github.com/rspec/rspec-mocks#expecting-arguments

Floating point comparison functions for C#

From Bruce Dawson's paper on comparing floats, you can also compare floats as integers. Closeness is determined by least significant bits.

public static bool AlmostEqual2sComplement( float a, float b, int maxDeltaBits ) 
{
    int aInt = BitConverter.ToInt32( BitConverter.GetBytes( a ), 0 );
    if ( aInt <  0 )
        aInt = Int32.MinValue - aInt;  // Int32.MinValue = 0x80000000

    int bInt = BitConverter.ToInt32( BitConverter.GetBytes( b ), 0 );
    if ( bInt < 0 )
        bInt = Int32.MinValue - bInt;

    int intDiff = Math.Abs( aInt - bInt );
    return intDiff <= ( 1 << maxDeltaBits );
}

EDIT: BitConverter is relatively slow. If you're willing to use unsafe code, then here is a very fast version:

    public static unsafe int FloatToInt32Bits( float f )
    {
        return *( (int*)&f );
    }

    public static bool AlmostEqual2sComplement( float a, float b, int maxDeltaBits )
    {
        int aInt = FloatToInt32Bits( a );
        if ( aInt < 0 )
            aInt = Int32.MinValue - aInt;

        int bInt = FloatToInt32Bits( b );
        if ( bInt < 0 )
            bInt = Int32.MinValue - bInt;

        int intDiff = Math.Abs( aInt - bInt );
        return intDiff <= ( 1 << maxDeltaBits );
    }

Get all dates between two dates in SQL Server

DECLARE @FirstDate DATE = '2018-01-01'
DECLARE @LastDate Date = '2018-12-31'
DECLARE @tbl TABLE(ID INT IDENTITY(1,1) PRIMARY KEY,CurrDate date)
INSERT @tbl VALUES( @FirstDate)
WHILE @FirstDate < @LastDate
BEGIN
SET @FirstDate = DATEADD( day,1, @FirstDate)
INSERT @tbl VALUES( @FirstDate)
END
INSERT @tbl VALUES( @LastDate) 

SELECT * FROM @tbl

HTML code for INR

How about using fontawesome icon for Indian Rupee (INR).

Add font awesome CSS from CDN in the Head section of your HTML page:

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

And then using the font like this:

<i class="fa fa-inr" aria-hidden="true"></i>

How to delete items from a dictionary while iterating over it?

You could first build a list of keys to delete, and then iterate over that list deleting them.

dict = {'one' : 1, 'two' : 2, 'three' : 3, 'four' : 4}
delete = []
for k,v in dict.items():
    if v%2 == 1:
        delete.append(k)
for i in delete:
    del dict[i]

Class name does not name a type in C++

It actually happend to me because I mistakenly named the source file "something.c" instead of "something.cpp". I hope this helps someone who has the same error.

Python, creating objects

when you create an object using predefine class, at first you want to create a variable for storing that object. Then you can create object and store variable that you created.

class Student:
     def __init__(self):

# creating an object....

   student1=Student()

Actually this init method is the constructor of class.you can initialize that method using some attributes.. In that point , when you creating an object , you will have to pass some values for particular attributes..

class Student:
      def __init__(self,name,age):
            self.name=value
            self.age=value

 # creating an object.......

     student2=Student("smith",25)

C++ auto keyword. Why is it magic?

This functionality hasn't been there your whole life. It's been supported in Visual Studio since the 2010 version. It's a new C++11 feature, so it's not exclusive to Visual Studio and is/will be portable. Most compilers support it already.

MySQL Event Scheduler on a specific time everyday

The documentation on CREATE EVENT is quite good, but it takes a while to get it right.

You have two problems, first, making the event recur, second, making it run at 13:00 daily.

This example creates a recurring event.

CREATE EVENT e_hourly
    ON SCHEDULE
      EVERY 1 HOUR
    COMMENT 'Clears out sessions table each hour.'
    DO
      DELETE FROM site_activity.sessions;

When in the command-line MySQL client, you can:

SHOW EVENTS;

This lists each event with its metadata, like if it should run once only, or be recurring.

The second problem: pointing the recurring event to a specific schedule item.

By trying out different kinds of expression, we can come up with something like:

CREATE EVENT IF NOT EXISTS `session_cleaner_event`
ON SCHEDULE
  EVERY 13 DAY_HOUR
  COMMENT 'Clean up sessions at 13:00 daily!'
  DO
    DELETE FROM site_activity.sessions;

How to dismiss AlertDialog in android

Try this:

   AlertDialog.Builder builder = new AlertDialog.Builder(this);
   AlertDialog OptionDialog = builder.create();
  background.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            SetBackground();
       OptionDialog .dismiss();
        }
    });

How do I iterate through each element in an n-dimensional matrix in MATLAB?

You want to simulate n-nested for loops.

Iterating through n-dimmensional array can be seen as increasing the n-digit number.

At each dimmension we have as many digits as the lenght of the dimmension.

Example:

Suppose we had array(matrix)

int[][][] T=new int[3][4][5];

in "for notation" we have:

for(int x=0;x<3;x++)
   for(int y=0;y<4;y++)
       for(int z=0;z<5;z++)
          T[x][y][z]=...

to simulate this you would have to use the "n-digit number notation"

We have 3 digit number, with 3 digits for first, 4 for second and five for third digit

We have to increase the number, so we would get the sequence

0 0 0
0 0 1
0 0 2    
0 0 3
0 0 4
0 1 0
0 1 1
0 1 2
0 1 3
0 1 4
0 2 0
0 2 1
0 2 2
0 2 3
0 2 4
0 3 0
0 3 1
0 3 2
0 3 3
0 3 4
and so on

So you can write the code for increasing such n-digit number. You can do it in such way that you can start with any value of the number and increase/decrease the digits by any numbers. That way you can simulate nested for loops that begin somewhere in the table and finish not at the end.

This is not an easy task though. I can't help with the matlab notation unfortunaly.

Entity Framework is Too Slow. What are my options?

One suggestion is to use LINQ to Entity Framework only for single-record CRUD statements.

For more involved queries, searches, reporting, etc, write a stored procedure and add it to the Entity Framework model as described on MSDN.

This is the approach I've taken with a couple of my sites and it seems to be a good compromise between productivity and performance. Entity Framework will not always generate the most efficient SQL for the task at hand. And rather than spending the time to figure out why, writing a stored procedure for the more complex queries actually saves time for me. Once you're familiar with the process, it's not too much of a hassle to add stored procs to your EF model. And of course the benefit of adding it to your model is that you get all that strongly typed goodness that comes from using an ORM.

Using Predicate in Swift

You can use filters available in swift to filter content from an array instead of using a predicate like in Objective-C.

An example in Swift 4.0 is as follows:

var stringArray = ["foundation","coredata","coregraphics"]
stringArray = stringArray.filter { $0.contains("core") }

In the above example, since each element in the array is a string you can use the contains method to filter the array.

If the array contains custom objects, then the properties of that object can be used to filter the elements similarly.

How to move table from one tablespace to another in oracle 11g

Use sql from sql:

spool output of this to a file:

select 'alter index '||owner||'.'||index_name||' rebuild tablespace TO_TABLESPACE_NAME;' from all_indexes where owner='OWNERNAME';

spoolfile will have something like this:

alter index OWNER.PK_INDEX rebuild tablespace CORRECT_TS_NAME;

Excel how to find values in 1 column exist in the range of values in another

This is what you need:

 =NOT(ISERROR(MATCH(<cell in col A>,<column B>, 0)))  ## pseudo code

For the first cell of A, this would be:

 =NOT(ISERROR(MATCH(A2,$B$2:$B$5, 0)))

Enter formula (and drag down) as follows:

enter image description here

You will get:

enter image description here

Bootstrap center heading

just use class='text-center' in element for center heading.

<h2 class="text-center">sample center heading</h2>

use class='text-left' in element for left heading, and use class='text-right' in element for right heading.

Convert a RGB Color Value to a Hexadecimal String

A one liner but without String.format for all RGB colors:

Color your_color = new Color(128,128,128);

String hex = "#"+Integer.toHexString(your_color.getRGB()).substring(2);

You can add a .toUpperCase()if you want to switch to capital letters. Note, that this is valid (as asked in the question) for all RGB colors.

When you have ARGB colors you can use:

Color your_color = new Color(128,128,128,128);

String buf = Integer.toHexString(your_color.getRGB());
String hex = "#"+buf.substring(buf.length()-6);

A one liner is theoretically also possible but would require to call toHexString twice. I benchmarked the ARGB solution and compared it with String.format():

enter image description here

CSS: fixed position on x-axis but not y?

Very easy solution is:

window.onscroll = function (){
  document.getElementById('header').style.left= 15 - (document.documentElement.scrollLeft + document.body.scrollLeft)+"px";
}

Magento addFieldToFilter: Two fields, match as OR, not AND

Here is my solution in Enterprise 1.11 (should work in CE 1.6):

    $collection->addFieldToFilter('max_item_count',
                    array(
                        array('gteq' => 10),
                        array('null' => true),
                    )
            )
            ->addFieldToFilter('max_item_price',
                    array(
                        array('gteq' => 9.99),
                        array('null' => true),
                    )
            )
            ->addFieldToFilter('max_item_weight',
                    array(
                        array('gteq' => 1.5),
                        array('null' => true),
                    )
            );

Which results in this SQL:

    SELECT `main_table`.*
    FROM `shipping_method_entity` AS `main_table`
    WHERE (((max_item_count >= 10) OR (max_item_count IS NULL)))
      AND (((max_item_price >= 9.99) OR (max_item_price IS NULL)))
      AND (((max_item_weight >= 1.5) OR (max_item_weight IS NULL)))

removing html element styles via javascript

Use

particular_node.classList.remove("<name-of-class>")

For native javascript

SyntaxError: expected expression, got '<'

Just simply add:

app.use(express.static(__dirname +'/app'));

where '/app' is the directory where your index.html resides or your Webapp.

is it possible to get the MAC address for machine using nmap

Use snmp-interfaces.nse nmap script (written in lua) to get the MAC address of remote machine like this:

nmap -sU -p 161 -T4 -d -v -n -Pn --script snmp-interfaces 80.234.33.182

Completed NSE at 13:25, 2.69s elapsed
Nmap scan report for 80.234.33.182
Host is up, received user-set (0.078s latency).
Scanned at 2014-08-22 13:25:29 ???????? ????? (????) for 3s
PORT    STATE SERVICE REASON
161/udp open  snmp    udp-response
| snmp-interfaces: 
|   eth
|     MAC address: 00:50:60:03:81:c9 (Tandberg Telecom AS)
|     Type: ethernetCsmacd  Speed: 10 Mbps
|     Status: up
|     Traffic stats: 1.27 Gb sent, 53.91 Mb received
|   lo
|     Type: softwareLoopback  Speed: 0 Kbps
|     Status: up
|_    Traffic stats: 4.10 Kb sent, 4.10 Kb received

Failed to execute 'postMessage' on 'DOMWindow': https://www.youtube.com !== http://localhost:9000

There could be any of the following, but all of them lead into DOM not loaded before its accessed by the javascript.

So here is what you have to ensure before actually calling JS code: * Make sure the container has loaded before any javascript is called * Make sure the target URL is loaded in whatever container it has to

I came across the similar issue but on my local when I am trying to have my Javascript run well before onLoad of the main page which causes the error message. I have fixed it by simply waiting for whole page to load and then call the required function.

You could simply do this by adding a timeout function when page has loaded and call your onload event like:

window.onload = new function() { setTimeout(function() { // some onload event }, 10); }

that will ensure what you are trying will execute well after onLoad is trigger.

SQL UPDATE all values in a field with appended string CONCAT not working

That's pretty much all you need:

mysql> select * from t;
+------+-------+
| id   | data  |
+------+-------+
|    1 | max   |
|    2 | linda |
|    3 | sam   |
|    4 | henry |
+------+-------+
4 rows in set (0.02 sec)

mysql> update t set data=concat(data, 'a');
Query OK, 4 rows affected (0.01 sec)
Rows matched: 4  Changed: 4  Warnings: 0

mysql> select * from t;
+------+--------+
| id   | data   |
+------+--------+
|    1 | maxa   |
|    2 | lindaa |
|    3 | sama   |
|    4 | henrya |
+------+--------+
4 rows in set (0.00 sec)

Not sure why you'd be having trouble, though I am testing this on 5.1.41

How do I build an import library (.lib) AND a DLL in Visual C++?

OK, so I found the answer from http://binglongx.wordpress.com/2009/01/26/visual-c-does-not-generate-lib-file-for-a-dll-project/ says that this problem was caused by not exporting any symbols and further instructs on how to export symbols to create the lib file. To do so, add the following code to your .h file for your DLL.

#ifdef BARNABY_EXPORTS
#define BARNABY_API __declspec(dllexport)
#else
#define BARNABY_API __declspec(dllimport)
#endif

Where BARNABY_EXPORTS and BARNABY_API are unique definitions for your project. Then, each function you export you simply precede by:

BARNABY_API int add(){
}

This problem could have been prevented either by clicking the Export Symbols box on the new project DLL Wizard or by voting yes for lobotomies for computer programmers.

How can I exclude all "permission denied" messages from "find"?

I had to use:

find / -name expect 2>/dev/null

specifying the name of what I wanted to find and then telling it to redirect all errors to /dev/null

expect being the location of the expect program I was searching for.

Pass arguments into C program from command line

Take a look at the getopt library; it's pretty much the gold standard for this sort of thing.

Difference between signature versions - V1 (Jar Signature) and V2 (Full APK Signature) while generating a signed APK in Android Studio?

According to this link: signature help

APK Signature Scheme v2 offers:

  1. Faster app install times
  2. More protection against unauthorized alterations to APK files.

Android 7.0 introduces APK Signature Scheme v2, a new app-signing scheme that offers faster app install times and more protection against unauthorized alterations to APK files. By default, Android Studio 2.2 and the Android Plugin for Gradle 2.2 sign your app using both APK Signature Scheme v2 and the traditional signing scheme, which uses JAR signing.

It is recommended to use APK Signature Scheme v2 but is not mandatory.

Although we recommend applying APK Signature Scheme v2 to your app, this new scheme is not mandatory. If your app doesn't build properly when using APK Signature Scheme v2, you can disable the new scheme.

Add string in a certain position in Python

This seems very easy:

>>> hash = "355879ACB6"
>>> hash = hash[:4] + '-' + hash[4:]
>>> print hash
3558-79ACB6

However if you like something like a function do as this:

def insert_dash(string, index):
    return string[:index] + '-' + string[index:]

print insert_dash("355879ACB6", 5)

XAMPP Apache Webserver localhost not working on MAC OS

try

sudo /Applications/XAMPP/xamppfiles/bin/apachectl start

in terminal

How can I add a space in between two outputs?

import java.util.Scanner;
public class class2 {

    public void Multipleclass(){
       String x,y;
       Scanner sc=new Scanner(System.in);

       System.out.println("Enter your First name");
       x=sc.next();
       System.out.println("Enter your Last name");
       y=sc.next();

       System.out.println(x+  " "  +y );
   }
}

Cannot Resolve Collation Conflict

The thing about collations is that although the database has its own collation, every table, and every column can have its own collation. If not specified it takes the default of its parent object, but can be different.

When you change collation of the database, it will be the new default for all new tables and columns, but it doesn't change the collation of existing objects inside the database. You have to go and change manually the collation of every table and column.

Luckily there are scripts available on the internet that can do the job. I am not going to recommend any as I haven't tried them but here are few links:

http://www.codeproject.com/Articles/302405/The-Easy-way-of-changing-Collation-of-all-Database

Update Collation of all fields in database on the fly

http://www.sqlservercentral.com/Forums/Topic820675-146-1.aspx

If you need to have different collation on two objects or can't change collations - you can still JOIN between them using COLLATE command, and choosing the collation you want for join.

SELECT * FROM A JOIN B ON A.Text = B.Text COLLATE Latin1_General_CI_AS 

or using default database collation:

SELECT * FROM A JOIN B ON A.Text = B.Text COLLATE DATABASE_DEFAULT

Converting ArrayList to Array in java

package com.v4common.shared.beans.audittrail;

import java.util.ArrayList;
import java.util.List;

public class test1 {
    public static void main(String arg[]){
        List<String> list = new ArrayList<String>();
        list.add("abcd#xyz");
        list.add("mnop#qrs");

        Object[] s = list.toArray();
        String[] s1= new String[list.size()];
        String[] s2= new String[list.size()];

        for(int i=0;i<s.length;i++){
            if(s[i] instanceof String){
                String temp = (String)s[i];
                if(temp.contains("#")){
                    String[] tempString = temp.split("#");
                    for(int j=0;j<tempString.length;j++) {
                        s1[i] = tempString[0];
                        s2[i] = tempString[1];
                    }

                }
            }   
        }
        System.out.println(s1.length);
        System.out.println(s2.length);
        System.out.println(s1[0]);
        System.out.println(s1[1]);
    }
}

Load image from url

Best Method I have tried instead of using any libraries

public Bitmap getbmpfromURL(String surl){
    try {
        URL url = new URL(surl);
        HttpURLConnection urlcon = (HttpURLConnection) url.openConnection();
        urlcon.setDoInput(true);
        urlcon.connect();
        InputStream in = urlcon.getInputStream();
        Bitmap mIcon = BitmapFactory.decodeStream(in);
        return  mIcon;
    } catch (Exception e) {
        Log.e("Error", e.getMessage());
        e.printStackTrace();
        return null;
    }
}

how to sort pandas dataframe from one column

Just as another solution:

Instead of creating the second column, you can categorize your string data(month name) and sort by that like this:

df.rename(columns={1:'month'},inplace=True)
df['month'] = pd.Categorical(df['month'],categories=['December','November','October','September','August','July','June','May','April','March','February','January'],ordered=True)
df = df.sort_values('month',ascending=False)

It will give you the ordered data by month name as you specified while creating the Categorical object.

Can I prevent text in a div block from overflowing?

overflow: scroll ? Or auto. in the style attribute.

How do I grant myself admin access to a local SQL Server instance?

Yes - it appears you forgot to add yourself to the sysadmin role when installing SQL Server. If you are a local administrator on your machine, this blog post can help you use SQLCMD to get your account into the SQL Server sysadmin group without having to reinstall. It's a bit of a security hole in SQL Server, if you ask me, but it'll help you out in this case.

how to convert string into time format and add two hours

tl;dr

LocalDateTime.parse( 
    "2018-01-23 01:23:45".replace( " " , "T" )  
).plusHours( 2 )

java.time

The modern approach uses the java.time classes added to Java 8, Java 9, and later.

user enters in the format YYYY-MM-DD HH:MM:SS

Parse that input string into a date-time object. Your format is close to complying with standard ISO 8601 format, used by default in the java.time classes for parsing/generating strings. To fully comply, replace the SPACE in the middle with a T.

String input = "2018-01-23 01:23:45".replace( " " , "T" ) ; // Yields: 2018-01-23T01:23:45

Parse as a LocalDateTime given that your input lacks any indicator of time zone or offset-from-UTC.

LocalDateTime ldt = LocalDateTime.parse( input ) ;

add two hours

The java.time classes can do the math for you.

LocalDateTime twoHoursLater = ldt.plusHours( 2 ) ;

Time Zone

Be aware that a LocalDateTime does not represent a moment, a point on the timeline. Without the context of a time zone or offset-from-UTC, it has no real meaning. The “Local” part of the name means any locality or no locality, rather than any one particular locality. Just saying "noon on Jan 21st" could mean noon in Auckland, New Zealand which happens several hours earlier than noon in Paris France.

To define an actual moment, you must specify a zone or offset.

ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
ZonedDateTime zdt = ldt.atZone( z ) ;  // Define an actual moment, a point on the timeline by giving a context with time zone.

If you know the intended time zone for certain, apply it before adding the two hours. The LocalDateTime class assumes simple generic 24-hour days when doing the math. But in various time zones on various dates, days may be 23 or 25 hours long, or may be other lengths. So, for correct results in a zoned context, add the hours to your ZonedDateTime rather than LocalDateTime.


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.

How to create a new img tag with JQuery, with the src and id from a JavaScript object?

For those who need the same feature in IE 8, this is how I solved the problem:

  var myImage = $('<img/>');

               myImage.attr('width', 300);
               myImage.attr('height', 300);
               myImage.attr('class', "groupMediaPhoto");
               myImage.attr('src', photoUrl);

I could not force IE8 to use object in constructor.