Programs & Examples On #Regsvr32

You can use the Regsvr32 tool (Regsvr32.exe) to register and unregister OLE controls such as DLL or ActiveX Controls (OCX) files in the Windows Registry.

Register comdlg32.dll gets Regsvr32: DllRegisterServer entry point was not found

I also had the similar problem while registering myinfo.dll file in windows 7. Following work for me: Create a short cut on your desktop C:\Windows\System32\regsvr32.exe c:\windows\system32\myinfo.dll right click on the short cut just created and select as Run as administrator.

The module ".dll" was loaded but the entry-point was not found

The error indicates that the DLL is either not a COM DLL or it's corrupt. If it's not a COM DLL and not being used as a COM DLL by an application then there is no need to register it.
From what you say in your question (the service is not registered) it seems that we are talking about a service not correctly installed. I will try to reinstall the application.

How do I register a DLL file on Windows 7 64-bit?

Type regsvr32 name.dll into the Command Prompt (executed in elevated mode!) and press "Enter." Note that name.dll should be replaced with the name of the DLL that you want to register. For example, if you want to register the iexplore.dll, type regsvr32 iexplore.dll.

How do I prevent a parent's onclick event from firing when a child anchor is clicked?

Writing if anyone needs (worked for me):

event.stopImmediatePropagation()

From this solution.

Java "lambda expressions not supported at this language level"

Actually, Eclipse support for Java 8 is available: see here and here.

  • For Kepler, it is available as a "feature patch" against SR2 (i.e. Eclipse 4.3.2)
  • For Luna (Eclipse 4.4) it will be in the standard release. (release schedule)

how to make log4j to write to the console as well

This works well for console in debug mode

log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.Threshold=DEBUG
log4j.appender.console.Target=System.out
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.conversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} %-5p - %m%n

Application Installation Failed in Android Studio

I also had the problem after globally changing the project name, applicationid and the folders containing the java files.

Disabling Instant run helped, but was not a good option, so this helped:

  • close Android Studio
  • deleted those files and folders: rm -Rf .gradle .tags local.properties .idea/workspace.xml .idea/caches/* .idea/libraries app/build
  • start Android Studio and let it resync everything
  • press run

How to pass in a react component into another react component to transclude the first component's content?

You can pass it as a normal prop: foo={<ComponentOne />}

For example:

const ComponentOne = () => <div>Hello world!</div>
const ComponentTwo = () => (
  <div>
    <div>Hola el mundo!</div>
    <ComponentThree foo={<ComponentOne />} />
  </div>
)
const ComponentThree = ({ foo }) => <div>{foo}</div>

C# list.Orderby descending

Sure:

var newList = list.OrderByDescending(x => x.Product.Name).ToList();

Doc: OrderByDescending(IEnumerable, Func).

In response to your comment:

var newList = list.OrderByDescending(x => x.Product.Name)
                  .ThenBy(x => x.Product.Price)
                  .ToList();

How to turn off gcc compiler optimization to enable buffer overflow

That's a good problem. In order to solve that problem you will also have to disable ASLR otherwise the address of g() will be unpredictable.

Disable ASLR:

sudo bash -c 'echo 0 > /proc/sys/kernel/randomize_va_space'

Disable canaries:

gcc overflow.c -o overflow -fno-stack-protector

After canaries and ASLR are disabled it should be a straight forward attack like the ones described in Smashing the Stack for Fun and Profit

Here is a list of security features used in ubuntu: https://wiki.ubuntu.com/Security/Features You don't have to worry about NX bits, the address of g() will always be in a executable region of memory because it is within the TEXT memory segment. NX bits only come into play if you are trying to execute shellcode on the stack or heap, which is not required for this assignment.

Now go and clobber that EIP!

When to use StringBuilder in Java

Ralph's answer is fabulous. I would rather use StringBuilder class to build/decorate the String because the usage of it is more look like Builder pattern.

public String decorateTheString(String orgStr){
            StringBuilder builder = new StringBuilder();
            builder.append(orgStr);
            builder.deleteCharAt(orgStr.length()-1);
            builder.insert(0,builder.hashCode());
            return builder.toString();
}

It can be use as a helper/builder to build the String, not the String itself.

Can I export a variable to the environment from a bash script without sourcing it?

The answer is no, but for me I did the following

the script: myExport

#! \bin\bash
export $1

an alias in my .bashrc

alias myExport='source myExport' 

Still you source it, but maybe in this way it is more useable and it is interesting for someone else.

Can enums be subclassed to add new elements?

The recommended solution to this is the extensible enum pattern.

This involves creating an interface and using that where you currently use the enum. Then make the enum implement the interface. You can add more constants by making that new enum also extend the interface.

Apache is downloading php files instead of displaying them

If you have virtualmin try to comment out these lines in your apache configuration in /etc/apache2/sites-available

  #RemoveHandler .php
  #RemoveHandler .php7.0
  #php_admin_value engine Off

Cannot find vcvarsall.bat when running a Python script

Here's a simple solution. I'm using Python 2.7 and Windows 7.

What you're trying to install requires a C/C++ compiler but Python isn't finding it. A lot of Python packages are actually written in C/C++ and need to be compiled. vcvarsall.bat is needed to compile C++ and pip is assuming your machine can do that.

  1. Try upgrading setuptools first, because v6.0 and above will automatically detect a compiler. You might already have a compiler but Python can't find it. Open up a command line and type:

    pip install --upgrade setuptools

  2. Now try and install your package again:

    pip install [yourpackagename]

  3. If that didn't work, then it's certain you don't have a compiler, so you'll need to install one:
    http://www.microsoft.com/en-us/download/details.aspx?id=44266

  4. Now try again:

    pip install [yourpackagename]

And there you go. It should work for you.

Set default value of javascript object attributes

Use destructuring (new in ES6)

There is great documentation by Mozila as well as a fantastic blog post that explains the syntax better than I can.

To Answer Your Question

var emptyObj = {};
const { nonExistingAttribute = defaultValue } = emptyObj;
console.log(nonExistingAttribute); // defaultValue

Going Further

Can I rename this variable? Sure!

const { nonExistingAttribute: coolerName = 15} = emptyObj;
console.log(coolerName); // 15

What about nested data? Bring it on!

var nestedData = {
    name: 'Awesome Programmer',
    languages: [
        {
            name: 'javascript',
            proficiency: 4,
        }
    ],
    country: 'Canada',
};

var {name: realName, languages: [{name: languageName}]} = nestedData ;

console.log(realName); // Awesome Programmer
console.log(languageName); // javascript

Android: Remove all the previous activities from the back stack

add to Manifest for your activity android:launchMode="singleTask"

HTTP GET in VB.NET

Public Function getLoginresponce(ByVal email As String, ByVal password As String) As String
    Dim requestUrl As String = "your api"
    Dim request As HttpWebRequest = TryCast(WebRequest.Create(requestUrl), HttpWebRequest)
    Dim response As HttpWebResponse = TryCast(request.GetResponse(), HttpWebResponse)
    Dim dataStream As Stream = response.GetResponseStream()
    Dim reader As New StreamReader(dataStream)
    Dim responseFromServer As String = reader.ReadToEnd()
    Dim result = responseFromServer
    reader.Close()
    response.Close()
    Return result
End Function

Preloading CSS Images

When there is no way to modify CSS code and preload images with CSS rules for :before or :after pseudo elements another approach with JavaScript code traversing CSS rules of loaded stylesheets can be used. In order to make it working scripts should be included after stylesheets in HTML, for example, before closing body tag or just after stylesheets.

getUrls() {
    const urlRegExp = /url\(('|")?([^'"()]+)('|")\)?/;

    let urls = [];
    for (let i = 0; i < document.styleSheets.length; i++) {
        let cssRules = document.styleSheets[i].cssRules;
        for (let j = 0; j < cssRules.length; j++) {
            let cssRule = cssRules[j];
            if (!cssRule.selectorText) {
                continue;
            }

            for (let k = 0; k < cssRule.style.length; k++) {
                let property = cssRule.style[k],
                    urlMatch = cssRule.style[property].match(urlRegExp);
                if (urlMatch !== null) {
                    urls.push(urlMatch[2]);
                }
            }
        }
    }
    return urls;
}

preloadImages() {
    return new Promise(resolve => {
        let urls = getUrls(),
            loadedCount = 0;

        const onImageLoad = () => {
            loadedCount++;
            if (urls.length === loadedCount) {
                resolve();
            }
        };

        for (var i = 0; i < urls.length; i++) {
            let image = new Image();
            image.src = urls[i];
            image.onload = onImageLoad;
        }
    });
}

document.addEventListener('DOMContentLoaded', () => {
    preloadImages().then(() => {
        // CSS images are loaded here
    });
});

How to exit if a command failed?

Try:

my_command || { echo 'my_command failed' ; exit 1; }

Four changes:

  • Change && to ||
  • Use { } in place of ( )
  • Introduce ; after exit and
  • spaces after { and before }

Since you want to print the message and exit only when the command fails ( exits with non-zero value) you need a || not an &&.

cmd1 && cmd2

will run cmd2 when cmd1 succeeds(exit value 0). Where as

cmd1 || cmd2

will run cmd2 when cmd1 fails(exit value non-zero).

Using ( ) makes the command inside them run in a sub-shell and calling a exit from there causes you to exit the sub-shell and not your original shell, hence execution continues in your original shell.

To overcome this use { }

The last two changes are required by bash.

how to display a javascript var in html body

Index.html:

<html>
<body>
    Javascript Version: <b id="version"></b>
    <script src="app.js"></script>
</body>
</html>

app.js:

var ver="1.1";
document.getElementById("version").innerHTML = ver;

What is the syntax for Typescript arrow functions with generics?

I to use this type of declaration:

const identity: { <T>(arg: T): T } = (arg) => arg;

It allows defining additional props to your function if you ever need to and in some cases, it helps keeping the function body cleaner from the generic definition.

If you don't need the additional props (namespace sort of thing), it can be simplified to:

const identity: <T>(arg: T) => T = (arg) => arg;

Combine two tables for one output

In your expected output, you've got the second last row sum incorrect, it should be 40 according to the data in your tables, but here is the query:

Select  ChargeNum, CategoryId, Sum(Hours)
From    (
    Select  ChargeNum, CategoryId, Hours
    From    KnownHours
    Union
    Select  ChargeNum, 'Unknown' As CategoryId, Hours
    From    UnknownHours
) As a
Group By ChargeNum, CategoryId
Order By ChargeNum, CategoryId

And here is the output:

ChargeNum  CategoryId 
---------- ---------- ----------------------
111111     1          40
111111     2          50
111111     Unknown    70
222222     1          40
222222     Unknown    25.5

Best way to convert an ArrayList to a string

If you're using Eclipse Collections, you can use the makeString() method.

ArrayList<String> list = new ArrayList<String>();
list.add("one");
list.add("two");
list.add("three");

Assert.assertEquals(
    "one\ttwo\tthree",
    ArrayListAdapter.adapt(list).makeString("\t"));

If you can convert your ArrayList to a FastList, you can get rid of the adapter.

Assert.assertEquals(
    "one\ttwo\tthree",
    FastList.newListWith("one", "two", "three").makeString("\t"));

Note: I am a committer for Eclipse Collections.

Converting map to struct

I adapt dave's answer, and add a recursive feature. I'm still working on a more user friendly version. For example, a number string in the map should be able to be converted to int in the struct.

package main

import (
    "fmt"
    "reflect"
)

func SetField(obj interface{}, name string, value interface{}) error {

    structValue := reflect.ValueOf(obj).Elem()
    fieldVal := structValue.FieldByName(name)

    if !fieldVal.IsValid() {
        return fmt.Errorf("No such field: %s in obj", name)
    }

    if !fieldVal.CanSet() {
        return fmt.Errorf("Cannot set %s field value", name)
    }

    val := reflect.ValueOf(value)

    if fieldVal.Type() != val.Type() {

        if m,ok := value.(map[string]interface{}); ok {

            // if field value is struct
            if fieldVal.Kind() == reflect.Struct {
                return FillStruct(m, fieldVal.Addr().Interface())
            }

            // if field value is a pointer to struct
            if fieldVal.Kind()==reflect.Ptr && fieldVal.Type().Elem().Kind() == reflect.Struct {
                if fieldVal.IsNil() {
                    fieldVal.Set(reflect.New(fieldVal.Type().Elem()))
                }
                // fmt.Printf("recursive: %v %v\n", m,fieldVal.Interface())
                return FillStruct(m, fieldVal.Interface())
            }

        }

        return fmt.Errorf("Provided value type didn't match obj field type")
    }

    fieldVal.Set(val)
    return nil

}

func FillStruct(m map[string]interface{}, s interface{}) error {
    for k, v := range m {
        err := SetField(s, k, v)
        if err != nil {
            return err
        }
    }
    return nil
}

type OtherStruct struct {
    Name string
    Age  int64
}


type MyStruct struct {
    Name string
    Age  int64
    OtherStruct *OtherStruct
}



func main() {
    myData := make(map[string]interface{})
    myData["Name"]        = "Tony"
    myData["Age"]         = int64(23)
    OtherStruct := make(map[string]interface{})
    myData["OtherStruct"] = OtherStruct
    OtherStruct["Name"]   = "roxma"
    OtherStruct["Age"]    = int64(23)

    result := &MyStruct{}
    err := FillStruct(myData,result)
    fmt.Println(err)
    fmt.Printf("%v %v\n",result,result.OtherStruct)
}

How to put a jpg or png image into a button in HTML

It should be

<input type="image" id="myimage" src="[...]" />

So "image" instead of "submit". It will still be a button which submits on click.

If your image is bigger than the button which is shown; let's say the image is 200x200 pixels; add this to your stylesheet:

#myimage {
    height: 200px;
    width: 200px;
}

or directly in the button tag:

<input type="image" id="myimage" style="height:200px;width:200px;" src="[...]" />

Note however that resizing the image like this might not yield ideal results; if e.g. your image is much smaller than you want it to be shown, you will see the single pixels; if on the other hand it is much bigger, you are wasting precious bandwidth of your users. So resizing the picture itself to the actual size is preferrable over rescaling via stylesheets!

How to get the current logged in user Id in ASP.NET Core

For .NET Core 2.0 Only The following is required to fetch the UserID of the logged-in User in a Controller class:

var userId = this.User.FindFirstValue(ClaimTypes.NameIdentifier);

or

var userId = HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier);

e.g.

contact.OwnerID = this.User.FindFirstValue(ClaimTypes.NameIdentifier);

How do I access call log for android?

in My project i am getting error int htc device.now this code is universal. I think this is help for you.

    public class CustomContentObserver extends ContentObserver {        
    public CustomContentObserver(Handler handler) {
        super(handler);
        System.out.println("Content obser");
    }     

    public void onChange(boolean selfChange) {
         super.onChange(selfChange);
         String lastCallnumber;

         currentDate = sdfcur.format(calender.getTime());
         System.out.println("Content obser onChange()");
         Log.d("PhoneService", "custom StringsContentObserver.onChange( " + selfChange + ")");
        //if(!callFlag){                   
         String[] projection = new String[]{CallLog.Calls.NUMBER,
                    CallLog.Calls.TYPE,
                    CallLog.Calls.DURATION,
                    CallLog.Calls.CACHED_NAME,
                    CallLog.Calls._ID};

            Cursor c;   
            c=mContext.getContentResolver().query(CallLog.Calls.CONTENT_URI, projection, null, null, CallLog.Calls._ID + " DESC");
            if(c.getCount()!=0){
                c.moveToFirst();
                 lastCallnumber = c.getString(0);
                 String type=c.getString(1);
                 String duration=c.getString(2);
                 String name=c.getString(3);
                 String id=c.getString(4);
                 System.out.println("CALLLLing:"+lastCallnumber+"Type:"+type);

                 Database db=new Database(mContext);
                 Cursor cur =db.getFirstRecord(lastCallnumber);
                 final String endCall=lastCallnumber;
                 //checking incoming/outgoing call
                 if(type.equals("3")){
                    //missed call
                    }else if(type.equals("1")){
                    //incoming call

                 }else if(type.equals("2")){
                    //outgoing call
                 }                  

            }
            c.close();
    }

}

Converting Java file:// URL to File(...) path, platform independent, including UNC paths

Building on @SotiriosDelimanolis's comment, here is a method to deal with URLs (such as file:...) and non-URLs (such as C:...), using Spring's FileSystemResource:

public FileSystemResource get(String file) {
    try {
        // First try to resolve as URL (file:...)
        Path path = Paths.get(new URL(file).toURI());
        FileSystemResource resource = new FileSystemResource(path.toFile());
        return resource;
    } catch (URISyntaxException | MalformedURLException e) {
        // If given file string isn't an URL, fall back to using a normal file 
        return new FileSystemResource(file);
    }
}

Split string into array of character strings

An efficient way of turning a String into an array of one-character Strings would be to do this:

String[] res = new String[str.length()];
for (int i = 0; i < str.length(); i++) {
    res[i] = Character.toString(str.charAt(i));
}

However, this does not take account of the fact that a char in a String could actually represent half of a Unicode code-point. (If the code-point is not in the BMP.) To deal with that you need to iterate through the code points ... which is more complicated.

This approach will be faster than using String.split(/* clever regex*/), and it will probably be faster than using Java 8+ streams. It is probable faster than this:

String[] res = new String[str.length()];
int 0 = 0;
for (char ch: str.toCharArray[]) {
    res[i++] = Character.toString(ch);
}  

because toCharArray has to copy the characters to a new array.

Checking if jquery is loaded using Javascript

something is not right

Well, you are using jQuery to check for the presence of jQuery. If jQuery isn't loaded then $() won't even run at all and your callback won't execute, unless you're using another library and that library happens to share the same $() syntax.

Remove your $(document).ready() (use something like window.onload instead):

window.onload = function() {
    if (window.jQuery) {  
        // jQuery is loaded  
        alert("Yeah!");
    } else {
        // jQuery is not loaded
        alert("Doesn't Work");
    }
}

How to Replace dot (.) in a string in Java

You need two backslashes before the dot, one to escape the slash so it gets through, and the other to escape the dot so it becomes literal. Forward slashes and asterisk are treated literal.

str=xpath.replaceAll("\\.", "/*/");          //replaces a literal . with /*/

http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#replaceAll(java.lang.String,%20java.lang.String)

Replace string within file contents

with open('Stud.txt','r') as f:
    newlines = []
    for line in f.readlines():
        newlines.append(line.replace('A', 'Orange'))
with open('Stud.txt', 'w') as f:
    for line in newlines:
        f.write(line)

CSS how to make scrollable list

As per your question vertical listing have a scrollbar effect.

CSS / HTML :

_x000D_
_x000D_
nav ul{height:200px; width:18%;}_x000D_
nav ul{overflow:hidden; overflow-y:scroll;}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
    <head>_x000D_
        <meta charset="utf-8">_x000D_
        <title>JS Bin</title>_x000D_
    </head>_x000D_
    <body>_x000D_
        <header>header area</header>_x000D_
        <nav>_x000D_
            <ul>_x000D_
                <li>Link 1</li>_x000D_
                <li>Link 2</li>_x000D_
                <li>Link 3</li>_x000D_
                <li>Link 4</li>_x000D_
                <li>Link 5</li>_x000D_
                <li>Link 6</li> _x000D_
                <li>Link 7</li> _x000D_
                <li>Link 8</li>_x000D_
                <li>Link 9</li>_x000D_
                <li>Link 10</li>_x000D_
                <li>Link 11</li>_x000D_
                <li>Link 13</li>_x000D_
                <li>Link 13</li>_x000D_
_x000D_
            </ul>_x000D_
        </nav>_x000D_
        _x000D_
        <footer>footer area</footer>_x000D_
    </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

laravel 5 : Class 'input' not found

In Laravel 5.2 Input:: is replaced with Request::

use

Request::

Add to the top of Controller or any other Class

use Illuminate\Http\Request;

Join between tables in two different databases?

Yes, assuming the account has appropriate permissions you can use:

SELECT <...>
FROM A.table1 t1 JOIN B.table2 t2 ON t2.column2 = t1.column1;

You just need to prefix the table reference with the name of the database it resides in.

Regular expression to limit number of characters to 10

/^[a-z]{0,10}$/ should work. /^[a-z]{1,10}$/ if you want to match at least one character, like /^[a-z]+$/ does.

SQL SERVER, SELECT statement with auto generate row id

Select (Select count(y.au_lname) from dbo.authors y
where y.au_lname + y.au_fname <= x.au_lname + y.au_fname) as Counterid,
x.au_lname,x.au_fname from authors x group by au_lname,au_fname
order by Counterid --Alternatively that can be done which is equivalent as above..

Split array into chunks of N length

It could be something like that:

_x000D_
_x000D_
var a = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'];

var arrays = [], size = 3;
    
while (a.length > 0)
  arrays.push(a.splice(0, size));

console.log(arrays);
_x000D_
_x000D_
_x000D_

See splice Array's method.

HTML - Alert Box when loading page

If you use jqueryui (or another toolset) this is the way you do it

http://codepen.io/anon/pen/jeLhJ

html

<div id="hw" title="Empty the recycle bin?">The new way</div>

javascript

$('#hw').dialog({
    close:function(){
        alert('the old way')
    }
})

UPDATE : how to include jqueryui by pointing to cdn

<link rel="stylesheet" type="text/css" href="http://code.jquery.com/ui/1.10.0/themes/base/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.9.0.js"></script>
<script src="http://code.jquery.com/ui/1.10.0/jquery-ui.js"></script>

Why doesn't Python have multiline comments?

Besides, multiline comments are a bitch. Sorry to say, but regardless of the language, I don't use them for anything else than debugging purposes. Say you have code like this:

void someFunction()
{
    Something
    /*Some comments*/
    Something else
}

Then you find out that there is something in your code you can't fix with the debugger, so you start manually debugging it by commenting out smaller and smaller chuncks of code with theese multiline comments. This would then give the function:

void someFunction()
{ /*
    Something
   /* Comments */
   Something more*/
}

This is really irritating.

R object identification

I usually start out with some combination of:

typeof(obj)
class(obj)
sapply(obj, class)
sapply(obj, attributes)
attributes(obj)
names(obj)

as appropriate based on what's revealed. For example, try with:

obj <- data.frame(a=1:26, b=letters)
obj <- list(a=1:26, b=letters, c=list(d=1:26, e=letters))
data(cars)
obj <- lm(dist ~ speed, data=cars)

..etc.

If obj is an S3 or S4 object, you can also try methods or showMethods, showClass, etc. Patrick Burns' R Inferno has a pretty good section on this (sec #7).

EDIT: Dirk and Hadley mention str(obj) in their answers. It really is much better than any of the above for a quick and even detailed peek into an object.

How to remove line breaks from a file in Java?

As noted in other answers, your code is not working primarily because String.replace(...) does not change the target String. (It can't - Java strings are immutable!) What replace actually does is to create and return a new String object with the characters changed as required. But your code then throws away that String ...


Here are some possible solutions. Which one is most correct depends on what exactly you are trying to do.

// #1
text = text.replace("\n", "");

Simply removes all the newline characters. This does not cope with Windows or Mac line terminations.

// #2
text = text.replace(System.getProperty("line.separator"), "");

Removes all line terminators for the current platform. This does not cope with the case where you are trying to process (for example) a UNIX file on Windows, or vice versa.

// #3
text = text.replaceAll("\\r|\\n", "");

Removes all Windows, UNIX or Mac line terminators. However, if the input file is text, this will concatenate words; e.g.

Goodbye cruel
world.

becomes

Goodbye cruelworld.

So you might actually want to do this:

// #4
text = text.replaceAll("\\r\\n|\\r|\\n", " ");

which replaces each line terminator with a space1. Since Java 8 you can also do this:

// #5
text = text.replaceAll("\\R", " ");

And if you want to replace multiple line terminator with one space:

// #6
text = text.replaceAll("\\R+", " ");

1 - Note there is a subtle difference between #3 and #4. The sequence \r\n represents a single (Windows) line terminator, so we need to be careful not to replace it with two spaces.

Git error on git pull (unable to update local ref)

with gitbach line commande, use git update-ref to update reference of your local branch:

$ git update-ref -d refs/remotes/origin/[locked branch name]

then pull using $ git pull

[locked branch name] is the name of the branch that the error is happening because of mismatch of commit Ids.

How to define Gradle's home in IDEA?

I couldn't get it to accept my Gradle JVM selection until I deleted a broken JDK

Th window below is from File -> Other Settings -> Structure For New Projects...

Gradle JVM i.e. JDK home path

I had a red 1.8 JDK SDK entry here, once I deleted that Gradle JVM error below disappeared and I could move on to the next step

Gradle JVM error

How to delete columns in pyspark dataframe

You can delete column like this:

df.drop("column Name).columns

In your case :

df.drop("id").columns

If you want to drop more than one column you can do:

dfWithLongColName.drop("ORIGIN_COUNTRY_NAME", "DEST_COUNTRY_NAME")

Node Version Manager (NVM) on Windows

1.downlad nvm 
2.install chocolaty
3.change C:\Program Files\node   to C:\Program Files\nodejsx

emphasized textThe first thing that we need to do is install NVM. website : https://docs.microsoft.com/en-us/windows/nodejs/setup-on-windows

How to declare a type as nullable in TypeScript?

To be more C# like, define the Nullable type like this:

type Nullable<T> = T | null;

interface Employee{
   id: number;
   name: string;
   salary: Nullable<number>;
}

Bonus:

To make Nullable behave like a built in Typescript type, define it in a global.d.ts definition file in the root source folder. This path worked for me: /src/global.d.ts

Maven: How to run a .java file from command line passing arguments

In addition to running it with mvn exec:java, you can also run it with mvn exec:exec

mvn exec:exec -Dexec.executable="java" -Dexec.args="-classpath %classpath your.package.MainClass"

How to perform OR condition in django queryset?

Just adding this for multiple filters attaching to Q object, if someone might be looking to it. If a Q object is provided, it must precede the definition of any keyword arguments. Otherwise its an invalid query. You should be careful when doing it.

an example would be

from django.db.models import Q
User.objects.filter(Q(income__gte=5000) | Q(income__isnull=True),category='income')

Here the OR condition and a filter with category of income is taken into account

FIFO class in Java

if you want to have a pipe to write/read data, you can use the http://docs.oracle.com/javase/6/docs/api/java/io/PipedWriter.html

Including another class in SCSS

Another option could be using an Attribute Selector:

[class^="your-class-name"]{
  //your style here
}

Whereas every class starting with "your-class-name" uses this style.

So in your case, you could do it like so:

[class^="class"]{
  display: inline-block;
  //some other properties
  &:hover{
   color: darken(#FFFFFF, 10%);
 }  
}

.class-b{
  //specifically for class b
  width: 100px;
  &:hover{
     color: darken(#FFFFFF, 20%);
  }
}

More about Attribute Selectors on w3Schools

Does adding a duplicate value to a HashSet/HashMap replace the previous value

Correct me if I'm wrong but what you're getting at is that with strings, "Hi" == "Hi" doesn't always come out true (because they're not necessarily the same object).

The reason you're getting an answer of 1 though is because the JVM will reuse strings objects where possible. In this case the JVM is reusing the string object, and thus overwriting the item in the Hashmap/Hashset.

But you aren't guaranteed this behavior (because it could be a different string object that has the same value "Hi"). The behavior you see is just because of the JVM's optimization.

How to run a Powershell script from the command line and pass a directory as a parameter

Change your code to the following :

Function Foo($directory)
    {
        echo $directory
    }

    if ($args.Length -eq 0)
    {
        echo "Usage: Foo <directory>"
    }
    else
    {
        Foo([string[]]$args)
    }

And then invoke it as:

powershell -ExecutionPolicy RemoteSigned -File "c:\foo.ps1" "c:\Documents and Settings" "c:\test"

Draggable div without jQuery UI

Dragging like jQueryUI: JsFiddle

You can drag the element from any point without weird centering.

$(document).ready(function() {

        var $body = $('body');
        var $target = null;
        var isDraggEnabled = false;

        $body.on("mousedown", "div", function(e) {

            $this = $(this);
            isDraggEnabled = $this.data("draggable");

            if (isDraggEnabled) {
                if(e.offsetX==undefined){
                    x = e.pageX-$(this).offset().left;
                    y = e.pageY-$(this).offset().top;
                }else{
                    x = e.offsetX;
                    y = e.offsetY;
                };

                $this.addClass('draggable');
                $body.addClass('noselect');
                $target = $(e.target);
            };

        });

         $body.on("mouseup", function(e) {
            $target = null;
            $body.find(".draggable").removeClass('draggable');
            $body.removeClass('noselect');
        });

         $body.on("mousemove", function(e) {
            if ($target) {
                $target.offset({
                    top: e.pageY  - y,
                    left: e.pageX - x
                });
            };     
         });

    });

SQL Combine Two Columns in Select Statement

In MySQL you can use:

SELECT CONCAT(Address1, " ", Address2)
WHERE SOUNDEX(CONCAT(Address1, " ", Address2)) = SOUNDEX("Center St 3B")

The SOUNDEX function works similarly in most database systems, I can't think of the syntax for MSSQL at the minute, but it wouldn't be too far away from the above.

powershell - list local users and their groups

try this one :),

Get-LocalGroup | %{ $groups = "$(Get-LocalGroupMember -Group $_.Name | %{ $_.Name } | Out-String)"; Write-Output "$($_.Name)>`r`n$($groups)`r`n" }

How to control border height?

You could create an image of whatever height you wish, and then position that with the CSS background(-position) property like:

#somid { background: url(path/to/img.png) no-repeat center top;

Instead of center topyou can also use pixel or % like 50% 100px.

http://www.w3.org/TR/CSS2/colors.html#propdef-background-position

Show whitespace characters in Visual Studio Code

UPDATE (June 2019)

For those willing to toggle whitespace characters using a keyboard shortcut, you can easily add a keybinding for that.

In the latest versions of Visual Studio Code there is now a user-friendly graphical interface (i.e. no need to type JSON data etc) for viewing and editing all the available keyboard shortcuts. It is still under

File > Preferences > Keyboard Shortcuts (or use Ctrl+K Ctrl+S)

There is also a search field to help quickly find (and filter) the desired keybindings. So now both adding new and editing the existing keybindings is much easier:

enter image description here


Toggling whitespace characters has no default keybinding so feel free to add one. Just press the + sign on the left side of the related line (or press Enter, or double click anywhere on that line) and enter the desired combination in the pop-up window.

And if the keybinding you have chosen is already used for some other action(s) there will be a convenient warning which you can click and observe what action(s) already use your chosen keybinding:

enter image description here

As you can see, everything is very intuitive and convenient.
Good job, Microsoft!


Original (old) answer

For those willing to toggle whitespace characters using a keyboard shortcut, you can add a custom binding to the keybindings.json file (File > Preferences > Keyboard Shortcuts).

Example:

// Place your key bindings in this file to overwrite the defaults
[
    {
        "key": "ctrl+shift+i",
        "command": "editor.action.toggleRenderWhitespace"
    }
]

Here I have assigned a combination of Ctrl+Shift+i to toggle invisible characters, you may of course choose another combination.

Bootstrap 3 Horizontal and Vertical Divider

Do you have to use Bootstrap for this? Here's a basic HTML/CSS example for obtaining this look that doesn't use any Bootstrap:

HTML:

<div class="bottom">
    <div class="box-content right">Rich Media Ad Production</div>
    <div class="box-content right">Web Design & Development</div>
    <div class="box-content right">Mobile Apps Development</div>
    <div class="box-content">Creative Design</div>
</div>
<div>
    <div class="box-content right">Web Analytics</div>
    <div class="box-content right">Search Engine Marketing</div>
    <div class="box-content right">Social Media</div>
    <div class="box-content">Quality Assurance</div>
</div>

CSS:

.box-content {
    display: inline-block;
    width: 200px;
    padding: 10px;
}

.bottom {
    border-bottom: 1px solid #ccc;
}

.right {
    border-right: 1px solid #ccc;
}

Here is the working Fiddle.


UPDATE

If you must use Bootstrap, here is a semi-responsive example that achieves the same effect, although you may need to write a few additional media queries.

HTML:

<div class="row">
    <div class="col-xs-3">Rich Media Ad Production</div>
    <div class="col-xs-3">Web Design & Development</div>
    <div class="col-xs-3">Mobile Apps Development</div>
    <div class="col-xs-3">Creative Design</div>
</div>
<div class="row">
    <div class="col-xs-3">Web Analytics</div>
    <div class="col-xs-3">Search Engine Marketing</div>
    <div class="col-xs-3">Social Media</div>
    <div class="col-xs-3">Quality Assurance</div>
</div>

CSS:

.row:not(:last-child) {
    border-bottom: 1px solid #ccc;
}

.col-xs-3:not(:last-child) {
    border-right: 1px solid #ccc;
}

Here is another working Fiddle.

Note:

Note that you may also use the <hr> element to insert a horizontal divider in Bootstrap as well if you'd like.

Excel to CSV with UTF8 encoding

I have written a small Python script that can export worksheets in UTF-8.

You just have to provide the Excel file as first parameter followed by the sheets that you would like to export. If you do not provide the sheets, the script will export all worksheets that are present in the Excel file.

#!/usr/bin/env python

# export data sheets from xlsx to csv

from openpyxl import load_workbook
import csv
from os import sys

reload(sys)
sys.setdefaultencoding('utf-8')

def get_all_sheets(excel_file):
    sheets = []
    workbook = load_workbook(excel_file,use_iterators=True,data_only=True)
    all_worksheets = workbook.get_sheet_names()
    for worksheet_name in all_worksheets:
        sheets.append(worksheet_name)
    return sheets

def csv_from_excel(excel_file, sheets):
    workbook = load_workbook(excel_file,use_iterators=True,data_only=True)
    for worksheet_name in sheets:
        print("Export " + worksheet_name + " ...")

        try:
            worksheet = workbook.get_sheet_by_name(worksheet_name)
        except KeyError:
            print("Could not find " + worksheet_name)
            sys.exit(1)

        your_csv_file = open(''.join([worksheet_name,'.csv']), 'wb')
        wr = csv.writer(your_csv_file, quoting=csv.QUOTE_ALL)
        for row in worksheet.iter_rows():
            lrow = []
            for cell in row:
                lrow.append(cell.value)
            wr.writerow(lrow)
        print(" ... done")
    your_csv_file.close()

if not 2 <= len(sys.argv) <= 3:
    print("Call with " + sys.argv[0] + " <xlxs file> [comma separated list of sheets to export]")
    sys.exit(1)
else:
    sheets = []
    if len(sys.argv) == 3:
        sheets = list(sys.argv[2].split(','))
    else:
        sheets = get_all_sheets(sys.argv[1])
    assert(sheets != None and len(sheets) > 0)
    csv_from_excel(sys.argv[1], sheets)

Foreach in a Foreach in MVC View

Controller

public ActionResult Index()
    {


        //you don't need to include the category bc it does it by itself
        //var model = db.Product.Include(c => c.Category).ToList()

        ViewBag.Categories = db.Category.OrderBy(c => c.Name).ToList();
        var model = db.Product.ToList()
        return View(model);
    }


View

you need to filter the model with the given category

like :=> Model.where(p=>p.CategoryID == category.CategoryID)

try this...

@foreach (var category in ViewBag.Categories)
{
    <h3><u>@category.Name</u></h3>

    <div>

        @foreach (var product in Model.where(p=>p.CategoryID == category.CategoryID))
        {

                <table cellpadding="5" cellspacing"5" style="border:1px solid black; width:100%;background-color:White;">
                    <thead>
                        <tr>
                            <th style="background-color:black; color:white;">
                                @product.Title  
                                @if (System.Web.Security.UrlAuthorizationModule.CheckUrlAccessForPrincipal("/admin", User, "GET"))
                                {
                                    @Html.Raw(" - ")  
                                    @Html.ActionLink("Edit", "Edit", new { id = product.ID }, new { style = "background-color:black; color:white !important;" })
                                }
                            </th>
                        </tr>
                    </thead>

                    <tbody>
                        <tr>
                            <td style="background-color:White;">
                                @product.Description
                            </td>
                        </tr>
                    </tbody>      
                </table>                       
            }


    </div>
}  

Python - Module Not Found

After trying to add the path using:

pip show

on command prompt and using

sys.path.insert(0, "/home/myname/pythonfiles")

and didn't work. Also got SSL error when trying to install the module again using conda this time instead of pip.

I simply copied the module that wasn't found from the path "Mine was in

C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages 

so I copied it to 'C:\Users\user\Anaconda3\Lib\site-packages'

How to check if a subclass is an instance of a class at runtime?

You have to read the API carefully for this methods. Sometimes you can get confused very easily.

It is either:

if (B.class.isInstance(view))

API says: Determines if the specified Object (the parameter) is assignment-compatible with the object represented by this Class (The class object you are calling the method at)

or:

if (B.class.isAssignableFrom(view.getClass()))

API says: Determines if the class or interface represented by this Class object is either the same as, or is a superclass or superinterface of, the class or interface represented by the specified Class parameter

or (without reflection and the recommended one):

if (view instanceof B)

Find the version of an installed npm package

Its very simple..Just type below line

npm view < package-name > version

** Example **

npm view redux version

I have version 7.2.0 of redux

Smooth scrolling with just pure css

You can do this with pure CSS but you will need to hard code the offset scroll amounts, which may not be ideal should you be changing page content- or should dimensions of your content change on say window resize.

You're likely best placed to use e.g. jQuery, specifically:

$('html, body').stop().animate({
   scrollTop: element.offset().top
}, 1000);

A complete implementation may be:

$('#up, #down').on('click', function(e){
    e.preventDefault();
    var target= $(this).get(0).id == 'up' ? $('#down') : $('#up');
    $('html, body').stop().animate({
       scrollTop: target.offset().top
    }, 1000);
});

Where element is the target element to scroll to and 1000 is the delay in ms before completion.

Demo Fiddle

The benefit being, no matter what changes to your content dimensions, the function will not need to be altered.

Access Enum value using EL with JSTL

A simple comparison against string works:

<c:when test="${someModel.status == 'OLD'}">

How to use <DllImport> in VB.NET?

I know this has already been answered, but here is an example for the people who are trying to use SQL Server Types in a vb project:

            Imports System
            Imports System.IO
            Imports System.Runtime.InteropServices

            Namespace SqlServerTypes
                Public Class Utilities



                    <DllImport("kernel32.dll", CharSet:=CharSet.Auto, SetLastError:=True)>
                    Public Shared Function LoadLibrary(ByVal libname As String) As IntPtr

                    End Function

                    Public Shared Sub LoadNativeAssemblies(ByVal rootApplicationPath As String)
                        Dim nativeBinaryPath = If(IntPtr.Size > 4, Path.Combine(rootApplicationPath, "SqlServerTypes\x64\"), Path.Combine(rootApplicationPath, "SqlServerTypes\x86\"))
                        LoadNativeAssembly(nativeBinaryPath, "msvcr120.dll")
                        LoadNativeAssembly(nativeBinaryPath, "SqlServerSpatial140.dll")
                    End Sub

                    Private Shared Sub LoadNativeAssembly(ByVal nativeBinaryPath As String, ByVal assemblyName As String)
                        Dim path = System.IO.Path.Combine(nativeBinaryPath, assemblyName)
                        Dim ptr = LoadLibrary(path)

                        If ptr = IntPtr.Zero Then
                            Throw New Exception(String.Format("Error loading {0} (ErrorCode: {1})", assemblyName, Marshal.GetLastWin32Error()))
                        End If
                    End Sub
                End Class
            End Namespace

HTML checkbox onclick called in Javascript

You can also extract the event code from the HTML, like this :

<input type="checkbox" id="check_all_1" name="check_all_1" title="Select All" />
<label for="check_all_1">Select All</label>

<script>
function selectAll(frmElement, chkElement) {
    // ...
}
document.getElementById("check_all_1").onclick = function() {
    selectAll(document.wizard_form, this);
}
</script>

Get The Current Domain Name With Javascript (Not the path, etc.)

       Feel free to visit our “<a href="javascript:document.location.href=document.location.origin+'/contact-us'" title="Click to Contact Us" class="coded_link" ><span class="ui-icon ui-icon-newwin"></span>Contact</a>” link

Indeed worked for me whereas I couldn't use PHP

Just tested that it worked thanks to the approach mentioned above in some of the answers, so quick and verified that worked

Trigger a button click with JavaScript on the Enter key in a text box

Nobody noticed the html attibute "accesskey" which is available since a while.

This is a no javascript way to keyboard shortcuts stuffs.

accesskey_browsers

The accesskey attributes shortcuts on MDN

Intented to be used like this. The html attribute itself is enough, howewer we can change the placeholder or other indicator depending of the browser and os. The script is a untested scratch approach to give an idea. You may want to use a browser library detector like the tiny bowser

_x000D_
_x000D_
let client = navigator.userAgent.toLowerCase(),_x000D_
    isLinux = client.indexOf("linux") > -1,_x000D_
    isWin = client.indexOf("windows") > -1,_x000D_
    isMac = client.indexOf("apple") > -1,_x000D_
    isFirefox = client.indexOf("firefox") > -1,_x000D_
    isWebkit = client.indexOf("webkit") > -1,_x000D_
    isOpera = client.indexOf("opera") > -1,_x000D_
    input = document.getElementById('guestInput');_x000D_
_x000D_
if(isFirefox) {_x000D_
   input.setAttribute("placeholder", "ALT+SHIFT+Z");_x000D_
} else if (isWin) {_x000D_
   input.setAttribute("placeholder", "ALT+Z");_x000D_
} else if (isMac) {_x000D_
  input.setAttribute("placeholder", "CTRL+ALT+Z");_x000D_
} else if (isOpera) {_x000D_
  input.setAttribute("placeholder", "SHIFT+ESCAPE->Z");_x000D_
} else {'Point me to operate...'}
_x000D_
<input type="text" id="guestInput" accesskey="z" placeholder="Acces shortcut:"></input>
_x000D_
_x000D_
_x000D_

How do I get whole and fractional parts from double in JSP/Java?

double value = 3.25;
double fractionalPart = value % 1;
double integralPart = value - fractionalPart;

Using ResourceManager

There's surprisingly simple way of reading resource by string:

ResourceNamespace.ResxFileName.ResourceManager.GetString("ResourceKey")

It's clean and elegant solution for reading resources by keys where "dot notation" cannot be used (for instance when resource key is persisted in the database).

Setting ANDROID_HOME enviromental variable on Mac OS X

Adding the following to my .bash_profile worked for me:

export ANDROID_HOME=/Users/$USER/Library/Android/sdk
export PATH=${PATH}:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools

Inserting the iframe into react component

You can use property dangerouslySetInnerHTML, like this

_x000D_
_x000D_
const Component = React.createClass({_x000D_
  iframe: function () {_x000D_
    return {_x000D_
      __html: this.props.iframe_x000D_
    }_x000D_
  },_x000D_
_x000D_
  render: function() {_x000D_
    return (_x000D_
      <div>_x000D_
        <div dangerouslySetInnerHTML={ this.iframe() } />_x000D_
      </div>_x000D_
    );_x000D_
  }_x000D_
});_x000D_
_x000D_
const iframe = '<iframe src="https://www.example.com/show?data..." width="540" height="450"></iframe>'; _x000D_
_x000D_
ReactDOM.render(_x000D_
  <Component iframe={iframe} />,_x000D_
  document.getElementById('container')_x000D_
);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id="container"></div>
_x000D_
_x000D_
_x000D_

also, you can copy all attributes from the string(based on the question, you get iframe as a string from a server) which contains <iframe> tag and pass it to new <iframe> tag, like that

_x000D_
_x000D_
/**_x000D_
 * getAttrs_x000D_
 * returns all attributes from TAG string_x000D_
 * @return Object_x000D_
 */_x000D_
const getAttrs = (iframeTag) => {_x000D_
  var doc = document.createElement('div');_x000D_
  doc.innerHTML = iframeTag;_x000D_
_x000D_
  const iframe = doc.getElementsByTagName('iframe')[0];_x000D_
  return [].slice_x000D_
    .call(iframe.attributes)_x000D_
    .reduce((attrs, element) => {_x000D_
      attrs[element.name] = element.value;_x000D_
      return attrs;_x000D_
    }, {});_x000D_
}_x000D_
_x000D_
const Component = React.createClass({_x000D_
  render: function() {_x000D_
    return (_x000D_
      <div>_x000D_
        <iframe {...getAttrs(this.props.iframe) } />_x000D_
      </div>_x000D_
    );_x000D_
  }_x000D_
});_x000D_
_x000D_
const iframe = '<iframe src="https://www.example.com/show?data..." width="540" height="450"></iframe>'; _x000D_
_x000D_
ReactDOM.render(_x000D_
  <Component iframe={iframe} />,_x000D_
  document.getElementById('container')_x000D_
);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id="container"><div>
_x000D_
_x000D_
_x000D_

How to configure PHP to send e-mail?

configure your php.ini like this

SMTP = smtp.gmail.com

[mail function]
; XAMPP: Comment out this if you want to work with an SMTP Server like Mercury

; SMTP = smtp.gmail.com

; smtp_port = 465

; For Win32 only.
; http://php.net/sendmail-from
;sendmail_from = postmaster@localhost

JPQL SELECT between date statement

public List<Student> findStudentByReports(Date startDate, Date endDate) {
    System.out.println("call findStudentMethd******************with this pattern"
                    + startDate
                    + endDate
                    + "*********************************************");

    return em
            .createQuery(
                    "' select attendence from Attendence attendence where attendence.admissionDate BETWEEN : startDate '' AND endDate ''"
                            + "'")
            .setParameter("startDate", startDate, TemporalType.DATE)
            .setParameter("endDate", endDate, TemporalType.DATE)
            .getResultList();

}

What "wmic bios get serialnumber" actually retrieves?

wmic bios get serialnumber     

if run from a command line (start-run should also do the trick) prints out on screen the Serial Number of the product,
(for example in a toshiba laptop it would print out the serial number of the laptop.
with this serial number you can then identify your laptop model if you need ,from the makers service website-usually..:):)

I had to do exactly that.:):)

Python setup.py develop vs install

Another thing that people may find useful when using the develop method is the --user option to install without sudo. Ex:

python setup.py develop --user

instead of

sudo python setup.py develop

Get environment value in controller

You can not access the environment variable like this.

Inside the .env file you write

IMAP_HOSTNAME_TEST=imap.gmail.com  // I am okay with this

Next, inside the config folder there is a file, mail.php. You may use this file to code. As you are working with mail functionality. You might use another file as well.

return [

//..... other declarations
'imap_hostname_test' => env('IMAP_HOSTNAME_TEST'),
// You are hiding the value inside the configuration as well

];

You can call the variable from a controller using 'config(. Whatever file you are using inside config folder. You need to use that file name (without extension) + '.' + 'variable name' + ')'. In the current case you can call the variable as follows.

$hostname = config('mail.imap_hostname_test');

Since you declare the variable inside mail.php and the variable name is imap_hostname_test, you need to call it like this. If you declare this variable inside app.php then you should call

$hostname = config('app.imap_hostname_test');

How to hide a div from code (c#)

Give the div "runat="server" and an id and you can reference it in your code behind.

<div runat="server" id="theDiv">

In code behind:

{
    theDiv.Visible = false;
}

What is the difference between GitHub and gist?

GitHub is the entire site. Gists are a particular service offered on that site, namely code snippets akin to pastebin. However, everything is driven by git revision control, so gists also have complete revision histories.

Programmatic equivalent of default(Type)

Why do you say generics are out of the picture?

    public static object GetDefault(Type t)
    {
        Func<object> f = GetDefault<object>;
        return f.Method.GetGenericMethodDefinition().MakeGenericMethod(t).Invoke(null, null);
    }

    private static T GetDefault<T>()
    {
        return default(T);
    }

Entity Framework: One Database, Multiple DbContexts. Is this a bad idea?

Distinguishing contexts by setting the default schema

In EF6 you can have multiple contexts, just specify the name for the default database schema in the OnModelCreating method of you DbContext derived class (where the Fluent-API configuration is). This will work in EF6:

public partial class CustomerModel : DbContext
{   
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.HasDefaultSchema("Customer");

        // Fluent API configuration
    }   
}

This example will use "Customer" as prefix for your database tables (instead of "dbo"). More importantly it will also prefix the __MigrationHistory table(s), e.g. Customer.__MigrationHistory. So you can have more than one __MigrationHistory table in a single database, one for each context. So the changes you make for one context will not mess with the other.

When adding the migration, specify the fully qualified name of your configuration class (derived from DbMigrationsConfiguration) as parameter in the add-migration command:

add-migration NAME_OF_MIGRATION -ConfigurationTypeName FULLY_QUALIFIED_NAME_OF_CONFIGURATION_CLASS


A short word on the context key

According to this MSDN article "Chapter - Multiple Models Targeting the Same Database" EF 6 would probably handle the situation even if only one MigrationHistory table existed, because in the table there is a ContextKey column to distinguish the migrations.

However I prefer having more than one MigrationHistory table by specifying the default schema like explained above.


Using separate migration folders

In such a scenario you might also want to work with different "Migration" folders in you project. You can set up your DbMigrationsConfiguration derived class accordingly using the MigrationsDirectory property:

internal sealed class ConfigurationA : DbMigrationsConfiguration<ModelA>
{
    public ConfigurationA()
    {
        AutomaticMigrationsEnabled = false;
        MigrationsDirectory = @"Migrations\ModelA";
    }
}

internal sealed class ConfigurationB : DbMigrationsConfiguration<ModelB>
{
    public ConfigurationB()
    {
        AutomaticMigrationsEnabled = false;
        MigrationsDirectory = @"Migrations\ModelB";
    }
}


Summary

All in all, you can say that everything is cleanly separated: Contexts, Migration folders in the project and tables in the database.

I would choose such a solution, if there are groups of entities which are part of a bigger topic, but are not related (via foreign keys) to one another.

If the groups of entities do not have anything to do which each other, I would created a separate database for each of them and also access them in different projects, probably with one single context in each project.

How can I count occurrences with groupBy?

Here are slightly different options to accomplish the task at hand.

using toMap:

list.stream()
    .collect(Collectors.toMap(Function.identity(), e -> 1, Math::addExact));

using Map::merge:

Map<String, Integer> accumulator = new HashMap<>();
list.forEach(s -> accumulator.merge(s, 1, Math::addExact));

Storing Images in DB - Yea or Nay?

I would go with the file system approach, primarily due to its better flexibility. Consider that if the number of images gets huge, one database may not be able to handle it. With file system, you can simple add more file servers, assuming that you're using NFS or kind.

Another advantage the file system approach has is to be able to do some fancy stuffs, such as you can use Amazon S3 as the primary storage (save the url in the database instead of file path). In case of outages happen to S3, you fall back to your file server (may be another database entry containing the file path). Some voodoo to apply to Apache or whatever web server you're using.

Facebook API - How do I get a Facebook user's profile image through the Facebook API (without requiring the user to "Allow" the application)

Simply fetch the data through this URL:

http://graph.facebook.com/userid_here/picture

Replace userid_here with id of the user you want to get the photo of. You can also use HTTPS as well.

You can use the PHP's file_get_contents function to read that URL and process the retrieved data.

Resource:

http://developers.facebook.com/docs/api

Note: In php.ini, you need to make sure that the OpenSSL extension is enabled to use thefile_get_contents function of PHP to read that URL.

Using reflection in Java to create a new instance with the reference variable type set to the new instance class name?

You want to be able to pass in a Class and get a type-safe instance of that class? Try the following:

public static void main(String [] args) throws Exception {
    String s = instanceOf(String.class);
}

public static <T> T instanceOf (Class<T> clazz) throws Exception {
    return clazz.newInstance();
}

How to get file_get_contents() to work with HTTPS?

$url= 'https://example.com';

$arrContextOptions=array(
      "ssl"=>array(
            "verify_peer"=>false,
            "verify_peer_name"=>false,
        ),
    );  

$response = file_get_contents($url, false, stream_context_create($arrContextOptions));

This will allow you to get the content from the url whether it is a HTTPS

MySQL: can't access root account

This worked for me:

https://blog.dotkam.com/2007/04/10/mysql-reset-lost-root-password/

Step 1: Stop MySQL daemon if it is currently running

  ps -ef | grep mysql      - checks if mysql/mysqld is one of the running processes.

  pkill mysqld             - kills the daemon, if it is running.

Step 2: Run MySQL safe daemon with skipping grant tables

  mysqld_safe --skip-grant-tables &

  mysql -u root mysql

Step 3: Login to MySQL as root with no password

  mysql -u root mysql

Step 4: Run UPDATE query to reset the root password

  UPDATE user SET password=PASSWORD("value=42") WHERE user="root";
  FLUSH PRIVILEGES;

In MySQL 5.7, the 'password' field was removed, now the field name is 'authentication_string':

  UPDATE user SET authentication_string=PASSWORD("42") WHERE 
  user="root";
  FLUSH PRIVILEGES;

Step 5: Stop MySQL safe daemon

Step 6: Start MySQL daemon

What is AndroidX?

Just some bits addition from my side to all available answers

Need of AndroidX

  1. As said in amazing answer by @KhemRaj,

With the current naming convention, it isn’t clear which packages are bundled with the Android operating system, and which are packaged with your application’s APK (Android Package Kit). To clear up this confusion, all the unbundled libraries will be moved to AndroidX’s androidx.* namespace, while the android.* package hierarchy will be reserved for packages that ship with the Android operating system.

  1. Other than this,

    Initially, the name of each package indicated the minimum API level supported by that package, for example support-v4. However, version 26.0.0 of the Support Library increased the minimum API to 14, so today many of the package names have nothing to do with the minimum supported API level. When support-v4 and the support-v7 packages both have a minimum API of 14, it’s easy to see why people get confused!. So now with AndroidX, there is no dependence on the API level.

Another important change is that the AndroidX artifacts will update independently, so you’ll be able to update individual AndroidX libraries in your project, rather than having to change every dependency at once. Those frustrating “All com.android.support libraries must use the exact same version specification” messages should become a thing of the past!

Pycharm and sys.argv arguments

Add the following to the top of your Python file.

import sys

sys.argv = [
    __file__,
    'arg1',
    'arg2'
]

Now, you can simply right click on the Python script.

How to split a string to 2 strings in C

You can use strtok() for that Example: it works for me

#include <stdio.h>
#include <string.h>

int main ()
{
    char str[] ="- This, a sample string.";
    char * pch;
    printf ("Splitting string \"%s\" into tokens:\n",str);
    pch = strtok (str," ,.-");
    while (pch != NULL)
    {
        printf ("%s\n",pch);
        pch = strtok (NULL, " ,.-");
    }
    return 0;
}

How to restrict SSH users to a predefined set of commands after login?

You should acquire `rssh', the restricted shell

You can follow the restriction guides mentioned above, they're all rather self-explanatory, and simple to follow. Understand the terms `chroot jail', and how to effectively implement sshd/terminal configurations, and so on.

Being as most of your users access your terminals via sshd, you should also probably look into sshd_conifg, the SSH daemon configuration file, to apply certain restrictions via SSH. Be careful, however. Understand properly what you try to implement, for the ramifications of incorrect configurations are probably rather dire.

How do I retrieve query parameters in Spring Boot?

To accept both @PathVariable and @RequestParam in the same /user endpoint:

@GetMapping(path = {"/user", "/user/{data}"})
public void user(@PathVariable(required=false,name="data") String data,
                 @RequestParam(required=false) Map<String,String> qparams) {
    qparams.forEach((a,b) -> {
        System.out.println(String.format("%s -> %s",a,b));
    }
  
    if (data != null) {
        System.out.println(data);
    }
}

Testing with curl:

  • curl 'http://localhost:8080/user/books'
  • curl 'http://localhost:8080/user?book=ofdreams&name=nietzsche'

Renaming a branch in GitHub

On GitHub side, you can use the new (Jan. 2021) "Support for renaming an existing branch"

Follow this tutorial: https://docs.github.com/en/github/administering-a-repository/renaming-a-branch

rename branch dialog -- https://i2.wp.com/user-images.githubusercontent.com/2503052/105069955-a231fa80-5a50-11eb-982c-a114c9c44c57.png?ssl=1

See "How do I rename branch on the GitHub website?".

This is a better approach, because renaming a branch that way (on github.com) will (source):

  • Re-target any open pull requests
  • Update any draft releases based on the branch
  • Move any branch protection rules that explicitly reference the old name
  • Update the branch used to build GitHub Pages, if applicable
  • Show a notice to repository contributors, maintainers, and admins on the repository homepage with instructions to update local copies of the repository
  • Show a notice to contributors who git push to the old branch
  • Redirect web requests for the old branch name to the new branch name
  • Return a "Moved Permanently" response in API requests for the old branch name

Checking if an Android application is running in the background

You should use a shared preference to store the property and act upon it using service binding from your activities. If you use binding only, (that is never use startService), then your service would run only when you bind to it, (bind onResume and unbind onPause) that would make it run on foreground only, and if you do want to work on background you can use the regular start stop service.

How to change maven java home

If you are in Linux, set JAVA_HOME using syntax export JAVA_HOME=<path-to-java>. Actually it is not only for Maven.

How to echo out table rows from the db (php)

$sql = "SELECT * FROM YOUR_TABLE_NAME";
$result = mysqli_query($conn, $sql); // First parameter is just return of "mysqli_connect()" function
echo "<br>";
echo "<table border='1'>";
while ($row = mysqli_fetch_assoc($result)) { // Important line !!!
    echo "<tr>";
    foreach ($row as $field => $value) { // If you want you can right this line like this: foreach($row as $value) {
        echo "<td>" . $value . "</td>"; 
    }
    echo "</tr>";
}
echo "</table>";

In PHP 7.x You should use mysqli functions and most important one in while loop condition use "mysqli_fetch_assoc()" function not "mysqli_fetch_array()" one. If you would use "mysqli_fetch_array()", you will see your results are duplicated. Just try these two and see the difference.

XSD - how to allow elements in any order any number of times?

In the schema you have in your question, child1 or child2 can appear in any order, any number of times. So this sounds like what you are looking for.

Edit: if you wanted only one of them to appear an unlimited number of times, the unbounded would have to go on the elements instead:

Edit: Fixed type in XML.

Edit: Capitalised O in maxOccurs

<xs:element name="foo">
   <xs:complexType>
     <xs:choice maxOccurs="unbounded">
       <xs:element name="child1" type="xs:int" maxOccurs="unbounded"/>
       <xs:element name="child2" type="xs:string" maxOccurs="unbounded"/>
     </xs:choice>
   </xs:complexType>
</xs:element>

Override valueof() and toString() in Java enum

You can use a static Map in your enum that maps Strings to enum constants. Use it in a 'getEnum' static method. This skips the need to iterate through the enums each time you want to get one from its String value.

public enum RandomEnum {

    StartHere("Start Here"),
    StopHere("Stop Here");

    private final String strVal;
    private RandomEnum(String strVal) {
        this.strVal = strVal;
    }

    public static RandomEnum getEnum(String strVal) {
        if(!strValMap.containsKey(strVal)) {
            throw new IllegalArgumentException("Unknown String Value: " + strVal);
        }
        return strValMap.get(strVal);
    }

    private static final Map<String, RandomEnum> strValMap;
    static {
        final Map<String, RandomEnum> tmpMap = Maps.newHashMap();
        for(final RandomEnum en : RandomEnum.values()) {
            tmpMap.put(en.strVal, en);
        }
        strValMap = ImmutableMap.copyOf(tmpMap);
    }

    @Override
    public String toString() {
        return strVal;
    }
}

Just make sure the static initialization of the map occurs below the declaration of the enum constants.

BTW - that 'ImmutableMap' type is from the Google guava API, and I definitely recommend it in cases like this.


EDIT - Per the comments:

  1. This solution assumes that each assigned string value is unique and non-null. Given that the creator of the enum can control this, and that the string corresponds to the unique & non-null enum value, this seems like a safe restriction.
  2. I added the 'toSTring()' method as asked for in the question

Is there a MySQL option/feature to track history of changes to records?

Just my 2 cents. I would create a solution which records exactly what changed, very similar to transient's solution.

My ChangesTable would simple be:

DateTime | WhoChanged | TableName | Action | ID |FieldName | OldValue

1) When an entire row is changed in the main table, lots of entries will go into this table, BUT that is very unlikely, so not a big problem (people are usually only changing one thing) 2) OldVaue (and NewValue if you want) have to be some sort of epic "anytype" since it could be any data, there might be a way to do this with RAW types or just using JSON strings to convert in and out.

Minimum data usage, stores everything you need and can be used for all tables at once. I'm researching this myself right now, but this might end up being the way I go.

For Create and Delete, just the row ID, no fields needed. On delete a flag on the main table (active?) would be good.

Error:could not create the Java Virtual Machine Error:A fatal exception has occured.Program will exit

Your command is wrong.

Linux

java -- version

macOS

java -version

You can't use those commands other way around.

How do I fix a NoSuchMethodError?

I fixed this problem in Eclipse by renaming a Junit test file.
In my Eclipse work space I have an App project and a Test project.
The Test project has the App project as a required project on the build path.

Started getting the NoSuchMethodError.
Then I realized the class in the Test project had the same name as the class in the App project.

App/  
  src/
     com.example/  
       Projection.java
Test/  
  src/
     com.example/
       Projection.java

After renaming the Test to the correct name "ProjectionTest.java" the exception went away.

.includes() not working in Internet Explorer

You can do the same with !! and ~ operators

 var myString = 'this is my string';

 !!~myString.indexOf('string');
 // -> true

 !!~myString.indexOf('hello');
 // -> false

here's the explanation of the two operators (!! and ~ )

What is the !! (not not) operator in JavaScript?

https://www.joezimjs.com/javascript/great-mystery-of-the-tilde/

How to pause for specific amount of time? (Excel/VBA)

Function Delay(ByVal T As Integer)
    'Function can be used to introduce a delay of up to 99 seconds
    'Call Function ex:  Delay 2 {introduces a 2 second delay before execution of code resumes}
        strT = Mid((100 + T), 2, 2)
            strSecsDelay = "00:00:" & strT
    Application.Wait (Now + TimeValue(strSecsDelay))
End Function

Copying a rsa public key to clipboard

cat .ssh/id_rsa.pub | bcopy

This works for me.

How to correctly link php-fpm and Nginx Docker containers?

As pointed out before, the problem was that the files were not visible by the fpm container. However to share data among containers the recommended pattern is using data-only containers (as explained in this article).

Long story short: create a container that just holds your data, share it with a volume, and link this volume in your apps with volumes_from.

Using compose (1.6.2 in my machine), the docker-compose.yml file would read:

version: "2"
services:
  nginx:
    build:
      context: .
      dockerfile: nginx/Dockerfile
    ports:
      - "80:80"
    links:
      - fpm
    volumes_from:
      - data
  fpm:
    image: php:fpm
    volumes_from:
      - data
  data:
    build:
      context: .
      dockerfile: data/Dockerfile
    volumes:
      - /var/www/html

Note that data publishes a volume that is linked to the nginx and fpm services. Then the Dockerfile for the data service, that contains your source code:

FROM busybox

# content
ADD path/to/source /var/www/html

And the Dockerfile for nginx, that just replaces the default config:

FROM nginx

# config
ADD config/default.conf /etc/nginx/conf.d

For the sake of completion, here's the config file required for the example to work:

server {
    listen 0.0.0.0:80;

    root /var/www/html;

    location / {
        index index.php index.html;
    }

    location ~ \.php$ {
        include fastcgi_params;
        fastcgi_pass fpm:9000;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root/$fastcgi_script_name;
    }
}

which just tells nginx to use the shared volume as document root, and sets the right config for nginx to be able to communicate with the fpm container (i.e.: the right HOST:PORT, which is fpm:9000 thanks to the hostnames defined by compose, and the SCRIPT_FILENAME).

Conditional WHERE clause with CASE statement in Oracle

You can write the where clause as:

where (case when (:stateCode = '') then (1)
            when (:stateCode != '') and (vw.state_cd in (:stateCode)) then 1
            else 0)
       end) = 1;

Alternatively, remove the case entirely:

where (:stateCode = '') or
      ((:stateCode != '') and vw.state_cd in (:stateCode));

Or, even better:

where (:stateCode = '') or vw.state_cd in (:stateCode)

Copying and pasting data using VBA code

Use the PasteSpecial method:

sht.Columns("A:G").Copy
Range("A1").PasteSpecial Paste:=xlPasteValues

BUT your big problem is that you're changing your ActiveSheet to "Data" and not changing it back. You don't need to do the Activate and Select, as per my code (this assumes your button is on the sheet you want to copy to).

Convert a JSON Object to Buffer and Buffer to JSON Object back

You need to stringify the json, not calling toString

var buf = Buffer.from(JSON.stringify(obj));

And for converting string to json obj :

var temp = JSON.parse(buf.toString());

How to save a PNG image server-side, from a base64 data string

It's simple :

Let's imagine that you are trying to upload a file within js framework, ajax request or mobile application (Client side)

  1. Firstly you send a data attribute that contains a base64 encoded string.
  2. In the server side you have to decode it and save it in a local project folder.

Here how to do it using PHP

<?php 

$base64String = "kfezyufgzefhzefjizjfzfzefzefhuze"; // I put a static base64 string, you can implement you special code to retrieve the data received via the request.

$filePath = "/MyProject/public/uploads/img/test.png";

file_put_contents($filePath, base64_decode($base64String));

?>

Nested iframes, AKA Iframe Inception

Thing is, the code you provided won't work because the <iframe> element has to have a "src" property, like:

<iframe id="uploads" src="http://domain/page.html"></iframe>

It's ok to use .contents() to get the content:

$('#uploads).contents() will give you access to the second iframe, but if that iframe is "INSIDE" the http://domain/page.html document the #uploads iframe loaded.

To test I'm right about this, I created 3 html files named main.html, iframe.html and noframe.html and then selected the div#element just fine with:

$('#uploads').contents().find('iframe').contents().find('#element');

There WILL be a delay in which the element will not be available since you need to wait for the iframe to load the resource. Also, all iframes have to be on the same domain.

Hope this helps ...

Here goes the html for the 3 files I used (replace the "src" attributes with your domain and url):

main.html

<!DOCTYPE HTML>
<html>
<head>
    <meta charset="utf-8">
    <title>main.html example</title>

    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

    <script>
        $(function () {
            console.log( $('#uploads').contents().find('iframe').contents().find('#element') ); // nothing at first

            setTimeout( function () {
                console.log( $('#uploads').contents().find('iframe').contents().find('#element') ); // wait and you'll have it
            }, 2000 );

        });
    </script>
</head>
<body>
    <iframe id="uploads" src="http://192.168.1.70/test/iframe.html"></iframe>
</body>

iframe.html

<!DOCTYPE HTML>
<html>
<head>
    <meta charset="utf-8">
    <title>iframe.html example</title>
</head>
<body>
    <iframe src="http://192.168.1.70/test/noframe.html"></iframe>
</body>

noframe.html

<!DOCTYPE HTML>
<html>
<head>
    <meta charset="utf-8">
    <title>noframe.html example</title>
</head>
<body>
    <div id="element">some content</div>
</body>

Using CSS to insert text

It is, but requires a CSS2 capable browser (all major browsers, IE8+).

.OwnerJoe:before {
  content: "Joe's Task:";
}

But I would rather recommend using Javascript for this. With jQuery:

$('.OwnerJoe').each(function() {
  $(this).before($('<span>').text("Joe's Task: "));
});

What is REST? Slightly confused

http://en.wikipedia.org/wiki/Representational_State_Transfer

The basic idea is that instead of having an ongoing connection to the server, you make a request, get some data, show that to a user, but maybe not all of it, and then when the user does something which calls for more data, or to pass some up to the server, the client initiates a change to a new state.

How do I use a Boolean in Python?

Boolean types are defined in documentation:
http://docs.python.org/library/stdtypes.html#boolean-values

Quoted from doc:

Boolean values are the two constant objects False and True. They are used to represent truth values (although other values can also be considered false or true). In numeric contexts (for example when used as the argument to an arithmetic operator), they behave like the integers 0 and 1, respectively. The built-in function bool() can be used to cast any value to a Boolean, if the value can be interpreted as a truth value (see section Truth Value Testing above).

They are written as False and True, respectively.

So in java code remove braces, change true to True and you will be ok :)

ImportError: No module named Image

The PIL distribution is mispackaged for egg installation.

Install Pillow instead, the friendly PIL fork.

"No resource identifier found for attribute 'showAsAction' in package 'android'"

Add "android-support-v7-appcompat.jar" to Android Private Libraries

Why do some functions have underscores "__" before and after the function name?

Actually I use _ method names when I need to differ between parent and child class names. I've read some codes that used this way of creating parent-child classes. As an example I can provide this code:

class ThreadableMixin:
   def start_worker(self):
       threading.Thread(target=self.worker).start()

   def worker(self):
      try:
        self._worker()
    except tornado.web.HTTPError, e:
        self.set_status(e.status_code)
    except:
        logging.error("_worker problem", exc_info=True)
        self.set_status(500)
    tornado.ioloop.IOLoop.instance().add_callback(self.async_callback(self.results))

...

and the child that have a _worker method

class Handler(tornado.web.RequestHandler, ThreadableMixin):
   def _worker(self):
      self.res = self.render_string("template.html",
        title = _("Title"),
        data = self.application.db.query("select ... where object_id=%s", self.object_id)
    )

...

How to call code behind server method from a client side JavaScript function?

In my projects, we usually call server side method like this:

in JavaScript:

document.getElementById("UploadButton").click();

Server side control:

<asp:Button runat="server" ID="UploadButton" Text="" style="display:none;" OnClick="UploadButton_Click" />

C#:

protected void Upload_Click(object sender, EventArgs e)
{

}

Why should I use a pointer rather than the object itself?

There are many excellent answers to this question, including the important use cases of forward declarations, polymorphism etc. but I feel a part of the "soul" of your question is not answered - namely what the different syntaxes mean across Java and C++.

Let's examine the situation comparing the two languages:

Java:

Object object1 = new Object(); //A new object is allocated by Java
Object object2 = new Object(); //Another new object is allocated by Java

object1 = object2; 
//object1 now points to the object originally allocated for object2
//The object originally allocated for object1 is now "dead" - nothing points to it, so it
//will be reclaimed by the Garbage Collector.
//If either object1 or object2 is changed, the change will be reflected to the other

The closest equivalent to this, is:

C++:

Object * object1 = new Object(); //A new object is allocated on the heap
Object * object2 = new Object(); //Another new object is allocated on the heap
delete object1;
//Since C++ does not have a garbage collector, if we don't do that, the next line would 
//cause a "memory leak", i.e. a piece of claimed memory that the app cannot use 
//and that we have no way to reclaim...

object1 = object2; //Same as Java, object1 points to object2.

Let's see the alternative C++ way:

Object object1; //A new object is allocated on the STACK
Object object2; //Another new object is allocated on the STACK
object1 = object2;//!!!! This is different! The CONTENTS of object2 are COPIED onto object1,
//using the "copy assignment operator", the definition of operator =.
//But, the two objects are still different. Change one, the other remains unchanged.
//Also, the objects get automatically destroyed once the function returns...

The best way to think of it is that -- more or less -- Java (implicitly) handles pointers to objects, while C++ may handle either pointers to objects, or the objects themselves. There are exceptions to this -- for example, if you declare Java "primitive" types, they are actual values that are copied, and not pointers. So,

Java:

int object1; //An integer is allocated on the stack.
int object2; //Another integer is allocated on the stack.
object1 = object2; //The value of object2 is copied to object1.

That said, using pointers is NOT necessarily either the correct or the wrong way to handle things; however other answers have covered that satisfactorily. The general idea though is that in C++ you have much more control on the lifetime of the objects, and on where they will live.

Take home point -- the Object * object = new Object() construct is actually what is closest to typical Java (or C# for that matter) semantics.

Why when I transfer a file through SFTP, it takes longer than FTP?

Yes, encryption add some load to your cpu, but if your cpu is not ancient that should not affect as much as you say.

If you enable compression for SSH, SCP is actually faster than FTP despite the SSH encryption (if I remember, twice as fast as FTP for the files I tried). I haven't actually used SFTP, but I believe it uses SCP for the actual file transfer. So please try this and let us know :-)

PHP check if date between two dates

You cannot compare date-strings. It is good habit to use PHP's DateTime object instead:

$paymentDate = new DateTime(); // Today
echo $paymentDate->format('d/m/Y'); // echos today! 
$contractDateBegin = new DateTime('2001-01-01');
$contractDateEnd  = new DateTime('2015-01-01');

if (
  $paymentDate->getTimestamp() > $contractDateBegin->getTimestamp() && 
  $paymentDate->getTimestamp() < $contractDateEnd->getTimestamp()){
  echo "is between";
}else{
   echo "NO GO!";  
}

Deleting multiple elements from a list

An alternative list comprehension method that uses list index values:

stuff = ['a', 'b', 'c', 'd', 'e', 'f', 'woof']
index = [0, 3, 6]
new = [i for i in stuff if stuff.index(i) not in index]

This returns:

['b', 'c', 'e', 'f']

Change R default library path using .libPaths in Rprofile.site fails to work

I was looking into this because R was having issues installing into the default location and was instead just putting the packages into the temp folder. It turned out to be the latest update for Mcaffee Endpoint Security which apparently has issues with R. You can disable the threat protection while you install the packages and it will work properly.

Access multiple elements of list knowing their index

My answer does not use numpy or python collections.

One trivial way to find elements would be as follows:

a = [-2, 1, 5, 3, 8, 5, 6]
b = [1, 2, 5]
c = [i for i in a if i in b]

Drawback: This method may not work for larger lists. Using numpy is recommended for larger lists.

Prevent double submission of forms in jQuery

this code will display loading on the button label, and set button to

disable state, then after processing, re-enable and return back the original button text**

$(function () {

    $(".btn-Loading").each(function (idx, elm) {
        $(elm).click(function () {
            //do processing
            if ($(".input-validation-error").length > 0)
                return;
            $(this).attr("label", $(this).text()).text("loading ....");
            $(this).delay(1000).animate({ disabled: true }, 1000, function () {
                //original event call
                $.when($(elm).delay(1000).one("click")).done(function () {
                    $(this).animate({ disabled: false }, 1000, function () {
                        $(this).text($(this).attr("label"));
                    })
                });
                //processing finalized
            });
        });
    });
    // and fire it after definition
});

Concatenating two std::vectors

If you are interested in strong exception guarantee (when copy constructor can throw an exception):

template<typename T>
inline void append_copy(std::vector<T>& v1, const std::vector<T>& v2)
{
    const auto orig_v1_size = v1.size();
    v1.reserve(orig_v1_size + v2.size());
    try
    {
        v1.insert(v1.end(), v2.begin(), v2.end());
    }
    catch(...)
    {
        v1.erase(v1.begin() + orig_v1_size, v1.end());
        throw;
    }
}

Similar append_move with strong guarantee can't be implemented in general if vector element's move constructor can throw (which is unlikely but still).

Jquery $.ajax fails in IE on cross domain calls

Microsoft always ploughs a self-defeating (at least in IE) furrow:

http://www.nczonline.net/blog/2010/05/25/cross-domain-ajax-with-cross-origin-resource-sharing/

CORS works with XDomainRequest in IE8. But IE 8 does not support Preflighted or Credentialed Requests while Firefox 3.5+, Safari 4+, and Chrome all support such requests.

Apache: The requested URL / was not found on this server. Apache

I had the same problem, but believe it or not is was a case of case sensitivity.

This on localhost: http://localhost/.../getdata.php?id=3

Did not behave the same as this on the server: http://server/.../getdata.php?id=3

Changing the server url to this (notice the capital D in getData) solved my issue. http://localhost/.../getData.php?id=3

Concatenate multiple node values in xpath

Try this expression...

string-join(//element3/(concat(element4/text(), '.', element5/text())), "&#10;")

Number of processors/cores in command line

I think the method you give is the most portable on Linux. Instead of spawning unnecessary cat and wc processes, you can shorten it a bit:

$ grep --count ^processor /proc/cpuinfo
2

How to sort a Ruby Hash by number value?

That's not the behavior I'm seeing:

irb(main):001:0> metrics = {"sitea.com" => 745, "siteb.com" => 9, "sitec.com" =>
 10 }
=> {"siteb.com"=>9, "sitec.com"=>10, "sitea.com"=>745}
irb(main):002:0> metrics.sort {|a1,a2| a2[1]<=>a1[1]}
=> [["sitea.com", 745], ["sitec.com", 10], ["siteb.com", 9]]

Is it possible that somewhere along the line your numbers are being converted to strings? Is there more code you're not posting?

Get next / previous element using JavaScript?

Well in pure javascript my thinking is that you would first have to collate them inside a collection.

var divs = document.getElementsByTagName("div");
//divs now contain each and every div element on the page
var selectionDiv = document.getElementById("MySecondDiv");

So basically with selectionDiv iterate through the collection to find its index, and then obviously -1 = previous +1 = next within bounds

for(var i = 0; i < divs.length;i++)
{
   if(divs[i] == selectionDiv)
   {
     var previous = divs[i - 1];
     var next = divs[i + 1];
   }
}

Please be aware though as I say that extra logic would be required to check that you are within the bounds i.e. you are not at the end or start of the collection.

This also will mean that say you have a div which has a child div nested. The next div would not be a sibling but a child, So if you only want siblings on the same level as the target div then definately use nextSibling checking the tagName property.

Convert UTC date time to local date time

In my point of view servers should always in the general case return a datetime in the standardized ISO 8601-format.

More info here:

IN this case the server would return '2011-06-29T16:52:48.000Z' which would feed directly into the JS Date object.

var utcDate = '2011-06-29T16:52:48.000Z';  // ISO-8601 formatted date returned from server
var localDate = new Date(utcDate);

The localDate will be in the right local time which in my case would be two hours later (DK time).

You really don't have to do all this parsing which just complicates stuff, as long as you are consistent with what format to expect from the server.

Android: I lost my android key store, what should I do?

No, there is no chance to do that. You just learned how important a backup can be.

How can I make sticky headers in RecyclerView? (Without external lib)

For those who may concern. Based on Sevastyan's answer, should you want to make it horizontal scroll. Simply change all getBottom() to getRight() and getTop() to getLeft()

Debugging PHP Mail() and/or PHPMailer

It looks like the class.phpmailer.php file is corrupt. I would download the latest version and try again.

I've always used phpMailer's SMTP feature:

$mail->IsSMTP();
$mail->Host = "localhost";

And if you need debug info:

$mail->SMTPDebug  = 2; // enables SMTP debug information (for testing)
                       // 1 = errors and messages
                       // 2 = messages only

How to unstage large number of files without deleting the content

I'm afraid that the first of those command lines unconditionally deleted from the working copy all the files that are in git's staging area. The second one unstaged all the files that were tracked but have now been deleted. Unfortunately this means that you will have lost any uncommitted modifications to those files.

If you want to get your working copy and index back to how they were at the last commit, you can (carefully) use the following command:

git reset --hard

I say "carefully" since git reset --hard will obliterate uncommitted changes in your working copy and index. However, in this situation it sounds as if you just want to go back to the state at your last commit, and the uncommitted changes have been lost anyway.

Update: it sounds from your comments on Amber's answer that you haven't yet created any commits (since HEAD cannot be resolved), so this won't help, I'm afraid.

As for how those pipes work: git ls-files -z and git diff --name-only --diff-filter=D -z both output a list of file names separated with the byte 0. (This is useful, since, unlike newlines, 0 bytes are guaranteed not to occur in filenames on Unix-like systems.) The program xargs essentially builds command lines from its standard input, by default by taking lines from standard input and adding them to the end of the command line. The -0 option says to expect standard input to by separated by 0 bytes. xargs may invoke the command several times to use up all the parameters from standard input, making sure that the command line never becomes too long.

As a simple example, if you have a file called test.txt, with the following contents:

hello
goodbye
hello again

... then the command xargs echo whatever < test.txt will invoke the command:

echo whatever hello goodbye hello again

Sending JSON to PHP using ajax

That's because $_POST is pre-populated with form data.

To get JSON data (or any raw input), use php://input.

$json = json_decode(file_get_contents("php://input"));

ImportError: No module named Crypto.Cipher

On the mac... if you run into this.. try to see if you can import crypto instead?

If so.. the package name is the issue C vs c. To get around this.. just add these lines to the top of your script.

import crypto
import sys
sys.modules['Crypto'] = crypto

You know should be able to import paramiko successfully.

minimize app to system tray

this.WindowState = FormWindowState.Minimized;

How to remove a virtualenv created by "pipenv run"

You can run the pipenv command with the --rm option as in:

pipenv --rm

This will remove the virtualenv created for you under ~/.virtualenvs

See https://pipenv.kennethreitz.org/en/latest/cli/#cmdoption-pipenv-rm

How to change the Title of the window in Qt?

You can also modify the windowTitle attribute in Qt Designer.

Math.random() explanation

Here's a method which receives boundaries and returns a random integer. It is slightly more advanced (completely universal): boundaries can be both positive and negative, and minimum/maximum boundaries can come in any order.

int myRand(int i_from, int i_to) {
  return (int)(Math.random() * (Math.abs(i_from - i_to) + 1)) + Math.min(i_from, i_to);
}

In general, it finds the absolute distance between the borders, gets relevant random value, and then shifts the answer based on the bottom border.

Auto highlight text in a textbox control

Here's the code I've been using. It requires adding the attached property to each textbox you wish to auto select. Seeing as I don't want every textbox in my application to do this, this was the best solution to me.

public class AutoSelectAll
{
    public static bool GetIsEnabled(DependencyObject obj) 
    { 
        return (bool)obj.GetValue(IsEnabledProperty); 
    } 
    public static void SetIsEnabled(DependencyObject obj, bool value) 
    { 
        obj.SetValue(IsEnabledProperty, value);
    }

    static void ue_Loaded(object sender, RoutedEventArgs e)
    {
        var ue = sender as FrameworkElement;
        if (ue == null)
            return;
        ue.GotFocus += ue_GotFocus;
        ue.GotMouseCapture += ue_GotMouseCapture;
    }

    private static void ue_Unloaded(object sender, RoutedEventArgs e)
    {
        var ue = sender as FrameworkElement;
        if (ue == null)
            return;
        //ue.Unloaded -= ue_Unloaded;
        ue.GotFocus -= ue_GotFocus;
        ue.GotMouseCapture -= ue_GotMouseCapture;
    }

    static void ue_GotFocus(object sender, RoutedEventArgs e)
    {
        if (sender is TextBox)
        {
            (sender as TextBox).SelectAll();
        }
        e.Handled = true;
    }

    static void ue_GotMouseCapture(object sender, MouseEventArgs e)
    {
        if (sender is TextBox)
        {
            (sender as TextBox).SelectAll();
        }
        e.Handled = true;
    }

    public static readonly DependencyProperty IsEnabledProperty = DependencyProperty.RegisterAttached("IsEnabled", typeof(bool),
        typeof(AutoSelectAll), new UIPropertyMetadata(false, IsEnabledChanged));

    static void IsEnabledChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var ue = d as FrameworkElement;
        if (ue == null)
            return;
        if ((bool)e.NewValue)
        {
            ue.Unloaded += ue_Unloaded;
            ue.Loaded += ue_Loaded;
        }
    }
} 

The main change I made here was adding a loaded event to many of the examples I've seen. This allows the code to continue working after it's unloaded (ie. a tab is changed). Also I included code to make sure the text gets selected if you click on the textbox with the mouse, and not just keyboard focus it. Note: If you actually click on the text in the textbox, the cursor is inserted between the letters as it should.

You can use this by including the following tag in your xaml.

<TextBox  
    Text="{Binding Property}"
    Library:AutoSelectAll.IsEnabled="True" />

Concatenating Matrices in R

cbindX from the package gdata combines multiple columns of differing column and row lengths. Check out the page here:

http://hosho.ees.hokudai.ac.jp/~kubo/Rdoc/library/gdata/html/cbindX.html

It takes multiple comma separated matrices and data.frames as input :) You just need to

install.packages("gdata", dependencies=TRUE)

and then

library(gdata)
concat_data <- cbindX(df1, df2, df3) # or cbindX(matrix1, matrix2, matrix3, matrix4)

how to compare the Java Byte[] array?

You can also use a ByteArrayComparator from Apache Directory. In addition to equals it lets you compare if one array is greater than the other.

Selenium C# WebDriver: Wait until element is present

Using the solution provided by Mike Kwan may have an impact in overall testing performance, since the implicit wait will be used in all FindElement calls.

Many times you'll want the FindElement to fail right away when an element is not present (you're testing for a malformed page, missing elements, etc.). With the implicit wait these operations would wait for the whole timeout to expire before throwing the exception. The default implicit wait is set to 0 seconds.

I've written a little extension method to IWebDriver that adds a timeout (in seconds) parameter to the FindElement() method. It's quite self-explanatory:

public static class WebDriverExtensions
{
    public static IWebElement FindElement(this IWebDriver driver, By by, int timeoutInSeconds)
    {
        if (timeoutInSeconds > 0)
        {
            var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(timeoutInSeconds));
            return wait.Until(drv => drv.FindElement(by));
        }
        return driver.FindElement(by);
    }
}

I didn't cache the WebDriverWait object as its creation is very cheap, this extension may be used simultaneously for different WebDriver objects, and I only do optimizations when ultimately needed.

Usage is straightforward:

var driver = new FirefoxDriver();
driver.Navigate().GoToUrl("http://localhost/mypage");
var btn = driver.FindElement(By.CssSelector("#login_button"));
btn.Click();
var employeeLabel = driver.FindElement(By.CssSelector("#VCC_VSL"), 10);
Assert.AreEqual("Employee", employeeLabel.Text);
driver.Close();

How do I copy the contents of one ArrayList into another?

You can use such trick:

myObject = new ArrayList<Object>(myTempObject);

or use

myObject = (ArrayList<Object>)myTempObject.clone();

You can get some information about clone() method here

But you should remember, that all these ways will give you a copy of your List, not all of its elements. So if you change one of the elements in your copied List, it will also be changed in your original List.

Prevent Android activity dialog from closing on outside touch

Use This Code it's Working For me

 AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
 alertDialog.setCancelable(false);

Checking Value of Radio Button Group via JavaScript?

Without loop:

document.getElementsByName('gender').reduce(function(value, checkable) {
    if(checkable.checked == true) 
        value = checkable.value; 
    return value;
}, '');

reduce is just a function that will feed sequentially array elements to second argument of callback, and previously returned function to value, while for the first run, it will use value of second argument.

The only minus of this approach is that reduce will traverse every element returned by getElementsByName even after it have found selected radio button.

MySQL: is a SELECT statement case sensitive?

The default is case insensitive, but the next most important thing you should take a look at is how the table was created in the first place, because you can specify case sensitivity when you create the table.

The script below creates a table. Notice down at the bottom it says "COLLATE latin1_general_cs". That cs at the end means case sensitive. If you wanted your table to be case insensitive you would either leave that part out or use "COLLATE latin1_general_ci".

   CREATE Table PEOPLE (

       USER_ID  INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,

       FIRST_NAME  VARCHAR(50) NOT NULL,
       LAST_NAME  VARCHAR(50) NOT NULL,

       PRIMARY KEY (USER_ID)

   )

   ENGINE=MyISAM DEFAULT CHARACTER SET latin1
    COLLATE latin1_general_cs AUTO_INCREMENT=0;

If your project is such that you can create your own table, then it makes sense to specify your case sensitivity preference when you create the table.

JSON Array iteration in Android/Java

While iterating over a JSON array (org.json.JSONArray, built into Android), watch out for null objects; for example, you may get "null" instead of a null string.

A check may look like:

s[i] = array.isNull(i) ? null : array.getString(i);

Where to change the value of lower_case_table_names=2 on windows xampp

If you have the file my-default.ini rename it to my.ini

Visual Studio Post Build Event - Copy to Relative Directory Location

I think this is related, but I had a problem when building directly using msbuild command line (from a batch file) vs building from within VS.

Using something like the following:

<PostBuildEvent>
  MOVE /Y "$(TargetDir)something.file1" "$(ProjectDir)something.file1"
  start XCOPY /Y /R "$(SolutionDir)SomeConsoleApp\bin\$(ConfigurationName)\*" "$(ProjectDir)App_Data\Consoles\SomeConsoleApp\"
</PostBuildEvent>

(note: start XCOPY rather than XCOPY used to get around a permissions issue which prevented copying)

The macro $(SolutionDir) evaluated to ..\ when executing msbuild from a batchfile, which resulted in the XCOPY command failing. It otherwise worked fine when built from within Visual Studio. Confirmed using /verbosity:diagnostic to see the evaluated output.

Using the macro $(ProjectDir)..\ instead, which amounts to the same thing, worked fine and retained the full path in both build scenarios.

Can you write virtual functions / methods in Java?

Yes, you can write virtual "functions" in Java.

Hibernate-sequence doesn't exist

You need to set for Hibernate5.x <property name="hibernate.id.new_generator_mappings">false</property>.. see and link.

For older version of hibernate 4.x: <prop key="hibernate.id.new_generator_mappings">false</prop>

How to get base64 encoded data from html image

You can try following sample http://jsfiddle.net/xKJB8/3/

<img id="preview" src="http://www.gravatar.com/avatar/0e39d18b89822d1d9871e0d1bc839d06?s=128&d=identicon&r=PG">
<canvas id="myCanvas" />

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var img = document.getElementById("preview");
ctx.drawImage(img, 10, 10);
alert(c.toDataURL());

Pandas How to filter a Series

As DACW pointed out, there are method-chaining improvements in pandas 0.18.1 that do what you are looking for very nicely.

Rather than using .where, you can pass your function to either the .loc indexer or the Series indexer [] and avoid the call to .dropna:

test = pd.Series({
383:    3.000000,
663:    1.000000,
726:    1.000000,
737:    9.000000,
833:    8.166667
})

test.loc[lambda x : x!=1]

test[lambda x: x!=1]

Similar behavior is supported on the DataFrame and NDFrame classes.

estimating of testing effort as a percentage of development time

Some years ago, in a safety critical field, I have heard something like one day for unit testing ten lines of code.

I have also observed 50% of effort for development and 50% for testing (not only unit testing).

Plot multiple lines (data series) each with unique color in R

Here is a sample code that includes a legend if that is of interest.

# First create an empty plot.
plot(1, type = 'n', xlim = c(xminp, xmaxp), ylim = c(0, 1), 
     xlab = "log transformed coverage", ylab = "frequency")

# Create a list of 22 colors to use for the lines.
cl <- rainbow(22)

# Now fill plot with the log transformed coverage data from the
# files one by one.
for(i in 1:length(data)) {
    lines(density(log(data[[i]]$coverage)), col = cl[i])
    plotcol[i] <- cl[i]
}
legend("topright", legend = c(list.files()), col = plotcol, lwd = 1,
       cex = 0.5)

Delete first character of a string in Javascript

Did you try the substring function?

string = string.indexOf(0) == '0' ? string.substring(1) : string;

Here's a reference - https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/substring

And you can always do this for multiple 0s:

while(string.indexOf(0) == '0')
{
    string = string.substring(1);
}

How to get the difference between two dictionaries in Python?

def flatten_it(d):
    if isinstance(d, list) or isinstance(d, tuple):
        return tuple([flatten_it(item) for item in d])
    elif isinstance(d, dict):
        return tuple([(flatten_it(k), flatten_it(v)) for k, v in sorted(d.items())])
    else:
        return d

dict1 = {'a': 1, 'b': 2, 'c': 3}
dict2 = {'a': 1, 'b': 1}

print set(flatten_it(dict1)) - set(flatten_it(dict2)) # set([('b', 2), ('c', 3)])
# or 
print set(flatten_it(dict2)) - set(flatten_it(dict1)) # set([('b', 1)])

How can I create a self-signed cert for localhost?

If you are trying to create a self signed certificate that lets you go http://localhost/mysite Then here is a way to create it

makecert -r -n "CN=localhost" -b 01/01/2000 -e 01/01/2099 -eku 1.3.6.1.5.5.7.3.1 -sv localhost.pvk localhost.cer
cert2spc localhost.cer localhost.spc
pvk2pfx -pvk localhost.pvk -spc localhost.spc -pfx localhost.pfx

From http://social.msdn.microsoft.com/Forums/en-US/wcf/thread/32bc5a61-1f7b-4545-a514-a11652f11200

Using Chrome, how to find to which events are bound to an element

For Chrome Version 52.0.2743.116:

  1. In Chrome's Developer Tools, bring up the 'Search' panel by hitting Ctrl+Shift+F.

  2. Type in the name of the element you're trying to find.

Results for binded elements should appear in the panel and state the file they're located in.

How to save all console output to file in R?

  1. If you want to get error messages saved in a file

    zz <- file("Errors.txt", open="wt")
    sink(zz, type="message")
    

    the output will be:

    Error in print(errr) : object 'errr' not found
    Execution halted
    

    This output will be saved in a file named Errors.txt

  2. In case, you want printed values of console to a file you can use 'split' argument:

    zz <- file("console.txt", open="wt")
    sink(zz,  split=TRUE)
    print("cool")
    print(errr)
    

    output will be:

    [1] "cool"
    

    in console.txt file. So all your console output will be printed in a file named console.txt

How to detect if multiple keys are pressed at once using JavaScript?

document.onkeydown = keydown; 

function keydown (evt) { 

    if (!evt) evt = event; 

    if (evt.ctrlKey && evt.altKey && evt.keyCode === 115) {

        alert("CTRL+ALT+F4"); 

    } else if (evt.shiftKey && evt.keyCode === 9) { 

        alert("Shift+TAB");

    } 

}

C non-blocking keyboard input

You can do that using select as follow:

  int nfds = 0;
  fd_set readfds;
  FD_ZERO(&readfds);
  FD_SET(0, &readfds); /* set the stdin in the set of file descriptors to be selected */
  while(1)
  {
     /* Do what you want */
     int count = select(nfds, &readfds, NULL, NULL, NULL);
     if (count > 0) {
      if (FD_ISSET(0, &readfds)) {
          /* If a character was pressed then we get it and exit */
          getchar();
          break;
      }
     }
  }

Not too much work :D

How can I upload files asynchronously?

The simplest and most robust way I have done this in the past, is to simply target a hidden iFrame tag with your form - then it will submit within the iframe without reloading the page.

That is if you don't want to use a plugin, JavaScript or any other forms of "magic" other than HTML. Of course you can combine this with JavaScript or what have you...

<form target="iframe" action="" method="post" enctype="multipart/form-data">
    <input name="file" type="file" />
    <input type="button" value="Upload" />
</form>

<iframe name="iframe" id="iframe" style="display:none" ></iframe>

You can also read the contents of the iframe onLoad for server errors or success responses and then output that to user.

Chrome, iFrames, and onLoad

-note- you only need to keep reading if you are interested in how to setup a UI blocker when doing uploading/downloading

Currently Chrome doesn't trigger the onLoad event for the iframe when it's used to transfer files. Firefox, IE, and Edge all fire the onload event for file transfers.

The only solution that I found works for Chrome was to use a cookie.

To do that basically when the upload/download is started:

  • [Client Side] Start an interval to look for the existence of a cookie
  • [Server Side] Do whatever you need to with the file data
  • [Server Side] Set cookie for client side interval
  • [Client Side] Interval sees the cookie and uses it like the onLoad event. For example you can start a UI blocker and then onLoad ( or when cookie is made ) you remove the UI blocker.

Using a cookie for this is ugly but it works.

I made a jQuery plugin to handle this issue for Chrome when downloading, you can find here

https://github.com/ArtisticPhoenix/jQuery-Plugins/blob/master/iDownloader.js

The same basic principal applies to uploading, as well.

To use the downloader ( include the JS, obviously )

 $('body').iDownloader({
     "onComplete" : function(){
          $('#uiBlocker').css('display', 'none'); //hide ui blocker on complete
     }
 });

 $('somebuttion').click( function(){
      $('#uiBlocker').css('display', 'block'); //block the UI
      $('body').iDownloader('download', 'htttp://example.com/location/of/download');
 });

And on the server side, just before transferring the file data, create the cookie

 setcookie('iDownloader', true, time() + 30, "/");

The plugin will see the cookie, and then trigger the onComplete callback.

How to change symbol for decimal point in double.ToString()?

Create an extension method?

Console.WriteLine(value.ToGBString());

// ...

public static class DoubleExtensions
{
    public static string ToGBString(this double value)
    {
        return value.ToString(CultureInfo.GetCultureInfo("en-GB"));
    }
}

Get the closest number out of an array

Here is the Code snippet to find the closest element to a number from an array in Complexity O(nlog(n)) :-

Input :- {1,60,0,-10,100,87,56} Element:- 56 Closest Number in Array:- 60

Source Code (Java):

package com.algo.closestnumberinarray;
import java.util.TreeMap;


public class Find_Closest_Number_In_Array {

    public static void main(String arsg[]) {
        int array[] = { 1, 60, 0, -10, 100, 87, 69 };
        int number = 56;
        int num = getClosestNumber(array, number);
        System.out.println("Number is=" + num);
    }

    public static int getClosestNumber(int[] array, int number) {
        int diff[] = new int[array.length];

        TreeMap<Integer, Integer> keyVal = new TreeMap<Integer, Integer>();
        for (int i = 0; i < array.length; i++) {

            if (array[i] > number) {
                diff[i] = array[i] - number;
                keyVal.put(diff[i], array[i]);
            } else {
                diff[i] = number - array[i];
                keyVal.put(diff[i], array[i]);
            }

        }

        int closestKey = keyVal.firstKey();
        int closestVal = keyVal.get(closestKey);

        return closestVal;
    }
}

Equivalent of Oracle's RowID in SQL Server

From http://vyaskn.tripod.com/programming_faq.htm#q17:

Oracle has a rownum to access rows of a table using row number or row id. Is there any equivalent for that in SQL Server? Or how to generate output with row number in SQL Server?

There is no direct equivalent to Oracle's rownum or row id in SQL Server. Strictly speaking, in a relational database, rows within a table are not ordered and a row id won't really make sense. But if you need that functionality, consider the following three alternatives:

  • Add an IDENTITY column to your table.

  • Use the following query to generate a row number for each row. The following query generates a row number for each row in the authors table of pubs database. For this query to work, the table must have a unique key.

    SELECT (SELECT COUNT(i.au_id) 
            FROM pubs..authors i 
            WHERE i.au_id >= o.au_id ) AS RowID, 
           au_fname + ' ' + au_lname AS 'Author name'
    FROM          pubs..authors o
    ORDER BY      RowID
    
  • Use a temporary table approach, to store the entire resultset into a temporary table, along with a row id generated by the IDENTITY() function. Creating a temporary table will be costly, especially when you are working with large tables. Go for this approach, if you don't have a unique key in your table.

How to create a custom scrollbar on a div (Facebook style)

Facebook uses a very clever technique I described in context of my scrollbar plugin jsFancyScroll:

The scrolled content is actually scrolled natively by the browser scrolling mechanisms while the native scrollbar is hidden by using overflow definitions and the custom scrollbar is kept in sync by bi-directional event listening.

Feel free to use my plugin for your project: :)

https://github.com/leoselig/jsFancyScroll/

I highly recommend it over plugins such as TinyScrollbar that come with terrible performance issues!

JSON parsing using Gson for Java

Firstly generate getter and setter using below parsing site

http://www.jsonschema2pojo.org/

Now use Gson

GettetSetterClass object=new Gson().fromjson(jsonLine, GettetSetterClass.class);

Now use object to get values such as data,translationText

How to Convert datetime value to yyyymmddhhmmss in SQL server?

This seems to work:

declare @d datetime
set @d = '2014-04-17 13:55:12'

select replace(convert(varchar(8), @d, 112)+convert(varchar(8), @d, 114), ':','') 

Result:

20140417135512

grunt: command not found when running from terminal

I'm guessing you used Brew to install Node, so the guide here might be helpful http://madebyhoundstooth.com/blog/install-node-with-homebrew-on-os-x/.

You need to ensure that the npm/bin is in your path as it describes export PATH="/usr/local/share/npm/bin:$PATH". This is the location that npm will install the bin stubs for the installed packages.


The nano version will also work as described here http://architectryan.com/2012/10/02/add-to-the-path-on-mac-os-x-mountain-lion/ but a restart of Terminal may be required to have the new path picked up.

CSS3 Transition - Fade out effect

.fadeOut{
    background-color: rgba(255, 0, 0, 0.83);
    border-radius: 8px;
    box-shadow: silver 3px 3px 5px 0px;
    border: 2px dashed yellow;
    padding: 3px;
}
.fadeOut.end{
    transition: all 1s ease-in-out;
    background-color: rgba(255, 0, 0, 0.0);
    box-shadow: none;
    border: 0px dashed yellow;
    border-radius: 0px;
}

demo here.

Using Oracle to_date function for date string with milliseconds

You have to change date class to timestamp.

String s=df.format(c.getTime());
java.util.Date parsedUtilDate = df.parse(s);  
java.sql.Timestamp timestamp = new java.sql.Timestamp(parsedUtilDate.getTime());

How to execute a .sql script from bash

You simply need to start mysql and feed it with the content of db.sql:

mysql -u user -p < db.sql

How do I store and retrieve a blob from sqlite?

In C++ (without error checking):

std::string blob = ...; // assume blob is in the string


std::string query = "INSERT INTO foo (blob_column) VALUES (?);";

sqlite3_stmt *stmt;
sqlite3_prepare_v2(db, query, query.size(), &stmt, nullptr);
sqlite3_bind_blob(stmt, 1, blob.data(), blob.size(), 
                  SQLITE_TRANSIENT);

That can be SQLITE_STATIC if the query will be executed before blob gets destructed.

Regex for Comma delimited list

You might want to specify language just to be safe, but

(\d+, ?)+(\d+)?

ought to work

Freely convert between List<T> and IEnumerable<T>

List<string> myList = new List<string>();
IEnumerable<string> myEnumerable = myList;
List<string> listAgain = myEnumerable.ToList();

BeanFactory vs ApplicationContext

I think it's better to always use ApplicationContext, unless you're in a mobile environment like someone else said already. ApplicationContext has more functionality and you definitely want to use the PostProcessors such as RequiredAnnotationBeanPostProcessor, AutowiredAnnotationBeanPostProcessor and CommonAnnotationBeanPostProcessor, which will help you simplify your Spring configuration files, and you can use annotations such as @Required, @PostConstruct, @Resource, etc in your beans.

Even if you don't use all the stuff ApplicationContext offers, it's better to use it anyway, and then later if you decide to use some resource stuff such as messages or post processors, or the other schema to add transactional advices and such, you will already have an ApplicationContext and won't need to change any code.

If you're writing a standalone app, load the ApplicationContext in your main method, using a ClassPathXmlApplicationContext, and get the main bean and invoke its run() (or whatever method) to start your app. If you're writing a web app, use the ContextLoaderListener in web.xml so that it creates the ApplicationContext and you can later get it from the ServletContext, regardless of whether you're using JSP, JSF, JSTL, struts, Tapestry, etc.

Also, remember you can use multiple Spring configuration files and you can either create the ApplicationContext by listing all the files in the constructor (or listing them in the context-param for the ContextLoaderListener), or you can just load a main config file which has import statements. You can import a Spring configuration file into another Spring configuration file by using <import resource="otherfile.xml" /> which is very useful when you programmatically create the ApplicationContext in the main method and load only one Spring config file.

How to get access to HTTP header information in Spring MVC REST controller?

When you annotate a parameter with @RequestHeader, the parameter retrieves the header information. So you can just do something like this:

@RequestHeader("Accept")

to get the Accept header.

So from the documentation:

@RequestMapping("/displayHeaderInfo.do")
public void displayHeaderInfo(@RequestHeader("Accept-Encoding") String encoding,
                              @RequestHeader("Keep-Alive") long keepAlive)  {

}

The Accept-Encoding and Keep-Alive header values are provided in the encoding and keepAlive parameters respectively.

And no worries. We are all noobs with something.

PHP - Redirect and send data via POST

An old post but here is how I handled it. Using newms87's method:

if($action == "redemption")
{
    if($redemptionId != "")
    {
        $results = json_decode($rewards->redeemPoints($redemptionId));

        if($results->success == true)
        {
            $redirectLocation = $GLOBALS['BASE_URL'] . 'rewards.phtml?a=redemptionComplete';
            // put results in session and redirect back to same page passing an action paraameter
            $_SESSION['post_data'] = json_encode($results);
            header("Location:" . $redirectLocation);
            exit();
        }
    }
}
elseif($action == "redemptionComplete")
{
    // if data is in session pull it and unset it.
    if(isset($_SESSION['post_data']))
    {
        $results = json_decode($_SESSION['post_data']);
        unset($_SESSION['post_data']);
    }
    // if you got here, you completed the redemption and reloaded the confirmation page. So redirect back to rewards.phtml page.
    else
    {
        $redirectLocation = $GLOBALS['BASE_URL'] . 'rewards.phtml';
        header("Location:" . $redirectLocation);
    }
}

Java collections maintaining insertion order

Okay ... so these posts are old as compared to now, but insertion order is needed depending on your need or application requirements, so just use the right type of collection. For most part, it is not needed, but in a situation where you need to utilize objects in the order they were stored, I see a definite need. I think order matters when you are creating for instance a wizard or a flow engine or something of that nature where you need to go from state to state or something. In that sense you can read off stuff from the list without having it keep track of what you need next or traverse a list to find what you want. It does help with performance in that sense. It does matter or else these collections would not make much sense.

How do I determine the size of an object in Python?

Use sys.getsizeof() if you DON'T want to include sizes of linked (nested) objects.

However, if you want to count sub-objects nested in lists, dicts, sets, tuples - and usually THIS is what you're looking for - use the recursive deep sizeof() function as shown below:

import sys
def sizeof(obj):
    size = sys.getsizeof(obj)
    if isinstance(obj, dict): return size + sum(map(sizeof, obj.keys())) + sum(map(sizeof, obj.values()))
    if isinstance(obj, (list, tuple, set, frozenset)): return size + sum(map(sizeof, obj))
    return size

You can also find this function in the nifty toolbox, together with many other useful one-liners:

https://github.com/mwojnars/nifty/blob/master/util.py

ORA-01008: not all variables bound. They are bound

I found how to run the query without error, but I hesitate to call it a "solution" without really understanding the underlying cause.

This more closely resembles the beginning of my actual query:

-- Comment
-- More comment
SELECT rf.flowrow, rf.stage, rf.process,
rf.instr instnum, rf.procedure_id, rtd_history.runtime, rtd_history.waittime
FROM
(
    -- Comment at beginning of subquery
    -- These two comment lines are the problem
    SELECT sub2.flowrow, sub2.stage, sub2.process, sub2.instr, sub2.pid
    FROM ( ...

The second set of comments above, at the beginning of the subquery, were the problem. When removed, the query executes. Other comments are fine. This is not a matter of some rogue or missing newline causing the following line to be commented, because the following line is a SELECT. A missing select would yield a different error than "not all variables bound."

I asked around and found one co-worker who has run into this -- comments causing query failures -- several times. Does anyone know how this can be the cause? It is my understanding that the very first thing a DBMS would do with comments is see if they contain hints, and if not, remove them during parsing. How can an ordinary comment containing no unusual characters (just letters and a period) cause an error? Bizarre.

:: (double colon) operator in Java 8

Yes, that is true. The :: operator is used for method referencing. So, one can extract static methods from classes by using it or methods from objects. The same operator can be used even for constructors. All cases mentioned here are exemplified in the code sample below.

The official documentation from Oracle can be found here.

You can have a better overview of the JDK 8 changes in this article. In the Method/Constructor referencing section a code example is also provided:

interface ConstructorReference {
    T constructor();
}

interface  MethodReference {
   void anotherMethod(String input);
}

public class ConstructorClass {
    String value;

   public ConstructorClass() {
       value = "default";
   }

   public static void method(String input) {
      System.out.println(input);
   }

   public void nextMethod(String input) {
       // operations
   }

   public static void main(String... args) {
       // constructor reference
       ConstructorReference reference = ConstructorClass::new;
       ConstructorClass cc = reference.constructor();

       // static method reference
       MethodReference mr = cc::method;

       // object method reference
       MethodReference mr2 = cc::nextMethod;

       System.out.println(cc.value);
   }
}

How to uninstall Python 2.7 on a Mac OS X 10.6.4?

Onur Güzel provides the solution in his blog post, "Uninstall Python Package from OS X.

You should type the following commands into the terminal:

  1. sudo rm -rf /Library/Frameworks/Python.framework

  2. cd /usr/local/bin

  3. ls -l . | grep '../Library/Frameworks/Python.framework' | awk '{print $9}' | xargs sudo rm

  4. sudo rm -rf "/Applications/Python x.y"

    where command x.y is the version of Python installed. According to your question, it should be 2.7.

In Onur's words:

WARNING: This commands will remove all Python versions installed with packages. Python provided from the system will not be affected.

If you have more than 1 Python version installed from python.org, then run the fourth command again, changing "x.y" for each version of Python that is to be uninstalled.

Table Naming Dilemma: Singular vs. Plural Names

I am a fan of singular table names as they make my ER diagrams using CASE syntax easier to read, but by reading these responses I'm getting the feeling it never caught on very well? I personally love it. There is a good overview with examples of how readable your models can be when you use singular table names, add action verbs to your relationships and form good sentences for every relationships. It's all a bit of overkill for a 20 table database but if you have a DB with hundreds of tables and a complex design how will your developers ever understand it without a good readable diagram?

http://www.aisintl.com/case/method.html

As for prefixing tables and views I absolutely hate that practice. Give a person no information at all before giving them possibly bad information. Anyone browsing a db for objects can quite easily tell a table from a view, but if I have a table named tblUsers that for some reason I decide to restructure in the future into two tables, with a view unifying them to keep from breaking old code I now have a view named tblUsers. At this point I am left with two unappealing options, leave a view named with a tbl prefix which may confuse some developers, or force another layer, either middle tier or application to be rewritten to reference my new structure or name viewUsers. That negates a large part of the value of views IMHO.

How to change MySQL timezone in a database connection using Java?

For applications such as Squirrel SQL Client (http://squirrel-sql.sourceforge.net/) version 4 you can set "serverTimezone" under "driver properties" to GMT+1 (example of timezone "Europe/Vienna).

Dealing with commas in a CSV file

You can use alternative "delimiters" like ";" or "|" but simplest might just be quoting which is supported by most (decent) CSV libraries and most decent spreadsheets.

For more on CSV delimiters and a spec for a standard format for describing delimiters and quoting see this webpage

How to return the current timestamp with Moment.js?

If you just want the milliseconds since 01-JAN-1970, then you can use

var theMoment = moment(); // or whatever your moment instance is
var millis;

millis = +theMoment; // a short but not very readable form
// or
millis = theMoment.valueOf();
// or (almost sure not as efficient as above)
millis = theMoment.toDate().getTime();

Pip freeze vs. pip list

pip list shows ALL installed packages.

pip freeze shows packages YOU installed via pip (or pipenv if using that tool) command in a requirements format.

Remark below that setuptools, pip, wheel are installed when pipenv shell creates my virtual envelope. These packages were NOT installed by me using pip:

test1 % pipenv shell
Creating a virtualenv for this project…
Pipfile: /Users/terrence/Development/Python/Projects/test1/Pipfile
Using /usr/local/Cellar/pipenv/2018.11.26_3/libexec/bin/python3.8 (3.8.1) to create virtualenv…
? Creating virtual environment...
<SNIP>
Installing setuptools, pip, wheel...
done.
? Successfully created virtual environment! 
<SNIP>

Now review & compare the output of the respective commands where I've only installed cool-lib and sampleproject (of which peppercorn is a dependency):

test1 % pip freeze       <== Packages I'VE installed w/ pip

-e git+https://github.com/gdamjan/hello-world-python-package.git@10<snip>71#egg=cool_lib
peppercorn==0.6
sampleproject==1.3.1


test1 % pip list         <== All packages, incl. ones I've NOT installed w/ pip

Package       Version Location                                                                    
------------- ------- --------------------------------------------------------------------------
cool-lib      0.1  /Users/terrence/.local/share/virtualenvs/test1-y2Zgz1D2/src/cool-lib           <== Installed w/ `pip` command
peppercorn    0.6       <== Dependency of "sampleproject"
pip           20.0.2  
sampleproject 1.3.1     <== Installed w/ `pip` command
setuptools    45.1.0  
wheel         0.34.2

How to write a basic swap function in Java

Here's a method to swap two variables in java in just one line using bitwise XOR(^) operator.

class Swap
{
   public static void main (String[] args)
   {
      int x = 5, y = 10;
      x = x ^ y ^ (y = x);
      System.out.println("New values of x and y are "+ x + ", " + y);
   }
} 

Output:

New values of x and y are 10, 5

NSUserDefaults - How to tell if a key exists

Try this little crumpet:

-(void)saveUserSettings{
NSNumber*   value;

value = [NSNumber numberWithFloat:self.sensativity];
[[NSUserDefaults standardUserDefaults] setObject:value forKey:@"sensativity"];
}
-(void)loadUserSettings{
    NSNumber*   value;
    value = [[NSUserDefaults standardUserDefaults] objectForKey:@"sensativity"];
    if(value == nil){
        self.sensativity = 4.0;
    }else{
        self.sensativity = [value floatValue];
    }
}

Treat everything as an object. Seems to work for me.

Validate email with a regex in jQuery

You probably want to use a regex like the one described here to check the format. When the form's submitted, run the following test on each field:

var userinput = $(this).val();
var pattern = /^\b[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b$/i

if(!pattern.test(userinput))
{
  alert('not a valid e-mail address');
}?

HTML5 phone number validation with pattern

enter image description here

^[789]\d{9,9}$

  • Minimum digits 10
  • Maximum digits 10
  • number starts with 7,8,9

Convert char array to string use C

Assuming array is a character array that does not end in \0, you will want to use strncpy:

char * strncpy(char * destination, const char * source, size_t num);

like so:

strncpy(string, array, 20);
string[20] = '\0'

Then string will be a null terminated C string, as desired.

Date only from TextBoxFor()

The Template Editor will work for display purposes only. If you use the same editor (which makes sense because its an editor) and you supplied a value like 31/01/2010 - you'll get an error message saying the format is invalid.