Programs & Examples On #Vsip

The Visual Studio Industry Partner (VSIP) Program (formerly Visual Studio Integration Program) allows third-party developers and software vendors to develop tools, components and languages for use in the Microsoft Visual Studio .NET IDE.

Visual Studio build fails: unable to copy exe-file from obj\debug to bin\debug

  1. Set another project as startup
  2. Build the project (the non problematic project will display)
  3. Go to the problematic bin\debug folder
  4. Rename myservice.vshost.exe to myservice.exe

How to open a new HTML page using jQuery?

You need to use ajax.

http://api.jquery.com/jQuery.ajax/

<code>
$.ajax({
  url: 'ajax/test.html',
  success: function(data) {
    $('.result').html(data);
    alert('Load was performed.');
  }
});
</code>

Combine two ActiveRecord::Relation objects

Relation objects can be converted to arrays. This negates being able to use any ActiveRecord methods on them afterwards, but I didn't need to. I did this:

name_relation = first_name_relation + last_name_relation

Ruby 1.9, rails 3.2

Can anyone confirm that phpMyAdmin AllowNoPassword works with MySQL databases?

Yes not working! I spent whole day with this stupid phpMyAdmin. Just add a new user with a password

1 - Login to mysql or mariadb mysql -u root -p

2 - Run these SQL commands to create a new user with all permissions (or grant your custom permissions)

CREATE USER 'someone'@'localhost' IDENTIFIED BY 'password';
GRANT ALL PRIVILEGES ON *.* TO 'someone'@'localhost';
FLUSH PRIVILEGES;

2 - Go to /etc/phpMyAdmin/config.inc.php and change this:

$cfg['Servers'][$i]['user']          = 'someone';
$cfg['Servers'][$i]['password']      = 'password';

WARNING: This config is for localhost development server only, If you're running a production server you must use strong credentials and not setting user pass in config.inc.php

PHP post_max_size overrides upload_max_filesize

post_max_size:

  • Sets max size of post data allowed. This setting also affects file upload
  • To upload large files, this value must be larger than upload_max_filesize
  • Generally speaking, memory_limit should be larger than post_max_size.
  • PHP Default: 8M

upload_max_filesize:

  • The maximum size of an uploaded file
  • PHP Default: 2M

memory_limit > post_max_size > upload_max_filesize

PHP Default: 128M > 8M > 2M

By default, post_max_size should be 4 times greater than upload_max_filesize.
In turn memory_limit should be 16 times greater than post_max_size

Auto Increment after delete in MySQL

What you're trying to do sounds dangerous, as that's not the intended use of AUTO_INCREMENT.

If you really want to find the lowest unused key value, don't use AUTO_INCREMENT at all, and manage your keys manually. However, this is NOT a recommended practice.

Take a step back and ask "why you need to recycle key values?" Do unsigned INT (or BIGINT) not provide a large enough key space?

Are you really going to have more than 18,446,744,073,709,551,615 unique records over the course of your application's lifetime?

How to rename a directory/folder on GitHub website?

There is no way to do this in the GitHub web application. I believe to only way to do this is in the command line using git mv <old name> <new name> or by using a Git client(like SourceTree).

Jquery check if element is visible in viewport

You can write a jQuery function like this to determine if an element is in the viewport.

Include this somewhere after jQuery is included:

$.fn.isInViewport = function() {
    var elementTop = $(this).offset().top;
    var elementBottom = elementTop + $(this).outerHeight();

    var viewportTop = $(window).scrollTop();
    var viewportBottom = viewportTop + $(window).height();

    return elementBottom > viewportTop && elementTop < viewportBottom;
};

Sample usage:

$(window).on('resize scroll', function() {
    if ($('#Something').isInViewport()) {
        // do something
    } else {
        // do something else
    }
});

Note that this only checks the top and bottom positions of elements, it doesn't check if an element is outside of the viewport horizontally.

Calendar.getInstance(TimeZone.getTimeZone("UTC")) is not returning UTC time

Try to use GMT instead of UTC. They refer to the same time zone, yet the name GMT is more common and might work.

String strip() for JavaScript?

Gumbo already noted this in a comment, but this bears repeating as an answer: the trim() method was added in JavaScript 1.8.1 and is supported by all modern browsers (Firefox 3.5+, IE 9, Chrome 10, Safari 5.x), although IE 8 and older do not support it. Usage is simple:

 "  foo\n\t  ".trim() => "foo"

See also:

Getting Exception(org.apache.poi.openxml4j.exception - no content type [M1.13]) when reading xlsx file using Apache POI?

Pretty sure that this exception is thrown when the Excel file is either password protected or the file itself is corrupted. If you just want to read a .xlsx file, try my code below. It's a lot more shorter and easier to read.

import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.Sheet;
//.....

static final String excelLoc = "C:/Documents and Settings/Users/Desktop/testing.xlsx";

public static void ReadExcel() {
InputStream inputStream = null;
   try {
        inputStream = new FileInputStream(new File(excelLoc));
        Workbook wb = WorkbookFactory.create(inputStream);
        int numberOfSheet = wb.getNumberOfSheets();

        for (int i = 0; i < numberOfSheet; i++) {
             Sheet sheet = wb.getSheetAt(i);
             //.... Customize your code here
             // To get sheet name, try -> sheet.getSheetName()
        }
   } catch {}
}

Why is setState in reactjs Async instead of Sync?

I know this question is old, but it has been causing a lot of confusion for many reactjs users for a long time, including me. Recently Dan Abramov (from the react team) just wrote up a great explanation as to why the nature of setState is async:

https://github.com/facebook/react/issues/11527#issuecomment-360199710

setState is meant to be asynchronous, and there are a few really good reasons for that in the linked explanation by Dan Abramov. This doesn't mean it will always be asynchronous - it mainly means that you just can't depend on it being synchronous. ReactJS takes into consideration many variables in the scenario that you're changing the state in, to decide when the state should actually be updated and your component rerendered.
A simple example to demonstrate this, is that if you call setState as a reaction to a user action, then the state will probably be updated immediately (although, again, you can't count on it), so the user won't feel any delay, but if you call setState in reaction to an ajax call response or some other event that isn't triggered by the user, then the state might be updated with a slight delay, since the user won't really feel this delay, and it will improve performance by waiting to batch multiple state updates together and rerender the DOM fewer times.

Comparing two arrays & get the values which are not common

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

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

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

Listing available com ports with Python

Probably late, but might help someone in need.

import serial.tools.list_ports


class COMPorts:

    def __init__(self, data: list):
        self.data = data

    @classmethod
    def get_com_ports(cls):
        data = []
        ports = list(serial.tools.list_ports.comports())

        for port_ in ports:
            obj = Object(data=dict({"device": port_.device, "description": port_.description.split("(")[0].strip()}))
            data.append(obj)

        return cls(data=data)

    @staticmethod
    def get_description_by_device(device: str):
        for port_ in COMPorts.get_com_ports().data:
            if port_.device == device:
                return port_.description

    @staticmethod
    def get_device_by_description(description: str):
        for port_ in COMPorts.get_com_ports().data:
            if port_.description == description:
                return port_.device


class Object:
    def __init__(self, data: dict):
        self.data = data
        self.device = data.get("device")
        self.description = data.get("description")


if __name__ == "__main__":
    for port in COMPorts.get_com_ports().data:
        print(port.device)
        print(port.description)

    print(COMPorts.get_device_by_description(description="Arduino Leonardo"))
    print(COMPorts.get_description_by_device(device="COM3"))

Best way to include CSS? Why use @import?

From a page speed standpoint, @import from a CSS file should almost never be used, as it can prevent stylesheets from being downloaded concurrently. For instance, if stylesheet A contains the text:

@import url("stylesheetB.css");

then the download of the second stylesheet may not start until the first stylesheet has been downloaded. If, on the other hand, both stylesheets are referenced in <link> elements in the main HTML page, both can be downloaded at the same time. If both stylesheets are always loaded together, it can also be helpful to simply combine them into a single file.

There are occasionally situations where @import is appropriate, but they are generally the exception, not the rule.

Try/catch does not seem to have an effect

If you want try/catch to work for all errors (not just the terminating errors) you can manually make all errors terminating by setting the ErrorActionPreference.

try {

   $ErrorActionPreference = "Stop"; #Make all errors terminating
   get-item filethatdoesntexist; # normally non-terminating
   write-host "You won't hit me";  
} catch{
   Write-Host "Caught the exception";
   Write-Host $Error[0].Exception;
}finally{
   $ErrorActionPreference = "Continue"; #Reset the error action pref to default
}

Alternatively... you can make your own trycatch function that accepts scriptblocks so that your try catch calls are not as kludge. I have mine return true/false just in case i need to check if there was an error... but it doesnt have to. Also, exception logging is optional, and can be taken care of in the catch, but i found myself always calling the logging function in the catch block, so i added it to the try catch function.

function log([System.String] $text){write-host $text;}

function logException{
    log "Logging current exception.";
    log $Error[0].Exception;
}


function mytrycatch ([System.Management.Automation.ScriptBlock] $try,
                    [System.Management.Automation.ScriptBlock] $catch,
                    [System.Management.Automation.ScriptBlock]  $finally = $({})){



# Make all errors terminating exceptions.
    $ErrorActionPreference = "Stop";

    # Set the trap
    trap [System.Exception]{
        # Log the exception.
        logException;

        # Execute the catch statement
        & $catch;

        # Execute the finally statement
        & $finally

        # There was an exception, return false
        return $false;
    }

    # Execute the scriptblock
    & $try;

    # Execute the finally statement
    & $finally

    # The following statement was hit.. so there were no errors with the scriptblock
    return $true;
}


#execute your own try catch
mytrycatch {
        gi filethatdoesnotexist; #normally non-terminating
        write-host "You won't hit me."
    } {
        Write-Host "Caught the exception";
    }

How To Make Circle Custom Progress Bar in Android

I've encountered same problem and not found any appropriate solution for my case, so I decided to go another way. I've created custom drawable class. Within this class I've created 2 Paints for progress line and background line (with some bigger stroke). First of all set startAngle and sweepAngle in constructor:

    mSweepAngle = 0;
    mStartAngle = 270;

Here is onDraw method of this class:

@Override
public void draw(Canvas canvas) {
    // draw background line
    canvas.drawArc(mRectF, 0, 360, false, mPaintBackground);
    // draw progress line
    canvas.drawArc(mRectF, mStartAngle, mSweepAngle, false, mPaintProgress);
}

So now all you need to do is set this drawable as a backgorund of the view, in background thread change sweepAngle:

mSweepAngle += 360 / totalTimerTime // this is mStep

and directly call InvalidateSelf() with some interval (e.g every 1 second or more often if you want smooth progress changes) on the view that have this drawable as a background. Thats it!

P.S. I know, I know...of course you want some more code. So here it is all flow:

  1. Create XML view :

     <View
     android:id="@+id/timer"
     android:layout_width="match_parent"
     android:layout_height="match_parent"/>
    
  2. Create and configure Custom Drawable class (as I described above). Don't forget to setup Paints for lines. Here paint for progress line:

    mPaintProgress = new Paint();
    mPaintProgress.setAntiAlias(true);
    mPaintProgress.setStyle(Paint.Style.STROKE);
    mPaintProgress.setStrokeWidth(widthProgress);
    mPaintProgress.setStrokeCap(Paint.Cap.ROUND);
    mPaintProgress.setColor(colorThatYouWant);
    

Same for backgroung paint (set width little more if you want)

  1. In drawable class create method for updating (Step calculation described above)

    public void update() {
        mSweepAngle += mStep;
        invalidateSelf();
    }
    
  2. Set this drawable class to YourTimerView (I did it in runtime) - view with @+id/timer from xml above:

    OurSuperDrawableClass superDrawable = new OurSuperDrawableClass(); YourTimerView.setBackgroundDrawable(superDrawable);

  3. Create background thread with runnable and update view:

    YourTimerView.post(new Runnable() {
        @Override
        public void run() {
            // update progress view
            superDrawable.update();
        }
    });
    

Thats it ! Enjoy your cool progress bar. Here screenshot of result if you're too bored of this amount of text.enter image description here

Use jQuery to hide a DIV when the user clicks outside of it

You'd better go with something like this:

var mouse_is_inside = false;

$(document).ready(function()
{
    $('.form_content').hover(function(){ 
        mouse_is_inside=true; 
    }, function(){ 
        mouse_is_inside=false; 
    });

    $("body").mouseup(function(){ 
        if(! mouse_is_inside) $('.form_wrapper').hide();
    });
});

How to Convert Datetime to Date in dd/MM/yyyy format

Give a different alias

SELECT  Convert(varchar,A.InsertDate,103) as converted_Tran_Date from table as A
order by A.InsertDate 

Labeling file upload button

I could achieve a button using jQueryMobile with following code:

<label for="ppt" data-role="button" data-inline="true" data-mini="true" data-corners="false">Upload</label>
<input id="ppt" type="file" name="ppt" multiple data-role="button" data-inline="true" data-mini="true" data-corners="false" style="opacity: 0;"/>

Above code creates a "Upload" button (custom text). On click of upload button, file browse is launched. Tested with Chrome 25 & IE9.

git still shows files as modified after adding to .gitignore

if you have .idea/* already added in your .gitignore and if git rm -r --cached .idea/ command does not work (note: shows error-> fatal: pathspec '.idea/' did not match any files) try this

remove .idea file from your app run this command

rm -rf .idea

run git status now and check while running the app .idea folder will be created again but it will not be tracked

Detect whether a Python string is a number or a letter

For a string of length 1 you can simply perform isdigit() or isalpha()

If your string length is greater than 1, you can make a function something like..

def isinteger(a):
    try:
        int(a)
        return True
    except ValueError:
        return False

How to convert a string with Unicode encoding to a string of letters

StringEscapeUtils from org.apache.commons.lang3 library is deprecated as of 3.6.

So you can use their new commons-text library instead:

compile 'org.apache.commons:commons-text:1.9'

OR

<dependency>
   <groupId>org.apache.commons</groupId>
   <artifactId>commons-text</artifactId>
   <version>1.9</version>
</dependency>

Example code:

org.apache.commons.text.StringEscapeUtils.unescapeJava(escapedString);

How do I make a C++ macro behave like a function?

As others have mentioned, you should avoid macros whenever possible. They are dangerous in the presence of side effects if the macro arguments are evaluated more than once. If you know the type of the arguments (or can use C++0x auto feature), you could use temporaries to enforce single evaluation.

Another problem: the order in which multiple evaluations happen may not be what you expect!

Consider this code:

#include <iostream>
using namespace std;

int foo( int & i ) { return i *= 10; }
int bar( int & i ) { return i *= 100; }

#define BADMACRO( X, Y ) do { \
    cout << "X=" << (X) << ", Y=" << (Y) << ", X+Y=" << ((X)+(Y)) << endl; \
    } while (0)

#define MACRO( X, Y ) do { \
    int x = X; int y = Y; \
    cout << "X=" << x << ", Y=" << y << ", X+Y=" << ( x + y ) << endl; \
    } while (0)

int main() {
    int a = 1; int b = 1;
    BADMACRO( foo(a), bar(b) );
    a = 1; b = 1;
    MACRO( foo(a), bar(b) );
    return 0;
}

And it's output as compiled and run on my machine:

X=100, Y=10000, X+Y=110
X=10, Y=100, X+Y=110

How do I print a double value without scientific notation using Java?

The following code detects if the provided number is presented in scientific notation. If so it is represented in normal presentation with a maximum of '25' digits.

 static String convertFromScientificNotation(double number) {
    // Check if in scientific notation
    if (String.valueOf(number).toLowerCase().contains("e")) {
        System.out.println("The scientific notation number'"
                + number
                + "' detected, it will be converted to normal representation with 25 maximum fraction digits.");
        NumberFormat formatter = new DecimalFormat();
        formatter.setMaximumFractionDigits(25);
        return formatter.format(number);
    } else
        return String.valueOf(number);
}

MIT vs GPL license

It seems to me that the chief difference between the MIT license and GPL is that the MIT doesn't require modifications be open sourced whereas the GPL does.

True - in general. You don't have to open-source your changes if you're using GPL. You could modify it and use it for your own purpose as long as you're not distributing it. BUT... if you DO distribute it, then your entire project that is using the GPL code also becomes GPL automatically. Which means, it must be open-sourced, and the recipient gets all the same rights as you - meaning, they can turn around and distribute it, modify it, sell it, etc. And that would include your proprietary code which would then no longer be proprietary - it becomes open source.

The difference with MIT is that even if you actually distribute your proprietary code that is using the MIT licensed code, you do not have to make the code open source. You can distribute it as a closed app where the code is encrypted or is a binary. Including the MIT-licensed code can be encrypted, as long as it carries the MIT license notice.

is the GPL is more restrictive than the MIT license?

Yes, very much so.

Cannot Resolve Collation Conflict

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

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

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

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

Update Collation of all fields in database on the fly

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

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

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

or using default database collation:

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

What is the $? (dollar question mark) variable in shell scripting?

$? is the result (exit code) of the last executed command.

Detect touch press vs long press vs movement?

From the Android Docs -

onLongClick()

From View.OnLongClickListener. This is called when the user either touches and holds the item (when in touch mode), or focuses upon the item with the navigation-keys or trackball and presses and holds the suitable "enter" key or presses and holds down on the trackball (for one second).

onTouch()

From View.OnTouchListener. This is called when the user performs an action qualified as a touch event, including a press, a release, or any movement gesture on the screen (within the bounds of the item).

As for the "moving happens even when I touch" I would set a delta and make sure the View has been moved by at least the delta before kicking in the movement code. If it hasn't been, kick off the touch code.

Difference between drop table and truncate table?

None of these answer point out an important difference about these two operations. Drop table is an operation that can be rolled back. However, truncate cannot be rolled back ['TRUNCATE TABLE' can be rolled back as well]. In this way dropping a very large table can be very expensive if there are many rows, because they all have to be recorded in a temporary space in case you decide to roll it back.

Usually, if I want to get rid of a large table, I will truncate it, then drop it. This way the data will be nixed without record, and the table can be dropped, and that drop will be very inexpensive because no data needs to be recorded.

It is important to point out though that truncate just deletes data, leaving the table, while drop will, in fact, delete the data and the table itself. (assuming foreign keys don't preclude such an action)

Just what is an IntPtr exactly?

An IntPtr is a value type that is primarily used to hold memory addresses or handles. A pointer is a memory address. A pointer can be typed (e.g. int*) or untyped (e.g. void*). A Windows handle is a value that is usually the same size (or smaller) than a memory address and represents a system resource (like a file or window).

React js onClick can't pass value to method

I have below 3 suggestion to this on JSX onClick Events -

  1. Actually, we don't need to use .bind() or Arrow function in our code. You can simple use in your code.

  2. You can also move onClick event from th(or ul) to tr(or li) to improve the performance. Basically you will have n number of "Event Listeners" for your n li element.

    So finally code will look like this:
    <ul onClick={this.onItemClick}>
        {this.props.items.map(item =>
               <li key={item.id} data-itemid={item.id}>
                   ...
               </li>
          )}
    </ul>
    

    // And you can access item.id in onItemClick method as shown below:

    onItemClick = (event) => {
       console.log(e.target.getAttribute("item.id"));
    }
    
  3. I agree with the approach mention above for creating separate React Component for ListItem and List. This make code looks good however if you have 1000 of li then 1000 Event Listeners will be created. Please make sure you should not have much event listener.

    import React from "react";
    import ListItem from "./ListItem";
    export default class List extends React.Component {
    
        /**
        * This List react component is generic component which take props as list of items and also provide onlick
        * callback name handleItemClick
        * @param {String} item - item object passed to caller
        */
        handleItemClick = (item) => {
            if (this.props.onItemClick) {
                this.props.onItemClick(item);
            }
        }
    
        /**
        * render method will take list of items as a props and include ListItem component
        * @returns {string} - return the list of items
        */
        render() {
            return (
                <div>
                  {this.props.items.map(item =>
                      <ListItem key={item.id} item={item} onItemClick={this.handleItemClick}/>
                  )}
                </div>
            );
        }
    
    }
    
    
    import React from "react";
    
    export default class ListItem extends React.Component {
        /**
        * This List react component is generic component which take props as item and also provide onlick
        * callback name handleItemClick
        * @param {String} item - item object passed to caller
        */
        handleItemClick = () => {
            if (this.props.item && this.props.onItemClick) {
                this.props.onItemClick(this.props.item);
            }
        }
        /**
        * render method will take item as a props and print in li
        * @returns {string} - return the list of items
        */
        render() {
            return (
                <li key={this.props.item.id} onClick={this.handleItemClick}>{this.props.item.text}</li>
            );
        }
    }
    

Aliases in Windows command prompt

Since you already have notepad++.exe in your path. Create a shortcut in that folder named np and point it to notepad++.exe.

How to get cookie's expire time

To get cookies expire time, use this simple method.

<?php

//#############PART 1#############
//expiration time (a*b*c*d) <- change D corresponding to number of days for cookie expiration
$time = time()+(60*60*24*365);
$timeMemo = (string)$time;

//sets cookie with expiration time defined above
setcookie("testCookie", "" . $timeMemo . "", $time);

//#############PART 2#############
//this function will convert seconds to days.
function secToDays($sec){

    return ($sec / 60 / 60 / 24);

}
//checks if cookie is set and prints out expiration time in days
if(isset($_COOKIE['testCookie'])){

    echo "Cookie is set<br />";
    if(round(secToDays((intval($_COOKIE['testCookie']) - time())),1) < 1){
        echo "Cookie will expire today.";
    }else{
        echo "Cookie will expire in " . round(secToDays((intval($_COOKIE['testCookie']) - time())),1) . " day(s)";
    }

}else{
    echo "not set...";
}

?>

You need to keep Part 1 and Part 2 in different files, otherwise you will get the same expire date everytime.

Where is array's length property defined?

Arrays are special objects in java, they have a simple attribute named length which is final.

There is no "class definition" of an array (you can't find it in any .class file), they're a part of the language itself.

10.7. Array Members

The members of an array type are all of the following:

  • The public final field length, which contains the number of components of the array. length may be positive or zero.
  • The public method clone, which overrides the method of the same name in class Object and throws no checked exceptions. The return type of the clone method of an array type T[] is T[].

    A clone of a multidimensional array is shallow, which is to say that it creates only a single new array. Subarrays are shared.

  • All the members inherited from class Object; the only method of Object that is not inherited is its clone method.

Resources:

Reading large text files with streams in C#

For binary files, the fastest way of reading them I have found is this.

 MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file);
 MemoryMappedViewStream mms = mmf.CreateViewStream();
 using (BinaryReader b = new BinaryReader(mms))
 {
 }

In my tests it's hundreds of times faster.

"could not find stored procedure"

Walk of shame:

The connection string was pointing at the live database. The error message was completely accurate - the stored procedure was only present in the dev DB. Thanks to all who provided excellent answers, and my apologies for wasting your time.

Best HTTP Authorization header type for JWT

Short answer

The Bearer authentication scheme is what you are looking for.

Long answer

Is it related to bears?

Errr... No :)

According to the Oxford Dictionaries, here's the definition of bearer:

bearer /'b??r?/
noun

  1. A person or thing that carries or holds something.

  2. A person who presents a cheque or other order to pay money.

The first definition includes the following synonyms: messenger, agent, conveyor, emissary, carrier, provider.

And here's the definition of bearer token according to the RFC 6750:

1.2. Terminology

Bearer Token

A security token with the property that any party in possession of the token (a "bearer") can use the token in any way that any other party in possession of it can. Using a bearer token does not require a bearer to prove possession of cryptographic key material (proof-of-possession).

The Bearer authentication scheme is registered in IANA and originally defined in the RFC 6750 for the OAuth 2.0 authorization framework, but nothing stops you from using the Bearer scheme for access tokens in applications that don't use OAuth 2.0.

Stick to the standards as much as you can and don't create your own authentication schemes.


An access token must be sent in the Authorization request header using the Bearer authentication scheme:

2.1. Authorization Request Header Field

When sending the access token in the Authorization request header field defined by HTTP/1.1, the client uses the Bearer authentication scheme to transmit the access token.

For example:

GET /resource HTTP/1.1
Host: server.example.com
Authorization: Bearer mF_9.B5f-4.1JqM

[...]

Clients SHOULD make authenticated requests with a bearer token using the Authorization request header field with the Bearer HTTP authorization scheme. [...]

In case of invalid or missing token, the Bearer scheme should be included in the WWW-Authenticate response header:

3. The WWW-Authenticate Response Header Field

If the protected resource request does not include authentication credentials or does not contain an access token that enables access to the protected resource, the resource server MUST include the HTTP WWW-Authenticate response header field [...].

All challenges defined by this specification MUST use the auth-scheme value Bearer. This scheme MUST be followed by one or more auth-param values. [...].

For example, in response to a protected resource request without authentication:

HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer realm="example"

And in response to a protected resource request with an authentication attempt using an expired access token:

HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer realm="example",
                         error="invalid_token",
                         error_description="The access token expired"

How to see docker image contents

docker save nginx > nginx.tar
tar -xvf nginx.tar

Following files are present:

  • manifest.json – Describes filesystem layers and name of json file that has the Container properties.
  • .json – Container properties
  • – Each “layerid” directory contains json file describing layer property and filesystem associated with that layer. Docker stores Container images as layers to optimize storage space by reusing layers across images.

https://sreeninet.wordpress.com/2016/06/11/looking-inside-container-images/

OR

you can use dive to view the image content interactively with TUI

enter image description here

https://github.com/wagoodman/dive

How do I access the $scope variable in browser's console using AngularJS?

This is a way of getting at scope without Batarang, you can do:

var scope = angular.element('#selectorId').scope();

Or if you want to find your scope by controller name, do this:

var scope = angular.element('[ng-controller=myController]').scope();

After you make changes to your model, you'll need to apply the changes to the DOM by calling:

scope.$apply();

How to get named excel sheets while exporting from SSRS

To export to different sheets and use custom names, as of SQL Server 2008 R2 this can be done using a combination of grouping, page breaks and the PageName property of the group.

Alternatively, if it's just the single sheet that you'd like to give a specific name, try the InitialPageName property on the report.

For a more detailed explanation, have a look here: http://blog.hoegaerden.be/2011/03/23/where-the-sheets-have-a-name-ssrs-excel-export/

Calculating text width

Sometimes you also need to measure additionally height and not only text, but also HTML width. I took @philfreo answer and made it more flexbile and useful:

function htmlDimensions(html, font) {
  if (!htmlDimensions.dummyEl) {
    htmlDimensions.dummyEl = $('<div>').hide().appendTo(document.body);
  }
  htmlDimensions.dummyEl.html(html).css('font', font);
  return {
    height: htmlDimensions.dummyEl.height(),
    width: htmlDimensions.dummyEl.width()
  };
}

Replace \n with actual new line in Sublime Text

Fool proof method (no RegEx and Ctrl+Enter didn't work for me as it was just jumping to next Find):

First, select an occurrence of \n and hit Ctrl+H (brings up the Replace... dialogue, also accessible through Find -> Replace... menu). This populates the Find what field.

Go to the end of any line of your file (press End if your keyboard has it) and select the end of line by holding down Shift and pressing ? (right arrow) EXACTLY once. Then copy-paste this into the Replace with field.

(the animation is for finding true new lines; works the same for replacing them)

enter image description here

Why is document.body null in my javascript?

Or add this part

<script type="text/javascript">

    var mySpan = document.createElement("span");
    mySpan.innerHTML = "This is my span!";

    mySpan.style.color = "red";
    document.body.appendChild(mySpan);

    alert("Why does the span change after this alert? Not before?");

</script>

after the HTML, like:

    <html>
    <head>...</head>
    <body>...</body>
   <script type="text/javascript">
        var mySpan = document.createElement("span");
        mySpan.innerHTML = "This is my span!";

        mySpan.style.color = "red";
        document.body.appendChild(mySpan);

        alert("Why does the span change after this alert? Not before?");

    </script>

    </html>

How to print all key and values from HashMap in Android?

String text="";

    for (Iterator i = keys.iterator(); i.hasNext() 
       {
           String key = (String) i.next();
           String value = (String) map.get(key);
           text+=key + " = " + value;
       }

        textview.setText(text);

How to scale images to screen size in Pygame

You can scale the image with pygame.transform.scale:

import pygame
picture = pygame.image.load(filename)
picture = pygame.transform.scale(picture, (1280, 720))

You can then get the bounding rectangle of picture with

rect = picture.get_rect()

and move the picture with

rect = rect.move((x, y))
screen.blit(picture, rect)

where screen was set with something like

screen = pygame.display.set_mode((1600, 900))

To allow your widgets to adjust to various screen sizes, you could make the display resizable:

import os
import pygame
from pygame.locals import *

pygame.init()
screen = pygame.display.set_mode((500, 500), HWSURFACE | DOUBLEBUF | RESIZABLE)
pic = pygame.image.load("image.png")
screen.blit(pygame.transform.scale(pic, (500, 500)), (0, 0))
pygame.display.flip()
while True:
    pygame.event.pump()
    event = pygame.event.wait()
    if event.type == QUIT:
        pygame.display.quit()
    elif event.type == VIDEORESIZE:
        screen = pygame.display.set_mode(
            event.dict['size'], HWSURFACE | DOUBLEBUF | RESIZABLE)
        screen.blit(pygame.transform.scale(pic, event.dict['size']), (0, 0))
        pygame.display.flip()

vuejs update parent data from child component

In Parent Conponent -->

data : function(){
            return {
                siteEntered : false, 
            };
        },

In Child Component -->

this.$parent.$data.siteEntered = true;

Android change SDK version in Eclipse? Unable to resolve target android-x

This Problem is because of Path so you need to build the path using following Steps

Goto project ----->Right Click on Project Name ---->properties ---->click on Than Java Build Path option than ---> click Android 4.2.2---->Ok

How to set an HTTP proxy in Python 2.7?

You can try downloading the Windows binaries for pip from here: http://www.lfd.uci.edu/~gohlke/pythonlibs/#pip.

For using pip to download other modules, see @Ben Burn's answer.

The specified child already has a parent. You must call removeView() on the child's parent first

in ActivitySaludo, this line,

    setContentView(txtCambiado);

you must set the content view for the activity only once.

Deserialize a json string to an object in python

While Alex's answer points us to a good technique, the implementation that he gave runs into a problem when we have nested objects.

class more_info
    string status

class payload
    string action
    string method
    string data
    class more_info

with the below code:

def as_more_info(dct):
    return MoreInfo(dct['status'])

def as_payload(dct):
    return Payload(dct['action'], dct['method'], dct['data'], as_more_info(dct['more_info']))

payload = json.loads(message, object_hook = as_payload)

payload.more_info will also be treated as an instance of payload which will lead to parsing errors.

From the official docs:

object_hook is an optional function that will be called with the result of any object literal decoded (a dict). The return value of object_hook will be used instead of the dict.

Hence, I would prefer to propose the following solution instead:

class MoreInfo(object):
    def __init__(self, status):
        self.status = status

    @staticmethod
    def fromJson(mapping):
        if mapping is None:
            return None

        return MoreInfo(
            mapping.get('status')
        )

class Payload(object):
    def __init__(self, action, method, data, more_info):
        self.action = action
        self.method = method
        self.data = data
        self.more_info = more_info

    @staticmethod
    def fromJson(mapping):
        if mapping is None:
            return None

        return Payload(
            mapping.get('action'),
            mapping.get('method'),
            mapping.get('data'),
            MoreInfo.fromJson(mapping.get('more_info'))
        )

import json
def toJson(obj, **kwargs):
    return json.dumps(obj, default=lambda j: j.__dict__, **kwargs)

def fromJson(msg, cls, **kwargs):
    return cls.fromJson(json.loads(msg, **kwargs))

info = MoreInfo('ok')
payload = Payload('print', 'onData', 'better_solution', info)
pl_json = toJson(payload)
l1 = fromJson(pl_json, Payload)

How to connect HTML Divs with Lines?

Check my fiddle from this thread: Draw a line connecting two clicked div columns

The layout is different, but basically the idea is to create invisible divs between the boxes and add corresponding borders with jQuery (the answer is only HTML and CSS)

What is the correct way to declare a boolean variable in Java?

In your example, You don't need to. As a standard programming practice, all variables being referred to inside some code block, say for example try{} catch(){}, and being referred to outside the block as well, you need to declare the variables outside the try block first e.g.

This is helpful when your equals method call throws some exception e.g. NullPointerException;

     boolean isMatch = false;

     try{
         isMatch = email1.equals (email2);
      }catch(NullPointerException npe){
         .....
      }
      System.out.print("Match=="+isMatch);
      if(isMatch){
        ......
      }

How can I include null values in a MIN or MAX?

In my expression, count(enddate) counts how many rows where the enddate column is not null. The count(*) expression counts total rows. By comparing, you can easily tell if any value in the enddate column contains null. If they are identical, then max(enddate) is the result. Otherwise the case will default to returning null which is also the answer. This is a very popular way to do this exact check.

SELECT recordid, 
MIN(startdate), 
case when count(enddate) = count(*) then max(enddate) end
FROM tmp 
GROUP BY recordid

Does MySQL foreign_key_checks affect the entire database?

It is session-based, when set the way you did in your question.

https://dev.mysql.com/doc/refman/5.7/en/server-system-variables.html

According to this, FOREIGN_KEY_CHECKS is "Both" for scope. This means it can be set for session:

SET FOREIGN_KEY_CHECKS=0;

or globally:

SET GLOBAL FOREIGN_KEY_CHECKS=0;

How to get current user, and how to use User class in MVC5?

This is how I got an AspNetUser Id and displayed it on my home page

I placed the following code in my HomeController Index() method

ViewBag.userId = User.Identity.GetUserId();

In the view page just call

ViewBag.userId 

Run the project and you will be able to see your userId

How to monitor Java memory usage?

There are tools that let you monitor the VM's memory usage. The VM can expose memory statistics using JMX. You can also print GC statistics to see how the memory is performing over time.

Invoking System.gc() can harm the GC's performance because objects will be prematurely moved from the new to old generations, and weak references will be cleared prematurely. This can result in decreased memory efficiency, longer GC times, and decreased cache hits (for caches that use weak refs). I agree with your consultant: System.gc() is bad. I'd go as far as to disable it using the command line switch.

Laravel 5.1 API Enable Cors

Here is my CORS middleware:

<?php namespace App\Http\Middleware;

use Closure;

class CORS {

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {

        header("Access-Control-Allow-Origin: *");

        // ALLOW OPTIONS METHOD
        $headers = [
            'Access-Control-Allow-Methods'=> 'POST, GET, OPTIONS, PUT, DELETE',
            'Access-Control-Allow-Headers'=> 'Content-Type, X-Auth-Token, Origin'
        ];
        if($request->getMethod() == "OPTIONS") {
            // The client-side application can set only headers allowed in Access-Control-Allow-Headers
            return Response::make('OK', 200, $headers);
        }

        $response = $next($request);
        foreach($headers as $key => $value)
            $response->header($key, $value);
        return $response;
    }

}

To use CORS middleware you have to register it first in your app\Http\Kernel.php file like this:

protected $routeMiddleware = [
        //other middlewares
        'cors' => 'App\Http\Middleware\CORS',
    ];

Then you can use it in your routes

Route::get('example', array('middleware' => 'cors', 'uses' => 'ExampleController@dummy'));

Unable to open debugger port in IntelliJ IDEA

Probably you get the same error message if the standalone.xml in your standalone/configuration folder cannot be found. At least I have the same error when using a WildFly 14.0.1:

Error running WildFly 14.01.1: Unable to open debugger port (127.0.0.1:1233): java.net.SocketException "socket closed"

MySQL select 10 random rows from 600K rows fast

If you have just one Read-Request

Combine the answer of @redsio with a temp-table (600K is not that much):

DROP TEMPORARY TABLE IF EXISTS tmp_randorder;
CREATE TABLE tmp_randorder (id int(11) not null auto_increment primary key, data_id int(11));
INSERT INTO tmp_randorder (data_id) select id from datatable;

And then take a version of @redsios Answer:

SELECT dt.*
FROM
       (SELECT (RAND() *
                     (SELECT MAX(id)
                        FROM tmp_randorder)) AS id)
        AS rnd
 INNER JOIN tmp_randorder rndo on rndo.id between rnd.id - 10 and rnd.id + 10
 INNER JOIN datatable AS dt on dt.id = rndo.data_id
 ORDER BY abs(rndo.id - rnd.id)
 LIMIT 1;

If the table is big, you can sieve on the first part:

INSERT INTO tmp_randorder (data_id) select id from datatable where rand() < 0.01;

If you have many read-requests

  1. Version: You could keep the table tmp_randorder persistent, call it datatable_idlist. Recreate that table in certain intervals (day, hour), since it also will get holes. If your table gets really big, you could also refill holes

    select l.data_id as whole from datatable_idlist l left join datatable dt on dt.id = l.data_id where dt.id is null;

  2. Version: Give your Dataset a random_sortorder column either directly in datatable or in a persistent extra table datatable_sortorder. Index that column. Generate a Random-Value in your Application (I'll call it $rand).

    select l.*
    from datatable l 
    order by abs(random_sortorder - $rand) desc 
    limit 1;
    

This solution discriminates the 'edge rows' with the highest and the lowest random_sortorder, so rearrange them in intervals (once a day).

ImageView - have height match width?

Here's how I solved that problem:

int pHeight =  picture.getHeight();
int pWidth = picture.getWidth();
int vWidth = preview.getWidth();
preview.getLayoutParams().height = (int)(vWidth*((double)pHeight/pWidth));

preview - imageView with width setted to "match_parent" and scaleType to "cropCenter"

picture - Bitmap object to set in imageView src.

That's works pretty well for me.

html5 input for money/currency

More easy and beautiful if you has vue.js v-money-spinner :)

enter image description here

File to byte[] in Java

ReadFully Reads b.length bytes from this file into the byte array, starting at the current file pointer. This method reads repeatedly from the file until the requested number of bytes are read. This method blocks until the requested number of bytes are read, the end of the stream is detected, or an exception is thrown.

RandomAccessFile f = new RandomAccessFile(fileName, "r");
byte[] b = new byte[(int)f.length()];
f.readFully(b);

RegEx match open tags except XHTML self-contained tags

It seems to me you're trying to match tags without a "/" at the end. Try this:

<([a-zA-Z][a-zA-Z0-9]*)[^>]*(?<!/)>

Checking from shell script if a directory contains files

I dislike the ls - A solutions posted. Most likely you wish to test if the directory is empty because you don't wish to delete it. The following does that. If however you just wish to log an empty file, surely deleting and recreating it is quicker then listing possibly infinite files?

This should work...

if !  rmdir ${target}
then
    echo "not empty"
else
    echo "empty"
    mkdir ${target}
fi

Biggest differences of Thrift vs Protocol Buffers?

They both offer many of the same features; however, there are some differences:

  • Thrift supports 'exceptions'
  • Protocol Buffers have much better documentation/examples
  • Thrift has a builtin Set type
  • Protocol Buffers allow "extensions" - you can extend an external proto to add extra fields, while still allowing external code to operate on the values. There is no way to do this in Thrift
  • I find Protocol Buffers much easier to read

Basically, they are fairly equivalent (with Protocol Buffers slightly more efficient from what I have read).

add onclick function to a submit button

if you need to do something before submitting data, you could use form's onsubmit.

<form method=post onsubmit="return doSomething()">
  <input type=text name=text1>
  <input type=submit>
</form>

php implode (101) with quotes

If you want to use loops you can also do:

$array = array('lastname', 'email', 'phone');
foreach($array as &$value){
   $value = "'$value'";
}
$comma_separated = implode(",", $array);

Demo: http://codepad.org/O2kB4fRo

Execute script after specific delay using JavaScript

I had some ajax commands I wanted to run with a delay in between. Here is a simple example of one way to do that. I am prepared to be ripped to shreds though for my unconventional approach. :)

//  Show current seconds and milliseconds
//  (I know there are other ways, I was aiming for minimal code
//  and fixed width.)
function secs()
{
    var s = Date.now() + ""; s = s.substr(s.length - 5);
  return s.substr(0, 2) + "." + s.substr(2);
}

//  Log we're loading
console.log("Loading: " + secs());

//  Create a list of commands to execute
var cmds = 
[
    function() { console.log("A: " + secs()); },
    function() { console.log("B: " + secs()); },
    function() { console.log("C: " + secs()); },
    function() { console.log("D: " + secs()); },
    function() { console.log("E: " + secs()); },
  function() { console.log("done: " + secs()); }
];

//  Run each command with a second delay in between
var ms = 1000;
cmds.forEach(function(cmd, i)
{
    setTimeout(cmd, ms * i);
});

// Log we've loaded (probably logged before first command)
console.log("Loaded: " + secs());

You can copy the code block and paste it into a console window and see something like:

Loading: 03.077
Loaded: 03.078
A: 03.079
B: 04.075
C: 05.075
D: 06.075
E: 07.076
done: 08.076

How to change the font size on a matplotlib plot

If you want to change the fontsize for just a specific plot that has already been created, try this:

import matplotlib.pyplot as plt

ax = plt.subplot(111, xlabel='x', ylabel='y', title='title')
for item in ([ax.title, ax.xaxis.label, ax.yaxis.label] +
             ax.get_xticklabels() + ax.get_yticklabels()):
    item.set_fontsize(20)

Session timeout in ASP.NET

After changing the session timeout value in IIS, Kindly restart the IIS. To achieve this go to command prompt. Type IISRESET and press enter.

C# how to wait for a webpage to finish loading before continuing

Check out the WatiN project:

Inspired by Watir development of WatiN started in December 2005 to make a similar kind of Web Application Testing possible for the .Net languages. Since then WatiN has grown into an easy to use, feature rich and stable framework. WatiN is developed in C# and aims to bring you an easy way to automate your tests with Internet Explorer and FireFox using .Net...

Spark - Error "A master URL must be set in your configuration" when submitting an app

Replacing :

SparkConf sparkConf = new SparkConf().setAppName("SOME APP NAME");
WITH
SparkConf sparkConf = new SparkConf().setAppName("SOME APP NAME").setMaster("local[2]").set("spark.executor.memory","1g");

Did the magic.

Find Nth occurrence of a character in a string

Marc Cals' LINQ Extended for generic.

   using System;
   using System.Collections.Generic;
   using System.Linq;

   namespace fNns
   {
       public class indexer<T> where T : IEquatable<T>
       {
           public T t { get; set; }
           public int index { get; set; }
       }
       public static class fN
       {
           public static indexer<T> findNth<T>(IEnumerable<T> tc, T t,
               int occurrencePosition) where T : IEquatable<T>
           {
               var result = tc.Select((ti, i) => new indexer<T> { t = ti, index = i })
                      .Where(item => item.t.Equals(t))
                      .Skip(occurrencePosition - 1)
                      .FirstOrDefault();
               return result;
           }
           public static indexer<T> findNthReverse<T>(IEnumerable<T> tc, T t,
       int occurrencePosition) where T : IEquatable<T>
           {
               var result = tc.Reverse<T>().Select((ti, i) => new indexer<T> {t = ti, index = i })
                      .Where(item => item.t.Equals(t))
                      .Skip(occurrencePosition - 1)
                      .FirstOrDefault();
               return result;
           }
       }
   }

Some tests.

   using System;
   using System.Collections.Generic;
   using NUnit.Framework;
   using Newtonsoft.Json;
   namespace FindNthNamespace.Tests
   {

       public class fNTests
       {
           [TestCase("pass", "dtststx", 't', 3, Result = "{\"t\":\"t\",\"index\":5}")]
           [TestCase("pass", new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 },
        0, 2, Result="{\"t\":0,\"index\":10}")]
           public string fNMethodTest<T>(string scenario, IEnumerable<T> tc, T t, int occurrencePosition) where T : IEquatable<T>
           {
               Console.WriteLine(scenario);
               return JsonConvert.SerializeObject(fNns.fN.findNth<T>(tc, t, occurrencePosition)).ToString();
           }

           [TestCase("pass", "dtststxx", 't', 3, Result = "{\"t\":\"t\",\"index\":6}")]
           [TestCase("pass", new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 },
        0, 2, Result = "{\"t\":0,\"index\":19}")]
           public string fNMethodTestReverse<T>(string scenario, IEnumerable<T> tc, T t, int occurrencePosition) where T : IEquatable<T>
           {
               Console.WriteLine(scenario);
               return JsonConvert.SerializeObject(fNns.fN.findNthReverse<T>(tc, t, occurrencePosition)).ToString();
           }


}

}

Command Prompt Error 'C:\Program' is not recognized as an internal or external command, operable program or batch file

I encountered a similar problem using windows command line for R script, Rscript.exe, which is very sensitive to spaces in the path. The solution was to create a virtual path to the binary folder using the windows subst command.

The following fails: "C:\Program Files\R\R-3.4.0\bin\Rscript.exe"

Doing following succeeds:

subst Z: "C:\Program Files\R\R-3.4.0"
Z:\bin\Rscript.exe

The reason the above-proposed solutions didn't work, evidently, has to do with the Rscript.exe executable's own internal path resolution from its working directory (which has a space in it) rather the windows command line being confused with the space. So using ~ or " to resolve the issue at the command line is moot. The executable must be called within a path lacking spaces.

How much does it cost to develop an iPhone application?

I'm one of the developers for Twitterrific and to be honest, I can't tell you how many hours have gone into the product. I can tell you everyone who upvoted the estimate of 160 hours for development and 40 hours for design is fricken' high. (I'd use another phrase, but this is my first post on Stack Overflow, so I'm being good.)

Twitterrific has had 4 major releases beginning with the iOS 1.0 (Jailbreak.) That's a lot of code, much of which is in the bit bucket (we refactor a lot with each major release.)

One thing that would be interesting to look at is the amount of time that we had to work on the iPad version. Apple set a product release date that gave us 60 days to do the development. (That was later extended by a week.)

We started the iPad development from scratch, but a lot of our underlying code (mostly models) was re-used. The development was done by two experienced iOS developers. One of them has even written a book: http://appdevmanual.com :-)

With such a short schedule, we worked some pretty long hours. Let's be conservative and say it's 10 hours per day for 6 days a week. That 60 hours for 9 weeks gives us 540 hours. With two developers, that's pretty close to 1,100 hours. Our rate for clients is $150 per hour giving $165,000 just for new code. Remember also that we were reusing a bunch existing code: I'm going to lowball the value of that code at $35,000 giving a total development cost of $200,000.

Anyone who's done serious iPhone development can tell you there's a lot of design work involved with any project. We had two designers working on that aspect of the product. They worked their asses off dealing with completely new interaction mechanics. Don't forget they didn't have any hardware to touch, either (LOTS of printouts!) Combined they spent at least 25 hours per week on the project. So 225 hours at $150/hr is about $34,000.

There are also other costs that many developer neglect to take into account: project management, testing, equipment. Again, if we lowball that figure at $16,000 we're at $250,000. This number falls in line with Jonathan Wight's (@schwa) $50-150K estimate with the 22 day Obama app.

Take another hit, dude.

Now if you want to build backend services for your app, that number's going to go up even more. Everyone seems surprised that Instagram chewed through $500K in venture funding to build a new frontend and backend. I'm not.

Vue.js data-bind style backgroundImage not working

I tried @david answer, and it didn't fix my issue. after a lot of hassle, I made a method and return the image with style string.

HTML Code

<div v-for="slide in loadSliderImages" :key="slide.id">
    <div v-else :style="bannerBgImage(slide.banner)"></div>
</div>

Method

bannerBgImage(image){
    return 'background-image: url("' + image + '")';
},

How can I subset rows in a data frame in R based on a vector of values?

This will give you what you want:

eg2011cleaned <- eg2011[!eg2011$ID %in% bg2011missingFromBeg, ]

The error in your second attempt is because you forgot the ,

In general, for convenience, the specification object[index] subsets columns for a 2d object. If you want to subset rows and keep all columns you have to use the specification object[index_rows, index_columns], while index_cols can be left blank, which will use all columns by default.

However, you still need to include the , to indicate that you want to get a subset of rows instead of a subset of columns.

Taking the record with the max date

Justin Cave answer is the best, but if you want antoher option, try this:

select A,col_date
from (select A,col_date
    from tablename 
      order by col_date desc)
      where rownum<2

Nuget connection attempt failed "Unable to load the service index for source"

I'm using VSO/Azure DevOps.

You can also visit the feed url directly in your browser. You may end up with a response that contains a message like this, which may make your diagnosis a lot quicker:

The user does not have a license for the extension ms.feed.

Set android shape color programmatically

Try this:

 public void setGradientColors(int bottomColor, int topColor) {
 GradientDrawable gradient = new GradientDrawable(Orientation.BOTTOM_TOP, new int[]  
 {bottomColor, topColor});
 gradient.setShape(GradientDrawable.RECTANGLE);
 gradient.setCornerRadius(10.f);
 this.setBackgroundDrawable(gradient);
 }

for more detail check this link this

hope help.

Download a file with Android, and showing the progress in a ProgressDialog

We can use the coroutine and work manager for downloading files in kotlin.

Add a dependency in build.gradle

    implementation "androidx.work:work-runtime-ktx:2.3.0-beta01"
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.1"

WorkManager class

    import android.content.Context
    import android.os.Environment
    import androidx.work.CoroutineWorker
    import androidx.work.WorkerParameters
    import androidx.work.workDataOf
    import com.sa.chat.utils.Const.BASE_URL_IMAGE
    import com.sa.chat.utils.Constants
    import kotlinx.coroutines.delay
    import java.io.BufferedInputStream
    import java.io.File
    import java.io.FileOutputStream
    import java.net.URL

    class DownloadMediaWorkManager(appContext: Context, workerParams: WorkerParameters)
        : CoroutineWorker(appContext, workerParams) {

        companion object {
            const val WORK_TYPE = "WORK_TYPE"
            const val WORK_IN_PROGRESS = "WORK_IN_PROGRESS"
            const val WORK_PROGRESS_VALUE = "WORK_PROGRESS_VALUE"
        }

        override suspend fun doWork(): Result {

            val imageUrl = inputData.getString(Constants.WORK_DATA_MEDIA_URL)
            val imagePath = downloadMediaFromURL(imageUrl)

            return if (!imagePath.isNullOrEmpty()) {
                Result.success(workDataOf(Constants.WORK_DATA_MEDIA_URL to imagePath))
            } else {
                Result.failure()
            }
        }

        private suspend fun downloadMediaFromURL(imageUrl: String?): String? {

            val file = File(
                    getRootFile().path,
                    "IMG_${System.currentTimeMillis()}.jpeg"
            )

            val url = URL(BASE_URL_IMAGE + imageUrl)
            val connection = url.openConnection()
            connection.connect()

            val lengthOfFile = connection.contentLength
            // download the file
            val input = BufferedInputStream(url.openStream(), 8192)
            // Output stream
            val output = FileOutputStream(file)

            val data = ByteArray(1024)
            var total: Long = 0
            var last = 0

            while (true) {

                val count = input.read(data)
                if (count == -1) break
                total += count.toLong()

                val progress = (total * 100 / lengthOfFile).toInt()

                if (progress % 10 == 0) {
                    if (last != progress) {
                        setProgress(workDataOf(WORK_TYPE to WORK_IN_PROGRESS,
                                WORK_PROGRESS_VALUE to progress))
                    }
                    last = progress
                    delay(50)
                }
                output.write(data, 0, count)
            }

            output.flush()
            output.close()
            input.close()

            return file.path

        }

        private fun getRootFile(): File {

            val rootDir = File(Environment.getExternalStorageDirectory().absolutePath + "/AppName")

            if (!rootDir.exists()) {
                rootDir.mkdir()
            }

            val dir = File("$rootDir/${Constants.IMAGE_FOLDER}/")

            if (!dir.exists()) {
                dir.mkdir()
            }
            return File(dir.absolutePath)
        }
    }

Start downloading through work manager in activity class

 private fun downloadImage(imagePath: String?, id: String) {

            val data = workDataOf(WORK_DATA_MEDIA_URL to imagePath)
            val downloadImageWorkManager = OneTimeWorkRequestBuilder<DownloadMediaWorkManager>()
                    .setInputData(data)
                    .addTag(id)
                    .build()

            WorkManager.getInstance(this).enqueue(downloadImageWorkManager)

            WorkManager.getInstance(this).getWorkInfoByIdLiveData(downloadImageWorkManager.id)
                    .observe(this, Observer { workInfo ->

                        if (workInfo != null) {
                            when {
                                workInfo.state == WorkInfo.State.SUCCEEDED -> {
                                    progressBar?.visibility = View.GONE
                                    ivDownload?.visibility = View.GONE
                                }
                                workInfo.state == WorkInfo.State.FAILED || workInfo.state == WorkInfo.State.CANCELLED || workInfo.state == WorkInfo.State.BLOCKED -> {
                                    progressBar?.visibility = View.GONE
                                    ivDownload?.visibility = View.VISIBLE
                                }
                                else -> {
                                    if(workInfo.progress.getString(WORK_TYPE) == WORK_IN_PROGRESS){
                                        val progress = workInfo.progress.getInt(WORK_PROGRESS_VALUE, 0)
                                        progressBar?.visibility = View.VISIBLE
                                        progressBar?.progress = progress
                                        ivDownload?.visibility = View.GONE

                                    }
                                }
                            }
                        }
                    })

        }

Integer value in TextView

String s = Integer.toString(10);

Then setText(s)

Simple search MySQL database using php

This is a better code that will help you through.
With your database, but rather, I have used mysql not mysqli
Enjoy it.

<body>

<form action="" method="post">

  <input name="search" type="search" autofocus><input type="submit" name="button">

</form>

<table>
  <tr><td><b>First Name</td><td></td><td><b>Last Name</td></tr>

<?php

$con=mysql_connect('localhost', 'root', '');
$db=mysql_select_db('employee');


if(isset($_POST['button'])){    //trigger button click

  $search=$_POST['search'];

  $query=mysql_query("select * from employees where first_name like '%{$search}%' || last_name like '%{$search}%' ");

if (mysql_num_rows($query) > 0) {
  while ($row = mysql_fetch_array($query)) {
    echo "<tr><td>".$row['first_name']."</td><td></td><td>".$row['last_name']."</td></tr>";
  }
}else{
    echo "No employee Found<br><br>";
  }

}else{                          //while not in use of search  returns all the values
  $query=mysql_query("select * from employees");

  while ($row = mysql_fetch_array($query)) {
    echo "<tr><td>".$row['first_name']."</td><td></td><td>".$row['last_name']."</td></tr>";
  }
}

mysql_close();
?>

Get screenshot on Windows with Python?

import pyautogui

s = pyautogui.screenshot()
s.save(r'C:\\Users\\NAME\\Pictures\\s.png')

how can I enable scrollbars on the WPF Datagrid?

Put the DataGrid in a Grid, DockPanel, ContentControl or directly in the Window. A vertically-oriented StackPanel will give its children whatever vertical space they ask for - even if that means it is rendered out of view.

Breaking up long strings on multiple lines in Ruby without stripping newlines

I modified Zack's answer since I wanted spaces and interpolation but not newlines and used:

%W[
  It's a nice day "#{name}"
  for a walk!
].join(' ')

where name = 'fred' this produces It's a nice day "fred" for a walk!

WordPress is giving me 404 page not found for all pages except the homepage

For nginx users

Use the following in your conf file for your site (usually /etc/nginx/sites-available/example.com)

location / { try_files $uri $uri/ /index.php?q=$uri&$args; }

This hands off all permalink requests to index.php with a URI string and supplied arguments. Do a systemctl reload nginx to see the changes and your non-homepage links should load.

Count character occurrences in a string in C++

Try

#include <iostream>
 #include <string>
 using namespace std;


int WordOccurrenceCount( std::string const & str, std::string const & word )
{
       int count(0);
       std::string::size_type word_pos( 0 );
       while ( word_pos!=std::string::npos )
       {
               word_pos = str.find(word, word_pos );
               if ( word_pos != std::string::npos )
               {
                       ++count;

         // start next search after this word 
                       word_pos += word.length();
               }
       }

       return count;
}


int main()
{

   string sting1="theeee peeeearl is in theeee riveeeer";
   string word1="e";
   cout<<word1<<" occurs "<<WordOccurrenceCount(sting1,word1)<<" times in ["<<sting1 <<"] \n\n";

   return 0;
}

How to use SQL LIKE condition with multiple values in PostgreSQL?

Use LIKE ANY(ARRAY['AAA%', 'BBB%', 'CCC%']) as per this cool trick @maniek showed earlier today.

Sorting std::map using value

You can't sort a std::map this way, because a the entries in the map are sorted by the key. If you want to sort by value, you need to create a new std::map with swapped key and value.

map<long, double> testMap;
map<double, long> testMap2;

// Insert values from testMap to testMap2
// The values in testMap2 are sorted by the double value

Remember that the double keys need to be unique in testMap2 or use std::multimap.

Display html text in uitextview

You can also use one more way. Three20 library offers a method through which we can construct a styled textView. You can get the library here: http://github.com/facebook/three20/

The class TTStyledTextLabel has a method called textFromXHTML: I guess this would serve the purpose. But it would be possible in readonly mode. I don't think it will allow to write or edit HTML content.

There is also a question which can help you regarding this: HTML String content for UILabel and TextView

I hope its helpful.

Combining "LIKE" and "IN" for SQL Server

No, MSSQL doesn't allow such queries. You should use col LIKE '...' OR col LIKE '...' etc.

Why I can't access remote Jupyter Notebook server?

I faced a similar issue, and I solved that after doing the following:

  1. check your jupyter configuration file: this is described here in details; https://testnb.readthedocs.io/en/stable/examples/Notebook/Configuring%20the%20Notebook%20and%20Server.html

-- you will simply need from the link above to learn how to make jupyter server listens to your local machin IP -- you will need to know your local machin IP (i use "ifconfig -a" on ubuntu to find that out) - please check for centos6

after you finish setting your configuration, you can run jupyter notebook at your local IP: jupyter notebook --ip=* --no-browser

please replace * with your IP address for example: jupyter notebook --ip=192.168.x.x --no-browser

you can now access your jupyter server from any device connected to the router using this ip:port (the port is usually 8888, so for my case for instance I used "192.168.x.x:8888" to access my server from other devices)

now if you want to access this server from public IP, you will have to:

  1. find your public IP (simply type on google what is my IP)
  2. use this IP address instead of your local IP to access the server from any device not connected to the same router kindly note: if your linux server runs on Virtual machine, you will need to set your router to allow accessing your VB from public IPs, settings depends on the router type. otherwise, you should be able to access the server using the public IP and the port set for it from any device not connected to your router, or using your local IP and the port set from any device connected to the same router!

jQuery's .click - pass parameters to user function

Yes, this is an old post. Regardless, someone may find it useful. Here is another way to send parameters to event handlers.

//click handler
function add_event(event, paramA, paramB)
{
    //do something with your parameters
    alert(paramA ? 'paramA:' + paramA : '' + paramB ? '  paramB:' + paramB : '');
}

//bind handler to click event
$('.leadtoscore').click(add_event);
...
//once you've processed some data and know your parameters, trigger a click event.
//In this case, we will send 'myfirst' and 'mysecond' as parameters
$('.leadtoscore').trigger('click', {'myfirst', 'mysecond'});

//or use variables
var a = 'first',
    b = 'second';

$('.leadtoscore').trigger('click', {a, b});
$('.leadtoscore').trigger('click', {a});

How to add a footer to the UITableView?

You need to implement the UITableViewDelegate method

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section

and return the desired view (e.g. a UILabel with the text you'd like in the footer) for the appropriate section of the table.

How to get the difference between two dictionaries in Python?

You were right to look at using a set, we just need to dig in a little deeper to get your method to work.

First, the example code:

test_1 = {"foo": "bar", "FOO": "BAR"}
test_2 = {"foo": "bar", "f00": "b@r"}

We can see right now that both dictionaries contain a similar key/value pair:

{"foo": "bar", ...}

Each dictionary also contains a completely different key value pair. But how do we detect the difference? Dictionaries don't support that. Instead, you'll want to use a set.

Here is how to turn each dictionary into a set we can use:

set_1 = set(test_1.items())
set_2 = set(test_2.items())

This returns a set containing a series of tuples. Each tuple represents one key/value pair from your dictionary.

Now, to find the difference between set_1 and set_2:

print set_1 - set_2
>>> {('FOO', 'BAR')}

Want a dictionary back? Easy, just:

dict(set_1 - set_2)
>>> {'FOO': 'BAR'}

How to check string length and then select substring in Sql Server

To conditionally check the length of the string, use CASE.

SELECT  CASE WHEN LEN(comments) <= 60 
             THEN comments
             ELSE LEFT(comments, 60) + '...'
        END  As Comments
FROM    myView

How to change the color of an image on hover

Use the background-color property instead of the background property in your CSS. So your code will look like this:
.fb-icon:hover {
background: blue;
}

GDB: Listing all mapped memory regions for a crashed process

I have just seen the following:

set mem inaccessible-by-default [on|off]

here

It might allow you to search without regard if the memory is accessible.

ionic build Android | error: No installed build tools found. Please install the Android build tools

as the error says 'No installed build tools found' it means that

1 : It really really really did not found build tools

2 : To make him find build tools you need to define these paths correctly

PATH IS SAME FOR UBUNTU(.bashrc) AND MAC(.bash_profile)

export ANDROID_HOME=/Users/vijay/Software/android-sdk-macosx
export PATH=${PATH}:/Users/vijay/Software/android-sdk-macosx/tools
export PATH=${PATH}:/Users/vijay/Software/android-sdk-macosx/platform-tools

3 : IMPORTANT IMPORTANT as soon as you set environmental variables you need to reload evnironmental variables.

//For ubuntu
$source .bashrc 

//For macos
$source .bash_profile

4 : Then check in terminal

$printenv ANDROID_HOME
$printenv PATH

Note : if you did not find your changes in printenv then restart the pc and try again printenv PATH, printenv ANDROID_HOME .There is also command to reload environmental variables .

4 : then open terminal and write HALF TEXT '$and' and hit tab. On hitting tab you should see full '$android' name.this verifys all paths are correct

5 : write $android in terminal and hit enter

How can I append a query parameter to an existing URL?

Use the URI class.

Create a new URI with your existing String to "break it up" to parts, and instantiate another one to assemble the modified url:

URI u = new URI("http://[email protected]&name=John#fragment");

// Modify the query: append your new parameter
StringBuilder sb = new StringBuilder(u.getQuery() == null ? "" : u.getQuery());
if (sb.length() > 0)
    sb.append('&');
sb.append(URLEncoder.encode("paramName", "UTF-8"));
sb.append('=');
sb.append(URLEncoder.encode("paramValue", "UTF-8"));

// Build the new url with the modified query:
URI u2 = new URI(u.getScheme(), u.getAuthority(), u.getPath(),
    sb.toString(), u.getFragment());

Spring Resttemplate exception handling

Spring cleverly treats http error codes as exceptions, and assumes that your exception handling code has the context to handle the error. To get exchange to function as you would expect it, do this:

    try {
        return restTemplate.exchange(url, httpMethod, httpEntity, String.class);
    } catch(HttpStatusCodeException e) {
        return ResponseEntity.status(e.getRawStatusCode()).headers(e.getResponseHeaders())
                .body(e.getResponseBodyAsString());
    }

This will return all the expected results from the response.

How can I exit from a javascript function?

if ( condition ) {
    return;
}

The return exits the function returning undefined.

The exit statement doesn't exist in javascript.

The break statement allows you to exit a loop, not a function. For example:

var i = 0;
while ( i < 10 ) {
    i++;
    if ( i === 5 ) {
        break;
    }
}

This also works with the for and the switch loops.

Parse error: syntax error, unexpected T_ECHO in

Missing ; after var_dump($row)

How to make bootstrap 3 fluid layout without horizontal scrollbar

Summarizing the most relevant comments in one answer:

  • this is a known bug
  • there are workarounds but you might not need them (read on)
  • it happens when elements are placed directly inside the body, rather than inside a container-fluid div or another containing div. Placing them directly in the body is exactly what most people do when testing stuff locally. Once you place your code in the complete page (so within a container-fluid or another container div) you will not face this problem (no need to change anything).

How to use Python to execute a cURL command?

Just use this website. It'll convert any curl command into Python, Node.js, PHP, R, or Go.

Example:

curl -X POST -H 'Content-type: application/json' --data '{"text":"Hello, World!"}' https://hooks.slack.com/services/asdfasdfasdf

Becomes this in Python,

import requests

headers = {
    'Content-type': 'application/json',
}

data = '{"text":"Hello, World!"}'

response = requests.post('https://hooks.slack.com/services/asdfasdfasdf', headers=headers, data=data)

Can an AWS Lambda function call another

You can trigger Lambda functions directly from other Lambda functions directly in an asynchronous manner.

https://docs.aws.amazon.com/lambda/latest/dg/invocation-async.html#invocation-async-destinations

Loop timer in JavaScript

Here the Automatic loop function with html code. I hope this may be useful for someone.

<!DOCTYPE html>
<html>
<head>
<style>
div {
position: relative;
background-color: #abc;
width: 40px;
height: 40px;
float: left;
margin: 5px;
}
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<p><button id="go">Run »</button></p>
<div class="block"></div>
<script>

function test() {
$(".block").animate({left: "+=50", opacity: 1}, 500 );
   setTimeout(mycode, 2000);
};
$( "#go" ).click(function(){
test();
});
</script>
</body>
</html>

Fiddle: DEMO

Calling javascript function in iframe

If you can not use it directly and if you encounter this error: Blocked a frame with origin "http://www..com" from accessing a cross-origin frame. You can use postMessage() instead of using the function directly.

How to delete a file from SD card?

This worked for me.

String myFile = "/Name Folder/File.jpg";  

String my_Path = Environment.getExternalStorageDirectory()+myFile;  

File f = new File(my_Path);
Boolean deleted = f.delete();

Add/remove class with jquery based on vertical scroll?

Its my code

jQuery(document).ready(function(e) {
    var WindowHeight = jQuery(window).height();

    var load_element = 0;

    //position of element
    var scroll_position = jQuery('.product-bottom').offset().top;

    var screen_height = jQuery(window).height();
    var activation_offset = 0;
    var max_scroll_height = jQuery('body').height() + screen_height;

    var scroll_activation_point = scroll_position - (screen_height * activation_offset);

    jQuery(window).on('scroll', function(e) {

        var y_scroll_pos = window.pageYOffset;
        var element_in_view = y_scroll_pos > scroll_activation_point;
        var has_reached_bottom_of_page = max_scroll_height <= y_scroll_pos && !element_in_view;

        if (element_in_view || has_reached_bottom_of_page) {
            jQuery('.product-bottom').addClass("change");
        } else {
            jQuery('.product-bottom').removeClass("change");
        }

    });

});

Its working Fine

How to change the map center in Leaflet.js

Use map.panTo(); does not do anything if the point is in the current view. Use map.setView() instead.

I had a polyline and I had to center map to a new point in polyline at every second. Check the code : GOOD: https://jsfiddle.net/nstudor/xcmdwfjk/

mymap.setView(point, 11, { animation: true });        

BAD: https://jsfiddle.net/nstudor/Lgahv905/

mymap.panTo(point);
mymap.setZoom(11);

How to make Bitmap compress without change the bitmap size?

Are you sure it is smaller?

Bitmap original = BitmapFactory.decodeStream(getAssets().open("1024x768.jpg"));
ByteArrayOutputStream out = new ByteArrayOutputStream();
original.compress(Bitmap.CompressFormat.PNG, 100, out);
Bitmap decoded = BitmapFactory.decodeStream(new ByteArrayInputStream(out.toByteArray()));

Log.e("Original   dimensions", original.getWidth()+" "+original.getHeight());
Log.e("Compressed dimensions", decoded.getWidth()+" "+decoded.getHeight());

Gives

12-07 17:43:36.333: E/Original   dimensions(278): 1024 768
12-07 17:43:36.333: E/Compressed dimensions(278): 1024 768

Maybe you get your bitmap from a resource, in which case the bitmap dimension will depend on the phone screen density

Bitmap bitmap=((BitmapDrawable)getResources().getDrawable(R.drawable.img_1024x768)).getBitmap();
Log.e("Dimensions", bitmap.getWidth()+" "+bitmap.getHeight());

12-07 17:43:38.733: E/Dimensions(278): 768 576

symfony2 twig path with parameter url creation

In Twig:

{% for l in locations %}

<tr>
    <td>
        <input type="checkbox" class="filled-in" id="filled-in-box-{{ l.idLocation }}" />
        <label for="filled-in-box-{{ l.idLocation }}"></label>
    </td>
    <td>{{ l.loc }}</td>
    <td>{{ l.mun }}</td>
    <td>{{ l.pro }}</td>
    <td>{{ l.cou }}</td>
    {#<td>
        {% if l.active == 1  %}
            <span class="fa fa-check"></span>
        {% else %}
            <span class="fa fa-close"></span>
        {% endif %}
    </td>#}
    <td><a href="{{ url('admin_edit_location',{'id': l.idLocation}) }}" class="db-list-edit"><span class="fa fa-pencil-square-o"></span></a>
    </td>
</tr>{% endfor %}

The route admin_edit_location:

admin_edit_location:
  path: /edit_location/{id}
  defaults: { _controller: "AppBundle:Admin:editLocation" }
  methods: GET

And the controller

public function editLocationAction($id){
    // use $id 

    $em = $this->getDoctrine()->getManager();
    $location = $em->getRepository('BackendBundle:locations')->findOneBy(array(
    'id'    => $id
    ));
}

Add text to textarea - Jquery

That should work. Better if you pass a function to val:

$('#replyBox').val(function(i, text) {
    return text + quote;
});

This way you avoid searching the element and calling val twice.

Get an element by index in jQuery

There is another way of getting an element by index in jQuery using CSS :nth-of-type pseudo-class:

<script>
    // css selector that describes what you need:
    // ul li:nth-of-type(3)
    var selector = 'ul li:nth-of-type(' + index + ')';
    $(selector).css({'background-color':'#343434'});
</script>

There are other selectors that you may use with jQuery to match any element that you need.

How do I convert a PDF document to a preview image in PHP?

Use the php extension Imagick. To control the desired size of the raster output image, use the setResolution function

<?php    
$im = new Imagick();
$im->setResolution(300, 300);     //set the resolution of the resulting jpg
$im->readImage('file.pdf[0]');    //[0] for the first page
$im->setImageFormat('jpg');
header('Content-Type: image/jpeg');
echo $im;
?>

(Extension on Paolo Bergantino his answer and Luis Melgratti his comment. You need to set the resolution before loading the image.)

How to change UIButton image in Swift

assume that this is your connected UIButton Name like

@IBOutlet var btn_refresh: UIButton!

your can directly place your image in three modes

 // for normal state
btn_refresh.setImage(UIImage(named: "xxx.png"), forState: UIControlState.Normal)
     // for Highlighted state
      btn_refresh.setImage(UIImage(named: "yyy.png"), forState: UIControlState.Highlighted)

        // for Selected state
         btn_refresh.setImage(UIImage(named: "zzzz.png"), forState: UIControlState.Selected)

on your button action

  //MARK: button_refresh action
@IBAction func button_refresh_touchup_inside(sender: UIButton)
{
    //if you set the image on same  UIButton
    sender.setImage(UIImage(named: "newimage.png"), forState: UIControlState.Normal)

    //if you set the image on another  UIButton
       youranotherbuttonName.setImage(UIImage(named: "newimage.png"), forState: UIControlState.Normal)
}

What is "export default" in JavaScript?

As explained on this MDN page

There are two different types of export, named and default. You can have multiple named exports per module but only one default export[...]Named exports are useful to export several values. During the import, it is mandatory to use the same name of the corresponding object.But a default export can be imported with any name

For example:

let myVar; export default myVar = 123; // in file my-module.js

import myExportedVar from './my-module' //  we have the freedom to use 'import myExportedVar' instead of 'import myVar' because myVar was defined as default export

console.log(myExportedVar);        // will log 123

Using prepared statements with JDBCTemplate

I've tried a select statement now with a PreparedStatement, but it turned out that it was not faster than the Jdbc template. Maybe, as mezmo suggested, it automatically creates prepared statements.

Anyway, the reason for my sql SELECTs being so slow was another one. In the WHERE clause I always used the operator LIKE, when all I wanted to do was finding an exact match. As I've found out LIKE searches for a pattern and therefore is pretty slow.

I'm using the operator = now and it's much faster.

Upload files from Java client to a HTTP server

protected void doPost(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {

    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    if (!isMultipart) {
        return;
    }

    DiskFileItemFactory factory = new DiskFileItemFactory();

    factory.setSizeThreshold(MAX_MEMORY_SIZE);

    factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

    String uploadFolder = getServletContext().getRealPath("")
            + File.separator + DATA_DIRECTORY;//DATA_DIRECTORY is directory where you upload this file on the server

    ServletFileUpload upload = new ServletFileUpload(factory);

    upload.setSizeMax(MAX_REQUEST_SIZE);//MAX_REQUEST_SIZE is the size which size you prefer

And use <form enctype="multipart/form-data"> and use <input type="file"> in the html

ImportError: No module named 'bottle' - PyCharm

The settings are changed for PyCharm 5+.

  • Go to File > Default Settings
  • In left sidebar, click Default Project > Project Interpreter
  • At bottom of window, click + to install or - to uninstall.
  • If we click +, a new window opens where we can decrease the results by entering the package name/keyword.
  • Install the package.
  • Go to File > Invalidate caches/restart and click Invalidate and Restart to apply changes and restart PyCharm.

    Settings

    Install package

Is it possible to install Xcode 10.2 on High Sierra (10.13.6)?

Cracked it. Just @Damnum steps and then follow the path to run xcode. Bad way but running like a charm.

Double click to /Applications/Xcode102.app/Contents/MacOS/Xcode

How to strip a specific word from a string?

A bit 'lazy' way to do this is to use startswith- it is easier to understand this rather regexps. However regexps might work faster, I haven't measured.

>>> papa = "papa is a good man"
>>> app = "app is important"
>>> strip_word = 'papa'
>>> papa[len(strip_word):] if papa.startswith(strip_word) else papa
' is a good man'
>>> app[len(strip_word):] if app.startswith(strip_word) else app
'app is important'

img onclick call to JavaScript function

You should probably be using a more unobtrusive approach. Here's the benefits

  • Separation of functionality (the "behavior layer") from a Web page's structure/content and presentation
  • Best practices to avoid the problems of traditional JavaScript programming (such as browser inconsistencies and lack of scalability)
  • Progressive enhancement to support user agents that may not support advanced JavaScript functionality

Here's a jsfiddle demo

Your JavaScript

function exportToForm(a, b, c, d, e) {
  console.log(a, b, c, d, e);
}

var images = document.getElementsByTagName("img");

for (var i=0, len=images.length, img; i<len; i++) {
  img = images[i];
  img.addEventListener("click", function() {
    var a = img.getAttribute("data-a"),
        b = img.getAttribute("data-b"),
        c = img.getAttribute("data-c"),
        d = img.getAttribute("data-d"),
        e = img.getAttribute("data-e");

    exportToForm(a, b, c, d, e);
  });
}

Your images will look like this

<img data-a="1" data-b="2" data-c="3" data-d="4" data-e="5" src="image.jpg">

Function or sub to add new row and data to table

Minor variation of phillfri's answer which was already a variation of Geoff's answer: I added the ability to handle completely empty tables that contain no data for the Array Code.

Sub AddDataRow(tableName As String, NewData As Variant)
    Dim sheet As Worksheet
    Dim table As ListObject
    Dim col As Integer
    Dim lastRow As Range

    Set sheet = Range(tableName).Parent
    Set table = sheet.ListObjects.Item(tableName)

    'First check if the last row is empty; if not, add a row
    If table.ListRows.Count > 0 Then
        Set lastRow = table.ListRows(table.ListRows.Count).Range
        If Application.CountBlank(lastRow) < lastRow.Columns.Count Then
            table.ListRows.Add
        End If
    End If

    'Iterate through the last row and populate it with the entries from values()
    If table.ListRows.Count = 0 Then 'If table is totally empty, set lastRow as first entry
        table.ListRows.Add Position:=1
        Set lastRow = table.ListRows(1).Range
    Else
        Set lastRow = table.ListRows(table.ListRows.Count).Range
    End If
    For col = 1 To lastRow.Columns.Count
        If col <= UBound(NewData) + 1 Then lastRow.Cells(1, col) = NewData(col - 1)
    Next col
End Sub

Required request body content is missing: org.springframework.web.method.HandlerMethod$HandlerMethodParameter

I also had the same problem. I use "Postman" for JSON request. The code itself is not wrong. I simply set the content type to JSON (application/json) and it worked, as you can see on the image below

My Code

Why functional languages?

I have a hard time envisioning a purely functional language being the common language of the day, the reasons for which I won't get in to (because they're flame fodder). That being said, programming in a functional way can provide benefits no matter the language (if it allows such). For me, it's the ability to test my code much easier. I work with databases a lot... I tend to:

  1. write a function that takes data, manipulates it, and returns data
  2. write a dead simple wrapper that calls the database and then returns the result of passing that data through my function

Doing so allows me to write unit tests for my manipulation function, without the need to create mocks and the like.

I do think purely functional languages are very interesting... I just think it's what we can learn from them that matters to me, not what we can do with them.

Java Map equivalent in C#

Dictionary<,> is the equivalent. While it doesn't have a Get(...) method, it does have an indexed property called Item which you can access in C# directly using index notation:

class Test {
  Dictionary<int,String> entities;

  public String getEntity(int code) {
    return this.entities[code];
  }
}

If you want to use a custom key type then you should consider implementing IEquatable<> and overriding Equals(object) and GetHashCode() unless the default (reference or struct) equality is sufficient for determining equality of keys. You should also make your key type immutable to prevent weird things happening if a key is mutated after it has been inserted into a dictionary (e.g. because the mutation caused its hash code to change).

How to increase request timeout in IIS?

To Increase request time out add this to web.config

<system.web>
    <httpRuntime executionTimeout="180" />
</system.web>

and for a specific page add this

<location path="somefile.aspx">
    <system.web>
        <httpRuntime executionTimeout="180"/>
    </system.web>
</location>

The default is 90 seconds for .NET 1.x.

The default 110 seconds for .NET 2.0 and later.

How to get the start time of a long-running Linux process?

The ps command (at least the procps version used by many Linux distributions) has a number of format fields that relate to the process start time, including lstart which always gives the full date and time the process started:

# ps -p 1 -wo pid,lstart,cmd
  PID                  STARTED CMD
    1 Mon Dec 23 00:31:43 2013 /sbin/init

# ps -p 1 -p $$ -wo user,pid,%cpu,%mem,vsz,rss,tty,stat,lstart,cmd
USER       PID %CPU %MEM    VSZ   RSS TT       STAT                  STARTED CMD
root         1  0.0  0.1   2800  1152 ?        Ss   Mon Dec 23 00:31:44 2013 /sbin/init
root      5151  0.3  0.1   4732  1980 pts/2    S    Sat Mar  8 16:50:47 2014 bash

For a discussion of how the information is published in the /proc filesystem, see https://unix.stackexchange.com/questions/7870/how-to-check-how-long-a-process-has-been-running

(In my experience under Linux, the time stamp on the /proc/ directories seem to be related to a moment when the virtual directory was recently accessed rather than the start time of the processes:

# date; ls -ld /proc/1 /proc/$$ 
Sat Mar  8 17:14:21 EST 2014
dr-xr-xr-x 7 root root 0 2014-03-08 16:50 /proc/1
dr-xr-xr-x 7 root root 0 2014-03-08 16:51 /proc/5151

Note that in this case I ran a "ps -p 1" command at about 16:50, then spawned a new bash shell, then ran the "ps -p 1 -p $$" command within that shell shortly afterward....)

java get file size efficiently

If you want the file size of multiple files in a directory, use Files.walkFileTree. You can obtain the size from the BasicFileAttributes that you'll receive.

This is much faster then calling .length() on the result of File.listFiles() or using Files.size() on the result of Files.newDirectoryStream(). In my test cases it was about 100 times faster.

GCM with PHP (Google Cloud Messaging)

I know this is a late Answer, but it may be useful for those who wants to develop similar apps with current FCM format (GCM has been deprecated).
The following PHP code has been used to send topic-wise podcast. All the apps registered with the mentioned channel/topis would receive this Push Notification.

<?php

try{
$fcm_token = 'your fcm token';
$service_url = 'https://fcm.googleapis.com/fcm/send';
$channel = '/topics/'.$adminChannel;
echo $channel.'</br>';
      $curl_post_body = array('to' => $channel,
        'content_available' => true,
        'notification' => array('click_action' => 'action_open',
                            'body'=> $contentTitle,
                            'title'=>'Title '.$contentCurrentCat. ' Updates' ,
                            'message'=>'44'),
        'data'=> array('click_action' => 'action_open',
                            'body'=>'test',
                            'title'=>'test',
                            'message'=>$catTitleId));

        $headers = array(
        'Content-Type:application/json',
        'Authorization:key='.$fcm_token);

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $service_url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($curl_post_body));

    $result = curl_exec($ch);
    if ($result === FALSE) {
        die('FCM Send Error: ' . curl_error($ch));
        echo 'failure';
    }else{

    echo 'success' .$result;
    }
    curl_close($ch);
    return $result;

}
catch(Exception $e){

    echo 'Message: ' .$e->getMessage();
}
?>

Sorting by date & time in descending order?

SELECT * FROM (
               SELECT id, name, form_id, DATE(updated_at) as date
               FROM wp_frm_items
               WHERE user_id = 11 && form_id=9
               ORDER BY updated_at DESC
             ) AS TEMP
    ORDER BY DATE(updated_at) DESC, name DESC

Give it a try.

Add Items to ListView - Android

Try this one it will work

public class Third extends ListActivity {
private ArrayAdapter<String> adapter;
private List<String> liste;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_third);
     String[] values = new String[] { "Android", "iPhone", "WindowsMobile",
                "Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X",
                "Linux", "OS/2" };
     liste = new ArrayList<String>();
     Collections.addAll(liste, values);
     adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, liste);
     setListAdapter(adapter);
}
 @Override
  protected void onListItemClick(ListView l, View v, int position, long id) {
     liste.add("Nokia");
     adapter.notifyDataSetChanged();
  }
}

Jquery/Ajax call with timer

If you want to set something on a timer, you can use JavaScript's setTimeout or setInterval methods:

setTimeout ( expression, timeout );
setInterval ( expression, interval );

Where expression is a function and timeout and interval are integers in milliseconds. setTimeout runs the timer once and runs the expression once whereas setInterval will run the expression every time the interval passes.

So in your case it would work something like this:

setInterval(function() {
    //call $.ajax here
}, 5000); //5 seconds

As far as the Ajax goes, see jQuery's ajax() method. If you run an interval, there is nothing stopping you from calling the same ajax() from other places in your code.


If what you want is for an interval to run every 30 seconds until a user initiates a form submission...and then create a new interval after that, that is also possible:

setInterval() returns an integer which is the ID of the interval.

var id = setInterval(function() {
    //call $.ajax here
}, 30000); // 30 seconds

If you store that ID in a variable, you can then call clearInterval(id) which will stop the progression.

Then you can reinstantiate the setInterval() call after you've completed your ajax form submission.

What is the garbage collector in Java?

The basic principles of garbage collection are to find data objects in a program that cannot be accessed in the future, and to reclaim the resources used by those objects. https://en.wikipedia.org/wiki/Garbage_collection_%28computer_science%29

Advantages

1) Saves from bugs, which occur when a piece of memory is freed while there are still pointers to it, and one of those pointers is dereferenced. https://en.wikipedia.org/wiki/Dangling_pointer

2) Double free bugs, which occur when the program tries to free a region of memory that has already been freed, and perhaps already been allocated again.

3) Prevents from certain kinds of memory leaks, in which a program fails to free memory occupied by objects that have become unreachable, which can lead to memory exhaustion.

Disadvantages

1) Consuming additional resources, performance impacts, possible stalls in program execution, and incompatibility with manual resource management. Garbage collection consumes computing resources in deciding which memory to free, even though the programmer may have already known this information.

2) The moment when the garbage is actually collected can be unpredictable, resulting in stalls (pauses to shift/free memory) scattered throughout a session. Unpredictable stalls can be unacceptable in real-time environments, in transaction processing, or in interactive programs.


Oracle tutorial http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/gc01/index.html

Garbage collection is the process identifying which objects are in use and which are not, and deleting the unused objects.

In a programming languages like C, C++, allocating and freeing memory is a manual process.

int * array = new int[size];
processArray(array); //do some work.
delete array; //Free memory

The first step in the process is called marking. This is where the garbage collector identifies which pieces of memory are in use and which are not.

Step 2a. Normal deletion removes unreferenced objects leaving referenced objects and pointers to free space.

To improve performance, we want to delete unreferenced objects and also compact the remaining referenced objects. We want to keep referenced objects together, so it will be faster to allocate new memory.

As stated earlier, having to mark and compact all the objects in a JVM is inefficient. As more and more objects are allocated, the list of objects grows and grows leading to longer and longer garbage collection time.

Continue reading this tutorial, and you will know how GC takes this challenge.

In short, there are three regions of the heap, YoungGeneration for short life objects, OldGeneration for long period objects, and PermanentGeneration for objects that live during the application life, for example, classes, libraries.

Where are the Properties.Settings.Default stored?

it is saved in your Documents and Settings\%user%\Local Settings\Application Data......etc search for a file called user.config there

the location may change however.

How to change date format (MM/DD/YY) to (YYYY-MM-DD) in date picker

If in jquery the dateformat option is not working then we can handle this situation in html page in input field of your date:

_x000D_
_x000D_
<input type="text" data-date-format='yyyy-mm-dd'  id="selectdateadmin" class="form-control" required>
_x000D_
_x000D_
_x000D_

And in javascript below this page add your date picker code:

_x000D_
_x000D_
 $('#selectdateadmin').focusin( function()_x000D_
     {_x000D_
       $("#selectdateadmin").datepicker();_x000D_
       _x000D_
     });
_x000D_
_x000D_
_x000D_

Maven is not working in Java 8 when Javadoc tags are incomplete

The best solution would be to fix the javadoc errors. If for some reason that is not possible (ie: auto generated source code) then you can disable this check.

DocLint is a new feature in Java 8, which is summarized as:

Provide a means to detect errors in Javadoc comments early in the development cycle and in a way that is easily linked back to the source code.

This is enabled by default, and will run a whole lot of checks before generating Javadocs. You need to turn this off for Java 8 as specified in this thread. You'll have to add this to your maven configuration:

<profiles>
  <profile>
    <id>java8-doclint-disabled</id>
    <activation>
      <jdk>[1.8,)</jdk>
    </activation>
    <properties>
      <javadoc.opts>-Xdoclint:none</javadoc.opts>
    </properties>
  </profile>
</profiles>
<build>
  <plugins>
    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-javadoc-plugin</artifactId>
        <version>2.9</version>
        <executions>
            <execution>
                <id>attach-javadocs</id>
                <goals>
                    <goal>jar</goal>
                </goals>
                <configuration>
                    <additionalparam>${javadoc.opts}</additionalparam>
                </configuration>
            </execution>
        </executions>
    </plugin>
    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-site-plugin</artifactId>
        <version>3.3</version>
        <configuration>
          <reportPlugins>
            <plugin>
              <groupId>org.apache.maven.plugins</groupId>
              <artifactId>maven-javadoc-plugin</artifactId>
              <configuration>
                <additionalparam>${javadoc.opts}</additionalparam>
              </configuration>
            </plugin>
          </reportPlugins>
        </configuration>
      </plugin>
   </plugins>
</build>

For maven-javadoc-plugin 3.0.0+: Replace

<additionalparam>-Xdoclint:none</additionalparam>

with

<doclint>none</doclint>

Can you require two form fields to match with HTML5?

You can with regular expressions Input Patterns (check browser compatibility)

<input id="password" name="password" type="password" pattern="^\S{6,}$" onchange="this.setCustomValidity(this.validity.patternMismatch ? 'Must have at least 6 characters' : ''); if(this.checkValidity()) form.password_two.pattern = this.value;" placeholder="Password" required>

<input id="password_two" name="password_two" type="password" pattern="^\S{6,}$" onchange="this.setCustomValidity(this.validity.patternMismatch ? 'Please enter the same Password as above' : '');" placeholder="Verify Password" required>

In Java, remove empty elements from a list of Strings

lukastymo's answer seems the best one.

But it may be worth mentioning this approach as well for it's extensibility:

List<String> list = new ArrayList<String>(Arrays.asList("", "Hi", null, "How", "are"));

list = list.stream()
           .filter(item -> item != null && !item.isEmpty())
           .collect(Collectors.toList());

System.out.println(list);

What I mean by that is you could then add additional filters, such as:

          .filter(item -> !item.startsWith("a"))

... although of course that's not specifically relevant to the question.

How to support HTTP OPTIONS verb in ASP.NET MVC/WebAPI application

I have managed to overcome 405 and 404 errors thrown on pre-flight ajax options requests only by custom code in global.asax

protected void Application_BeginRequest()
    {            
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
        if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
        {
            //These headers are handling the "pre-flight" OPTIONS call sent by the browser
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, OPTIONS");
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
            HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
            HttpContext.Current.Response.End();
        }
    }

PS: Consider security issues when allowing everything *.

I had to disable CORS since it was returning 'Access-Control-Allow-Origin' header contains multiple values.

Also needed this in web.config:

<handlers>
  <remove name="ExtensionlessUrlHandler-Integrated-4.0"/>
  <remove name="OPTIONSVerbHandler"/>
  <remove name="TRACEVerbHandler"/>
  <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0"/>
</handlers>

And app.pool needs to be set to Integrated mode.

How to use <sec:authorize access="hasRole('ROLES)"> for checking multiple Roles?

i used hasAnyRole('ROLE_ADMIN','ROLE_USER') but i was getting bean creation below error

Error creating bean with name     'org.springframework.security.web.access.intercept.FilterSecurityInterceptor#0': Cannot create inner bean '(inner bean)' of type [org.springframework.security.web.access.expression.ExpressionBasedFilterInvocationSecurityMetadataSource] while setting bean property 'securityMetadataSource'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#2': Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [org.springframework.security.web.access.expression.ExpressionBasedFilterInvocationSecurityMetadataSource]: Constructor threw exception; nested exception is java.lang.IllegalArgumentException: Expected a single expression attribute for [/user/*]

then i tried

access="hasRole('ROLE_ADMIN') or hasRole('ROLE_USER')" and it's working fine for me.

as one of my user is admin as well as user.

for this you need to add use-expressions="true" auto-config="true" followed by http tag

<http use-expressions="true" auto-config="true" >.....</http>

Comparing the contents of two files in Sublime Text

You can actually compare files natively right in Sublime Text.

  1. Navigate to the folder containing them through Open Folder... or in a project
  2. Select the two files (ie, by holding Ctrl on Windows or ? on macOS) you want to compare in the sidebar
  3. Right click and select the Diff files... option.

How to stop and restart memcached server?

If you have an older version of memcached and need a script to wrap memcached as a service, here it is: Memcached Service Script

Difference between IISRESET and IIS Stop-Start command

Take IISReset as a suite of commands that helps you manage IIS start / stop etc.

Which means you need to specify option (/switch) what you want to do to carry any operation.

Default behavior OR default switch is /restart with iisreset so you do not need to run command twice with /start and /stop.

Hope this clarifies your question. For reference the output of iisreset /? is:

IISRESET.EXE (c) Microsoft Corp. 1998-2005

Usage:
iisreset [computername]

    /RESTART            Stop and then restart all Internet services.
    /START              Start all Internet services.
    /STOP               Stop all Internet services.
    /REBOOT             Reboot the computer.
    /REBOOTONERROR      Reboot the computer if an error occurs when starting,
                        stopping, or restarting Internet services.
    /NOFORCE            Do not forcefully terminate Internet services if
                        attempting to stop them gracefully fails.
    /TIMEOUT:val        Specify the timeout value ( in seconds ) to wait for
                        a successful stop of Internet services. On expiration
                        of this timeout the computer can be rebooted if
                        the /REBOOTONERROR parameter is specified.
                        The default value is 20s for restart, 60s for stop,
                        and 0s for reboot.
    /STATUS             Display the status of all Internet services.
    /ENABLE             Enable restarting of Internet Services
                        on the local system.
    /DISABLE            Disable restarting of Internet Services
                        on the local system.

How to implement the ReLU function in Numpy

There are a couple of ways.

>>> x = np.random.random((3, 2)) - 0.5
>>> x
array([[-0.00590765,  0.18932873],
       [-0.32396051,  0.25586596],
       [ 0.22358098,  0.02217555]])
>>> np.maximum(x, 0)
array([[ 0.        ,  0.18932873],
       [ 0.        ,  0.25586596],
       [ 0.22358098,  0.02217555]])
>>> x * (x > 0)
array([[-0.        ,  0.18932873],
       [-0.        ,  0.25586596],
       [ 0.22358098,  0.02217555]])
>>> (abs(x) + x) / 2
array([[ 0.        ,  0.18932873],
       [ 0.        ,  0.25586596],
       [ 0.22358098,  0.02217555]])

If timing the results with the following code:

import numpy as np

x = np.random.random((5000, 5000)) - 0.5
print("max method:")
%timeit -n10 np.maximum(x, 0)

print("multiplication method:")
%timeit -n10 x * (x > 0)

print("abs method:")
%timeit -n10 (abs(x) + x) / 2

We get:

max method:
10 loops, best of 3: 239 ms per loop
multiplication method:
10 loops, best of 3: 145 ms per loop
abs method:
10 loops, best of 3: 288 ms per loop

So the multiplication seems to be the fastest.

TimeStamp on file name using PowerShell

Here's some PowerShell code that should work. You can combine most of this into fewer lines, but I wanted to keep it clear and readable.

[string]$filePath = "C:\tempFile.zip";

[string]$directory = [System.IO.Path]::GetDirectoryName($filePath);
[string]$strippedFileName = [System.IO.Path]::GetFileNameWithoutExtension($filePath);
[string]$extension = [System.IO.Path]::GetExtension($filePath);
[string]$newFileName = $strippedFileName + [DateTime]::Now.ToString("yyyyMMdd-HHmmss") + $extension;
[string]$newFilePath = [System.IO.Path]::Combine($directory, $newFileName);

Move-Item -LiteralPath $filePath -Destination $newFilePath;

Immutable array in Java

The of(E... elements) method in Java9 can be used to create immutable list using just a line:

List<Integer> items = List.of(1,2,3,4,5);

The above method returns an immutable list containing an arbitrary number of elements. And adding any integer to this list would result in java.lang.UnsupportedOperationExceptionexception. This method also accepts a single array as an argument.

String[] array = ... ;
List<String[]> list = List.<String[]>of(array);

Adding a directory to PATH in Ubuntu

The file .bashrc is read when you start an interactive shell. This is the file that you should update. E.g:

export PATH=$PATH:/opt/ActiveTcl-8.5/bin

Restart the shell for the changes to take effect or source it, i.e.:

source .bashrc

Print a list of all installed node.js modules

for package in `sudo npm -g ls --depth=0 --parseable`; do
    printf "${package##*/}\n";
done

Installing mcrypt extension for PHP on OSX Mountain Lion

Brew base solution worked for me

  1. Install these packages

    $brew install brew install mcrypt php54-mcrypt

  2. Copy default php.ini.default to php.ini

    $sudo cp /private/etc/php.ini.default /private/etc/php.ini

  3. Add this line to php.ini file extension section - please verify extension path with install location in your machine

    extension="/usr/local/Cellar/php54-mcrypt/5.3.26/mcrypt.so"

  4. Restart your apache server

    $apache restart

Recursively looping through an object to build a property list

You can use a recursive Object.keys to achieve that.

var keys = []

const findKeys = (object, prevKey = '') => {
  Object.keys(object).forEach((key) => {
    const nestedKey = prevKey === '' ? key : `${prevKey}.${key}`

    if (typeof object[key] !== 'object') return keys.push(nestedKey)

    findKeys(object[key], nestedKey)
  })
}

findKeys(object)

console.log(keys)

Which results in this array

[
  "aProperty.aSetting1",
  "aProperty.aSetting2",
  "aProperty.aSetting3",
  "aProperty.aSetting4",
  "aProperty.aSetting5",
  "bProperty.bSetting1.bPropertySubSetting",
  "bProperty.bSetting2",
  "cProperty.cSetting"
]

To test, you can provide your object:

object = {
  aProperty: {
    aSetting1: 1,
    aSetting2: 2,
    aSetting3: 3,
    aSetting4: 4,
    aSetting5: 5
  },
  bProperty: {
    bSetting1: {
      bPropertySubSetting: true
    },
    bSetting2: "bString"
  },
  cProperty: {
    cSetting: "cString"
  }
}

Update Jenkins from a war file

To Upgrade Jenkins WAR file, follow the steps below:

  • Stop Jenkins server using command: systemctl stop jenkins
  • Go to Jenkins war location: ex: /usr/lib/jenkins
  • Take a backup from jenkins.war: mv jenkins.war jenkins.war_bkp
  • Download Jenkins using wget or curl command: wget http://updates.jenkinsci.org/download/war/(version)/jenkins.war
  • Starting Jenkins server using command: systemctl start jenkins
  • Check Jenkins server status using command: systemctl status jenkin

Check if table exists

Adding to Gaby's post, my jdbc getTables() for Oracle 10g requires all caps to work:

"employee" -> "EMPLOYEE"

Otherwise I would get an exception:

java.sql.SqlExcepcion exhausted resultset

(even though "employee" is in the schema)

Assembly - JG/JNLE/JL/JNGE after CMP

Wikibooks has a fairly good summary of jump instructions. Basically, there's actually two stages:

cmp_instruction op1, op2

Which sets various flags based on the result, and

jmp_conditional_instruction address

which will execute the jump based on the results of those flags.

Compare (cmp) will basically compute the subtraction op1-op2, however, this is not stored; instead only flag results are set. So if you did cmp eax, ebx that's the same as saying eax-ebx - then deciding based on whether that is positive, negative or zero which flags to set.

More detailed reference here.

Watching variables in SSIS during debug

Drag the variable from Variables pane to Watch pane and voila!

Why does HTML think “chucknorris” is a color?

The WHATWG HTML spec has the exact algorithm for parsing a legacy color value: https://html.spec.whatwg.org/multipage/infrastructure.html#rules-for-parsing-a-legacy-colour-value.

The code Netscape Classic used for parsing color strings is open source: https://dxr.mozilla.org/classic/source/lib/layout/layimage.c#155.

For example, notice that each character is parsed as a hex digit and then is shifted into a 32-bit integer without checking for overflow. Only eight hex digits fit into a 32-bit integer, which is why only the last 8 characters are considered. After parsing the hex digits into 32-bit integers, they are then truncated into 8-bit integers by dividing them by 16 until they fit into 8-bit, which is why leading zeros are ignored.

Update: This code does not exactly match what is defined in the spec, but the only difference there is a few lines of code. I think it is these lines that was added (in Netscape 4):

if (bytes_per_val > 4)
{
    bytes_per_val = 4;
}

Java, Calculate the number of days between two dates

I'm really really REALLY new at Java, so i'm sure that there's an even better way to do what i'm proposing.

I had this same demand and i did it using the difference between the DAYOFYEAR of the two dates. It seemed an easier way to do it...

I can't really evaluate this solution in performance and stability terms, but i think it's ok.

here:

    public static void main(String[] args) throws ParseException {



//Made this part of the code just to create the variables i'll use.
//I'm in Brazil and the date format here is DD/MM/YYYY, but wont be an issue to you guys. 
//It will work anyway with your format.

    String s1 = "18/09/2014"; 
    String s2 = "01/01/2014";
    DateFormat f = DateFormat.getDateInstance();
    Date date1 = f.parse(s1); 
    Date date2 = f.parse(s2);




//Here's the part where we get the days between two dates.

    Calendar day1 = Calendar.getInstance();
    Calendar day2 = Calendar.getInstance(); 
    day1.setTime(date1);
    day2.setTime(date2);

    int daysBetween = day1.get(Calendar.DAY_OF_YEAR) - day2.get(Calendar.DAY_OF_YEAR);      




//Some code just to show the result...
    f = DateFormat.getDateInstance(DateFormat.MEDIUM);
    System.out.println("There's " + daysBetween + " days between " + f.format(day1.getTime()) + " and " + f.format(day2.getTime()) + ".");



    }

In this case, the output would be (remembering that i'm using the Date Format DD/MM/YYYY):

There's 260 days between 18/09/2014 and 01/01/2014.

How to get IntPtr from byte[] in C#

You could use Marshal.UnsafeAddrOfPinnedArrayElement to get a memory pointer to the array (or to a specific element in the array). Keep in mind that the array must be pinned first as per the API documentation:

The array must be pinned using a GCHandle before it is passed to this method. For maximum performance, this method does not validate the array passed to it; this can result in unexpected behavior.

dynamically add and remove view to viewpager

I've created a custom PagerAdapters library to change items in PagerAdapters dynamically.

You can change items dynamically like following by using this library.

@Override
protected void onCreate(Bundle savedInstanceState) {
        /** ... **/
    adapter = new MyStatePagerAdapter(getSupportFragmentManager()
                            , new String[]{"1", "2", "3"});
    ((ViewPager)findViewById(R.id.view_pager)).setAdapter(adapter);
     adapter.add("4");
     adapter.remove(0);
}

class MyPagerAdapter extends ArrayViewPagerAdapter<String> {

    public MyPagerAdapter(String[] data) {
        super(data);
    }

    @Override
    public View getView(LayoutInflater inflater, ViewGroup container, String item, int position) {
        View v = inflater.inflate(R.layout.item_page, container, false);
        ((TextView) v.findViewById(R.id.item_txt)).setText(item);
        return v;
    }
}

Thils library also support pages created by Fragments.

Search and get a line in Python

With regular expressions

import re
s="""
    qwertyuiop
    asdfghjkl

    zxcvbnm
    token qwerty

    asdfghjklñ
"""
>>> items=re.findall("token.*$",s,re.MULTILINE)
>>> for x in items:
...     print x
...
token qwerty

What is the most "pythonic" way to iterate over a list in chunks?

The ideal solution for this problem works with iterators (not just sequences). It should also be fast.

This is the solution provided by the documentation for itertools:

def grouper(n, iterable, fillvalue=None):
    #"grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return itertools.izip_longest(fillvalue=fillvalue, *args)

Using ipython's %timeit on my mac book air, I get 47.5 us per loop.

However, this really doesn't work for me since the results are padded to be even sized groups. A solution without the padding is slightly more complicated. The most naive solution might be:

def grouper(size, iterable):
    i = iter(iterable)
    while True:
        out = []
        try:
            for _ in range(size):
                out.append(i.next())
        except StopIteration:
            yield out
            break

        yield out

Simple, but pretty slow: 693 us per loop

The best solution I could come up with uses islice for the inner loop:

def grouper(size, iterable):
    it = iter(iterable)
    while True:
        group = tuple(itertools.islice(it, None, size))
        if not group:
            break
        yield group

With the same dataset, I get 305 us per loop.

Unable to get a pure solution any faster than that, I provide the following solution with an important caveat: If your input data has instances of filldata in it, you could get wrong answer.

def grouper(n, iterable, fillvalue=None):
    #"grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    for i in itertools.izip_longest(fillvalue=fillvalue, *args):
        if tuple(i)[-1] == fillvalue:
            yield tuple(v for v in i if v != fillvalue)
        else:
            yield i

I really don't like this answer, but it is significantly faster. 124 us per loop

Can a PDF file's print dialog be opened with Javascript?

Another solution:

<input type="button" value="Print" onclick="document.getElementById('PDFtoPrint').focus(); document.getElementById('PDFtoPrint').contentWindow.print();">

Bulk insert with SQLAlchemy ORM

The sqlalchemy docs have a writeup on the performance of various techniques that can be used for bulk inserts:

ORMs are basically not intended for high-performance bulk inserts - this is the whole reason SQLAlchemy offers the Core in addition to the ORM as a first-class component.

For the use case of fast bulk inserts, the SQL generation and execution system that the ORM builds on top of is part of the Core. Using this system directly, we can produce an INSERT that is competitive with using the raw database API directly.

Alternatively, the SQLAlchemy ORM offers the Bulk Operations suite of methods, which provide hooks into subsections of the unit of work process in order to emit Core-level INSERT and UPDATE constructs with a small degree of ORM-based automation.

The example below illustrates time-based tests for several different methods of inserting rows, going from the most automated to the least. With cPython 2.7, runtimes observed:

classics-MacBook-Pro:sqlalchemy classic$ python test.py
SQLAlchemy ORM: Total time for 100000 records 12.0471920967 secs
SQLAlchemy ORM pk given: Total time for 100000 records 7.06283402443 secs
SQLAlchemy ORM bulk_save_objects(): Total time for 100000 records 0.856323003769 secs
SQLAlchemy Core: Total time for 100000 records 0.485800027847 secs
sqlite3: Total time for 100000 records 0.487842082977 sec

Script:

import time
import sqlite3

from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String,  create_engine
from sqlalchemy.orm import scoped_session, sessionmaker

Base = declarative_base()
DBSession = scoped_session(sessionmaker())
engine = None


class Customer(Base):
    __tablename__ = "customer"
    id = Column(Integer, primary_key=True)
    name = Column(String(255))


def init_sqlalchemy(dbname='sqlite:///sqlalchemy.db'):
    global engine
    engine = create_engine(dbname, echo=False)
    DBSession.remove()
    DBSession.configure(bind=engine, autoflush=False, expire_on_commit=False)
    Base.metadata.drop_all(engine)
    Base.metadata.create_all(engine)


def test_sqlalchemy_orm(n=100000):
    init_sqlalchemy()
    t0 = time.time()
    for i in xrange(n):
        customer = Customer()
        customer.name = 'NAME ' + str(i)
        DBSession.add(customer)
        if i % 1000 == 0:
            DBSession.flush()
    DBSession.commit()
    print(
        "SQLAlchemy ORM: Total time for " + str(n) +
        " records " + str(time.time() - t0) + " secs")


def test_sqlalchemy_orm_pk_given(n=100000):
    init_sqlalchemy()
    t0 = time.time()
    for i in xrange(n):
        customer = Customer(id=i+1, name="NAME " + str(i))
        DBSession.add(customer)
        if i % 1000 == 0:
            DBSession.flush()
    DBSession.commit()
    print(
        "SQLAlchemy ORM pk given: Total time for " + str(n) +
        " records " + str(time.time() - t0) + " secs")


def test_sqlalchemy_orm_bulk_insert(n=100000):
    init_sqlalchemy()
    t0 = time.time()
    n1 = n
    while n1 > 0:
        n1 = n1 - 10000
        DBSession.bulk_insert_mappings(
            Customer,
            [
                dict(name="NAME " + str(i))
                for i in xrange(min(10000, n1))
            ]
        )
    DBSession.commit()
    print(
        "SQLAlchemy ORM bulk_save_objects(): Total time for " + str(n) +
        " records " + str(time.time() - t0) + " secs")


def test_sqlalchemy_core(n=100000):
    init_sqlalchemy()
    t0 = time.time()
    engine.execute(
        Customer.__table__.insert(),
        [{"name": 'NAME ' + str(i)} for i in xrange(n)]
    )
    print(
        "SQLAlchemy Core: Total time for " + str(n) +
        " records " + str(time.time() - t0) + " secs")


def init_sqlite3(dbname):
    conn = sqlite3.connect(dbname)
    c = conn.cursor()
    c.execute("DROP TABLE IF EXISTS customer")
    c.execute(
        "CREATE TABLE customer (id INTEGER NOT NULL, "
        "name VARCHAR(255), PRIMARY KEY(id))")
    conn.commit()
    return conn


def test_sqlite3(n=100000, dbname='sqlite3.db'):
    conn = init_sqlite3(dbname)
    c = conn.cursor()
    t0 = time.time()
    for i in xrange(n):
        row = ('NAME ' + str(i),)
        c.execute("INSERT INTO customer (name) VALUES (?)", row)
    conn.commit()
    print(
        "sqlite3: Total time for " + str(n) +
        " records " + str(time.time() - t0) + " sec")

if __name__ == '__main__':
    test_sqlalchemy_orm(100000)
    test_sqlalchemy_orm_pk_given(100000)
    test_sqlalchemy_orm_bulk_insert(100000)
    test_sqlalchemy_core(100000)
    test_sqlite3(100000)

Appending to list in Python dictionary

dates_dict[key] = dates_dict.get(key, []).append(date) sets dates_dict[key] to None as list.append returns None.

In [5]: l = [1,2,3]

In [6]: var = l.append(3)

In [7]: print var
None

You should use collections.defaultdict

import collections
dates_dict = collections.defaultdict(list)

What is the best way to prevent session hijacking?

There is no way to prevent session hijaking 100%, but with some approach can we reduce the time for an attacker to hijaking the session.

Method to prevent session hijaking:

1 - always use session with ssl certificate;

2 - send session cookie only with httponly set to true(prevent javascript to access session cookie)

2 - use session regenerate id at login and logout(note: do not use session regenerate at each request because if you have consecutive ajax request then you have a chance to create multiple session.)

3 - set a session timeout

4 - store browser user agent in a $_SESSION variable an compare with $_SERVER['HTTP_USER_AGENT'] at each request

5 - set a token cookie ,and set expiration time of that cookie to 0(until the browser is closed). Regenerate the cookie value for each request.(For ajax request do not regenerate token cookie). EX:

    //set a token cookie if one not exist
    if(!isset($_COOKIE['user_token'])){
                    //generate a random string for cookie value
        $cookie_token = bin2hex(mcrypt_create_iv('16' , MCRYPT_DEV_URANDOM));

        //set a session variable with that random string
        $_SESSION['user_token'] = $cookie_token;
        //set cookie with rand value
        setcookie('user_token', $cookie_token , 0 , '/' , 'donategame.com' , true , true);
    }

    //set a sesison variable with request of www.example.com
    if(!isset($_SESSION['request'])){
        $_SESSION['request'] = -1;
    }
    //increment $_SESSION['request'] with 1 for each request at www.example.com
    $_SESSION['request']++;

    //verify if $_SESSION['user_token'] it's equal with $_COOKIE['user_token'] only for $_SESSION['request'] > 0
    if($_SESSION['request'] > 0){

        // if it's equal then regenerete value of token cookie if not then destroy_session
        if($_SESSION['user_token'] === $_COOKIE['user_token']){
            $cookie_token = bin2hex(mcrypt_create_iv('16' , MCRYPT_DEV_URANDOM));

            $_SESSION['user_token'] = $cookie_token;

            setcookie('user_token', $cookie_token , 0 , '/' , 'donategame.com' , true , true);
        }else{
            //code for session_destroy
        }

    }

            //prevent session hijaking with browser user agent
    if(!isset($_SESSION['user_agent'])){
        $_SESSION['user_agent'] = $_SERVER['HTTP_USER_AGENT'];
    }

    if($_SESSION['user_agent'] != $_SERVER['HTTP_USER_AGENT']){
      die('session hijaking - user agent');
    }

note: do not regenerate token cookie with ajax request note: the code above is an example. note: if users logout then the cookie token must be destroyed as well as the session

6 - it's not a good aproach to use user ip for preventing session hijaking because some users ip change with each request. THAT AFFECT VALID USERS

7 - personally I store session data in database , it's up to you what method you adopt

If you find mistake in my approach please correct me. If you have more ways to prevent session hyjaking please tell me.

Convert DateTime to String PHP

Shorter way using list. And you can do what you want with each date component.

list($day,$month,$year,$hour,$min,$sec) = explode("/",date('d/m/Y/h/i/s'));
echo $month.'/'.$day.'/'.$year.' '.$hour.':'.$min.':'.$sec;

HTTP Content-Type Header and JSON

Content-Type: application/json is just the content header. The content header is just information about the type of returned data, ex::JSON,image(png,jpg,etc..),html.

Keep in mind, that JSON in JavaScript is an array or object. If you want to see all the data, use console.log instead of alert:

alert(response.text); // Will alert "[object Object]" string
console.log(response.text); // Will log all data objects

If you want to alert the original JSON content as a string, then add single quotation marks ('):

echo "'" . json_encode(array('text' => 'omrele')) . "'";
// alert(response.text) will alert {"text":"omrele"}

Do not use double quotes. It will confuse JavaScript, because JSON uses double quotes on each value and key:

echo '<script>var returndata=';
echo '"' . json_encode(array('text' => 'omrele')) . '"';
echo ';</script>';

// It will return the wrong JavaScript code:
<script>var returndata="{"text":"omrele"}";</script>

Could not load type 'System.ServiceModel.Activation.HttpModule' from assembly 'System.ServiceModel

Details

http://msdn.microsoft.com/en-us/library/hh169179(v=nav.71).aspx

"This error can occur when there are multiple versions of the .NET Framework on the computer that is running IIS..."

How can I display the current branch and folder path in terminal?

To expand on the existing great answers, a very simple way to get a great looking terminal is to use the open source Dotfiles project.

https://github.com/mathiasbynens/dotfiles


enter image description here


Installation is dead simple on OSX and Linux. Run the following command in Terminal.

git clone https://github.com/mathiasbynens/dotfiles.git && cd dotfiles && source bootstrap.sh

This is going to:

  1. Git clone the repo.
  2. cd into the folder.
  3. Run the installation bash script.

Functional, Declarative, and Imperative Programming

Imperative programming: telling the “machine” how to do something, and as a result what you want to happen will happen.

Declarative programming: telling the “machine” what you would like to happen, and letting the computer figure out how to do it.

Example of imperative

function makeWidget(options) {
    const element = document.createElement('div');
    element.style.backgroundColor = options.bgColor;
    element.style.width = options.width;
    element.style.height = options.height;
    element.textContent = options.txt;

    return element;
}

Example of declarative

function makeWidget(type, txt) {
    return new Element(type, txt);
}

Note: The difference is not one of brevity or complexity or abstraction. As stated, the difference is how vs what.

Why rgb and not cmy?

This is nothing to do with hardware nor software. Simply that RGB are the 3 primary colours which can be combined in various ways to produce every other colour. It is more about the human convention/perception of colours which carried over.

You may find this article interesting.

How to inspect Javascript Objects

Use your console:

console.log(object);

Or if you are inspecting html dom elements use console.dir(object). Example:

let element = document.getElementById('alertBoxContainer');
console.dir(element);

Or if you have an array of js objects you could use:

console.table(objectArr);

If you are outputting a lot of console.log(objects) you can also write

console.log({ objectName1 });
console.log({ objectName2 });

This will help you label the objects written to console.

Declare a Range relative to the Active Cell with VBA

There is an .Offset property on a Range class which allows you to do just what you need

ActiveCell.Offset(numRows, numCols)

follow up on a comment:

Dim newRange as Range
Set newRange = Range(ActiveCell, ActiveCell.Offset(numRows, numCols))

and you can verify by MsgBox newRange.Address

and here's how to assign this range to an array

Foreign key referring to primary keys across multiple tables?

Yes, it is possible. You will need to define 2 FKs for 3rd table. Each FK pointing to the required field(s) of one table (ie 1 FK per foreign table).

Use of Application.DoEvents()

Yes.

However, if you need to use Application.DoEvents, this is mostly an indication of a bad application design. Perhaps you'd like to do some work in a separate thread instead?

UnsatisfiedDependencyException: Error creating bean with name 'entityManagerFactory'

Well, you're getting a java.lang.NoClassDefFoundError. In your pom.xml, hibernate-core version is 3.3.2.GA and declared after hibernate-entitymanager, so it prevails. You can remove that dependency, since will be inherited version 3.6.7.Final from hibernate-entitymanager.

You're using spring-boot as parent, so no need to declare version of some dependencies, since they are managed by spring-boot.

Also, hibernate-commons-annotations is inherited from hibernate-entitymanager and hibernate-annotations is an old version of hibernate-commons-annotations, you can remove both.

Finally, your pom.xml can look like this:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.elsys.internetprogramming.trafficspy.server</groupId>
    <artifactId>TrafficSpyService</artifactId>
    <version>0.1.0</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.2.3.RELEASE</version>
    </parent>

    <dependencies>
        <!-- Spring -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cloud-connectors</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <dependency>
            <groupId>org.eclipse.persistence</groupId>
            <artifactId>javax.persistence</artifactId>
            <version>2.0.0</version>
        </dependency>

        <!-- Hibernate -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-pool</groupId>
            <artifactId>commons-pool</artifactId>
        </dependency>

        <!-- MySQL -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
    </dependencies>

    <properties>
        <java.version>1.7</java.version>
    </properties>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

    <repositories>
        <repository>
            <id>spring-releases</id>
            <url>https://repo.spring.io/libs-release</url>
        </repository>

        <repository>
            <id>codehaus</id>
            <url>http://repository.codehaus.org/org/codehaus</url>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <id>spring-releases</id>
            <url>https://repo.spring.io/libs-release</url>
        </pluginRepository>
    </pluginRepositories>

</project>

Let me know if you have a problem.

Rails and PostgreSQL: Role postgres does not exist

My answer was much more simple. Just went to the db folder and deleted the id column, which I had tried to forcefully create, but which is actually created automagically. I also deleted the USERNAME in the database.yml file (under the config folder).

How do I set the figure title and axes labels font size in Matplotlib?

You can also do this globally via a rcParams dictionary:

import matplotlib.pylab as pylab
params = {'legend.fontsize': 'x-large',
          'figure.figsize': (15, 5),
         'axes.labelsize': 'x-large',
         'axes.titlesize':'x-large',
         'xtick.labelsize':'x-large',
         'ytick.labelsize':'x-large'}
pylab.rcParams.update(params)

How to configure Eclipse build path to use Maven dependencies?

Adding my answers for a couple of reasons:

  • Somehow none of the answers listed directly resolved my problem.
  • I couldn't find "Enable dependency management" under Maven. I'm using Eclipse 4.4.2 build on Wed, 4 Feb 2015.

What helped me was another option under Maven called as "Update Project" and then when I click it this window opens which has a checkbox that says "Force update of Snapshot/Releases". The real purpose of this checkbox is different I know but somehow it resolved the dependencies issue. enter image description here

Mock MVC - Add Request Parameter to test

If anyone came to this question looking for ways to add multiple parameters at the same time (my case), you can use .params with a MultivalueMap instead of adding each .param :

LinkedMultiValueMap<String, String> requestParams = new LinkedMultiValueMap<>()
requestParams.add("id", "1");
requestParams.add("name", "john");
requestParams.add("age", "30");

mockMvc.perform(get("my/endpoint").params(requestParams)).andExpect(status().isOk())

Jquery href click - how can I fire up an event?

If you own the HTML code then it might be wise to assign an id to this href. Then your code would look like this:

<a id="sign_up" class="sign_new">Sign up</a>

And jQuery:

$(document).ready(function(){
    $('#sign_up').click(function(){
        alert('Sign new href executed.');
    });
});

If you do not own the HTML then you'd need to change $('#sign_up') to $('a.sign_new'). You might also fire event.stopPropagation() if you have a href in anchor and do not want it handled (AFAIR return false might work as well).

$(document).ready(function(){
    $('#sign_up').click(function(event){
        alert('Sign new href executed.');
        event.stopPropagation();
    });
});

What is the fastest factorial function in JavaScript?

It is very simple using ES6

const factorial = n => n ? (n * factorial(n-1)) : 1;

See an example here

Is there a way to make numbers in an ordered list bold?

A new ::marker pseudo-element selector has been added to CSS Pseudo-Elements Level 4, which makes styling list item numbers in bold as simple as

ol > li::marker {
  font-weight: bold;
}

It is currently supported by Firefox 68+, Chrome/Edge 86+, and Safari 11.1+.

c - warning: implicit declaration of function ‘printf’

the warning or error of kind IMPLICIT DECLARATION is that the compiler is expecting a Function Declaration/Prototype..

It might either be a header file or your own function Declaration..

When would you use the Builder Pattern?

/// <summary>
/// Builder
/// </summary>
public interface IWebRequestBuilder
{
    IWebRequestBuilder BuildHost(string host);

    IWebRequestBuilder BuildPort(int port);

    IWebRequestBuilder BuildPath(string path);

    IWebRequestBuilder BuildQuery(string query);

    IWebRequestBuilder BuildScheme(string scheme);

    IWebRequestBuilder BuildTimeout(int timeout);

    WebRequest Build();
}

/// <summary>
/// ConcreteBuilder #1
/// </summary>
public class HttpWebRequestBuilder : IWebRequestBuilder
{
    private string _host;

    private string _path = string.Empty;

    private string _query = string.Empty;

    private string _scheme = "http";

    private int _port = 80;

    private int _timeout = -1;

    public IWebRequestBuilder BuildHost(string host)
    {
        _host = host;
        return this;
    }

    public IWebRequestBuilder BuildPort(int port)
    {
        _port = port;
        return this;
    }

    public IWebRequestBuilder BuildPath(string path)
    {
        _path = path;
        return this;
    }

    public IWebRequestBuilder BuildQuery(string query)
    {
        _query = query;
        return this;
    }

    public IWebRequestBuilder BuildScheme(string scheme)
    {
        _scheme = scheme;
        return this;
    }

    public IWebRequestBuilder BuildTimeout(int timeout)
    {
        _timeout = timeout;
        return this;
    }

    protected virtual void BeforeBuild(HttpWebRequest httpWebRequest) {
    }

    public WebRequest Build()
    {
        var uri = _scheme + "://" + _host + ":" + _port + "/" + _path + "?" + _query;

        var httpWebRequest = WebRequest.CreateHttp(uri);

        httpWebRequest.Timeout = _timeout;

        BeforeBuild(httpWebRequest);

        return httpWebRequest;
    }
}

/// <summary>
/// ConcreteBuilder #2
/// </summary>
public class ProxyHttpWebRequestBuilder : HttpWebRequestBuilder
{
    private string _proxy = null;

    public ProxyHttpWebRequestBuilder(string proxy)
    {
        _proxy = proxy;
    }

    protected override void BeforeBuild(HttpWebRequest httpWebRequest)
    {
        httpWebRequest.Proxy = new WebProxy(_proxy);
    }
}

/// <summary>
/// Director
/// </summary>
public class SearchRequest
{

    private IWebRequestBuilder _requestBuilder;

    public SearchRequest(IWebRequestBuilder requestBuilder)
    {
        _requestBuilder = requestBuilder;
    }

    public WebRequest Construct(string searchQuery)
    {
        return _requestBuilder
        .BuildHost("ajax.googleapis.com")
        .BuildPort(80)
        .BuildPath("ajax/services/search/web")
        .BuildQuery("v=1.0&q=" + HttpUtility.UrlEncode(searchQuery))
        .BuildScheme("http")
        .BuildTimeout(-1)
        .Build();
    }

    public string GetResults(string searchQuery) {
        var request = Construct(searchQuery);
        var resp = request.GetResponse();

        using (StreamReader stream = new StreamReader(resp.GetResponseStream()))
        {
            return stream.ReadToEnd();
        }
    }
}

class Program
{
    /// <summary>
    /// Inside both requests the same SearchRequest.Construct(string) method is used.
    /// But finally different HttpWebRequest objects are built.
    /// </summary>
    static void Main(string[] args)
    {
        var request1 = new SearchRequest(new HttpWebRequestBuilder());
        var results1 = request1.GetResults("IBM");
        Console.WriteLine(results1);

        var request2 = new SearchRequest(new ProxyHttpWebRequestBuilder("localhost:80"));
        var results2 = request2.GetResults("IBM");
        Console.WriteLine(results2);
    }
}

Default FirebaseApp is not initialized

If you're using Xamarin and came here searching for a solution for this problem, here it's from Microsoft:

In some cases, you may see this error message: Java.Lang.IllegalStateException: Default FirebaseApp is not initialized in this process Make sure to call FirebaseApp.initializeApp(Context) first.

This is a known problem that you can work around by cleaning the solution and rebuilding the project (Build > Clean Solution, Build > Rebuild Solution).

Why am I getting "Received fatal alert: protocol_version" or "peer not authenticated" from Maven Central?

In June 2018, in an effort to raise security and comply with modern standards, the insecure TLS 1.0 & 1.1 protocols will no longer be supported for SSL connections to Central. This should only affect users of Java 6 (and Java 7) that are also using https to access central, which by our metrics is less than .2% of users.

For more details and workarounds, see the blog and faq here: https://blog.sonatype.com/enhancing-ssl-security-and-http/2-support-for-central

Difference between break and continue statement

so you are inside a for or while loop. Using break; will put you outside of the loop. As in, it will end. Continue; will tell it to run the next iteration.

No point in using continue in if statement, but break; is useful. In switch...case, always use break; to end a case, so it does not executes another case.

How to validate inputs dynamically created using ng-repeat, ng-show (angular)

This will get the name in the ng-repeat to come up seperate in the form validation.

<td>
    <input ng-model="r.QTY" class="span1" name="{{'QTY' + $index}}" ng-pattern="/^[\d]*\.?[\d]*$/" required/>
</td>

But I had trouble getting it to look up in its validation message so I had to use an ng-init to get it to resolve a variable as the object key.

<td>
    <input ng-model="r.QTY" class="span1" ng-init="name = 'QTY' + $index" name="{{name}}" ng-pattern="/^[\d]*\.?[\d]*$/" required/>
    <span class="alert-error" ng-show="form[name].$error.pattern"><strong>Requires a number.</strong></span>
    <span class="alert-error" ng-show="form[name].$error.required"><strong>*Required</strong></span> 

Determining Referer in PHP

Using $_SERVER['HTTP_REFERER']

The address of the page (if any) which referred the user agent to the current page. This is set by the user agent. Not all user agents will set this, and some provide the ability to modify HTTP_REFERER as a feature. In short, it cannot really be trusted.

if (!empty($_SERVER['HTTP_REFERER'])) {
    header("Location: " . $_SERVER['HTTP_REFERER']);
} else {
    header("Location: index.php");
}
exit;

SQL Server find and replace specific word in all rows of specific column

UPDATE tblKit
SET number = REPLACE(number, 'KIT', 'CH')
WHERE number like 'KIT%'

or simply this if you are sure that you have no values like this CKIT002

UPDATE tblKit
SET number = REPLACE(number, 'KIT', 'CH')