Programs & Examples On #Squirrel

Squirrel is a high-level object-oriented light-weight scripting language that's designed to be used in real-time requirements applications, like video games.

Using Lato fonts in my css (@font-face)

Font Squirrel has a wonderful web font generator.

I think you should find what you need here to generate OTF fonts and the needed CSS to use them. It will even support older IE versions.

Rails: Address already in use - bind(2) (Errno::EADDRINUSE)

You need to use kill -9 59780 with 59780 replaced with found PID number (use lsof -wni tcp:3000 to see which process used 3000 port and get the process PID).

Or you can just modify your puma config change the tcp port tcp://127.0.0.1:3000 from 3000 to 9292 or other port that not been used.

Or you can start your rails app by using:

bundle exec puma -C config/puma.rb -b tcp://127.0.0.1:3001

Jenkins could not run git

Like Darksaint2014 said, you need to configure two parts if you installed Jenkins in Windows.

If you installed your Jenkins in windows, you need to install Git in both local and your linux server, then configure below in both locations:


Global tool configuration:

global tool configuration


For server side:

For server side


Why is @font-face throwing a 404 error on woff files?

If you dont have access to your webserver config, you can also just RENAME the font file so that it ends in svg (but retain the format). Works fine for me in Chrome and Firefox.

@font-face src: local - How to use the local font if the user already has it?

I haven’t actually done anything with font-face, so take this with a pinch of salt, but I don’t think there’s any way for the browser to definitively tell if a given web font installed on a user’s machine or not.

The user could, for example, have a different font with the same name installed on their machine. The only way to definitively tell would be to compare the font files to see if they’re identical. And the browser couldn’t do that without downloading your web font first.

Does Firefox download the font when you actually use it in a font declaration? (e.g. h1 { font: 'DejaVu Serif';)?

String comparison in Python: is vs. ==

For all built-in Python objects (like strings, lists, dicts, functions, etc.), if x is y, then x==y is also True.

Not always. NaN is a counterexample. But usually, identity (is) implies equality (==). The converse is not true: Two distinct objects can have the same value.

Also, is it generally considered better to just use '==' by default, even when comparing int or Boolean values?

You use == when comparing values and is when comparing identities.

When comparing ints (or immutable types in general), you pretty much always want the former. There's an optimization that allows small integers to be compared with is, but don't rely on it.

For boolean values, you shouldn't be doing comparisons at all. Instead of:

if x == True:
    # do something

write:

if x:
    # do something

For comparing against None, is None is preferred over == None.

I've always liked to use 'is' because I find it more aesthetically pleasing and pythonic (which is how I fell into this trap...), but I wonder if it's intended to just be reserved for when you care about finding two objects with the same id.

Yes, that's exactly what it's for.

Embedding JavaScript engine into .NET

Hey take a look for Javascript .NET on codeplex (http://javascriptdotnet.codeplex.com/) with the version 0.3.1 there is some pretty sweet new features that will probly interest you.

Check out a sample code:

// Initialize the context
JavascriptContext context = new JavascriptContext();

// Setting the externals parameters of the context
context.SetParameter("console", new SystemConsole());
context.SetParameter("message", "Hello World !");
context.SetParameter("number", 1);

// Running the script
context.Run("var i; for (i = 0; i < 5; i++) console.Print(message + ' (' + i + ')'); number += i;");

// Getting a parameter
Console.WriteLine("number: " + context.GetParameter("number"));

IOS 7 Navigation Bar text and arrow color

Swift / iOS8

let textAttributes = NSMutableDictionary(capacity:1)
textAttributes.setObject(UIColor.whiteColor(), forKey: NSForegroundColorAttributeName)
navigationController?.navigationBar.titleTextAttributes = textAttributes

How to enable CORS in flask

All the responses above work okay, but you'll still probably get a CORS error, if the application throws an error you are not handling, like a key-error, if you aren't doing input validation properly, for example. You could add an error handler to catch all instances of exceptions and add CORS response headers in the server response

So define an error handler - errors.py:

from flask import json, make_response, jsonify
from werkzeug.exceptions import HTTPException

# define an error handling function
def init_handler(app):

    # catch every type of exception
    @app.errorhandler(Exception)
    def handle_exception(e):

        #loggit()!          

        # return json response of error
        if isinstance(e, HTTPException):
            response = e.get_response()
            # replace the body with JSON
            response.data = json.dumps({
                "code": e.code,
                "name": e.name,
                "description": e.description,
            })
        else:
            # build response
            response = make_response(jsonify({"message": 'Something went wrong'}), 500)

        # add the CORS header
        response.headers['Access-Control-Allow-Origin'] = '*'
        response.content_type = "application/json"
        return response

then using Billal's answer:

from flask import Flask
from flask_cors import CORS

# import error handling file from where you have defined it
from . import errors

app = Flask(__name__)
CORS(app) # This will enable CORS for all routes
errors.init_handler(app) # initialise error handling 

Load arrayList data into JTable

I created an arrayList from it and I somehow can't find a way to store this information into a JTable.

The DefaultTableModel doesn't support displaying custom Objects stored in an ArrayList. You need to create a custom TableModel.

You can check out the Bean Table Model. It is a reusable class that will use reflection to find all the data in your FootballClub class and display in a JTable.

Or, you can extend the Row Table Model found in the above link to make is easier to create your own custom TableModel by implementing a few methods. The JButtomTableModel.java source code give a complete example of how you can do this.

How to submit a form using PhantomJS

Sending raw POST requests can be sometimes more convenient. Below you can see post.js original example from PhantomJS

// Example using HTTP POST operation

var page = require('webpage').create(),
    server = 'http://posttestserver.com/post.php?dump',
    data = 'universe=expanding&answer=42';

page.open(server, 'post', data, function (status) {
    if (status !== 'success') {
        console.log('Unable to post!');
    } else {
        console.log(page.content);
    }
    phantom.exit();
});

How to use setprecision in C++

#include <iostream>
#include <iomanip>
 
int main(void) 
{
    float value;
    cin >> value;
    cout << setprecision(4) << value;
    return 0;
}

Preloading CSS Images

If the page elements and their background images are already in the DOM (i.e. you are not creating/changing them dynamically), then their background images will already be loaded. At that point, you may want to look at compression methods :)

How change default SVN username and password to commit changes?

For Windows (7), the same folder is located at,

%APPDATA%\Subversion\auth

Type in the above in the Run(Win key + R) dialog box and hit Enter,

To check the existing username open the below file as a text file,

%APPDATA%\Subversion\auth\svn.simple\xxxxxxxxxx

How do I fix a compilation error for unhandled exception on call to Thread.sleep()?

Thread.sleep can throw an InterruptedException which is a checked exception. All checked exceptions must either be caught and handled or else you must declare that your method can throw it. You need to do this whether or not the exception actually will be thrown. Not declaring a checked exception that your method can throw is a compile error.

You either need to catch it:

try {
    Thread.sleep(1000);
} catch (InterruptedException e) {
    e.printStackTrace();
    // handle the exception...        
    // For example consider calling Thread.currentThread().interrupt(); here.
}

Or declare that your method can throw an InterruptedException:

public static void main(String[]args) throws InterruptedException

Related

What are some good SSH Servers for windows?

I agree that cygwin/OpenSSH is the best choice, but its setup can be involved to say the least. Here is a document to get you started though: Installing OpenSSH

Selecting Multiple Values from a Dropdown List in Google Spreadsheet

I have found a great work-around for this. It really only works practically if you want to be able to select up to 4 or so options from your drop down list but here it is:

For each "item" create as many rows as drop-down items you'd like to be able to select. So if you want to be able to select up to 3 characteristics from a given drop down list for each person on your list, create a total of 3 rows for each person. Then merge A:1-A:3, B:1-B:3, C:1-C:3 etc until you reach the column that you'd like your drop-down list to be. Don't merge those cells, instead place the your Data Validation drop-down in each of those cells.

enter image description here

Hope this is clear!!

How do you create a Distinct query in HQL

You can you the distinct keyword in you criteria builder like this.

CriteriaBuilder builder = session.getCriteriaBuilder();
CriteriaQuery<Orders> query = builder.createQuery(Orders.class);
Root<Orders> root = query.from(Orders.class);
query.distinct(true).multiselect(root.get("cust_email").as(String.class));

And create the field constructor in your model class.

Byte Array and Int conversion in Java

Instead of allocating space, et al, an approach using ByteBuffer from java.nio....

byte[] arr = { 0x01, 0x00, 0x00, 0x00, 0x48, 0x01};

// say we want to consider indices 1, 2, 3, 4 {0x00, 0x00, 0x00, 0x48};
ByteBuffer bf = ByteBuffer.wrap(arr, 1, 4); // big endian by default
int num = bf.getInt();    // 72

Now, to go the other way.

ByteBuffer newBuf = ByteBuffer.allocate(4);
newBuf.putInt(num);
byte[] bytes = newBuf.array();  // [0, 0, 0, 72] {0x48 = 72}

Sorting an array in C?

In C, you can use the built in qsort command:

int compare( const void* a, const void* b)
{
     int int_a = * ( (int*) a );
     int int_b = * ( (int*) b );

     if ( int_a == int_b ) return 0;
     else if ( int_a < int_b ) return -1;
     else return 1;
}

qsort( a, 6, sizeof(int), compare )

see: http://www.cplusplus.com/reference/clibrary/cstdlib/qsort/


To answer the second part of your question: an optimal (comparison based) sorting algorithm is one that runs with O(n log(n)) comparisons. There are several that have this property (including quick sort, merge sort, heap sort, etc.), but which one to use depends on your use case.

As a side note, you can sometime do better than O(n log(n)) if you know something about your data - see the wikipedia article on Radix Sort

Compare objects in Angular

Bit late on this thread. angular.equals does deep check, however does anyone know that why its behave differently if one of the member contain "$" in prefix ?

You can try this Demo with following input

var obj3 = {}
obj3.a=  "b";
obj3.b={};
obj3.b.$c =true;

var obj4 = {}
obj4.a=  "b";
obj4.b={};
obj4.b.$c =true;

angular.equals(obj3,obj4);

adb command for getting ip address assigned by operator

You also can try this:

Step 1: adb shell Step 2: ip -f inet addr show wlan0

DateTime2 vs DateTime in SQL Server

DATETIME2 has a date range of "0001 / 01 / 01" through "9999 / 12 / 31" while the DATETIME type only supports year 1753-9999.

Also, if you need to, DATETIME2 can be more precise in terms of time; DATETIME is limited to 3 1/3 milliseconds, while DATETIME2 can be accurate down to 100ns.

Both types map to System.DateTime in .NET - no difference there.

If you have the choice, I would recommend using DATETIME2 whenever possible. I don't see any benefits using DATETIME (except for backward compatibility) - you'll have less trouble (with dates being out of range and hassle like that).

Plus: if you only need the date (without time part), use DATE - it's just as good as DATETIME2 and saves you space, too! :-) Same goes for time only - use TIME. That's what these types are there for!

What datatype should be used for storing phone numbers in SQL Server 2005?

Use SSIS to extract and process the information. That way you will have the processing of the XML files separated from SQL Server. You can also do the SSIS transformations on a separate server if needed. Store the phone numbers in a standard format using VARCHAR. NVARCHAR would be unnecessary since we are talking about numbers and maybe a couple of other chars, like '+', ' ', '(', ')' and '-'.

How to do a subquery in LINQ?

This is how I've been doing subqueries in LINQ, I think this should get what you want. You can replace the explicit CompanyRoleId == 2... with another subquery for the different roles you want or join it as well.

from u in Users
join c in (
    from crt in CompanyRolesToUsers
    where CompanyRoleId == 2
    || CompanyRoleId == 3
    || CompanyRoleId == 4) on u.UserId equals c.UserId
where u.lastname.Contains("fra")
select u;

Docker-Compose persistent data MySQL

Adding on to the answer from @Ohmen, you could also add an external flag to create the data volume outside of docker compose. This way docker compose would not attempt to create it. Also you wouldn't have to worry about losing the data inside the data-volume in the event of $ docker-compose down -v. The below example is from the official page.

version: "3.8"

services:
  db:
    image: postgres
    volumes:
      - data:/var/lib/postgresql/data

volumes:
  data:
    external: true

How to Execute stored procedure from SQL Plus?

You forgot to put z as an bind variable.

The following EXECUTE command runs a PL/SQL statement that references a stored procedure:

SQL> EXECUTE -
> :Z := EMP_SALE.HIRE('JACK','MANAGER','JONES',2990,'SALES')

Note that the value returned by the stored procedure is being return into :Z

Symbol for any number of any characters in regex?

Yes, there is one, it's the asterisk: *

a* // looks for 0 or more instances of "a"

This should be covered in any Java regex tutorial or documentation that you look up.

php - get numeric index of associative array


  $a = array(
      'blue' => 'nice',
      'car' => 'fast',
      'number' => 'none'
  );  
var_dump(array_search('car', array_keys($a)));
var_dump(array_search('blue', array_keys($a)));
var_dump(array_search('number', array_keys($a)));

Convert Unix timestamp to a date string

With GNU's date you can do:

date -d "@$TIMESTAMP"
# date -d @0
Wed Dec 31 19:00:00 EST 1969

(From: BASH: Convert Unix Timestamp to a Date)

On OS X, use date -r.

date -r "$TIMESTAMP"

Alternatively, use strftime(). It's not available directly from the shell, but you can access it via gawk. The %c specifier displays the timestamp in a locale-dependent manner.

echo "$TIMESTAMP" | gawk '{print strftime("%c", $0)}'
# echo 0 | gawk '{print strftime("%c", $0)}'
Wed 31 Dec 1969 07:00:00 PM EST

jQuery - on change input text

I recently was wondering why my code doesn't work, then I realized, I need to setup the event handlers as soon as the document is loaded, otherwise when browser loads the code line by line, it loads the JavaScript, but it does not yet have the element to assign the event handler to it. with your example, it should be like this:

$(document).ready(function(){
     $("#kat").change(function(){ 
         alert("Hello");
     });
});

Index of duplicates items in a python list

def find_duplicate(list_):
    duplicate_list=[""]

    for k in range(len(list_)):
        if duplicate_list.__contains__(list_[k]):
            continue
        for j in range(len(list_)):
            if k == j:
                continue
            if list_[k] == list_[j]:
                duplicate_list.append(list_[j])
                print("duplicate "+str(list_.index(list_[j]))+str(list_.index(list_[k])))

Get loop count inside a Python FOR loop

Agree with Nick. Here is more elaborated code.

#count=0
for idx, item in enumerate(list):
    print item
    #count +=1
    #if count % 10 == 0:
    if (idx+1) % 10 == 0:
        print 'did ten'

I have commented out the count variable in your code.

How to replace blank (null ) values with 0 for all records?

I used a two step process to change rows with "blank" values to "Null" values as place holders.

UPDATE [TableName] SET [TableName].[ColumnName] = "0"
WHERE ((([TableName].[ColumnName])=""));

UPDATE [TableName] SET [TableName].[ColumnName] = "Null"
WHERE ((([TableName].[ColumnName])="0"));

How to convert milliseconds into human readable form?

Here is more precise method in JAVA , I have implemented this simple logic , hope this will help you:

    public String getDuration(String _currentTimemilliSecond)
    {
        long _currentTimeMiles = 1;         
        int x = 0;
        int seconds = 0;
        int minutes = 0;
        int hours = 0;
        int days = 0;
        int month = 0;
        int year = 0;

        try 
        {
            _currentTimeMiles = Long.parseLong(_currentTimemilliSecond);
            /**  x in seconds **/   
            x = (int) (_currentTimeMiles / 1000) ; 
            seconds = x ;

            if(seconds >59)
            {
                minutes = seconds/60 ;

                if(minutes > 59)
                {
                    hours = minutes/60;

                    if(hours > 23)
                    {
                        days = hours/24 ;

                        if(days > 30)
                        {
                            month = days/30;

                            if(month > 11)
                            {
                                year = month/12;

                                Log.d("Year", year);
                                Log.d("Month", month%12);
                                Log.d("Days", days % 30);
                                Log.d("hours ", hours % 24);
                                Log.d("Minutes ", minutes % 60);
                                Log.d("Seconds  ", seconds % 60);   

                                return "Year "+year + " Month "+month%12 +" Days " +days%30 +" hours "+hours%24 +" Minutes "+minutes %60+" Seconds "+seconds%60;
                            }
                            else
                            {
                                Log.d("Month", month);
                                Log.d("Days", days % 30);
                                Log.d("hours ", hours % 24);
                                Log.d("Minutes ", minutes % 60);
                                Log.d("Seconds  ", seconds % 60);   

                                return "Month "+month +" Days " +days%30 +" hours "+hours%24 +" Minutes "+minutes %60+" Seconds "+seconds%60;
                            }

                        }
                        else
                        {
                            Log.d("Days", days );
                            Log.d("hours ", hours % 24);
                            Log.d("Minutes ", minutes % 60);
                            Log.d("Seconds  ", seconds % 60);   

                            return "Days " +days +" hours "+hours%24 +" Minutes "+minutes %60+" Seconds "+seconds%60;
                        }

                    }
                    else
                    {
                        Log.d("hours ", hours);
                        Log.d("Minutes ", minutes % 60);
                        Log.d("Seconds  ", seconds % 60);

                        return "hours "+hours+" Minutes "+minutes %60+" Seconds "+seconds%60;
                    }
                }
                else
                {
                    Log.d("Minutes ", minutes);
                    Log.d("Seconds  ", seconds % 60);

                    return "Minutes "+minutes +" Seconds "+seconds%60;
                }
            }
            else
            {
                Log.d("Seconds ", x);
                return " Seconds "+seconds;
            }
        }
        catch (Exception e) 
        {
            Log.e(getClass().getName().toString(), e.toString());
        }
        return "";
    }

    private Class Log
    {
        public static void d(String tag , int value)
        {
            System.out.println("##### [ Debug ]  ## "+tag +" :: "+value);
        }
    }

Javascript negative number

How about something as simple as:

function negative(number){
    return number < 0;
}

The * 1 part is to convert strings to numbers.

In Python, what happens when you import inside of a function?

The very first time you import goo from anywhere (inside or outside a function), goo.py (or other importable form) is loaded and sys.modules['goo'] is set to the module object thus built. Any future import within the same run of the program (again, whether inside or outside a function) just look up sys.modules['goo'] and bind it to barename goo in the appropriate scope. The dict lookup and name binding are very fast operations.

Assuming the very first import gets totally amortized over the program's run anyway, having the "appropriate scope" be module-level means each use of goo.this, goo.that, etc, is two dict lookups -- one for goo and one for the attribute name. Having it be "function level" pays one extra local-variable setting per run of the function (even faster than the dictionary lookup part!) but saves one dict lookup (exchanging it for a local-variable lookup, blazingly fast) for each goo.this (etc) access, basically halving the time such lookups take.

We're talking about a few nanoseconds one way or another, so it's hardly a worthwhile optimization. The one potentially substantial advantage of having the import within a function is when that function may well not be needed at all in a given run of the program, e.g., that function deals with errors, anomalies, and rare situations in general; if that's the case, any run that does not need the functionality will not even perform the import (and that's a saving of microseconds, not just nanoseconds), only runs that do need the functionality will pay the (modest but measurable) price.

It's still an optimization that's only worthwhile in pretty extreme situations, and there are many others I would consider before trying to squeeze out microseconds in this way.

deny directory listing with htaccess

For showing Forbidden error then include these lines in your .htaccess file:

Options -Indexes 

If we want to index our files and showing them with some information, then use:

IndexOptions -FancyIndexing

If we want for some particular extension not to show, then:

IndexIgnore *.zip *.css

Make EditText ReadOnly

Try using

editText.setEnabled(false);
editText.setClickable(false);

How do I choose grid and block dimensions for CUDA kernels?

There are two parts to that answer (I wrote it). One part is easy to quantify, the other is more empirical.

Hardware Constraints:

This is the easy to quantify part. Appendix F of the current CUDA programming guide lists a number of hard limits which limit how many threads per block a kernel launch can have. If you exceed any of these, your kernel will never run. They can be roughly summarized as:

  1. Each block cannot have more than 512/1024 threads in total (Compute Capability 1.x or 2.x and later respectively)
  2. The maximum dimensions of each block are limited to [512,512,64]/[1024,1024,64] (Compute 1.x/2.x or later)
  3. Each block cannot consume more than 8k/16k/32k/64k/32k/64k/32k/64k/32k/64k registers total (Compute 1.0,1.1/1.2,1.3/2.x-/3.0/3.2/3.5-5.2/5.3/6-6.1/6.2/7.0)
  4. Each block cannot consume more than 16kb/48kb/96kb of shared memory (Compute 1.x/2.x-6.2/7.0)

If you stay within those limits, any kernel you can successfully compile will launch without error.

Performance Tuning:

This is the empirical part. The number of threads per block you choose within the hardware constraints outlined above can and does effect the performance of code running on the hardware. How each code behaves will be different and the only real way to quantify it is by careful benchmarking and profiling. But again, very roughly summarized:

  1. The number of threads per block should be a round multiple of the warp size, which is 32 on all current hardware.
  2. Each streaming multiprocessor unit on the GPU must have enough active warps to sufficiently hide all of the different memory and instruction pipeline latency of the architecture and achieve maximum throughput. The orthodox approach here is to try achieving optimal hardware occupancy (what Roger Dahl's answer is referring to).

The second point is a huge topic which I doubt anyone is going to try and cover it in a single StackOverflow answer. There are people writing PhD theses around the quantitative analysis of aspects of the problem (see this presentation by Vasily Volkov from UC Berkley and this paper by Henry Wong from the University of Toronto for examples of how complex the question really is).

At the entry level, you should mostly be aware that the block size you choose (within the range of legal block sizes defined by the constraints above) can and does have a impact on how fast your code will run, but it depends on the hardware you have and the code you are running. By benchmarking, you will probably find that most non-trivial code has a "sweet spot" in the 128-512 threads per block range, but it will require some analysis on your part to find where that is. The good news is that because you are working in multiples of the warp size, the search space is very finite and the best configuration for a given piece of code relatively easy to find.

Global Git ignore

on windows subsystem for linux I had to navigate to the subsystem root by cd ~/ then touch .gitignore and then update the global gitignore configuration in there.

I hope it helps someone.

Installing python module within code

If you want to use pip to install required package and import it after installation, you can use this code:

def install_and_import(package):
    import importlib
    try:
        importlib.import_module(package)
    except ImportError:
        import pip
        pip.main(['install', package])
    finally:
        globals()[package] = importlib.import_module(package)


install_and_import('transliterate')

If you installed a package as a user you can encounter the problem that you cannot just import the package. See How to refresh sys.path? for additional information.

Checking if a worksheet-based checkbox is checked

Is this what you are trying?

Sub Sample()
    Dim cb As Shape

    Set cb = ActiveSheet.Shapes("Check Box 1")

    If cb.OLEFormat.Object.Value = 1 Then
        MsgBox "Checkbox is Checked"
    Else
        MsgBox "Checkbox is not Checked"
    End If
End Sub

Replace Activesheet with the relevant sheetname. Also replace Check Box 1 with the relevant checkbox name.

How to insert 1000 rows at a time

By the way why don't you use XML data insertion through Stored Procedure?

Here is the link to do that... Inserting Bulk Data through XML-Stored Procedure

How to use if - else structure in a batch file?

I think in the question and in some of the answers there is a bit of confusion about the meaning of this pseudocode in DOS: IF A IF B X ELSE Y. It does not mean IF(A and B) THEN X ELSE Y, but in fact means IF A( IF B THEN X ELSE Y). If the test of A fails, then he whole of the inner if-else will be ignored.

As one of the answers mentioned, in this case only one of the tests can succeed so the 'else' is not needed, but of course that only works in this example, it isn't a general solution for doing if-else.

There are lots of ways around this. Here is a few ideas, all are quite ugly but hey, this is (or at least was) DOS!

@echo off

set one=1
set two=2

REM Example 1

IF %one%_%two%==1_1 (
   echo Example 1 fails
) ELSE IF %one%_%two%==1_2 (
   echo Example 1 works correctly
) ELSE (
    echo Example 1 fails
)

REM Example 2

set test1result=0
set test2result=0

if %one%==1 if %two%==1 set test1result=1
if %one%==1 if %two%==2 set test2result=1

IF %test1result%==1 (
   echo Example 2 fails
) ELSE IF %test2result%==1 (
   echo Example 2 works correctly
) ELSE (
    echo Example 2 fails
)

REM Example 3

if %one%==1 if %two%==1 (
   echo Example 3 fails
   goto :endoftests
)
if %one%==1 if %two%==2 (
   echo Example 3 works correctly
   goto :endoftests
)
echo Example 3 fails
)
:endoftests

Android studio: emulator is running but not showing up in Run App "choose a running device"

try to open the emulator and run it parallel with android studio/eclipse and the option will be displayed to select in the choose the device(emuator name, mine is Genymotion).

Hashing a dictionary?

Here is a clearer solution.

def freeze(o):
  if isinstance(o,dict):
    return frozenset({ k:freeze(v) for k,v in o.items()}.items())

  if isinstance(o,list):
    return tuple([freeze(v) for v in o])

  return o


def make_hash(o):
    """
    makes a hash out of anything that contains only list,dict and hashable types including string and numeric types
    """
    return hash(freeze(o))  

How do I convert from BLOB to TEXT in MySQL?

phpMyAdmin screenshot Using phpMyAdmin you can also set the options to show BLOB content and show complete text.

How to enable CORS on Firefox?

I was stucked with this problem for a long time (CORS does not work in FF, but works in Chrome and others). No advice could help. Finally, i found that my local dev subdomain (like sub.example.dev) was not explicitly mentioned in /etc/hosts, thus FF just is not able to find it and shows confusing error message 'Aborted...' in dev tools panel.

Putting the exact subdomain into my local /etc/hosts fixed the problem. /etc/hosts is just a plain-text file in unix systems, so you can open it under the root user and put your subdomain in front of '127.0.0.1' ip address.

How to set or change the default Java (JDK) version on OS X?

Adding to the above answers, I put the following lines in my .bash_profile (or .zshrc for MacOS 10.15+) which makes it really convenient to switch (including @elektromin's comment for java 9):

alias j12="export JAVA_HOME=`/usr/libexec/java_home -v 12`; java -version"
alias j11="export JAVA_HOME=`/usr/libexec/java_home -v 11`; java -version"
alias j10="export JAVA_HOME=`/usr/libexec/java_home -v 10`; java -version"
alias j9="export JAVA_HOME=`/usr/libexec/java_home -v 9`; java -version"
alias j8="export JAVA_HOME=`/usr/libexec/java_home -v 1.8`; java -version"
alias j7="export JAVA_HOME=`/usr/libexec/java_home -v 1.7`; java -version"

After inserting, execute $ source .bash_profile

I can switch to Java 8 by typing the following:

$ j8
java version "1.8.0_102"
Java(TM) SE Runtime Environment (build 1.8.0_102-b14)
Java HotSpot(TM) 64-Bit Server VM (build 25.102-b14, mixed mode)

.gitignore all the .DS_Store files in every folder and subfolder

Your .gitignore file should look like this:

# Ignore Mac DS_Store files
.DS_Store

As long as you don't include a slash, it is matched against the file name in all directories. (from here)

Cocoa: What's the difference between the frame and the bounds?

Frame vs bounds

  • If you create a view at X:0, Y:0, width:400, height:400, its frame and bounds are the same.
  • If you move that view to X:400, its frame will reflect that change but its bounds will not. Remember, the bounds is relative to the view’s own space, and internally to the view nothing has changed.
  • If you transform the view, e.g. rotating it or scaling it up, the frame will change to reflect that, but the bounds still won’t – as far as the view is concerned internally, it hasn’t changed.
  • If you change the bounds then it will change the content inside the frame because the origin of the bounds rectangle starts at a different part of the view.

PHP : send mail in localhost

I spent hours on this. I used to not get errors but mails were never sent. Finally I found a solution and I would like to share it.

<?php
include 'nav.php';
/*
    Download PhpMailer from the following link:
    https://github.com/Synchro/PHPMailer (CLick on Download zip on the right side)
    Extract the PHPMailer-master folder into your xampp->htdocs folder
    Make changes in the following code and its done :-)

    You will receive the mail with the name Root User.
    To change the name, go to class.phpmailer.php file in your PHPMailer-master folder,
    And change the name here: 
    public $FromName = 'Root User';
*/
require("PHPMailer-master/PHPMailerAutoload.php"); //or select the proper destination for this file if your page is in some   //other folder
ini_set("SMTP","ssl://smtp.gmail.com"); 
ini_set("smtp_port","465"); //No further need to edit your configuration files.
$mail = new PHPMailer();
$mail->SMTPAuth = true;
$mail->Host = "smtp.gmail.com"; // SMTP server
$mail->SMTPSecure = "ssl";
$mail->Username = "[email protected]"; //account with which you want to send mail. Or use this account. i dont care :-P
$mail->Password = "trials.php.php"; //this account's password.
$mail->Port = "465";
$mail->isSMTP();  // telling the class to use SMTP
$rec1="[email protected]"; //receiver. email addresses to which u want to send the mail.
$mail->AddAddress($rec1);
$mail->Subject  = "Eventbook";
$mail->Body     = "Hello hi, testing";
$mail->WordWrap = 200;
if(!$mail->Send()) {
echo 'Message was not sent!.';
echo 'Mailer error: ' . $mail->ErrorInfo;
} else {
echo  //Fill in the document.location thing
'<script type="text/javascript">
                        if(confirm("Your mail has been sent"))
                        document.location = "/";
        </script>';
}
?>

Ignoring upper case and lower case in Java

You have to use the String method .toLowerCase() or .toUpperCase() on both the input and the string you are trying to match it with.

Example:

public static void findPatient() {
    System.out.print("Enter part of the patient name: ");
    String name = sc.nextLine();

    System.out.print(myPatientList.showPatients(name));
}

//the other class
ArrayList<String> patientList;

public void showPatients(String name) {
    boolean match = false;

    for(String matchingname : patientList) {
        if (matchingname.toLowerCase().contains(name.toLowerCase())) {
            match = true;
        }
    }
}

org.springframework.web.client.HttpClientErrorException: 400 Bad Request

This is what worked for me. Issue is earlier I didn't set Content Type(header) when I used exchange method.

MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
map.add("param1", "123");
map.add("param2", "456");
map.add("param3", "789");
map.add("param4", "123");
map.add("param5", "456");

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

final HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<MultiValueMap<String, String>>(map ,
        headers);
JSONObject jsonObject = null;

try {
    RestTemplate restTemplate = new RestTemplate();
    ResponseEntity<String> responseEntity = restTemplate.exchange(
            "https://url", HttpMethod.POST, entity,
            String.class);

    if (responseEntity.getStatusCode() == HttpStatus.CREATED) {
        try {
            jsonObject = new JSONObject(responseEntity.getBody());
        } catch (JSONException e) {
            throw new RuntimeException("JSONException occurred");
        }
    }
  } catch (final HttpClientErrorException httpClientErrorException) {
        throw new ExternalCallBadRequestException();
  } catch (HttpServerErrorException httpServerErrorException) {
        throw new ExternalCallServerErrorException(httpServerErrorException);
  } catch (Exception exception) {
        throw new ExternalCallServerErrorException(exception);
    } 

ExternalCallBadRequestException and ExternalCallServerErrorException are the custom exceptions here.

Note: Remember HttpClientErrorException is thrown when a 4xx error is received. So if the request you send is wrong either setting header or sending wrong data, you could receive this exception.

PowerShell Script to Find and Replace for all Files with a Specific Extension

When doing recursive replacement, the path and filename need to be included:

Get-ChildItem -Recurse | ForEach {  (Get-Content $_.PSPath | 
ForEach {$ -creplace "old", "new"}) | Set-Content $_.PSPath }

This wil replace all "old" with "new" case-sensitive in all the files of your folders of your current directory.

How can I find all *.js file in directory recursively in Linux?

If you just want the list, then you should ask here: http://unix.stackexchange.com

The answer is: cd / && find -name *.js

If you want to implement this, you have to specify the language.

Transfer data between iOS and Android via Bluetooth?

This question has been asked many times on this site and the definitive answer is: NO, you can't connect an Android phone to an iPhone over Bluetooth, and YES Apple has restrictions that prevent this.

Some possible alternatives:

  1. Bonjour over WiFi, as you mentioned. However, I couldn't find a comprehensive tutorial for it.
  2. Some internet based sync service, like Dropbox, Google Drive, Amazon S3. These usually have libraries for several platforms.
  3. Direct TCP/IP communication over sockets. (How to write a small (socket) server in iOS)
  4. Bluetooth Low Energy will be possible once the issues on the Android side are solved (Communicating between iOS and Android with Bluetooth LE)

Coolest alternative: use the Bump API. It has iOS and Android support and really easy to integrate. For small payloads this can be the most convenient solution.

Details on why you can't connect an arbitrary device to the iPhone. iOS allows only some bluetooth profiles to be used without the Made For iPhone (MFi) certification (HPF, A2DP, MAP...). The Serial Port Profile that you would require to implement the communication is bound to MFi membership. Membership to this program provides you to the MFi authentication module that has to be added to your hardware and takes care of authenticating the device towards the iPhone. Android phones don't have this module, so even though the physical connection may be possible to build up, the authentication step will fail. iPhone to iPhone communication is possible as both ends are able to authenticate themselves.

String comparison - Android

String g1="Male";
String g2="Female";
String salutation="";
String gender="Male";
if(gender.toLowerCase().trim().equals(g1.toLowerCase().trim()));
   salutation ="Mr.";
if(gender.toLowerCase().trim().equals(g2.toLowerCase().trim()));
   salutation ="Ms.";

What does the 'u' symbol mean in front of string values?

This is a feature, not a bug.

See http://docs.python.org/howto/unicode.html, specifically the 'unicode type' section.

Google maps responsive resize

Move your map variable into a scope where the event listener can use it. You are creating the map inside your initialize() function and nothing else can use it when created that way.

var map; //<-- This is now available to both event listeners and the initialize() function
function initialize() {
  var mapOptions = {
   center: new google.maps.LatLng(40.5472,12.282715),
   zoom: 6,
   mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  map = new google.maps.Map(document.getElementById("map-canvas"),
            mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
google.maps.event.addDomListener(window, "resize", function() {
 var center = map.getCenter();
 google.maps.event.trigger(map, "resize");
 map.setCenter(center); 
});

Sending email with attachments from C#, attachments arrive as Part 1.2 in Thunderbird

Try this:

private void btnAtt_Click(object sender, EventArgs e) {

    openFileDialog1.ShowDialog();
    Attachment myFile = new Attachment(openFileDialog1.FileName);

    MyMsg.Attachments.Add(myFile);


}

How to fire AJAX request Periodically?

You can use setTimeout or setInterval.

The difference is - setTimeout triggers your function only once, and then you must set it again. setInterval keeps triggering expression again and again, unless you tell it to stop

How to resize an image to fit in the browser window?

If you are willing to put a container element around your image, a pure CSS solution is simple. You see, 99% height has no meaning when the parent element will extend vertically to contain its children. The parent needs to have a fixed height, say... the height of the viewport.

HTML

<!-- use a tall image to illustrate the problem -->
<div class='fill-screen'>
    <img class='make-it-fit' 
         src='https://upload.wikimedia.org/wikipedia/commons/f/f2/Leaning_Tower_of_Pisa.jpg'>
</div>

CSS

div.fill-screen {
    position: fixed;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    text-align: center;
}

img.make-it-fit {
    max-width: 99%;
    max-height: 99%;
}

Play with the fiddle.

Python, creating objects

Objects are instances of classes. Classes are just the blueprints for objects. So given your class definition -

# Note the added (object) - this is the preferred way of creating new classes
class Student(object):
    name = "Unknown name"
    age = 0
    major = "Unknown major"

You can create a make_student function by explicitly assigning the attributes to a new instance of Student -

def make_student(name, age, major):
    student = Student()
    student.name = name
    student.age = age
    student.major = major
    return student

But it probably makes more sense to do this in a constructor (__init__) -

class Student(object):
    def __init__(self, name="Unknown name", age=0, major="Unknown major"):
        self.name = name
        self.age = age
        self.major = major

The constructor is called when you use Student(). It will take the arguments defined in the __init__ method. The constructor signature would now essentially be Student(name, age, major).

If you use that, then a make_student function is trivial (and superfluous) -

def make_student(name, age, major):
    return Student(name, age, major)

For fun, here is an example of how to create a make_student function without defining a class. Please do not try this at home.

def make_student(name, age, major):
    return type('Student', (object,),
                {'name': name, 'age': age, 'major': major})()

xxxxxx.exe is not a valid Win32 application

I believe this error can also be thrown if your project is targeting a framework version that is not installed on the server you are deploying to.

How can I tell what edition of SQL Server runs on the machine?

SELECT  CASE WHEN SERVERPROPERTY('EditionID') = -1253826760 THEN 'Desktop'
         WHEN SERVERPROPERTY('EditionID') = -1592396055 THEN 'Express'
         WHEN SERVERPROPERTY('EditionID') = -1534726760 THEN 'Standard'
         WHEN SERVERPROPERTY('EditionID') = 1333529388 THEN 'Workgroup'
         WHEN SERVERPROPERTY('EditionID') = 1804890536 THEN 'Enterprise'
         WHEN SERVERPROPERTY('EditionID') = -323382091 THEN 'Personal'
         WHEN SERVERPROPERTY('EditionID') = -2117995310  THEN 'Developer'
         WHEN SERVERPROPERTY('EditionID') = 610778273  THEN 'Windows Embedded SQL'
         WHEN SERVERPROPERTY('EditionID') = 4161255391   THEN 'Express with Advanced Services'
    END AS 'Edition'; 

Start script missing error when running npm start

Installing create-react-app globally is now discouraged. Instead uninstall globally installed create-react-app package by doing: npm uninstall -g create-react-app (you may have to manually delete package folder if this command didn't work for you. Some users have reported they had to delete folders manually)

Then you can run npx create-react-app my-app to create react app again.

ref: https://github.com/facebook/create-react-app/issues/8086

Converting HTML string into DOM elements?

Why not use insertAdjacentHTML

for example:

// <div id="one">one</div> 
var d1 = document.getElementById('one'); 
d1.insertAdjacentHTML('afterend', '<div id="two">two</div>');

// At this point, the new structure is:
// <div id="one">one</div><div id="two">two</div>here

How to redirect cin and cout to files?

Try this to redirect cout to file.

#include <iostream>
#include <fstream>

int main()
{
    /** backup cout buffer and redirect to out.txt **/
    std::ofstream out("out.txt");

    auto *coutbuf = std::cout.rdbuf();
    std::cout.rdbuf(out.rdbuf());

    std::cout << "This will be redirected to file out.txt" << std::endl;

    /** reset cout buffer **/
    std::cout.rdbuf(coutbuf);

    std::cout << "This will be printed on console" << std::endl;

    return 0;
}

Read full article Use std::rdbuf to Redirect cin and cout

SQL: Insert all records from one table to another table without specific the columns

Per this other post: Insert all values of a..., you can do the following:

INSERT INTO new_table (Foo, Bar, Fizz, Buzz)
SELECT Foo, Bar, Fizz, Buzz
FROM initial_table

It's important to specify the column names as indicated by the other answers.

Is there any difference between a GUID and a UUID?

Not really. GUID is more Microsoft-centric whereas UUID is used more widely (e.g., as in the urn:uuid: URN scheme, and in CORBA).

Count number of occurences for each unique value

It is a one-line approach by using aggregate.

> aggregate(data.frame(count = v), list(value = v), length)

  value count
1     1    25
2     2    75

Select records from NOW() -1 Day

when search field is timestamp and you want find records from 0 hours yesterday and 0 hour today use construction

MY_DATE_TIME_FIELD between makedate(year(now()), date_format(now(),'%j')-1) and makedate(year(now()), date_format(now(),'%j'))  

instead

 now() - interval 1 day

Check if a string is a date value

Would Date.parse() suffice?

See its relative MDN Documentation page.

Sending Windows key using SendKeys

OK turns out what you really want is this: http://inputsimulator.codeplex.com/

Which has done all the hard work of exposing the Win32 SendInput methods to C#. This allows you to directly send the windows key. This is tested and works:

InputSimulator.SimulateModifiedKeyStroke(VirtualKeyCode.LWIN, VirtualKeyCode.VK_E);

Note however that in some cases you want to specifically send the key to the application (such as ALT+F4), in which case use the Form library method. In others, you want to send it to the OS in general, use the above.


Old

Keeping this here for reference, it will not work in all operating systems, and will not always behave how you want. Note that you're trying to send these key strokes to the app, and the OS usually intercepts them early. In the case of Windows 7 and Vista, too early (before the E is sent).

SendWait("^({ESC}E)") or Send("^({ESC}E)")

Note from here: http://msdn.microsoft.com/en-us/library/system.windows.forms.sendkeys.aspx

To specify that any combination of SHIFT, CTRL, and ALT should be held down while several other keys are pressed, enclose the code for those keys in parentheses. For example, to specify to hold down SHIFT while E and C are pressed, use "+(EC)". To specify to hold down SHIFT while E is pressed, followed by C without SHIFT, use "+EC".

Note that since you want ESC and (say) E pressed at the same time, you need to enclose them in brackets.

Replace negative values in an numpy array

Try numpy.clip:

>>> import numpy
>>> a = numpy.arange(-10, 10)
>>> a
array([-10,  -9,  -8,  -7,  -6,  -5,  -4,  -3,  -2,  -1,   0,   1,   2,
         3,   4,   5,   6,   7,   8,   9])
>>> a.clip(0, 10)
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

You can clip only the bottom half with clip(0).

>>> a = numpy.array([1, 2, 3, -4, 5])
>>> a.clip(0)
array([1, 2, 3, 0, 5])

You can clip only the top half with clip(max=n). (This is much better than my previous suggestion, which involved passing NaN to the first parameter and using out to coerce the type.):

>>> a.clip(max=2)
array([ 1,  2,  2, -4,  2])

Another interesting approach is to use where:

>>> numpy.where(a <= 2, a, 2)
array([ 1,  2,  2, -4,  2])

Finally, consider aix's answer. I prefer clip for simple operations because it's self-documenting, but his answer is preferable for more complex operations.

Can't include C++ headers like vector in Android NDK

If you are using ndk r10c or later, simply add APP_STL=c++_static to Application.mk

Single Line Nested For Loops

You can use two for loops in same line by using zip function

Code:

list1 = ['Abbas', 'Ali', 'Usman']
list2 = ['Kamran', 'Asgar', 'Hamza', 'Umer']
list3 = []
for i,j in zip(list1,list2):
    list3.append(i)
    list3.append(j)
print(list3)

Output:

['Abbas', 'Kamran', 'Ali', 'Asgar', 'Usman', 'Hamza']

So, by using zip function, we can use two for loops or we can iterate two lists in same row.

How to get Real IP from Visitor?

This is the most common technique I've seen:

function getUserIP() {
    if( array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER) && !empty($_SERVER['HTTP_X_FORWARDED_FOR']) ) {
        if (strpos($_SERVER['HTTP_X_FORWARDED_FOR'], ',')>0) {
            $addr = explode(",",$_SERVER['HTTP_X_FORWARDED_FOR']);
            return trim($addr[0]);
        } else {
            return $_SERVER['HTTP_X_FORWARDED_FOR'];
        }
    }
    else {
        return $_SERVER['REMOTE_ADDR'];
    }
}

Note that it does not guarantee it you will get always the correct user IP because there are many ways to hide it.

overlay two images in android to set an imageview

You can skip the complex Canvas manipulation and do this entirely with Drawables, using LayerDrawable. You have one of two choices: You can either define it in XML then simply set the image, or you can configure a LayerDrawable dynamically in code.

Solution #1 (via XML):

Create a new Drawable XML file, let's call it layer.xml:

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/t" />
    <item android:drawable="@drawable/tt" />
</layer-list>

Now set the image using that Drawable:

testimage.setImageDrawable(getResources().getDrawable(R.layout.layer));

Solution #2 (dynamic):

Resources r = getResources();
Drawable[] layers = new Drawable[2];
layers[0] = r.getDrawable(R.drawable.t);
layers[1] = r.getDrawable(R.drawable.tt);
LayerDrawable layerDrawable = new LayerDrawable(layers);
testimage.setImageDrawable(layerDrawable);

(I haven't tested this code so there may be a mistake, but this general outline should work.)

.attr('checked','checked') does not work

I don't think you can call

$.attr('checked',true);

because there is no element selector in the first place. $ must be followed by $('selector_name'). GOod luck!

Get characters after last / in url

You can use substr and strrchr:

$url = 'http://www.vimeo.com/1234567';
$str = substr(strrchr($url, '/'), 1);
echo $str;      // Output: 1234567

How to sort a list/tuple of lists/tuples by the element at a given index?

sorted_by_second = sorted(data, key=lambda tup: tup[1])

or:

data.sort(key=lambda tup: tup[1])  # sorts in place

Is it possible to forward-declare a function in Python?

What you can do is to wrap the invocation into a function of its own.

So that

foo()

def foo():
    print "Hi!"

will break, but

def bar():
    foo()

def foo():
    print "Hi!"

bar()

will be working properly.

General rule in Python is not that function should be defined higher in the code (as in Pascal), but that it should be defined before its usage.

Hope that helps.

How to access environment variable values?

There's also a number of great libraries. Envs for example will allow you to parse objects out of your environment variables, which is rad. For example:

from envs import env
env('SECRET_KEY') # 'your_secret_key_here'
env('SERVER_NAMES',var_type='list') #['your', 'list', 'here']

Is there a Java API that can create rich Word documents?

There's a tool called JODConverter which hooks into open office to expose it's file format converters, there's versions available as a webapp (sits in tomcat) which you post to and a command line tool. I've been firing html at it and converting to .doc and pdf succesfully it's in a fairly big project, haven't gone live yet but I think I'm going to be using it. http://sourceforge.net/projects/jodconverter/

Append key/value pair to hash with << in Ruby

There is merge!.

h = {}
h.merge!(key: "bar")
# => {:key=>"bar"}

Prevent browser caching of AJAX call result

A small addition to the excellent answers given: If you're running with a non-ajax backup solution for users without javascript, you will have to get those server-side headers correct anyway. This is not impossible, although I understand those that give it up ;)

I'm sure there's another question on SO that will give you the full set of headers that are appropriate. I am not entirely conviced miceus reply covers all the bases 100%.

How do AX, AH, AL map onto EAX?

No -- AL is the 8 least significant bits of AX. AX is the 16 least significant bits of EAX.

Perhaps it's easiest to deal with if we start with 04030201h in eax. In this case, AX will contain 0201h, AH wil contain 02h and AL will contain 01h.

SQL Server 2008- Get table constraints

Here's a script to get foreign keys:

    SELECT TOP(150)
       t.[name] AS [Table],
       cols.[name] AS [Column],
       t2.[name] AS [Referenced Table],
       c2.[name] AS [Referenced Column],
       constr.[name] AS [Constraint]
  FROM sys.tables t
 INNER JOIN sys.foreign_keys constr ON constr.parent_object_id = t.object_id
 INNER JOIN sys.tables t2 ON t2.object_id = constr.referenced_object_id
 INNER JOIN sys.foreign_key_columns fkc ON fkc.constraint_object_id = constr.object_id
 INNER JOIN sys.columns cols ON cols.object_id = fkc.parent_object_id AND cols.column_id = fkc.parent_column_id
 INNER JOIN sys.columns c2 ON c2.object_id = fkc.referenced_object_id AND c2.column_id = fkc.referenced_column_id
 --WHERE t.[name] IN ('?', '?', ...)
 ORDER BY t.[Name], cols.[name]

how to git commit a whole folder?

I ran into the same problem. Placing a forward slash after the folder name worked for me.

ex: git add foldername/

Does VBA have Dictionary Structure?

The scripting runtime dictionary seems to have a bug that can ruin your design at advanced stages.

If the dictionary value is an array, you cannot update values of elements contained in the array through a reference to the dictionary.

Remove '\' char from string c#

Try to replace

string result = line.Replace("\\","");

Android Studio Image Asset Launcher Icon Background Color

These are the steps I took to make an image transparent:

1- I used an online website which makes the image transparent, there are a lot of them. For me, I use this https://www241.lunapic.com/editor/?action=transparent and sometimes this http://www.online-image-editor.com/help/transparency

2- In Android Studio (I'm using version 3.1.3), open Image Asset from app > res (right click) > New > Image Asset Image Asset

3- In the Path, choose the location of the transparent image which you downloaded from the online website, and make the other options as shown, then Next, then Finish. The five different sizes of image mdpi(48×48), hdpi(72×72), xhdpi(96×96), xxhdpi(144×144), and xxxhdpi(192×192) will be created in the res/mipmap-density folders. Image Asset Configuration

4- If you need sizes (dimensions) different from above, you can use this website http://nsimage.brosteins.com/ to upload your PNG image of biggest size that will be used in xxxhdpi. After uploading, you can download a zip file containing the five different sizes of image in the res/drawable-density folders. enter image description here

Fitting a Normal distribution to 1D data

There is a much simpler way to do it using seaborn:

import seaborn as sns
from scipy.stats import norm

data = norm.rvs(5,0.4,size=1000) # you can use a pandas series or a list if you want

sns.distplot(data)
plt.show()

output:

enter image description here

for more information:seaborn.distplot

What is the best way to clone/deep copy a .NET generic Dictionary<string, T>?

In the case you have a Dictionary of "object" and object can be anything like (double, int, ... or ComplexClass):

Dictionary<string, object> dictSrc { get; set; }

public class ComplexClass : ICloneable
{
    
    private Point3D ...;
    private Vector3D ....;
    [...]

    public object Clone()
    {
        ComplexClass clone = new ComplexClass();
        clone = (ComplexClass)this.MemberwiseClone();
        return clone;
    }

}


dictSrc["toto"] = new ComplexClass()
dictSrc["tata"] = 12.3
...

dictDest = dictSrc.ToDictionary(entry => entry.Key,
                                entry => ((entry.Value is ICloneable) ? (entry.Value as ICloneable).Clone() : entry.Value) );


.htaccess deny from all

This syntax has changed with the newer Apache HTTPd server, please see upgrade to apache 2.4 doc for full details.

2.2 configuration syntax was

Order deny,allow
Deny from all

2.4 configuration now is

Require all denied

Thus, this 2.2 syntax

order deny,allow
deny from all
allow from 127.0.0.1

Would ne now written

Require local

Check if multiple strings exist in another string

You can use any:

a_string = "A string is more than its parts!"
matches = ["more", "wholesome", "milk"]

if any(x in a_string for x in matches):

Similarly to check if all the strings from the list are found, use all instead of any.

how do I initialize a float to its max/min value?

May I suggest that you initialize your "max and min so far" variables not to infinity, but to the first number in the array?

Change HTML email body font type and size in VBA

FYI I did a little research as well and if the name of the font-family you want to apply contains spaces (as an example I take Gill Alt One MT Light), you should write it this way :

strbody= "<BODY style=" & Chr(34) & "font-family:Gill Alt One MT Light" & Chr(34) & ">" & YOUR_TEXT & "</BODY>"

How to use enums in C++

I think your root issue is the use of . instead of ::, which will use the namespace.

Try:

enum Days {Saturday, Sunday, Tuesday, Wednesday, Thursday, Friday};
Days day = Days::Saturday;
if(Days::Saturday == day)  // I like literals before variables :)
{
    std::cout<<"Ok its Saturday";
}

QuotaExceededError: Dom exception 22: An attempt was made to add something to storage that exceeded the quota

I happened to run with the same issue in iOS 7 (with some devices no simulators).

Looks like Safari in iOS 7 has a lower storage quota, which apparently is reached by having a long history log.

I guess the best practice will be to catch the exception.

The Modernizr project has an easy patch, you should try something similar: https://github.com/Modernizr/Modernizr/blob/master/feature-detects/storage/localstorage.js

Error creating bean with name 'entityManagerFactory' defined in class path resource : Invocation of init method failed

People using Java 9 include this dependency:

<dependency>
    <groupId>javax.xml.bind</groupId>
    <artifactId>jaxb-api</artifactId>
    <version>2.3.0</version>
</dependency>

Creating a BLOB from a Base64 string in JavaScript

For all copy-paste lovers out there like me, here is a cooked download function which works on Chrome, Firefox and Edge:

window.saveFile = function (bytesBase64, mimeType, fileName) {
var fileUrl = "data:" + mimeType + ";base64," + bytesBase64;
fetch(fileUrl)
    .then(response => response.blob())
    .then(blob => {
        var link = window.document.createElement("a");
        link.href = window.URL.createObjectURL(blob, { type: mimeType });
        link.download = fileName;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    });
}

What is two way binding?

Two-way binding just means that:

  1. When properties in the model get updated, so does the UI.
  2. When UI elements get updated, the changes get propagated back to the model.

Backbone doesn't have a "baked-in" implementation of #2 (although you can certainly do it using event listeners). Other frameworks like Knockout do wire up two-way binding automagically.


enter image description here


In Backbone, you can easily achieve #1 by binding a view's "render" method to its model's "change" event. To achieve #2, you need to also add a change listener to the input element, and call model.set in the handler.

Here's a Fiddle with two-way binding set up in Backbone.

typeof operator in C

It's not exactly an operator, rather a keyword. And no, it doesn't do any runtime-magic.

Force IE compatibility mode off using tags

The meta tag solution wasn't working for us but setting it in the response header did:

header('X-UA-Compatible: IE=edge,chrome=1');

Define css class in django Forms

Answered my own question. Sigh

http://docs.djangoproject.com/en/dev/ref/forms/widgets/#django.forms.Widget.attrs

I didn't realize it was passed into the widget constructor.

How can I retrieve Id of inserted entity using Entity framework?

The object you're saving should have a correct Id after propagating changes into database.

MySQL root password change

You have to reset the password! steps for mac osx(tested and working) and ubuntu

Stop MySQL

$ sudo /usr/local/mysql/support-files/mysql.server stop

Start it in safe mode:

$ sudo mysqld_safe --skip-grant-tables

(above line is the whole command)

This will be an ongoing command until the process is finished so open another shell/terminal window, log in without a password:

$ mysql -u root

mysql> UPDATE mysql.user SET Password=PASSWORD('password') WHERE User='root';

Start MySQL

sudo /usr/local/mysql/support-files/mysql.server start

your new password is 'password'.

Windows task scheduler error 101 launch failure code 2147943785

The user that is configured to run this scheduled task must have "Log on as a batch job" rights on the computer that hosts the exe you are launching. This can be configured on the local security policy of the computer that hosts the exe. You can change the policy (on the server hosting the exe) under

Administrative Tools -> Local Security Policy -> Local Policies -> User Rights Assignment -> Log On As Batch Job

Add your user to this list (you could also make the user account a local admin on the machine hosting the exe).

Finally, you could also simply copy your exe from the network location to your local computer and run it from there instead.

Note also that a domain policy could be restricting "Log on as a batch job" rights at your organization.

How to split/partition a dataset into training and test datasets for, e.g., cross validation?

Thanks pberkes for your answer. I just modified it to avoid (1) replacement while sampling (2) duplicated instances occurred in both training and testing:

training_idx = np.random.choice(X.shape[0], int(np.round(X.shape[0] * 0.8)),replace=False)
training_idx = np.random.permutation(np.arange(X.shape[0]))[:np.round(X.shape[0] * 0.8)]
    test_idx = np.setdiff1d( np.arange(0,X.shape[0]), training_idx)

Convert a string to integer with decimal in Python

You could use:

s = '23.245678'
i = int(float(s))

Check if object value exists within a Javascript array of objects and if not add a new object to array

It's rather trivial to check for existing username:

var arr = [{ id: 1, username: 'fred' }, 
  { id: 2, username: 'bill'}, 
  { id: 3, username: 'ted' }];

function userExists(username) {
  return arr.some(function(el) {
    return el.username === username;
  }); 
}

console.log(userExists('fred')); // true
console.log(userExists('bred')); // false

But it's not so obvious what to do when you have to add a new user to this array. The easiest way out - just pushing a new element with id equal to array.length + 1:

function addUser(username) {
  if (userExists(username)) {
    return false; 
  }
  arr.push({ id: arr.length + 1, username: username });
  return true;
}

addUser('fred'); // false
addUser('bred'); // true, user `bred` added

It will guarantee the IDs uniqueness, but will make this array look a bit strange if some elements will be taken off its end.

Numpy: Creating a complex array from 2 real ones?

If you really want to eke out performance (with big arrays), numexpr can be used, which takes advantage of multiple cores.

Setup:

>>> import numpy as np
>>> Data = np.random.randn(64, 64, 64, 2)
>>> x, y = Data[...,0], Data[...,1]

With numexpr:

>>> import numexpr as ne
>>> %timeit result = ne.evaluate("complex(x, y)")
573 µs ± 21.1 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

Compared to fast numpy method:

>>> %timeit result = np.empty(x.shape, dtype=complex); result.real = x; result.imag = y
1.39 ms ± 5.74 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

Convert a Pandas DataFrame to a dictionary

The to_dict() method sets the column names as dictionary keys so you'll need to reshape your DataFrame slightly. Setting the 'ID' column as the index and then transposing the DataFrame is one way to achieve this.

to_dict() also accepts an 'orient' argument which you'll need in order to output a list of values for each column. Otherwise, a dictionary of the form {index: value} will be returned for each column.

These steps can be done with the following line:

>>> df.set_index('ID').T.to_dict('list')
{'p': [1, 3, 2], 'q': [4, 3, 2], 'r': [4, 0, 9]}

In case a different dictionary format is needed, here are examples of the possible orient arguments. Consider the following simple DataFrame:

>>> df = pd.DataFrame({'a': ['red', 'yellow', 'blue'], 'b': [0.5, 0.25, 0.125]})
>>> df
        a      b
0     red  0.500
1  yellow  0.250
2    blue  0.125

Then the options are as follows.

dict - the default: column names are keys, values are dictionaries of index:data pairs

>>> df.to_dict('dict')
{'a': {0: 'red', 1: 'yellow', 2: 'blue'}, 
 'b': {0: 0.5, 1: 0.25, 2: 0.125}}

list - keys are column names, values are lists of column data

>>> df.to_dict('list')
{'a': ['red', 'yellow', 'blue'], 
 'b': [0.5, 0.25, 0.125]}

series - like 'list', but values are Series

>>> df.to_dict('series')
{'a': 0       red
      1    yellow
      2      blue
      Name: a, dtype: object, 

 'b': 0    0.500
      1    0.250
      2    0.125
      Name: b, dtype: float64}

split - splits columns/data/index as keys with values being column names, data values by row and index labels respectively

>>> df.to_dict('split')
{'columns': ['a', 'b'],
 'data': [['red', 0.5], ['yellow', 0.25], ['blue', 0.125]],
 'index': [0, 1, 2]}

records - each row becomes a dictionary where key is column name and value is the data in the cell

>>> df.to_dict('records')
[{'a': 'red', 'b': 0.5}, 
 {'a': 'yellow', 'b': 0.25}, 
 {'a': 'blue', 'b': 0.125}]

index - like 'records', but a dictionary of dictionaries with keys as index labels (rather than a list)

>>> df.to_dict('index')
{0: {'a': 'red', 'b': 0.5},
 1: {'a': 'yellow', 'b': 0.25},
 2: {'a': 'blue', 'b': 0.125}}

Curl and PHP - how can I pass a json through curl by PUT,POST,GET

You can use this small library: https://github.com/ledfusion/php-rest-curl

Making a call is as simple as:

// GET
$result = RestCurl::get($URL, array('id' => 12345678));

// POST
$result = RestCurl::post($URL, array('name' => 'John'));

// PUT
$result = RestCurl::put($URL, array('$set' => array('lastName' => "Smith")));

// DELETE
$result = RestCurl::delete($URL); 

And for the $result variable:

  • $result['status'] is the HTTP response code
  • $result['data'] an array with the JSON response parsed
  • $result['header'] a string with the response headers

Hope it helps

Repeat each row of data.frame the number of times specified in a column

I know this is not the case but if you need to keep the original freq column, you can use another tidyverse approach together with rep:

library(purrr)

df <- data.frame(var1 = c('a', 'b', 'c'), var2 = c('d', 'e', 'f'), freq = 1:3)

df %>% 
  map_df(., rep, .$freq)
#> # A tibble: 6 x 3
#>   var1  var2   freq
#>   <fct> <fct> <int>
#> 1 a     d         1
#> 2 b     e         2
#> 3 b     e         2
#> 4 c     f         3
#> 5 c     f         3
#> 6 c     f         3

Created on 2019-12-21 by the reprex package (v0.3.0)

Video format or MIME type is not supported

In my case, this error:

Video format or MIME type is not supported.

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

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

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

Best way to save a trained model in PyTorch?

It depends on what you want to do.

Case # 1: Save the model to use it yourself for inference: You save the model, you restore it, and then you change the model to evaluation mode. This is done because you usually have BatchNorm and Dropout layers that by default are in train mode on construction:

torch.save(model.state_dict(), filepath)

#Later to restore:
model.load_state_dict(torch.load(filepath))
model.eval()

Case # 2: Save model to resume training later: If you need to keep training the model that you are about to save, you need to save more than just the model. You also need to save the state of the optimizer, epochs, score, etc. You would do it like this:

state = {
    'epoch': epoch,
    'state_dict': model.state_dict(),
    'optimizer': optimizer.state_dict(),
    ...
}
torch.save(state, filepath)

To resume training you would do things like: state = torch.load(filepath), and then, to restore the state of each individual object, something like this:

model.load_state_dict(state['state_dict'])
optimizer.load_state_dict(state['optimizer'])

Since you are resuming training, DO NOT call model.eval() once you restore the states when loading.

Case # 3: Model to be used by someone else with no access to your code: In Tensorflow you can create a .pb file that defines both the architecture and the weights of the model. This is very handy, specially when using Tensorflow serve. The equivalent way to do this in Pytorch would be:

torch.save(model, filepath)

# Then later:
model = torch.load(filepath)

This way is still not bullet proof and since pytorch is still undergoing a lot of changes, I wouldn't recommend it.

How to calculate the sum of the datatable column in asp.net?

Try this

int sum = 0;
foreach (DataRow dr in dt.Rows)
{
     dynamic value = dr[index].ToString();
     if (!string.IsNullOrEmpty(value))
     { 
         sum += Convert.ToInt32(value);
     }
}

Visual Studio Code - Convert spaces to tabs

  1. Highlight your Code (in file)
  2. Click Tab Size in bottom righthand corner of application window Tab Size in bottom righthand corner of application window image
  3. Select the appropriate Convert Indentation to Tabs Select the appropriate Convert Indentation to Tabs image

How to get ID of the last updated row in MySQL?

I've found an answer to this problem :)

SET @update_id := 0;
UPDATE some_table SET column_name = 'value', id = (SELECT @update_id := id)
WHERE some_other_column = 'blah' LIMIT 1; 
SELECT @update_id;

EDIT by aefxx

This technique can be further expanded to retrieve the ID of every row affected by an update statement:

SET @uids := null;
UPDATE footable
   SET foo = 'bar'
 WHERE fooid > 5
   AND ( SELECT @uids := CONCAT_WS(',', fooid, @uids) );
SELECT @uids;

This will return a string with all the IDs concatenated by a comma.

How to programmatically tell if a Bluetooth device is connected?

Big thanks to Skylarsutton for his answer. I'm posting this as a response to his, but because I'm posting code I can't reply as a comment. I already upvoted his answer so am not looking for any points. Just paying it forward.

For some reason BluetoothAdapter.ACTION_ACL_CONNECTED could not be resolved by Android Studio. Perhaps it was deprecated in Android 4.2.2? Here is a modification of his code. The registration code is the same; the receiver code differs slightly. I use this in a service which updates a Bluetooth-connected flag that other parts of the app reference.

    public void onCreate() {
        //...
        IntentFilter filter = new IntentFilter();
        filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
        filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED);
        filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
        this.registerReceiver(BTReceiver, filter);
    }

    //The BroadcastReceiver that listens for bluetooth broadcasts
    private final BroadcastReceiver BTReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();

        if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
            //Do something if connected
            Toast.makeText(getApplicationContext(), "BT Connected", Toast.LENGTH_SHORT).show();
        }
        else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
            //Do something if disconnected
            Toast.makeText(getApplicationContext(), "BT Disconnected", Toast.LENGTH_SHORT).show();
        }
        //else if...
    }
};

How would I get a cron job to run every 30 minutes?

You mention you are using OS X- I have used cronnix in the past. It's not as geeky as editing it yourself, but it helped me learn what the columns are in a jiffy. Just a thought.

Error: the entity type requires a primary key

Make sure you have the following condition:

  1. Use [key] if your primary key name is not Id or ID.
  2. Use the public keyword.
  3. Primary key should have getter and setter.

Example:

public class MyEntity {
   [key]
   public Guid Id {get; set;}
}

How to serialize Joda DateTime with Jackson JSON processor?

For those with Spring Boot you have to add the module to your context and it will be added to your configuration like this.

@Bean
public Module jodaTimeModule() {
    return new JodaModule();
}

And if you want to use the new java8 time module jsr-310.

@Bean
public Module jodaTimeModule() {
    return new JavaTimeModule();
}

How can I pad a String in Java?

Padding to 10 characters:

String.format("%10s", "foo").replace(' ', '*');
String.format("%-10s", "bar").replace(' ', '*');
String.format("%10s", "longer than 10 chars").replace(' ', '*');

output:

  *******foo
  bar*******
  longer*than*10*chars

Display '*' for characters of password:

String password = "secret123";
String padded = String.format("%"+password.length()+"s", "").replace(' ', '*');

output has the same length as the password string:

  secret123
  *********

Ansible: get current target host's IP address

http://docs.ansible.com/ansible/latest/plugins/lookup/dig.html

so in template, for e. g.:

{{ lookup('dig', ansible_host) }}

Notes:

  • Since not only DNS name could be used in inventory a check if it's not IP already better be added
  • Obviously enough this receipt wouldn't work as intended for indirect host specifications (like using jump hosts, for e. g.)

But still it serves 99 % (figuratively speaking) of use cases.

MySQL stored procedure return value

Update your SP and handle exception in it using declare handler with get diagnostics so that you will know if there is an exception. e.g.

CREATE DEFINER=`root`@`localhost` PROCEDURE `validar_egreso`(
IN codigo_producto VARCHAR(100),
IN cantidad INT,
OUT valido INT(11)
)
BEGIN
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
    GET DIAGNOSTICS CONDITION 1
    @p1 = RETURNED_SQLSTATE, @p2 = MESSAGE_TEXT;
    SELECT @p1, @p2;
END
DECLARE resta INT(11);
SET resta = 0;

SELECT (s.stock - cantidad) INTO resta
FROM stock AS s
WHERE codigo_producto = s.codigo;

IF (resta > s.stock_minimo) THEN
    SET valido = 1;
ELSE
    SET valido = -1;
END IF;
SELECT valido;
END

jQuery equivalent to Prototype array.last()

url : www.mydomain.com/user1/1234

$.params = window.location.href.split("/"); $.params[$.params.length-1];

You can split based on your query string separator

get jquery `$(this)` id

this is the DOM element on which the event was hooked. this.id is its ID. No need to wrap it in a jQuery instance to get it, the id property reflects the attribute reliably on all browsers.

$("select").change(function() {    
    alert("Changed: " + this.id);
}

Live example

You're not doing this in your code sample, but if you were watching a container with several form elements, that would give you the ID of the container. If you want the ID of the element that triggered the event, you could get that from the event object's target property:

$("#container").change(function(event) {
    alert("Field " + event.target.id + " changed");
});

Live example

(jQuery ensures that the change event bubbles, even on IE where it doesn't natively.)

Default value in Go's method

NO,but there are some other options to implement default value. There are some good blog posts on the subject, but here are some specific examples.


**Option 1:** The caller chooses to use default values
// Both parameters are optional, use empty string for default value
func Concat1(a string, b int) string {
  if a == "" {
    a = "default-a"
  }
  if b == 0 {
    b = 5
  }

  return fmt.Sprintf("%s%d", a, b)
}

**Option 2:** A single optional parameter at the end
// a is required, b is optional.
// Only the first value in b_optional will be used.
func Concat2(a string, b_optional ...int) string {
  b := 5
  if len(b_optional) > 0 {
    b = b_optional[0]
  }

  return fmt.Sprintf("%s%d", a, b)
}

**Option 3:** A config struct
// A declarative default value syntax
// Empty values will be replaced with defaults
type Parameters struct {
  A string `default:"default-a"` // this only works with strings
  B string // default is 5
}

func Concat3(prm Parameters) string {
  typ := reflect.TypeOf(prm)

  if prm.A == "" {
    f, _ := typ.FieldByName("A")
    prm.A = f.Tag.Get("default")
  }

  if prm.B == 0 {
    prm.B = 5
  }

  return fmt.Sprintf("%s%d", prm.A, prm.B)
}

**Option 4:** Full variadic argument parsing (javascript style)
func Concat4(args ...interface{}) string {
  a := "default-a"
  b := 5

  for _, arg := range args {
    switch t := arg.(type) {
      case string:
        a = t
      case int:
        b = t
      default:
        panic("Unknown argument")
    }
  }

  return fmt.Sprintf("%s%d", a, b)
}

Mysql SELECT CASE WHEN something then return field

You are mixing the 2 different CASE syntaxes inappropriately.

Use this style (Searched)

  CASE  
  WHEN u.nnmu ='0' THEN mu.naziv_mesta
  WHEN u.nnmu ='1' THEN m.naziv_mesta
 ELSE 'GRESKA'
 END as mesto_utovara,

Or this style (Simple)

  CASE u.nnmu 
  WHEN '0' THEN mu.naziv_mesta
  WHEN '1' THEN m.naziv_mesta
 ELSE 'GRESKA'
 END as mesto_utovara,

Not This (Simple but with boolean search predicates)

  CASE u.nnmu 
  WHEN u.nnmu ='0' THEN mu.naziv_mesta
  WHEN u.nnmu ='1' THEN m.naziv_mesta
 ELSE 'GRESKA'
 END as mesto_utovara,

In MySQL this will end up testing whether u.nnmu is equal to the value of the boolean expression u.nnmu ='0' itself. Regardless of whether u.nnmu is 1 or 0 the result of the case expression itself will be 1

For example if nmu = '0' then (nnmu ='0') evaluates as true (1) and (nnmu ='1') evaluates as false (0). Substituting these into the case expression gives

 SELECT CASE  '0'
  WHEN 1 THEN '0'
  WHEN 0 THEN '1'
 ELSE 'GRESKA'
 END as mesto_utovara

if nmu = '1' then (nnmu ='0') evaluates as false (0) and (nnmu ='1') evaluates as true (1). Substituting these into the case expression gives

 SELECT CASE  '1'
  WHEN 0 THEN '0'
  WHEN 1 THEN '1'
 ELSE 'GRESKA'
 END as mesto_utovara

How to install mod_ssl for Apache httpd?

I found I needed to enable the SSL module in Apache (obviously prefix commands with sudo if you are not running as root):

a2enmod ssl

then restart Apache:

/etc/init.d/apache2 restart

More details of SSL in Apache for Ubuntu / Debian here.

SHOW PROCESSLIST in MySQL command: sleep

Sleep meaning that thread is do nothing. Time is too large beacuse anthor thread query,but not disconnect server, default wait_timeout=28800;so you can set values smaller,eg 10. also you can kill the thread.

How can I reorder my divs using only CSS?

This can be done with CSS only!

Please check my answer to this similar question:

https://stackoverflow.com/a/25462829/1077230

I don't want to double post my answer but the short of it is that the parent needs to become a flexbox element. Eg:

(only using the webkit vendor prefix here.)

#main {
    display: -webkit-box;
    display: -webkit-flex;
    display: flex;
    -webkit-box-orient: vertical;
    -webkit-flex-direction: column;
    flex-direction: column;
    -webkit-box-align: start;
    -webkit-align-items: flex-start;
    align-items: flex-start;
}

Then, swap divs around by indicating their order with:

#main > div#one{
    -webkit-box-ordinal-group: 2;
    -moz-box-ordinal-group: 2;
    -ms-flex-order: 2;
    -webkit-order: 2;
    order: 2;
    overflow:visible;
}

#main > div#two{
    -webkit-box-ordinal-group: 1;
    -moz-box-ordinal-group: 1;
    -ms-flex-order: 1;
    -webkit-order: 1;
    order: 1;
}

How to write to a file without overwriting current contents?

Instead of "w" use "a" (append) mode with open function:

with open("games.txt", "a") as text_file:

How can I get stock quotes using Google Finance API?

This is no longer an active API for google, you can try Xignite, although they charge: http://www.xignite.com

^[A-Za-Z ][A-Za-z0-9 ]* regular expression?

How about

^[A-Za-z]\S*

a letter followed by 0 or more non-space characters (will include all special symbols).

ImportError: No module named requests

Requests is not a built in module (does not come with the default python installation), so you will have to install it:

OSX/Linux

Use $ pip install requests (or pip3 install requests for python3) if you have pip installed. If pip is installed but not in your path you can use python -m pip install requests (or python3 -m pip install requests for python3)

Alternatively you can also use sudo easy_install -U requests if you have easy_install installed.

Alternatively you can use your systems package manager:

For centos: yum install python-requests For Ubuntu: apt-get install python-requests

Windows

Use pip install requests (or pip3 install requests for python3) if you have pip installed and Pip.exe added to the Path Environment Variable. If pip is installed but not in your path you can use python -m pip install requests (or python3 -m pip install requests for python3)

Alternatively from a cmd prompt, use > Path\easy_install.exe requests, where Path is your Python*\Scripts folder, if it was installed. (For example: C:\Python32\Scripts)

If you manually want to add a library to a windows machine, you can download the compressed library, uncompress it, and then place it into the Lib\site-packages folder of your python path. (For example: C:\Python27\Lib\site-packages)

From Source (Universal)

For any missing library, the source is usually available at https://pypi.python.org/pypi/. You can download requests here: https://pypi.python.org/pypi/requests

On mac osx and windows, after downloading the source zip, uncompress it and from the termiminal/cmd run python setup.py install from the uncompressed dir.

(source)

Open the terminal in visual studio?

Visual Studio 2019 update:

Now vs has built-in terminal

TerminalSS

View > Terminal (Ctrl+")

To change default terminal

Tools > Options - Terminal > Set As Default

enter image description here


Before Visual Studio 2019

From comments best answer is from @Hans Passant

  1. Add an external tool.

Tools > External Tools > Add

Title: Terminal (or name it yourself)

Command=cmd.exe Or Command=powershell.exe

Arguments= /k

Initial Directory=$(ProjectDir)

  1. Tools > Terminal (or whatever you put in title)

  2. Enjoy!

Firebase: how to generate a unique numeric ID for key?

As explained above, you can use the Firebase default push id.

If you want something numeric you can do something based on the timestamp to avoid collisions

f.e. something based on date,hour,second,ms, and some random int at the end

01612061353136799031

Which translates to:

016-12-06 13:53:13:679 9031

It all depends on the precision you need (social security numbers do the same with some random characters at the end of the date). Like how many transactions will be expected during the day, hour or second. You may want to lower precision to favor ease of typing.

You can also do a transaction that increments the number id, and on success you will have a unique consecutive number for that user. These can be done on the client or server side.

(https://firebase.google.com/docs/database/android/read-and-write)

Using BeautifulSoup to extract text without tags

I think you can get it using subc1.text.

>>> html = """
<p>
    <strong class="offender">YOB:</strong> 1987<br />
    <strong class="offender">RACE:</strong> WHITE<br />
    <strong class="offender">GENDER:</strong> FEMALE<br />
    <strong class="offender">HEIGHT:</strong> 5'05''<br />
    <strong class="offender">WEIGHT:</strong> 118<br />
    <strong class="offender">EYE COLOR:</strong> GREEN<br />
    <strong class="offender">HAIR COLOR:</strong> BROWN<br />
</p>
"""
>>> from bs4 import BeautifulSoup
>>> soup = BeautifulSoup(html)
>>> print soup.text


YOB: 1987
RACE: WHITE
GENDER: FEMALE
HEIGHT: 5'05''
WEIGHT: 118
EYE COLOR: GREEN
HAIR COLOR: BROWN

Or if you want to explore it, you can use .contents :

>>> p = soup.find('p')
>>> from pprint import pprint
>>> pprint(p.contents)
[u'\n',
 <strong class="offender">YOB:</strong>,
 u' 1987',
 <br/>,
 u'\n',
 <strong class="offender">RACE:</strong>,
 u' WHITE',
 <br/>,
 u'\n',
 <strong class="offender">GENDER:</strong>,
 u' FEMALE',
 <br/>,
 u'\n',
 <strong class="offender">HEIGHT:</strong>,
 u" 5'05''",
 <br/>,
 u'\n',
 <strong class="offender">WEIGHT:</strong>,
 u' 118',
 <br/>,
 u'\n',
 <strong class="offender">EYE COLOR:</strong>,
 u' GREEN',
 <br/>,
 u'\n',
 <strong class="offender">HAIR COLOR:</strong>,
 u' BROWN',
 <br/>,
 u'\n']

and filter out the necessary items from the list:

>>> data = dict(zip([x.text for x in p.contents[1::4]], [x.strip() for x in p.contents[2::4]]))
>>> pprint(data)
{u'EYE COLOR:': u'GREEN',
 u'GENDER:': u'FEMALE',
 u'HAIR COLOR:': u'BROWN',
 u'HEIGHT:': u"5'05''",
 u'RACE:': u'WHITE',
 u'WEIGHT:': u'118',
 u'YOB:': u'1987'}

How can I set the request header for curl?

Just use the -H parameter several times:

curl -H "Accept-Charset: utf-8" -H "Content-Type: application/x-www-form-urlencoded" http://www.some-domain.com

How to execute VBA Access module?

Well it depends on how you want to call this code.

Are you calling it from a button click on a form, if so then on the properties for the button on form, go to the Event tab, then On Click item, select [Event Procedure]. This will open the VBA code window for that button. You would then call your Module.Routine and then this would trigger when you click the button.

Similar to this:

Private Sub Command1426_Click()
    mdl_ExportMorning.ExportMorning
End Sub

This button click event calls the Module mdl_ExportMorning and the Public Sub ExportMorning.

How to style a div to have a background color for the entire width of the content, and not just for the width of the display?

It is because you set the width:100% which by definition only spans the width of the screen. You want to set the min-width:100% which sets it to the width of the screen... with the ability to grow beyond that.

Also make sure you set min-width:100% for body and html.

Set Content-Type to application/json in jsp file

You can do via Page directive.

For example:

<%@ page language="java" contentType="application/json; charset=UTF-8"
    pageEncoding="UTF-8"%>
  • contentType="mimeType [ ;charset=characterSet ]" | "text/html;charset=ISO-8859-1"

The MIME type and character encoding the JSP file uses for the response it sends to the client. You can use any MIME type or character set that are valid for the JSP container. The default MIME type is text/html, and the default character set is ISO-8859-1.

Create an empty data.frame

I created empty data frame using following code

df = data.frame(id = numeric(0), jobs = numeric(0));

and tried to bind some rows to populate the same as follows.

newrow = c(3, 4)
df <- rbind(df, newrow)

but it started giving incorrect column names as follows

  X3 X4
1  3  4

Solution to this is to convert newrow to type df as follows

newrow = data.frame(id=3, jobs=4)
df <- rbind(df, newrow)

now gives correct data frame when displayed with column names as follows

  id nobs
1  3   4 

How to check is Apache2 is stopped in Ubuntu?

In the command line type service apache2 status then hit enter. The result should say:

Apache2 is running (pid xxxx)

jQuery Cross Domain Ajax

Unfortunately it seems that this web service returns JSON which contains another JSON - parsing contents of the inner JSON is successful. The solution is ugly but works for me. JSON.parse(...) tries to convert the entire string and fails. Assuming that you always get the answer starting with {"AuthenticateUserResult": and interesting data is after this, try:

$.ajax({
    type: 'GET',
    dataType: "text",
    crossDomain: true,
    url: "http://someotherdomain.com/service.svc",
    success: function (responseData, textStatus, jqXHR) {
        var authResult = JSON.parse(
            responseData.replace(
                '{"AuthenticateUserResult":"', ''
            ).replace('}"}', '}')
        );
        console.log("in");
    },
    error: function (responseData, textStatus, errorThrown) {
        alert('POST failed.');
    }
});

It is very important that dataType must be text to prevent auto-parsing of malformed JSON you are receiving from web service.

Basically, I'm wiping out the outer JSON by removing topmost braces and key AuthenticateUserResult along with leading and trailing quotation marks. The result is a well formed JSON, ready for parsing.

How to open a web page from my application?

System.Diagnostics.Process.Start("http://www.webpage.com");

One of many ways.

How to improve a case statement that uses two columns

You could do it this way:

-- Notice how STATE got moved inside the condition:
CASE WHEN STATE = 2 AND RetailerProcessType IN (1, 2) THEN '"AUTHORISED"'
     WHEN STATE = 1 AND RetailerProcessType = 2 THEN '"PENDING"'
     ELSE '"DECLINED"'
END

The reason you can do an AND here is that you are not checking the CASE of STATE, but instead you are CASING Conditions.

The key part here is that the STATE condition is a part of the WHEN.

How to detect scroll position of page using jQuery

GET Scroll Position:

var scrolled_val = window.scrollY;

DETECT Scroll Position:

$(window).scroll
(
     function (event) 
     {
          var scrolled_val = window.scrollY;
          alert(scrolled_val);
     }
 );

Confirm deletion using Bootstrap 3 modal box

Create modal dialog in HTML with id="confirmation" and use function showConfirmation.

Also remember you should to unbind (modal.unbind()) cancel and success buttons after hide modal dialog. If you do not make this you will get double binding. For example: if you open dialog once and press 'Cancel' and then open dialog in second time and press 'Ok' you will get 2 executions of success callback.

showConfirmation = function(title, message, success, cancel) {
    title = title ? title : 'Are you sure?';
    var modal = $("#confirmation");
    modal.find(".modal-title").html(title).end()
        .find(".modal-body").html(message).end()
        .modal({ backdrop: 'static', keyboard: false })
        .on('hidden.bs.modal', function () {
            modal.unbind();
        });
    if (success) {
        modal.one('click', '.modal-footer .btn-primary', success);
    }
    if (cancel) {
        modal.one('click', '.modal-header .close, .modal-footer .btn-default', cancel);
    }
};

// bind confirmation dialog on delete buttons
$(document).on("click", ".delete-event, .delete-all-event", function(event){
    event.preventDefault();
    var self = $(this);
    var url = $(this).data('url');
    var success = function(){
        alert('window.location.href=url');
    }
    var cancel = function(){
        alert('Cancel');
    };
    if (self.data('confirmation')) {
        var title = self.data('confirmation-title') ? self.data('confirmation-title') : undefined;
        var message = self.data('confirmation');
        showConfirmation(title, message, success, cancel);
    } else {
        success();
    }
});

https://jsfiddle.net/yiiBoy/hne9sp6g/

Iterate two Lists or Arrays with one ForEach statement in C#

This is known as a Zip operation and will be supported in .NET 4.

With that, you would be able to write something like:

var numbers = new [] { 1, 2, 3, 4 };
var words = new [] { "one", "two", "three", "four" };

var numbersAndWords = numbers.Zip(words, (n, w) => new { Number = n, Word = w });
foreach(var nw in numbersAndWords)
{
    Console.WriteLine(nw.Number + nw.Word);
}

As an alternative to the anonymous type with the named fields, you can also save on braces by using a Tuple and its static Tuple.Create helper:

foreach (var nw in numbers.Zip(words, Tuple.Create)) 
{
    Console.WriteLine(nw.Item1 + nw.Item2);
}

Displaying all table names in php from MySQL database

The square brackets in your code are used in the mysql documentation to indicate groups of optional parameters. They should not be in the actual query.

The only command you actually need is:

show tables;

If you want tables from a specific database, let's say the database "books", then it would be

show tables from books;

You only need the LIKE part if you want to find tables whose names match a certain pattern. e.g.,

show tables from books like '%book%';

would show you the names of tables that have "book" somewhere in the name.

Furthermore, just running the "show tables" query will not produce any output that you can see. SQL answers the query and then passes it to PHP, but you need to tell PHP to echo it to the page.

Since it sounds like you're very new to SQL, I'd recommend running the mysql client from the command line (or using phpmyadmin, if it's installed on your system). That way you can see the results of various queries without having to go through PHP's functions for sending queries and receiving results.

If you have to use PHP, here's a very simple demonstration. Try this code after connecting to your database:

$result = mysql_query("show tables"); // run the query and assign the result to $result
while($table = mysql_fetch_array($result)) { // go through each row that was returned in $result
    echo($table[0] . "<BR>");    // print the table that was returned on that row.
}

How long will my session last?

If session.cookie_lifetime is 0, the session cookie lives until the browser is quit.

EDIT: Others have mentioned the session.gc_maxlifetime setting. When session garbage collection occurs, the garbage collector will delete any session data that has not been accessed in longer than session.gc_maxlifetime seconds. To set the time-to-live for the session cookie, call session_set_cookie_params() or define the session.cookie_lifetime PHP setting. If this setting is greater than session.gc_maxlifetime, you should increase session.gc_maxlifetime to a value greater than or equal to the cookie lifetime to ensure that your sessions won't expire.

FFmpeg on Android

For various reasons, Multimedia was and is never easy in terms of achieving the task without compromising on efficiency. ffmpeg is an effort in improving it day by day. It supports different formats of codecs and containers.

Now to answer the question of how to use this library, i would say that it is not so simple to write it here. But i can guide you in following ways.

1) Inside the ffmpeg directory of source code, you have output_example.c or api_example.c. Here, you can see the code where encoding/decoding is done. You will get an idea as to which API's inside ffmpeg you should call. This would be your first step.

2) Dolphin player is a open source project for Android. Currently it is having bugs but developers are working continuously. In that project you have the whole setup ready which you can use to continue your investigation. Here is a link to the project from code.google.com or run the command "git clone https://code.google.com/p/dolphin-player/" in a terminal. You can see two projects named P and P86 . You can use either of them.

Extra tip i would like to offer is that when you are building the ffmpeg code, inside build.sh you need to enable the muxers/demuxers/encoders/decoders of the formats you want to use. Else the corresponding code will not be included in the libraries. It took a lot of time for me to realize this. So thought of sharing it with you.

Few Basics : When we say a video file, ex : avi, it is combination of both audio and video

Video file = Video + Audio


Video = Codec + Muxer + Demuxer

codec = encoder + Decoder

=> Video = encoder + decoder + Muxer + Demuxer(Mpeg4 + Mpeg4 + avi +avi - Example for avi container)


Audio = Codec + Muxer + Demuxer

codec = encoder + Decoder

=> Audio = encoder + decoder + Muxer + Demuxer(mp2 + mp2 + avi + avi - Example for avi container)


Codec(name is deriverd from a combination of en*co*der/*dec*oder) is just a part of format which defines the algorithms used to encode/decode a frame. AVI is not a codec, it is a container which uses Video codec of Mpeg4 and Audio codec of mp2.

Muxer/demuxer is used to combine/separate the frames from a file used while encoding/decoding.

So if you want to use avi format, you need to enable Video components + Audio components.

Ex, for avi, you need to enable the following. mpeg4 Encoder, mpeg4 decoder, mp2 encoder, mp2 decoder, avi muxer, avi demuxer.

phewwwwwww...

Programmatically build.sh should contain the following code:

--enable-muxer=avi --enable-demuxer=avi (Generic for both audio/video. generally Specific to a container)
--enable-encoder=mpeg4 --enable-decoder=mpeg4(For video support)
--enable-encoder=mp2 --enable-decoder=mp2 (For Audio support)

Hope i idid not confuse you more after all this...

Thanks, Any assistance needed, please let me know.

Check if instance is of a type

bool isValid = c.GetType() == typeof(TForm) ? true : false;

or simpler

bool isValid = c.GetType() == typeof(TForm);

repaint() in Java

You're doing things in the wrong order.

You need to first add all JComponents to the JFrame, and only then call pack() and then setVisible(true) on the JFrame

If you later added JComponents that could change the GUI's size you will need to call pack() again, and then repaint() on the JFrame after doing so.

Initialising an array of fixed size in python

Why don't these questions get answered with the obvious answer?

a = numpy.empty(n, dtype=object)

This creates an array of length n that can store objects. It can't be resized or appended to. In particular, it doesn't waste space by padding its length. This is the Python equivalent of Java's

Object[] a = new Object[n];

If you're really interested in performance and space and know that your array will only store certain numeric types then you can change the dtype argument to some other value like int. Then numpy will pack these elements directly into the array rather than making the array reference int objects.

HTML5 Email Validation

I know you are not after the Javascript solution however there are some things such as the customized validation message that, from my experience, can only be done using JS.

Also, by using JS, you can dynamically add the validation to all input fields of type email within your site instead of having to modify every single input field.

var validations ={
    email: [/^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/, 'Please enter a valid email address']
};
$(document).ready(function(){
    // Check all the input fields of type email. This function will handle all the email addresses validations
    $("input[type=email]").change( function(){
        // Set the regular expression to validate the email 
        validation = new RegExp(validations['email'][0]);
        // validate the email value against the regular expression
        if (!validation.test(this.value)){
            // If the validation fails then we show the custom error message
            this.setCustomValidity(validations['email'][1]);
            return false;
        } else {
            // This is really important. If the validation is successful you need to reset the custom error message
            this.setCustomValidity('');
        }
    });
})

Default value to a parameter while passing by reference in C++

You can do it for a const reference, but not for a non-const one. This is because C++ does not allow a temporary (the default value in this case) to be bound to non-const reference.

One way round this would be to use an actual instance as the default:

static int AVAL = 1;

void f( int & x = AVAL ) {
   // stuff
} 

int main() {
     f();       // equivalent to f(AVAL);
}

but this is of very limited practical use.

How to remove .html from URL?

I use this .htacess for removing .html extantion from my url site, please verify this is correct code:

    RewriteEngine on
RewriteBase /
RewriteCond %{http://www.proofers.co.uk/new} !(\.[^./]+)$
RewriteCond %{REQUEST_fileNAME} !-d
RewriteCond %{REQUEST_fileNAME} !-f
RewriteRule (.*) /$1.html [L]
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /([^.]+)\.html\ HTTP
RewriteRule ^([^.]+)\.html$ http://www.proofers.co.uk/new/$1 [R=301,L]

How to detect the end of loading of UITableView

To know when a table view finishes loading its content, we first need to have a basic understanding of how the views are put on screen.

In the life cycle of an app, there are 4 key moments :

  1. The app receives an event (touch, timer, block dispatched etc)
  2. The app handles the event (it modifies a constraint, starts an animation, changes background etc)
  3. The app computes the new view hierarchy
  4. The app renders the view hierarchy and displays it

The 2 and 3 times are totally separated. Why ? For performance reasons, we don't want to perform all the computations (done at 3) each time a modification is done.

So, I think you are facing a case like this :

tableView.reloadData()
tableView.visibleCells.count // wrong count oO

What’s wrong here?

A table view reloads its content lazily. Actually, if you call reloadData multiple times it won’t create performance issues. The table view only recomputes its content size based on its delegate implementation and waits the moment 3 to loads its cells. This time is called a layout pass.

Okay, how to get involved in the layout pass?

During the layout pass, the app computes all the frames of the view hierarchy. To get involved, you can override the dedicated methods layoutSubviews, updateLayoutConstraints etc in a UIView subclass and the equivalent methods in a view controller subclass.

That’s exactly what a table view does. It overrides layoutSubviews and based on your delegate implementation adds or removes cells. It calls cellForRow right before adding and laying out a new cell, willDisplay right after. If you called reloadData or just added the table view to the hierarchy, the tables view adds as many cells as necessary to fill its frame at this key moment.

Alright, but now, how to know when a tables view has finished reloading its content?

We can rephrase this question: how to know when a table view has finished laying out its subviews?

The easiest way is to get into the layout of the table view :

class MyTableView: UITableView {
    func layoutSubviews() {
        super.layoutSubviews()
        // the displayed cells are loaded
    }
}

Note that this method is called many times in the life cycle of the table view. Because of the scroll and the dequeue behavior of the table view, cells are modified, removed and added often. But it works, right after the super.layoutSubviews(), cells are loaded. This solution is equivalent to wait the willDisplay event of the last index path. This event is called during the execution of layoutSubviews of the table view when a cell is added.

Another way is to be notified when the app finishes a layout pass.

As described in the documentation, you can use an option of the UIView.animate(withDuration:completion):

tableView.reloadData()
UIView.animate(withDuration: 0) {
    // layout done
}

This solution works but the screen will refresh once between the time the layout is done and the time the block is executed. This is equivalent to the DispatchMain.async solution but specified.

Alternatively, I would prefer to force the layout of the table view

There is a dedicated method to force any view to compute immediately its subview frames layoutIfNeeded:

tableView.reloadData()
table.layoutIfNeeded()
// layout done

Be careful however, doing so will remove the lazy loading used by the system. Calling those methods repeatedly could create performance issues. Make sure that they won’t be called before the frame of the table view is computed, otherwise the table view will be loaded again and you won’t be notified.


I think there is no perfect solution. Subclassing classes could lead to trubles. A layout pass starts from the top and goes to the bottom so it’s not easy to get notified when all the layout is done. And layoutIfNeeded() could create performance issues etc.

Vue - Deep watching an array of objects and calculating the change?

Your comparison function between old value and new value is having some issue. It is better not to complicate things so much, as it will increase your debugging effort later. You should keep it simple.

The best way is to create a person-component and watch every person separately inside its own component, as shown below:

<person-component :person="person" v-for="person in people"></person-component>

Please find below a working example for watching inside person component. If you want to handle it on parent side, you may use $emit to send an event upwards, containing the id of modified person.

_x000D_
_x000D_
Vue.component('person-component', {_x000D_
    props: ["person"],_x000D_
    template: `_x000D_
        <div class="person">_x000D_
            {{person.name}}_x000D_
            <input type='text' v-model='person.age'/>_x000D_
        </div>`,_x000D_
    watch: {_x000D_
        person: {_x000D_
            handler: function(newValue) {_x000D_
                console.log("Person with ID:" + newValue.id + " modified")_x000D_
                console.log("New age: " + newValue.age)_x000D_
            },_x000D_
            deep: true_x000D_
        }_x000D_
    }_x000D_
});_x000D_
_x000D_
new Vue({_x000D_
    el: '#app',_x000D_
    data: {_x000D_
        people: [_x000D_
          {id: 0, name: 'Bob', age: 27},_x000D_
          {id: 1, name: 'Frank', age: 32},_x000D_
          {id: 2, name: 'Joe', age: 38}_x000D_
        ]_x000D_
    }_x000D_
});
_x000D_
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>_x000D_
<body>_x000D_
    <div id="app">_x000D_
        <p>List of people:</p>_x000D_
        <person-component :person="person" v-for="person in people"></person-component>_x000D_
    </div>_x000D_
</body>
_x000D_
_x000D_
_x000D_

What is the equivalent of 'describe table' in SQL Server?

SELECT C.COLUMN_NAME, C.IS_NULLABLE, C.DATA_TYPE, TC.CONSTRAINT_TYPE, C.COLUMN_DEFAULT
    FROM INFORMATION_SCHEMA.COLUMNS AS C
    FULL JOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE AS CC ON C.COLUMN_NAME = CC.COLUMN_NAME 
    FULL JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS TC ON CC.CONSTRAINT_NAME = TC.CONSTRAINT_NAME
WHERE C.TABLE_NAME = '<Table Name>';

Sample Output

list all files in the folder and also sub folders

Use FileUtils from Apache commons.

listFiles

public static Collection<File> listFiles(File directory,
                                         String[] extensions,
                                         boolean recursive)
Finds files within a given directory (and optionally its subdirectories) which match an array of extensions.
Parameters:
directory - the directory to search in
extensions - an array of extensions, ex. {"java","xml"}. If this parameter is null, all files are returned.
recursive - if true all subdirectories are searched as well
Returns:
an collection of java.io.File with the matching files

Best practice multi language website

I had the same probem a while ago, before starting using Symfony framework.

  1. Just use a function __() which has arameters pageId (or objectId, objectTable described in #2), target language and an optional parameter of fallback (default) language. The default language could be set in some global config in order to have an easier way to change it later.

  2. For storing the content in database i used following structure: (pageId, language, content, variables).

    • pageId would be a FK to your page you want to translate. if you have other objects, like news, galleries or whatever, just split it into 2 fields objectId, objectTable.

    • language - obviously it would store the ISO language string EN_en, LT_lt, EN_us etc.

    • content - the text you want to translate together with the wildcards for variable replacing. Example "Hello mr. %%name%%. Your account balance is %%balance%%."

    • variables - the json encoded variables. PHP provides functions to quickly parse these. Example "name: Laurynas, balance: 15.23".

    • you mentioned also slug field. you could freely add it to this table just to have a quick way to search for it.

  3. Your database calls must be reduced to minimum with caching the translations. It must be stored in PHP array, because it is the fastest structure in PHP language. How you will make this caching is up to you. From my experience you should have a folder for each language supported and an array for each pageId. The cache should be rebuilt after you update the translation. ONLY the changed array should be regenerated.

  4. i think i answered that in #2

  5. your idea is perfectly logical. this one is pretty simple and i think will not make you any problems.

URLs should be translated using the stored slugs in the translation table.

Final words

it is always good to research the best practices, but do not reinvent the wheel. just take and use the components from well known frameworks and use them.

take a look at Symfony translation component. It could be a good code base for you.

Extracting a parameter from a URL in WordPress

Why not just use the WordPress get_query_var() function? WordPress Code Reference

// Test if the query exists at the URL
if ( get_query_var('ppc') ) {

    // If so echo the value
    echo get_query_var('ppc');

}

Since get_query_var can only access query parameters available to WP_Query, in order to access a custom query var like 'ppc', you will also need to register this query variable within your plugin or functions.php by adding an action during initialization:

add_action('init','add_get_val');
function add_get_val() { 
    global $wp; 
    $wp->add_query_var('ppc'); 
}

Or by adding a hook to the query_vars filter:

function add_query_vars_filter( $vars ){
  $vars[] = "ppc";
  return $vars;
}
add_filter( 'query_vars', 'add_query_vars_filter' );

SimpleDateFormat returns 24-hour date: how to get 12-hour date?

SimpleDateFormat dateFormat = new SimpleDateFormat("dd/mm/yyyy hh:mm:ss a");

use hh in place of HH

Filter Linq EXCEPT on properties

MoreLinq has something useful for this MoreLinq.Source.MoreEnumerable.ExceptBy

https://github.com/gsscoder/morelinq/blob/master/MoreLinq/ExceptBy.cs

namespace MoreLinq
{
    using System;
    using System.Collections.Generic;
    using System.Linq;

    static partial class MoreEnumerable
    {
        /// <summary>
        /// Returns the set of elements in the first sequence which aren't
        /// in the second sequence, according to a given key selector.
        /// </summary>
        /// <remarks>
        /// This is a set operation; if multiple elements in <paramref name="first"/> have
        /// equal keys, only the first such element is returned.
        /// This operator uses deferred execution and streams the results, although
        /// a set of keys from <paramref name="second"/> is immediately selected and retained.
        /// </remarks>
        /// <typeparam name="TSource">The type of the elements in the input sequences.</typeparam>
        /// <typeparam name="TKey">The type of the key returned by <paramref name="keySelector"/>.</typeparam>
        /// <param name="first">The sequence of potentially included elements.</param>
        /// <param name="second">The sequence of elements whose keys may prevent elements in
        /// <paramref name="first"/> from being returned.</param>
        /// <param name="keySelector">The mapping from source element to key.</param>
        /// <returns>A sequence of elements from <paramref name="first"/> whose key was not also a key for
        /// any element in <paramref name="second"/>.</returns>

        public static IEnumerable<TSource> ExceptBy<TSource, TKey>(this IEnumerable<TSource> first,
            IEnumerable<TSource> second,
            Func<TSource, TKey> keySelector)
        {
            return ExceptBy(first, second, keySelector, null);
        }

        /// <summary>
        /// Returns the set of elements in the first sequence which aren't
        /// in the second sequence, according to a given key selector.
        /// </summary>
        /// <remarks>
        /// This is a set operation; if multiple elements in <paramref name="first"/> have
        /// equal keys, only the first such element is returned.
        /// This operator uses deferred execution and streams the results, although
        /// a set of keys from <paramref name="second"/> is immediately selected and retained.
        /// </remarks>
        /// <typeparam name="TSource">The type of the elements in the input sequences.</typeparam>
        /// <typeparam name="TKey">The type of the key returned by <paramref name="keySelector"/>.</typeparam>
        /// <param name="first">The sequence of potentially included elements.</param>
        /// <param name="second">The sequence of elements whose keys may prevent elements in
        /// <paramref name="first"/> from being returned.</param>
        /// <param name="keySelector">The mapping from source element to key.</param>
        /// <param name="keyComparer">The equality comparer to use to determine whether or not keys are equal.
        /// If null, the default equality comparer for <c>TSource</c> is used.</param>
        /// <returns>A sequence of elements from <paramref name="first"/> whose key was not also a key for
        /// any element in <paramref name="second"/>.</returns>

        public static IEnumerable<TSource> ExceptBy<TSource, TKey>(this IEnumerable<TSource> first,
            IEnumerable<TSource> second,
            Func<TSource, TKey> keySelector,
            IEqualityComparer<TKey> keyComparer)
        {
            if (first == null) throw new ArgumentNullException("first");
            if (second == null) throw new ArgumentNullException("second");
            if (keySelector == null) throw new ArgumentNullException("keySelector");
            return ExceptByImpl(first, second, keySelector, keyComparer);
        }

        private static IEnumerable<TSource> ExceptByImpl<TSource, TKey>(this IEnumerable<TSource> first,
            IEnumerable<TSource> second,
            Func<TSource, TKey> keySelector,
            IEqualityComparer<TKey> keyComparer)
        {
            var keys = new HashSet<TKey>(second.Select(keySelector), keyComparer);
            foreach (var element in first)
            {
                var key = keySelector(element);
                if (keys.Contains(key))
                {
                    continue;
                }
                yield return element;
                keys.Add(key);
            }
        }
    }
}

How to assign a select result to a variable?

In order to assign a variable safely you have to use the SET-SELECT statement:

SET @PrimaryContactKey = (SELECT c.PrimaryCntctKey
    FROM tarcustomer c, tarinvoice i
    WHERE i.custkey = c.custkey 
    AND i.invckey = @tmp_key)

Make sure you have both a starting and an ending parenthesis!

The reason the SET-SELECT version is the safest way to set a variable is twofold.

1. The SELECT returns several posts

What happens if the following select results in several posts?

SELECT @PrimaryContactKey = c.PrimaryCntctKey
FROM tarcustomer c, tarinvoice i
WHERE i.custkey = c.custkey 
    AND i.invckey = @tmp_key

@PrimaryContactKey will be assigned the value from the last post in the result.

In fact @PrimaryContactKey will be assigned one value per post in the result, so it will consequently contain the value of the last post the SELECT-command was processing.

Which post is "last" is determined by any clustered indexes or, if no clustered index is used or the primary key is clustered, the "last" post will be the most recently added post. This behavior could, in a worst case scenario, be altered every time the indexing of the table is changed.

With a SET-SELECT statement your variable will be set to null.

2. The SELECT returns no posts

What happens, when using the second version of the code, if your select does not return a result at all?

In a contrary to what you may believe the value of the variable will not be null - it will retain it's previous value!

This is because, as stated above, SQL will assign a value to the variable once per post - meaning it won't do anything with the variable if the result contains no posts. So, the variable will still have the value it had before you ran the statement.

With the SET-SELECT statement the value will be null.

See also: SET versus SELECT when assigning variables?

How to disable an input box using angular.js

I created a directive for this (angular stable 1.0.8)

<input type="text" input-disabled="editableInput" />
<button ng-click="editableInput = !editableInput">enable/disable</button>

app.controller("myController", function(){
  $scope.editableInput = false;
});

app.directive("inputDisabled", function(){
  return function(scope, element, attrs){
    scope.$watch(attrs.inputDisabled, function(val){
      if(val)
        element.removeAttr("disabled");
      else
        element.attr("disabled", "disabled");
    });
  }
});

Animate background image change with jQuery

building on XGreen's approach above, with a few tweaks you can have an animated looping background. See here for example:

http://jsfiddle.net/srd76/36/

$(document).ready(function(){

var images = Array("http://placekitten.com/500/200",
               "http://placekitten.com/499/200",
               "http://placekitten.com/501/200",
               "http://placekitten.com/500/199");
var currimg = 0;


function loadimg(){

   $('#background').animate({ opacity: 1 }, 500,function(){

        //finished animating, minifade out and fade new back in           
        $('#background').animate({ opacity: 0.7 }, 100,function(){

            currimg++;

            if(currimg > images.length-1){

                currimg=0;

            }

            var newimage = images[currimg];

            //swap out bg src                
            $('#background').css("background-image", "url("+newimage+")"); 

            //animate fully back in
            $('#background').animate({ opacity: 1 }, 400,function(){

                //set timer for next
                setTimeout(loadimg,5000);

            });

        });

    });

  }
  setTimeout(loadimg,5000);

});

When correctly use Task.Run and when just async-await

One issue with your ContentLoader is that internally it operates sequentially. A better pattern is to parallelize the work and then sychronize at the end, so we get

public class PageViewModel : IHandle<SomeMessage>
{
   ...

   public async void Handle(SomeMessage message)
   {
      ShowLoadingAnimation();

      // makes UI very laggy, but still not dead
      await this.contentLoader.LoadContentAsync(); 

      HideLoadingAnimation();   
   }
}

public class ContentLoader 
{
    public async Task LoadContentAsync()
    {
        var tasks = new List<Task>();
        tasks.Add(DoCpuBoundWorkAsync());
        tasks.Add(DoIoBoundWorkAsync());
        tasks.Add(DoCpuBoundWorkAsync());
        tasks.Add(DoSomeOtherWorkAsync());

        await Task.WhenAll(tasks).ConfigureAwait(false);
    }
}

Obviously, this doesn't work if any of the tasks require data from other earlier tasks, but should give you better overall throughput for most scenarios.

gson throws MalformedJsonException

From my recent experience, JsonReader#setLenient basically makes the parser very tolerant, even to allow malformed JSON data.

But for certain data retrieved from your trusted RESTful API(s), this error might be caused by trailing white spaces. In such cases, simply trim the data would avoid the error:

String trimmed = result1.trim();

Then gson.fromJson(trimmed, T) might work. Surely this only covers a special case, so YMMV.

git: diff between file in local repo and origin

For that I wrote a bash script:

#set -x 
branchname=`git branch | grep -F '*' |  awk '{print $2}'`
echo $branchname
git fetch origin ${branchname}
for file in `git status | awk '{if ($1 == "modified:") print $2;}'`
do
echo "PLEASE CHECK OUT GIT DIFF FOR "$file 
git difftool  FETCH_HEAD $file ;
done

In the above script, I fetch the remote main branch (not necessary its master branch ANY branch) to FETCH_HEAD, then make a list of my modified file only and compare modified files to git difftool.

There are many difftool supported by git, I configured Meld Diff Viewer for good GUI comparison.
From the above script, I have prior knowledge what changes done by other teams in same file, before I follow git stages untrack-->staged-->commit which help me to avoid unnecessary resolve merge conflict with remote team or make new local branch and compare and merge on the main branch.

jQuery click event not working after adding class

I Know this is an old topic...but none of the above helped me. And after searching a lot and trying everything...I came up with this.

First remove the click code out of the $(document).ready part and put it in a separate section. then put your click code in an $(function(){......}); code.

Like this:

<script>
  $(function(){
    //your click code
    $("a.tabclick").on('click',function() {
      //do something
    });
  });
</script>

Pass variables between two PHP pages without using a form or the URL of page

Sessions would be good choice for you. Take a look at these two examples from PHP Manual:

Code of page1.php

<?php
// page1.php

session_start();

echo 'Welcome to page #1';

$_SESSION['favcolor'] = 'green';
$_SESSION['animal']   = 'cat';
$_SESSION['time']     = time();

// Works if session cookie was accepted
echo '<br /><a href="page2.php">page 2</a>';

// Or pass along the session id, if needed
echo '<br /><a href="page2.php?' . SID . '">page 2</a>';
?>

Code of page2.php

<?php
// page2.php

session_start();

echo 'Welcome to page #2<br />';

echo $_SESSION['favcolor']; // green
echo $_SESSION['animal'];   // cat
echo date('Y m d H:i:s', $_SESSION['time']);

// You may want to use SID here, like we did in page1.php
echo '<br /><a href="page1.php">page 1</a>';
?>

To clear up things - SID is PHP's predefined constant which contains session name and its id. Example SID value:

PHPSESSID=d78d0851898450eb6aa1e6b1d2a484f1

Best practices for circular shift (rotate) operations in C++

In details you can apply the following logic.

If Bit Pattern is 33602 in Integer

1000 0011 0100 0010

and you need to Roll over with 2 right shifs then: first make a copy of bit pattern and then left shift it: Length - RightShift i.e. length is 16 right shift value is 2 16 - 2 = 14

After 14 times left shifting you get.

1000 0000 0000 0000

Now right shift the value 33602, 2 times as required. You get

0010 0000 1101 0000

Now take an OR between 14 time left shifted value and 2 times right shifted value.

1000 0000 0000 0000
0010 0000 1101 0000
===================
1010 0000 1101 0000
===================

And you get your shifted rollover value. Remember bit wise operations are faster and this don't even required any loop.

event.returnValue is deprecated. Please use the standard event.preventDefault() instead

This is a warning related to the fact that most JavaScript frameworks (jQuery, Angular, YUI, Bootstrap...) offer backward support for old-nasty-most-hated Internet Explorer starting from IE8 down to IE6 :/

One day that backward compatibility support will be dropped (for IE8/7/6 since IE9 deals with it), and you will no more see this warning (and other IEish bugs)..

It's a question of time (now IE8 has 10% worldwide share, once it reaches 1% it is DEAD), meanwhile, just ignore the warning and stay zen :)

.NET DateTime to SqlDateTime Conversion

Also please remember resolutions [quantum of time] are different.

http://msdn.microsoft.com/en-us/library/system.data.sqltypes.sqldatetime.aspx

SQL one is 3.33 ms and .net one is 100 ns.

Installing SciPy with pip

Besides all of these answers, If you install python of 32bit on your 64bit machine, you have to download scipy of 32-bit irrespective of your machine. http://www.lfd.uci.edu/~gohlke/pythonlibs/ In the above URL you can download the packages and command is: pip install

Ruby on Rails: Clear a cached page

More esoteric ways:

Rails.cache.delete_matched("*")

For Redis:

Redis.new.keys.each{ |key| Rails.cache.delete(key) }

How to edit one specific row in Microsoft SQL Server Management Studio 2008?

The menu location seems to have changed to:

Query Designer --> Pane --> SQL

How do I specify the columns and rows of a multiline Editor-For in ASP.MVC?

Use TextAreaFor

@Html.TextAreaFor(model => model.Description, new { @class = "whatever-class", @cols = 80, @rows = 10 })

or use style for multi-line class.

You could also write EditorTemplate for this.

Align text to the bottom of a div

Flex Solution

It is perfectly fine if you want to go with the display: table-cell solution. But instead of hacking it out, we have a better way to accomplish the same using display: flex;. flex is something which has a decent support.

_x000D_
_x000D_
.wrap {_x000D_
  height: 200px;_x000D_
  width: 200px;_x000D_
  border: 1px solid #aaa;_x000D_
  margin: 10px;_x000D_
  display: flex;_x000D_
}_x000D_
_x000D_
.wrap span {_x000D_
  align-self: flex-end;_x000D_
}
_x000D_
<div class="wrap">_x000D_
  <span>Align me to the bottom</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

In the above example, we first set the parent element to display: flex; and later, we use align-self to flex-end. This helps you push the item to the end of the flex parent.


Old Solution (Valid if you are not willing to use flex)

If you want to align the text to the bottom, you don't have to write so many properties for that, using display: table-cell; with vertical-align: bottom; is enough

_x000D_
_x000D_
div {_x000D_
  display: table-cell;_x000D_
  vertical-align: bottom;_x000D_
  border: 1px solid #f00;_x000D_
  height: 100px;_x000D_
  width: 100px;_x000D_
}
_x000D_
<div>Hello</div>
_x000D_
_x000D_
_x000D_

(Or JSFiddle)

Horizontal scroll css?

use max-width instead of width

max-width:530px;

demo:http://jsfiddle.net/FPBWr/161/

How to manually trigger validation with jQuery validate?

My approach was as below. Now I just wanted my form to be validated when one specific checkbox was clicked/changed:

$('#myForm input:checkbox[name=yourChkBxName]').click(
 function(e){
  $("#myForm").valid();
}
)

Switch android x86 screen resolution

Set resolution in android x86

Libvirt/qemu

Temporarily

  • Add nomodeset and vga=ask to android x86 grub entry's kernel loading options;
  • Find your best resolution and note the code you used.

Permanently

  • Convert that code to decimal from hex;
  • Add vga=decimal_code to your preferred entry in /mnt/grub/menu.lst (mounted if android is started in debug mode).

Parse String to Date with Different Format in Java

Check the javadocs for java.text.SimpleDateFormat It describes everything you need.

sudo: port: command not found

if you use zsh.please add flowing string to the line 'export PATH="..."' in file '~/.zshrc'

:/opt/local/bin:/opt/local/sbin

Get Application Directory

If you're trying to get access to a file, try the openFileOutput() and openFileInput() methods as described here. They automatically open input/output streams to the specified file in internal memory. This allows you to bypass the directory and File objects altogether which is a pretty clean solution.

How to select a specific node with LINQ-to-XML

Assuming the ID is unique:

var result = xmldoc.Element("Customers")
                   .Elements("Customer")
                   .Single(x => (int?)x.Attribute("ID") == 2);

You could also use First, FirstOrDefault, SingleOrDefault or Where, instead of Single for different circumstances.

How to prevent scientific notation in R?

To set the use of scientific notation in your entire R session, you can use the scipen option. From the documentation (?options):

‘scipen’: integer.  A penalty to be applied when deciding to print
          numeric values in fixed or exponential notation.  Positive
          values bias towards fixed and negative towards scientific
          notation: fixed notation will be preferred unless it is more
          than ‘scipen’ digits wider.

So in essence this value determines how likely it is that scientific notation will be triggered. So to prevent scientific notation, simply use a large positive value like 999:

options(scipen=999)

Output a NULL cell value in Excel

I've been frustrated by this problem as well. Find/Replace can be helpful though, because if you don't put anything in the "replace" field it will replace with an -actual- NULL. So the steps would be something along the lines of:

1: Place some unique string in your formula in place of the NULL output (i like to use a password-like string)

2: Run your formula

3: Open Find/Replace, and fill in the unique string as the search value. Leave "replace with" blank

4: Replace All

Obviously, this has limitations. It only works when the context allows you to do a find/replace, so for more dynamic formulas this won't help much. But, I figured I'd put it up here anyway.

Adding and removing extensionattribute to AD object

To clear the value you can always reset it to $Null. For example:

Set-Mailbox -Identity "username" -CustomAttribute1 $Null

Where can I set path to make.exe on Windows?

here I'm providing solution to setup terraform enviroment variable in windows to beginners.

  1. Download the terraform package from portal either 32/64 bit version.
  2. make a folder in C drive in program files if its 32 bit package you have to create folder inside on programs(x86) folder or else inside programs(64 bit) folder.
  3. Extract a downloaded file in this location or copy terraform.exe file into this folder. copy this path location like C:\Programfile\terraform\
  4. Then got to Control Panel -> System -> System settings -> Environment Variables

Open system variables, select the path > edit > new > place the terraform.exe file location like > C:\Programfile\terraform\

and Save it.

  1. Open new terminal and now check the terraform.

How to create json by JavaScript for loop?

If I want to create JavaScript Object from string generated by for loop then I would JSON to Object approach. I would generate JSON string by iterating for loop and then use any popular JavaScript Framework to evaluate JSON to Object.

I have used Prototype JavaScript Framework. I have two array with keys and values. I iterate through for loop and generate valid JSON string. I use evalJSON() function to convert JSON string to JavaScript object.

Here is example code. Tryout on your FireBug Console

var key = ["color", "size", "fabric"];
var value = ["Black", "XL", "Cotton"];

var json = "{ ";
for(var i = 0; i < key.length; i++) {
    (i + 1) == key.length ? json += "\"" + key[i] + "\" : \"" + value[i] + "\"" : json += "\"" + key[i] + "\" : \"" + value[i] + "\",";
}
json += " }";
var obj = json.evalJSON(true);
console.log(obj);