Programs & Examples On #Qglwidget

The QGLWidget class, part of the Qt framework, is a widget for rendering OpenGL graphics.

Error: expected type-specifier before 'ClassName'

For future people struggling with a similar problem, the situation is that the compiler simply cannot find the type you are using (even if your Intelisense can find it).

This can be caused in many ways:

  • You forgot to #include the header that defines it.
  • Your inclusion guards (#ifndef BLAH_H) are defective (your #ifndef BLAH_H doesn't match your #define BALH_H due to a typo or copy+paste mistake).
  • Your inclusion guards are accidentally used twice (two separate files both using #define MYHEADER_H, even if they are in separate directories)
  • You forgot that you are using a template (eg. new Vector() should be new Vector<int>())
  • The compiler is thinking you meant one scope when really you meant another (For example, if you have NamespaceA::NamespaceB, AND a <global scope>::NamespaceB, if you are already within NamespaceA, it'll look in NamespaceA::NamespaceB and not bother checking <global scope>::NamespaceB) unless you explicitly access it.
  • You have a name clash (two entities with the same name, such as a class and an enum member).

To explicitly access something in the global namespace, prefix it with ::, as if the global namespace is a namespace with no name (e.g. ::MyType or ::MyNamespace::MyType).

CORS header 'Access-Control-Allow-Origin' missing

You must have got the idea why you are getting this problem after going through above answers.

self.send_header('Access-Control-Allow-Origin', '*')

You just have to add the above line in your server side.

How to install a Python module via its setup.py in Windows?

setup.py is designed to be run from the command line. You'll need to open your command prompt (In Windows 7, hold down shift while right-clicking in the directory with the setup.py file. You should be able to select "Open Command Window Here").

From the command line, you can type

python setup.py --help

...to get a list of commands. What you are looking to do is...

python setup.py install

Spring CORS No 'Access-Control-Allow-Origin' header is present

Following on Omar's answer, I created a new class file in my REST API project called WebConfig.java with this configuration:

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {

  @Override
  public void addCorsMappings(CorsRegistry registry) {
    registry.addMapping("/**").allowedOrigins("*");
  }
} 

This allows any origin to access the API and applies it to all controllers in the Spring project.

IOError: [Errno 22] invalid mode ('r') or filename: 'c:\\Python27\test.txt'

\t is a tab character. Use a raw string instead:

test_file=open(r'c:\Python27\test.txt','r')

or double the slashes:

test_file=open('c:\\Python27\\test.txt','r')

or use forward slashes instead:

test_file=open('c:/Python27/test.txt','r')

Unknown SSL protocol error in connection

If you meet "Unknown SSL protocol error in connection to bitbucket.org:443" and you are in China, maybe github is been blocked by firewall temporarily. You can try to use VPN, which would work out. Good Luck!

jQuery Scroll to Div

Could just use JQuery position function to get coordinates of your div, then use javascript scroll:

var position = $("div").position();
scroll(0,position.top);

Changing case in Vim

Visual select the text, then U for uppercase or u for lowercase. To swap all casing in a visual selection, press ~ (tilde).

Without using a visual selection, gU<motion> will make the characters in motion uppercase, or use gu<motion> for lowercase.

For more of these, see Section 3 in Vim's change.txt help file.

How do you get the contextPath from JavaScript, the right way?

Reviewer the solution by this Checking the solution of this page, make the following solution I hope it works: Example:

Javascript:

var context = window.location.pathname.substring(0, window.location.pathname.indexOf("/",2)); 
var url =window.location.protocol+"//"+ window.location.host +context+"/bla/bla";

Using a Python subprocess call to invoke a Python script

First, check if somescript.py is executable and starts with something along the lines of #!/usr/bin/python. If this is done, then you can use subprocess.call('./somescript.py').

Or as another answer points out, you could do subprocess.call(['python', 'somescript.py']).

Check if string matches pattern

regular expressions make this easy ...

[A-Z] will match exactly one character between A and Z

\d+ will match one or more digits

() group things (and also return things... but for now just think of them grouping)

+ selects 1 or more

PHP array value passes to next row

Change the checkboxes so that the name includes the index inside the brackets:

<input type="checkbox" class="checkbox_veh" id="checkbox_addveh<?php echo $i; ?>" <?php if ($vehicle_feature[$i]->check) echo "checked"; ?> name="feature[<?php echo $i; ?>]" value="<?php echo $vehicle_feature[$i]->id; ?>"> 

The checkboxes that aren't checked are never submitted. The boxes that are checked get submitted, but they get numbered consecutively from 0, and won't have the same indexes as the other corresponding input fields.

Mocking python function based on input arguments

Just to show another way of doing it:

def mock_isdir(path):
    return path in ['/var/log', '/var/log/apache2', '/var/log/tomcat']

with mock.patch('os.path.isdir') as os_path_isdir:
    os_path_isdir.side_effect = mock_isdir

How do I determine k when using k-means clustering?

Another approach is using Self Organizing Maps (SOP) to find optimal number of clusters. The SOM (Self-Organizing Map) is an unsupervised neural network methodology, which needs only the input is used to clustering for problem solving. This approach used in a paper about customer segmentation.

The reference of the paper is

Abdellah Amine et al., Customer Segmentation Model in E-commerce Using Clustering Techniques and LRFM Model: The Case of Online Stores in Morocco, World Academy of Science, Engineering and Technology International Journal of Computer and Information Engineering Vol:9, No:8, 2015, 1999 - 2010

Toggle button using two image on different state

Do this:

<ToggleButton 
        android:id="@+id/toggle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/check"   <!--check.xml-->
        android:layout_margin="10dp"
        android:textOn=""
        android:textOff=""
        android:focusable="false"
        android:focusableInTouchMode="false"
        android:layout_centerVertical="true"/>

create check.xml in drawable folder

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- When selected, use grey -->
    <item android:drawable="@drawable/selected_image"
          android:state_checked="true" />
    <!-- When not selected, use white-->
    <item android:drawable="@drawable/unselected_image"
        android:state_checked="false"/>

 </selector>

The source was not found, but some or all event logs could not be searched

Didnt work for me.

I created a new key and string value and managed to get it working

Key= HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\eventlog\Application\<Your app name>\
String EventMessageFile value=C:\Windows\Microsoft.NET\Framework\v2.0.50727\EventLogMessages.dll

How can I split this comma-delimited string in Python?

Question is a little vague.

list_of_lines = multiple_lines.split("\n")
for line in list_of_lines:
    list_of_items_in_line = line.split(",")
    first_int = int(list_of_items_in_line[0])

etc.

Type converting slices of interfaces

Try interface{} instead. To cast back as slice, try

func foo(bar interface{}) {
    s := bar.([]string)
    // ...
}

How do I remove all non alphanumeric characters from a string except dash?

Here is a non-regex heap allocation friendly fast solution which was what I was looking for.

Unsafe edition.

public static unsafe void ToAlphaNumeric(ref string input)
{
    fixed (char* p = input)
    {
        int offset = 0;
        for (int i = 0; i < input.Length; i++)
        {
            if (char.IsLetterOrDigit(p[i]))
            {
                p[offset] = input[i];
                offset++;
            }
        }
        ((int*)p)[-1] = offset; // Changes the length of the string
        p[offset] = '\0';
    }
}

And for those who don't want to use unsafe or don't trust the string length hack.

public static string ToAlphaNumeric(string input)
{
    int j = 0;
    char[] newCharArr = new char[input.Length];

    for (int i = 0; i < input.Length; i++)
    {
        if (char.IsLetterOrDigit(input[i]))
        {
            newCharArr[j] = input[i];
            j++;
        }
    }

    Array.Resize(ref newCharArr, j);

    return new string(newCharArr);
}

Convert Swift string to array

Updated for Swift 4

Here are 3 ways.

//array of Characters
let charArr1 = [Character](myString)

//array of String.element
let charArr2 = Array(myString)

for char in myString {
  //char is of type Character
}

In some cases, what people really want is a way to convert a string into an array of little strings with 1 character length each. Here is a super efficient way to do that:

//array of String
var strArr = myString.map { String($0)}

Swift 3

Here are 3 ways.

let charArr1 = [Character](myString.characters)
let charArr2 = Array(myString.characters)
for char in myString.characters {
  //char is of type Character
}

In some cases, what people really want is a way to convert a string into an array of little strings with 1 character length each. Here is a super efficient way to do that:

var strArr = myString.characters.map { String($0)}

Or you can add an extension to String.

extension String {
   func letterize() -> [Character] {
     return Array(self.characters)
  }
}

Then you can call it like this:

let charArr = "Cat".letterize()

SQL : BETWEEN vs <= and >=

Disclaimer: Everything below is only anecdotal and drawn directly from my personal experience. Anyone that feels up to conducting a more empirically rigorous analysis is welcome to carry it out and down vote if I'm. I am also aware that SQL is a declarative language and you're not supposed to have to consider HOW your code is processed when you write it, but, because I value my time, I do.

There are infinite logically equivalent statements, but I'll consider three(ish).

Case 1: Two Comparisons in a standard order (Evaluation order fixed)

A >= MinBound AND A <= MaxBound

Case 2: Syntactic sugar (Evaluation order is not chosen by author)

A BETWEEN MinBound AND MaxBound

Case 3: Two Comparisons in an educated order (Evaluation order chosen at write time)

A >= MinBound AND A <= MaxBound

Or

A <= MaxBound AND A >= MinBound

In my experience, Case 1 and Case 2 do not have any consistent or notable differences in performance as they are dataset ignorant.

However, Case 3 can greatly improve execution times. Specifically, if you're working with a large data set and happen to have some heuristic knowledge about whether A is more likely to be greater than the MaxBound or lesser than the MinBound you can improve execution times noticeably by using Case 3 and ordering the comparisons accordingly.

One use case I have is querying a large historical dataset with non-indexed dates for records within a specific interval. When writing the query, I will have a good idea of whether or not more data exists BEFORE the specified interval or AFTER the specified interval and can order my comparisons accordingly. I've had execution times cut by as much as half depending on the size of the dataset, the complexity of the query, and the amount of records filtered by the first comparison.

Java 8 Lambda filter by Lists

Look this:

List<Client> result = clients
    .stream()
    .filter(c -> 
        (users.stream().map(User::getName).collect(Collectors.toList())).contains(c.getName()))
        .collect(Collectors.toList());

How do I create a MongoDB dump of my database?

You can also use gzip for taking backup of one collection and compressing the backup on the fly:

mongodump --db somedb --collection somecollection --out - | gzip > collectiondump.gz

or with a date in the file name:

mongodump --db somedb --collection somecollection --out - | gzip > dump_`date "+%Y-%m-%d"`.gz

Update:
Backup all collections of a database in a date folder. The files are gziped:

mongodump --db somedb --gzip --out /backups/`date +"%Y-%m-%d"`

Or for a single archive:

mongodump --db somedb --gzip --archive > dump_`date "+%Y-%m-%d"`.gz

Or when mongodb is running inside docker:

docker exec <CONTAINER> sh -c 'exec mongodump --db somedb --gzip --archive' > dump_`date "+%Y-%m-%d"`.gz

ASP.Net MVC Redirect To A Different View

Here's what you can do:

return View("another view name", anotherviewmodel);

Request failed: unacceptable content-type: text/html using AFNetworking 2.0

On the server side, I added:

header('Content-type: application/json');

into my .php code and this also fixed the problem.

Spring Boot - Loading Initial Data

In Spring Boot 2 data.sql was not working with me as in spring boot 1.5

import.sql

In addition, a file named import.sql in the root of the classpath is executed on startup if Hibernate creates the schema from scratch (that is, if the ddl-auto property is set to create or create-drop).

Note very important if you insert Keys cannot be duplicated do not use ddl-auto property is set to update because with each restart will insert same data again

For more information you vist spring websit

https://docs.spring.io/spring-boot/docs/current/reference/html/howto-database-initialization.html

How to clone a Date object?

Use the Date object's getTime() method, which returns the number of milliseconds since 1 January 1970 00:00:00 UTC (epoch time):

var date = new Date();
var copiedDate = new Date(date.getTime());

In Safari 4, you can also write:

var date = new Date();
var copiedDate = new Date(date);

...but I'm not sure whether this works in other browsers. (It seems to work in IE8).

How do I use an INSERT statement's OUTPUT clause to get the identity value?

You can either have the newly inserted ID being output to the SSMS console like this:

INSERT INTO MyTable(Name, Address, PhoneNo)
OUTPUT INSERTED.ID
VALUES ('Yatrix', '1234 Address Stuff', '1112223333')

You can use this also from e.g. C#, when you need to get the ID back to your calling app - just execute the SQL query with .ExecuteScalar() (instead of .ExecuteNonQuery()) to read the resulting ID back.

Or if you need to capture the newly inserted ID inside T-SQL (e.g. for later further processing), you need to create a table variable:

DECLARE @OutputTbl TABLE (ID INT)

INSERT INTO MyTable(Name, Address, PhoneNo)
OUTPUT INSERTED.ID INTO @OutputTbl(ID)
VALUES ('Yatrix', '1234 Address Stuff', '1112223333')

This way, you can put multiple values into @OutputTbl and do further processing on those. You could also use a "regular" temporary table (#temp) or even a "real" persistent table as your "output target" here.

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

Boto3 to download all files from a S3 Bucket

I have a workaround for this that runs the AWS CLI in the same process.

Install awscli as python lib:

pip install awscli

Then define this function:

from awscli.clidriver import create_clidriver

def aws_cli(*cmd):
    old_env = dict(os.environ)
    try:

        # Environment
        env = os.environ.copy()
        env['LC_CTYPE'] = u'en_US.UTF'
        os.environ.update(env)

        # Run awscli in the same process
        exit_code = create_clidriver().main(*cmd)

        # Deal with problems
        if exit_code > 0:
            raise RuntimeError('AWS CLI exited with code {}'.format(exit_code))
    finally:
        os.environ.clear()
        os.environ.update(old_env)

To execute:

aws_cli('s3', 'sync', '/path/to/source', 's3://bucket/destination', '--delete')

Open Facebook page from Android app?

Declare constants

  private String FACEBOOK_URL="https://www.facebook.com/approids";
    private String FACEBOOK_PAGE_ID="approids";

Declare Method

public String getFacebookPageURL(Context context) {
        PackageManager packageManager = context.getPackageManager();
        try {
            int versionCode = packageManager.getPackageInfo("com.facebook.katana", 0).versionCode;

            boolean activated =  packageManager.getApplicationInfo("com.facebook.katana", 0).enabled;
            if(activated){
                if ((versionCode >= 3002850)) {
                    Log.d("main","fb first url");
                    return "fb://facewebmodal/f?href=" + FACEBOOK_URL;
                } else {
                    return "fb://page/" + FACEBOOK_PAGE_ID;
                }
            }else{
                return FACEBOOK_URL;
            }
        } catch (PackageManager.NameNotFoundException e) {
            return FACEBOOK_URL;
        }
    }

Call Function

Intent facebookIntent = new Intent(Intent.ACTION_VIEW);
                String facebookUrl = getFacebookPageURL(MainActivity.this);
                facebookIntent.setData(Uri.parse(facebookUrl));
                startActivity(facebookIntent);

Python, print all floats to 2 decimal places in output

I have just discovered the round function - it is in Python 2.7, not sure about 2.6. It takes a float and the number of dps as arguments, so round(22.55555, 2) gives the result 22.56.

Creating a simple configuration file and parser in C++

SimpleConfigFile is a library that does exactly what you require and it is very simple to use.

# File file.cfg
url = http://example.com
file = main.exe
true = 0 

The following program reads the previous configuration file:

#include<iostream>
#include<string>
#include<vector>
#include "config_file.h"

int main(void)
{
    // Variables that we want to read from the config file
    std::string url, file;
    bool true_false;

    // Names for the variables in the config file. They can be different from the actual variable names.
    std::vector<std::string> ln = {"url","file","true"};

    // Open the config file for reading
    std::ifstream f_in("file.cfg");

    CFG::ReadFile(f_in, ln, url, file, true_false);
    f_in.close();

    std::cout << "url: " << url << std::endl;
    std::cout << "file: " << file << std::endl;
    std::cout << "true: " << true_false << std::endl;

    return 0;
}

The function CFG::ReadFile uses variadic templates. This way, you can pass the variables you want to read and the corresponding type is used for reading the data in the appropriate way.

Getting error "The package appears to be corrupt" while installing apk file

When you are releasing signed apk , please make sure you tick both v1 and v2 in signature versions

See below screenshot for more info Signed APK generation

Remove folder and its contents from git/GitHub's history

In addition to the popular answer above I would like to add a few notes for Windows-systems. The command

git filter-branch --tree-filter 'rm -rf node_modules' --prune-empty HEAD
  • works perfectly without any modification! Therefore, you must not use Remove-Item, del or anything else instead of rm -rf.

  • If you need to specify a path to a file or directory use slashes like ./path/to/node_modules

How do I get TimeSpan in minutes given two Dates?

TimeSpan span = end-start;
double totalMinutes = span.TotalMinutes;

Best practices for adding .gitignore file for Python projects?

Here are some other files that may be left behind by setuptools:

MANIFEST
*.egg-info

Fatal error: Namespace declaration statement has to be the very first statement in the script in

This thread seems to be talking about the same issue - it sounds like this error is usually caused by having some data sent out of the server before the namespace statement is encountered.

  1. Could your web hosting be inserting some code into your page before the PHP code?
  2. Is there a UTF-8 Byte Order Mark at the beginning of the document?

On the other hand, it could also be a bug in ImageUploader... the main PHP file puts the namespace after the class definition, which I haven't seen in the PHP documentation, which says it should be the very first PHP code. From this page:

Namespaces are declared using the namespace keyword. A file containing a namespace must declare the namespace at the top of the file before any other code - with one exception: the declare keyword.

There's no declare keyword here, so perhaps this is a bug in the source code that slips by the developer's version of PHP, because he doesn't put the namespace first:

<?php
class BulletProofException extends Exception{}

namespace BulletProof;
/**
 * BulletProof ImageUploder:
...

How to minify php page html output?

Thanks to Andrew. Here's what a did to use this in cakePHP:

  1. Download minify-2.1.7
  2. Unpack the file and copy min subfolder to cake's Vendor folder
  3. Creates MinifyCodeHelper.php in cake's View/Helper like this:

    App::import('Vendor/min/lib/Minify/', 'HTML');
    App::import('Vendor/min/lib/Minify/', 'CommentPreserver');
    App::import('Vendor/min/lib/Minify/CSS/', 'Compressor');
    App::import('Vendor/min/lib/Minify/', 'CSS');
    App::import('Vendor/min/lib/', 'JSMin');
    class MinifyCodeHelper extends Helper {
        public function afterRenderFile($file, $data) {
            if( Configure::read('debug') < 1 ) //works only e production mode
                $data = Minify_HTML::minify($data, array(
                    'cssMinifier' => array('Minify_CSS', 'minify'),
                    'jsMinifier' => array('JSMin', 'minify')
                ));
            return $data;
        }
    }
    
  4. Enabled my Helper in AppController

    public $helpers = array ('Html','...','MinifyCode');

5... Voila!

My conclusion: If apache's deflate and headers modules is disabled in your server your gain is 21% less size and 0.35s plus in request to compress (this numbers was in my case).

But if you had enable apache's modules the compressed response has no significant difference (1.3% to me) and the time to compress is the samne (0.3s to me).

So... why did I do that? 'couse my project's doc is all in comments (php, css and js) and my final user dont need to see this ;)

Angular, content type is not being sent with $http

You need to include a body with the request. Angular removes the content-type header otherwise.

Add data: '' to the argument to $http.

How to sort an array of associative arrays by value of a given key in PHP?

Here is a method that I found long ago and cleaned up a bit. This works great, and can be quickly changed to accept objects as well.

/**
 * A method for sorting arrays by a certain key:value.
 * SortByKey is the key you wish to sort by
 * Direction can be ASC or DESC.
 *
 * @param $array
 * @param $sortByKey
 * @param $sortDirection
 * @return array
 */
private function sortArray($array, $sortByKey, $sortDirection) {

    $sortArray = array();
    $tempArray = array();

    foreach ( $array as $key => $value ) {
        $tempArray[] = strtolower( $value[ $sortByKey ] );
    }

    if($sortDirection=='ASC'){ asort($tempArray ); }
        else{ arsort($tempArray ); }

    foreach ( $tempArray as $key => $temp ){
        $sortArray[] = $array[ $key ];
    }

    return $sortArray;

}

to change the method to sort objects simply change the following line:

$tempArray[] = strtolower( $value[ $sortByKey ] ); to $tempArray[] = strtolower( $value->$sortByKey );

To run the method simply do

sortArray($inventory,'price','ASC');

multiple prints on the same line in Python

Just in case you have pre-stored the values in an array, you can call them in the following format:

for i in range(0,n):
       print arr[i],

CS0234: Mvc does not exist in the System.Web namespace

This problem can happen when you deploy your web application to a server, so you must check if you already installed MVC3.

Check if the folder C:\Program Files\Microsoft ASP.NET\ASP.NET MVC 3 exists.

If it doesn't exist, you need to install it from http://www.microsoft.com/en-us/download/details.aspx?id=1491


If you wont to install you can add all DLLs locally in bin folder and add references to them this work fine if you host on server don't deploy ASP.NET Web Pages or MVC3.

How can jQuery deferred be used?

Another example using Deferreds to implement a cache for any kind of computation (typically some performance-intensive or long-running tasks):

var ResultsCache = function(computationFunction, cacheKeyGenerator) {
    this._cache = {};
    this._computationFunction = computationFunction;
    if (cacheKeyGenerator)
        this._cacheKeyGenerator = cacheKeyGenerator;
};

ResultsCache.prototype.compute = function() {
    // try to retrieve computation from cache
    var cacheKey = this._cacheKeyGenerator.apply(this, arguments);
    var promise = this._cache[cacheKey];

    // if not yet cached: start computation and store promise in cache 
    if (!promise) {
        var deferred = $.Deferred();
        promise = deferred.promise();
        this._cache[cacheKey] = promise;

        // perform the computation
        var args = Array.prototype.slice.call(arguments);
        args.push(deferred.resolve);
        this._computationFunction.apply(null, args);
    }

    return promise;
};

// Default cache key generator (works with Booleans, Strings, Numbers and Dates)
// You will need to create your own key generator if you work with Arrays etc.
ResultsCache.prototype._cacheKeyGenerator = function(args) {
    return Array.prototype.slice.call(arguments).join("|");
};

Here is an example of using this class to perform some (simulated heavy) calculation:

// The addingMachine will add two numbers
var addingMachine = new ResultsCache(function(a, b, resultHandler) {
    console.log("Performing computation: adding " + a + " and " + b);
    // simulate rather long calculation time by using a 1s timeout
    setTimeout(function() {
        var result = a + b;
        resultHandler(result);
    }, 1000);
});

addingMachine.compute(2, 4).then(function(result) {
    console.log("result: " + result);
});

addingMachine.compute(1, 1).then(function(result) {
    console.log("result: " + result);
});

// cached result will be used
addingMachine.compute(2, 4).then(function(result) {
    console.log("result: " + result);
});

The same underlying cache could be used to cache Ajax requests:

var ajaxCache = new ResultsCache(function(id, resultHandler) {
    console.log("Performing Ajax request for id '" + id + "'");
    $.getJSON('http://jsfiddle.net/echo/jsonp/?callback=?', {value: id}, function(data) {
        resultHandler(data.value);
    });
});

ajaxCache.compute("anID").then(function(result) {
    console.log("result: " + result);
});

ajaxCache.compute("anotherID").then(function(result) {
    console.log("result: " + result);
});

// cached result will be used
ajaxCache.compute("anID").then(function(result) {
    console.log("result: " + result);
});

You can play with the above code in this jsFiddle.

Replacing .NET WebBrowser control with a better browser, like Chrome?

Checkout CefSharp .Net bindings, a project I started a while back that thankfully got picked up by the community and turned into something wonderful.

The project wraps the Chromium Embedded Framework and has been used in a number of major projects including Rdio's Windows client, Facebook Messenger for Windows and Github for Windows.

It features browser controls for WPF and Winforms and has tons of features and extension points. Being based on Chromium it's blisteringly fast too.

Grab it from NuGet: Install-Package CefSharp.Wpf or Install-Package CefSharp.WinForms

Check out examples and give your thoughts/feedback/pull-requests: https://github.com/cefsharp/CefSharp

BSD Licensed

Using subprocess to run Python script on Windows

Just found sys.executable - the full path to the current Python executable, which can be used to run the script (instead of relying on the shbang, which obviously doesn't work on Windows)

import sys
import subprocess

theproc = subprocess.Popen([sys.executable, "myscript.py"])
theproc.communicate()

How to update single value inside specific array item in redux

You can use map. Here is an example implementation:

case 'SOME_ACTION':
   return { 
       ...state, 
       contents: state.contents.map(
           (content, i) => i === 1 ? {...content, text: action.payload}
                                   : content
       )
    }

how to check if a form is valid programmatically using jQuery Validation Plugin

2015 answer: we have this out of the box on modern browsers, just use the HTML5 CheckValidity API from jQuery. I've also made a jquery-html5-validity module to do this:

npm install jquery-html5-validity

Then:

var $ = require('jquery')
require("jquery-html5-validity")($);

then you can run:

$('.some-class').isValid()

true

I just discovered why all ASP.Net websites are slow, and I am trying to work out what to do about it

If you are using the updated Microsoft.Web.RedisSessionStateProvider(starting from 3.0.2) you can add this to your web.config to allow concurrent sessions.

<appSettings>
    <add key="aspnet:AllowConcurrentRequestsPerSession" value="true"/>
</appSettings>

Source

How to serialize a JObject without the formatting?

You can also do the following;

string json = myJObject.ToString(Newtonsoft.Json.Formatting.None);

ORA-06550: line 1, column 7 (PL/SQL: Statement ignored) Error

If the value stored in PropertyLoader.RET_SECONDARY_V_ARRAY is not "V_ARRAY", then you are using different types; even if they are declared identically (e.g. both are table of number) this will not work.

You're hitting this data type compatibility restriction:

You can assign a collection to a collection variable only if they have the same data type. Having the same element type is not enough.

You're trying to call the procedure with a parameter that is a different type to the one it's expecting, which is what the error message is telling you.

Retrieve a Fragment from a ViewPager

Create integer resource id in /values/integers.xml

<integer name="page1">1</integer>
<integer name="page2">2</integer>
<integer name="page3">3</integer>

Then in PagerAdapter getItem function:

public Fragment getItem(int position) {

        Fragment fragment = null;

        if (position == 0) {
            fragment = FragmentOne.newInstance();
            mViewPager.setTag(R.integer.page1,fragment);

        }
        else if (position == 1) {

            fragment = FragmentTwo.newInstance();
            mViewPager.setTag(R.integer.page2,fragment);

        } else if (position == 2) {

            fragment = FragmentThree.newInstance();
            mViewPager.setTag(R.integer.page3,fragment);

        }

        return fragment;
        }

Then in activity write this function to get fragment reference:

private Fragment getFragmentByPosition(int position) {
    Fragment fragment = null;

    switch (position) {
        case 0:
            fragment = (Fragment) mViewPager.getTag(R.integer.page1);
            break;

        case 1:

            fragment = (Fragment) mViewPager.getTag(R.integer.page2);
            break;

        case 2:
            fragment = (Fragment) mViewPager.getTag(R.integer.page3);
            break;
            }

            return fragment;
    }

Get the fragment reference by calling the above function and then cast it to your custom fragment:

Fragment fragment = getFragmentByPosition(position);

        if (fragment != null) {
                    FragmentOne fragmentOne = (FragmentOne) fragment;
                    }

Number of days between past date and current date in Google spreadsheet

  1. Today() does return value in DATE format.

  2. Select your "Days left field" and paste this formula in the field =DAYS360(today(),C2)

  3. Go to Format > Number > More formats >Custom number format and select the number with no decimal numbers.

I tested, it works, at least in new version of Sheets, March 2015.

Choice between vector::resize() and vector::reserve()

From your description, it looks like that you want to "reserve" the allocated storage space of vector t_Names.

Take note that resize initialize the newly allocated vector where reserve just allocates but does not construct. Hence, 'reserve' is much faster than 'resize'

You can refer to the documentation regarding the difference of resize and reserve

How to convert a string from uppercase to lowercase in Bash?

The correct way to implement your code is

y="HELLO"
val=$(echo "$y" | tr '[:upper:]' '[:lower:]')
string="$val world"

This uses $(...) notation to capture the output of the command in a variable. Note also the quotation marks around the string variable -- you need them there to indicate that $val and world are a single thing to be assigned to string.

If you have bash 4.0 or higher, a more efficient & elegant way to do it is to use bash builtin string manipulation:

y="HELLO"
string="${y,,} world"

Get sum of MySQL column in PHP

Try this:

$sql = mysql_query("SELECT SUM(Value) as total FROM Codes");
$row = mysql_fetch_array($sql);
$sum = $row['total'];

How to create a 100% screen width div inside a container in bootstrap?

2019's answer as this is still actively seen today

You should likely change the .container to .container-fluid, which will cause your container to stretch the entire screen. This will allow any div's inside of it to naturally stretch as wide as they need.

original hack from 2015 that still works in some situations

You should pull that div outside of the container. You're asking a div to stretch wider than its parent, which is generally not recommended practice.

If you cannot pull it out of the div for some reason, you should change the position style with this css:

.full-width-div {
    position: absolute;
    width: 100%;
    left: 0;
}

Instead of absolute, you could also use fixed, but then it will not move as you scroll.

How do I find out if first character of a string is a number?

Regular expressions are very strong but expensive tool. It is valid to use them for checking if the first character is a digit but it is not so elegant :) I prefer this way:

public boolean isLeadingDigit(final String value){
    final char c = value.charAt(0);
    return (c >= '0' && c <= '9');
}

firestore: PERMISSION_DENIED: Missing or insufficient permissions

the problem is that you tried to read or write data to realtime database or firestore before the user has be authenticated. please try to check the scope of your code. hope it helped!

Difference between a class and a module

The first answer is good and gives some structural answers, but another approach is to think about what you're doing. Modules are about providing methods that you can use across multiple classes - think about them as "libraries" (as you would see in a Rails app). Classes are about objects; modules are about functions.

For example, authentication and authorization systems are good examples of modules. Authentication systems work across multiple app-level classes (users are authenticated, sessions manage authentication, lots of other classes will act differently based on the auth state), so authentication systems act as shared APIs.

You might also use a module when you have shared methods across multiple apps (again, the library model is good here).

How to format a date using ng-model?

Use custom validation of forms http://docs.angularjs.org/guide/forms Demo: http://plnkr.co/edit/NzeauIDVHlgeb6qF75hX?p=preview

Directive using formaters and parsers and MomentJS )

angModule.directive('moDateInput', function ($window) {
    return {
        require:'^ngModel',
        restrict:'A',
        link:function (scope, elm, attrs, ctrl) {
            var moment = $window.moment;
            var dateFormat = attrs.moDateInput;
            attrs.$observe('moDateInput', function (newValue) {
                if (dateFormat == newValue || !ctrl.$modelValue) return;
                dateFormat = newValue;
                ctrl.$modelValue = new Date(ctrl.$setViewValue);
            });

            ctrl.$formatters.unshift(function (modelValue) {
                if (!dateFormat || !modelValue) return "";
                var retVal = moment(modelValue).format(dateFormat);
                return retVal;
            });

            ctrl.$parsers.unshift(function (viewValue) {
                var date = moment(viewValue, dateFormat);
                return (date && date.isValid() && date.year() > 1950 ) ? date.toDate() : "";
            });
        }
    };
});

How do I convert an integer to string as part of a PostgreSQL query?

Because the number can be up to 15 digits, you'll need to cast to an 64 bit (8-byte) integer. Try this:

SELECT * FROM table
WHERE myint = mytext::int8

The :: cast operator is historical but convenient. Postgres also conforms to the SQL standard syntax

myint = cast ( mytext as int8)

If you have literal text you want to compare with an int, cast the int to text:

SELECT * FROM table
WHERE myint::varchar(255) = mytext

Unable to start MySQL server

Try manually start the service from Windows services, Start -> cmd.exe -> services.msc. Also try to configure the MySQL server to run on another port and try starting it again. Change the my.ini file to change the port number.

Unstage a deleted file in git

I tried the above solutions and I was still having difficulties. I had other files staged with two files that were deleted accidentally.

To undo the two deleted files I had to unstage all of the files:

git reset HEAD .

At that point I was able to do the checkout of the deleted items:

git checkout -- WorkingFolder/FileName.ext

Finally I was able to restage the rest of the files and continue with my commit.

How do you change the size of figures drawn with matplotlib?

I always use the following pattern:

x_inches = 150*(1/25.4)     # [mm]*constant
y_inches = x_inches*(0.8)
dpi = 96

fig = plt.figure(1, figsize = (x_inches,y_inches), dpi = dpi, constrained_layout = True)

With this example you are able to set figure dimensions in inches or in milimiters and setting constrained_layout to True plots fill your figure without borders.

.substring error: "is not a function"

you can also quote string

''+document.location+''.substring(2,3);

How to handle anchor hash linking in AngularJS

I'm using AngularJS 1.3.15 and looks like I don't have to do anything special.

https://code.angularjs.org/1.3.15/docs/api/ng/provider/$anchorScrollProvider

So, the following works for me in my html:

<ul>
  <li ng-repeat="page in pages"><a ng-href="#{{'id-'+id}}">{{id}}</a>
  </li>
</ul>
<div ng-attr-id="{{'id-'+id}}" </div>

I didn't have to make any changes to my controller or JavaScript at all.

How do you sort an array on multiple columns?

Sourced from GitHub

_x000D_
_x000D_
function sortMethodAsc(a, b) {_x000D_
    return a == b ? 0 : a > b ? 1 : -1;_x000D_
}_x000D_
_x000D_
function sortMethodWithDirection(direction) { _x000D_
    if (direction === undefined || direction == "asc") {_x000D_
        return sortMethodAsc;_x000D_
    } else {_x000D_
        return function(a, b) {_x000D_
            return -sortMethodAsc(a, b);_x000D_
        } _x000D_
    }_x000D_
}_x000D_
_x000D_
function sortMethodWithDirectionByColumn(columnName, direction){   _x000D_
    const sortMethod = sortMethodWithDirection(direction)_x000D_
    return function(a, b){_x000D_
        return sortMethod(a[columnName], b[columnName]);_x000D_
    } _x000D_
}_x000D_
_x000D_
function sortMethodWithDirectionMultiColumn(sortArray) {_x000D_
    //sample of sortArray_x000D_
    // sortArray = [_x000D_
    //     { column: "column5", direction: "asc" },_x000D_
    //     { column: "column3", direction: "desc" }_x000D_
    // ]_x000D_
    const sortMethodsForColumn = (sortArray || []).map( item => sortMethodWithDirectionByColumn(item.column, item.direction) );_x000D_
    return function(a,b) {_x000D_
        let sorted = 0;_x000D_
        let index = 0;_x000D_
        while (sorted === 0 && index < sortMethodsForColumn.length) {_x000D_
            sorted = sortMethodsForColumn[index++](a,b);_x000D_
        }_x000D_
        return sorted;_x000D_
    }_x000D_
} _x000D_
_x000D_
//=============================================_x000D_
//=============================================_x000D_
//=============================================_x000D_
//test_x000D_
_x000D_
var data = [_x000D_
    {"CountryName":"Aruba","CountryCode":"ABW","GNI":280},{_x000D_
        "CountryName":"Afghanistan","CountryCode":"ABW","GNI":280},{"CountryName":"Angola","CountryCode":"AGO","GNI":280},{"CountryName":"Albania","CountryCode":"ALB","GNI":4320},_x000D_
        {"CountryName":"Arab World","CountryCode":"ARB","GNI":280},{"CountryName":"United Arab Emirates","CountryCode":"ARE","GNI":39130},_x000D_
        {"CountryName":"Argentina","CountryCode":"ARG","GNI":13030},{"CountryName":"Armenia","CountryCode":"ARM","GNI":3990},{"CountryName":"American Samoa","CountryCode":"ASM","GNI":280},_x000D_
        {"CountryName":"Antigua and Barbuda","CountryCode":"ATG","GNI":13810},{"CountryName":"Australia","CountryCode":"AUS","GNI":51360},_x000D_
        {"CountryName":"Austria","CountryCode":"AUT","GNI":45440},{"CountryName":"Azerbaijan","CountryCode":"AZE","GNI":4080},{"CountryName":"Burundi","CountryCode":"BDI","GNI":280},_x000D_
        {"CountryName":"Belgium","CountryCode":"BEL","GNI":41790},{"CountryName":"Benin","CountryCode":"BEN","GNI":800},{"CountryName":"Burkina Faso","CountryCode":"BFA","GNI":590},_x000D_
        {"CountryName":"Bangladesh","CountryCode":"BGD","GNI":1470},{"CountryName":"Bulgaria","CountryCode":"BGR","GNI":7860},{"CountryName":"Bahrain","CountryCode":"BHR","GNI":21150},_x000D_
        {"CountryName":"Bosnia and Herzegovina","CountryCode":"BIH","GNI":4910},{"CountryName":"Belarus","CountryCode":"BLR","GNI":5280},_x000D_
        {"CountryName":"Belize","CountryCode":"BLZ","GNI":4390},{"CountryName":"Bolivia","CountryCode":"BOL","GNI":3130},{"CountryName":"Brazil","CountryCode":"BRA","GNI":8600},_x000D_
        {"CountryName":"Barbados","CountryCode":"BRB","GNI":15270},{"CountryName":"Brunei Darussalam","CountryCode":"BRN","GNI":29600},_x000D_
        {"CountryName":"Bhutan","CountryCode":"BTN","GNI":2660},{"CountryName":"Botswana","CountryCode":"BWA","GNI":6730},_x000D_
        {"CountryName":"Central African Republic","CountryCode":"CAF","GNI":390},{"CountryName":"Canada","CountryCode":"CAN","GNI":42870},_x000D_
        {"CountryName":"Central Europe and the Baltics","CountryCode":"CEB","GNI":13009},{"CountryName":"Switzerland","CountryCode":"CHE","GNI":80560},_x000D_
        {"CountryName":"Chile","CountryCode":"CHL","GNI":13610},{"CountryName":"China","CountryCode":"CHN","GNI":8690},{"CountryName":"Cote d'Ivoire","CountryCode":"CIV","GNI":1580},_x000D_
        {"CountryName":"Cameroon","CountryCode":"CMR","GNI":1370},{"CountryName":"Colombia","CountryCode":"COL","GNI":5890},{"CountryName":"Comoros","CountryCode":"COM","GNI":1280},_x000D_
        {"CountryName":"Cabo Verde","CountryCode":"CPV","GNI":3030},{"CountryName":"Costa Rica","CountryCode":"CRI","GNI":11120},_x000D_
        {"CountryName":"Caribbean small states","CountryCode":"CSS","GNI":8909},{"CountryName":"Cyprus","CountryCode":"CYP","GNI":23720},_x000D_
        {"CountryName":"Czech Republic","CountryCode":"CZE","GNI":18160},{"CountryName":"Germany","CountryCode":"DEU","GNI":43490},_x000D_
        {"CountryName":"Djibouti","CountryCode":"DJI","GNI":1880},{"CountryName":"Dominica","CountryCode":"DMA","GNI":6590},{"CountryName":"Denmark","CountryCode":"DNK","GNI":55220},_x000D_
        {"CountryName":"Dominican Republic","CountryCode":"DOM","GNI":6630},{"CountryName":"Algeria","CountryCode":"DZA","GNI":3940},_x000D_
        {"CountryName":"East Asia & Pacific (excluding high income)","CountryCode":"EAP","GNI":6987},{"CountryName":"Early-demographic dividend","CountryCode":"EAR","GNI":3352},_x000D_
        {"CountryName":"East Asia & Pacific","CountryCode":"EAS","GNI":10171},{"CountryName":"Europe & Central Asia (excluding high income)","CountryCode":"ECA","GNI":7375},_x000D_
        {"CountryName":"Europe & Central Asia","CountryCode":"ECS","GNI":22656},{"CountryName":"Ecuador","CountryCode":"ECU","GNI":5920},_x000D_
        {"CountryName":"Euro area","CountryCode":"EMU","GNI":35645},{"CountryName":"Spain","CountryCode":"ESP","GNI":27180},{"CountryName":"Estonia","CountryCode":"EST","GNI":18190},_x000D_
        {"CountryName":"Ethiopia","CountryCode":"ETH","GNI":740},{"CountryName":"European Union","CountryCode":"EUU","GNI":32784},_x000D_
        {"CountryName":"Fragile and conflict affected situations","CountryCode":"FCS","GNI":1510},{"CountryName":"Finland","CountryCode":"FIN","GNI":44580},_x000D_
        {"CountryName":"Fiji","CountryCode":"FJI","GNI":4970},{"CountryName":"France","CountryCode":"FRA","GNI":37970},{"CountryName":"Gabon","CountryCode":"GAB","GNI":6650},_x000D_
        {"CountryName":"United Kingdom","CountryCode":"GBR","GNI":40530},{"CountryName":"Georgia","CountryCode":"GEO","GNI":3780},{"CountryName":"Ghana","CountryCode":"GHA","GNI":1880},_x000D_
        {"CountryName":"Guinea","CountryCode":"GIN","GNI":790},{"CountryName":"Guinea-Bissau","CountryCode":"GNB","GNI":660},_x000D_
        {"CountryName":"Equatorial Guinea","CountryCode":"GNQ","GNI":7050},{"CountryName":"Greece","CountryCode":"GRC","GNI":18090},_x000D_
        {"CountryName":"Grenada","CountryCode":"GRD","GNI":9180},{"CountryName":"Guatemala","CountryCode":"GTM","GNI":4060},{"CountryName":"Guyana","CountryCode":"GUY","GNI":4500},_x000D_
        {"CountryName":"High income","CountryCode":"HIC","GNI":40142},{"CountryName":"Honduras","CountryCode":"HND","GNI":2250},{"CountryName":"Heavily indebted poor countries (HIPC)","CountryCode":"HPC","GNI":904},{"CountryName":"Croatia","CountryCode":"HRV","GNI":12570},{"CountryName":"Haiti","CountryCode":"HTI","GNI":760},{"CountryName":"Hungary","CountryCode":"HUN","GNI":12870},{"CountryName":"IBRD only","CountryCode":"IBD","GNI":5745},{"CountryName":"IDA & IBRD total","CountryCode":"IBT","GNI":4620},{"CountryName":"IDA total","CountryCode":"IDA","GNI":1313},{"CountryName":"IDA blend","CountryCode":"IDB","GNI":1791},_x000D_
        {"CountryName":"Indonesia","CountryCode":"IDN","GNI":3540},{"CountryName":"IDA only","CountryCode":"IDX","GNI":1074},{"CountryName":"India","CountryCode":"IND","GNI":1800},{"CountryName":"Ireland","CountryCode":"IRL","GNI":55290},{"CountryName":"Iraq","CountryCode":"IRQ","GNI":4630},{"CountryName":"Iceland","CountryCode":"ISL","GNI":60830},{"CountryName":"Israel","CountryCode":"ISR","GNI":37270},{"CountryName":"Italy","CountryCode":"ITA","GNI":31020},{"CountryName":"Jamaica","CountryCode":"JAM","GNI":4760},{"CountryName":"Jordan","CountryCode":"JOR","GNI":3980},{"CountryName":"Japan","CountryCode":"JPN","GNI":38550},{"CountryName":"Kazakhstan","CountryCode":"KAZ","GNI":7970},{"CountryName":"Kenya","CountryCode":"KEN","GNI":1460},{"CountryName":"Kyrgyz Republic","CountryCode":"KGZ","GNI":1130},_x000D_
        {"CountryName":"Cambodia","CountryCode":"KHM","GNI":1230},{"CountryName":"Kiribati","CountryCode":"KIR","GNI":3010},{"CountryName":"St. Kitts and Nevis","CountryCode":"KNA","GNI":16240},{"CountryName":"Kuwait","CountryCode":"KWT","GNI":31430},{"CountryName":"Latin America & Caribbean (excluding high income)","CountryCode":"LAC","GNI":7470},{"CountryName":"Lao PDR","CountryCode":"LAO","GNI":2270},{"CountryName":"Lebanon","CountryCode":"LBN","GNI":8400},{"CountryName":"Liberia","CountryCode":"LBR","GNI":620},{"CountryName":"Libya","CountryCode":"LBY","GNI":5500},{"CountryName":"St. Lucia","CountryCode":"LCA","GNI":8830},{"CountryName":"Latin America & Caribbean","CountryCode":"LCN","GNI":8251},{"CountryName":"Least developed countries: UN classification","CountryCode":"LDC","GNI":1011},{"CountryName":"Low income","CountryCode":"LIC","GNI":774},{"CountryName":"Sri Lanka","CountryCode":"LKA","GNI":3850},{"CountryName":"Lower middle income","CountryCode":"LMC","GNI":2118},{"CountryName":"Low & middle income","CountryCode":"LMY","GNI":4455},{"CountryName":"Lesotho","CountryCode":"LSO","GNI":1210},{"CountryName":"Late-demographic dividend","CountryCode":"LTE","GNI":8518},{"CountryName":"Lithuania","CountryCode":"LTU","GNI":15200},{"CountryName":"Luxembourg","CountryCode":"LUX","GNI":70260},{"CountryName":"Latvia","CountryCode":"LVA","GNI":14740},{"CountryName":"Morocco","CountryCode":"MAR","GNI":2860},{"CountryName":"Moldova","CountryCode":"MDA","GNI":2200},{"CountryName":"Madagascar","CountryCode":"MDG","GNI":400},{"CountryName":"Maldives","CountryCode":"MDV","GNI":9760},_x000D_
        {"CountryName":"Middle East & North Africa","CountryCode":"MEA","GNI":7236},{"CountryName":"Mexico","CountryCode":"MEX","GNI":8610},{"CountryName":"Marshall Islands","CountryCode":"MHL","GNI":4840},{"CountryName":"Middle income","CountryCode":"MIC","GNI":4942},{"CountryName":"Mali","CountryCode":"MLI","GNI":770},_x000D_
        {"CountryName":"Malta","CountryCode":"MLT","GNI":24080},{"CountryName":"Myanmar","CountryCode":"MMR","GNI":1210},{"CountryName":"Middle East & North Africa (excluding high income)","CountryCode":"MNA","GNI":3832},{"CountryName":"Montenegro","CountryCode":"MNE","GNI":7400},{"CountryName":"Mongolia","CountryCode":"MNG","GNI":3270},{"CountryName":"Mozambique","CountryCode":"MOZ","GNI":420},{"CountryName":"Mauritania","CountryCode":"MRT","GNI":1100},{"CountryName":"Mauritius","CountryCode":"MUS","GNI":10130},{"CountryName":"Malawi","CountryCode":"MWI","GNI":320},{"CountryName":"Malaysia","CountryCode":"MYS","GNI":9650},{"CountryName":"North America","CountryCode":"NAC","GNI":56721},{"CountryName":"Namibia","CountryCode":"NAM","GNI":4570},{"CountryName":"Niger","CountryCode":"NER","GNI":360},{"CountryName":"Nigeria","CountryCode":"NGA","GNI":2100},_x000D_
        {"CountryName":"Nicaragua","CountryCode":"NIC","GNI":2130},{"CountryName":"Netherlands","CountryCode":"NLD","GNI":46180},{"CountryName":"Norway","CountryCode":"NOR","GNI":75990},{"CountryName":"Nepal","CountryCode":"NPL","GNI":800},{"CountryName":"Nauru","CountryCode":"NRU","GNI":10220},{"CountryName":"New Zealand","CountryCode":"NZL","GNI":38970},{"CountryName":"OECD members","CountryCode":"OED","GNI":37273},{"CountryName":"Oman","CountryCode":"OMN","GNI":14440},{"CountryName":"Other small states","CountryCode":"OSS","GNI":12199},{"CountryName":"Pakistan","CountryCode":"PAK","GNI":1580},{"CountryName":"Panama","CountryCode":"PAN","GNI":13280},{"CountryName":"Peru","CountryCode":"PER","GNI":5960},{"CountryName":"Philippines","CountryCode":"PHL","GNI":3660},{"CountryName":"Palau","CountryCode":"PLW","GNI":12700},{"CountryName":"Papua New Guinea","CountryCode":"PNG","GNI":2340},{"CountryName":"Poland","CountryCode":"POL","GNI":12730},{"CountryName":"Pre-demographic dividend","CountryCode":"PRE","GNI":1379},{"CountryName":"Portugal","CountryCode":"PRT","GNI":19820},{"CountryName":"Paraguay","CountryCode":"PRY","GNI":5470},{"CountryName":"West Bank and Gaza","CountryCode":"PSE","GNI":3180},{"CountryName":"Pacific island small states","CountryCode":"PSS","GNI":3793},{"CountryName":"Post-demographic dividend","CountryCode":"PST","GNI":41609},{"CountryName":"Qatar","CountryCode":"QAT","GNI":60510},{"CountryName":"Romania","CountryCode":"ROU","GNI":10000},{"CountryName":"Russian Federation","CountryCode":"RUS","GNI":9230},{"CountryName":"Rwanda","CountryCode":"RWA","GNI":720},{"CountryName":"South Asia","CountryCode":"SAS","GNI":1729},{"CountryName":"Saudi Arabia","CountryCode":"SAU","GNI":20090},{"CountryName":"Sudan","CountryCode":"SDN","GNI":2380},{"CountryName":"Senegal","CountryCode":"SEN","GNI":1240},{"CountryName":"Singapore","CountryCode":"SGP","GNI":54530},{"CountryName":"Solomon Islands","CountryCode":"SLB","GNI":1920},{"CountryName":"Sierra Leone","CountryCode":"SLE","GNI":510},{"CountryName":"El Salvador","CountryCode":"SLV","GNI":3560},{"CountryName":"Serbia","CountryCode":"SRB","GNI":5180},{"CountryName":"Sub-Saharan Africa (excluding high income)","CountryCode":"SSA","GNI":1485},{"CountryName":"Sub-Saharan Africa","CountryCode":"SSF","GNI":1486},{"CountryName":"Small states","CountryCode":"SST","GNI":11099},{"CountryName":"Sao Tome and Principe","CountryCode":"STP","GNI":1770},{"CountryName":"Suriname","CountryCode":"SUR","GNI":5150},{"CountryName":"Slovak Republic","CountryCode":"SVK","GNI":16610},{"CountryName":"Slovenia","CountryCode":"SVN","GNI":22000},{"CountryName":"Sweden","CountryCode":"SWE","GNI":52590},{"CountryName":"Eswatini","CountryCode":"SWZ","GNI":2950},{"CountryName":"Seychelles","CountryCode":"SYC","GNI":14170},{"CountryName":"Chad","CountryCode":"TCD","GNI":640},{"CountryName":"East Asia & Pacific (IDA & IBRD countries)","CountryCode":"TEA","GNI":7061},_x000D_
        {"CountryName":"Europe & Central Asia (IDA & IBRD countries)","CountryCode":"TEC","GNI":7866},{"CountryName":"Togo","CountryCode":"TGO","GNI":610},{"CountryName":"Thailand","CountryCode":"THA","GNI":5950},{"CountryName":"Tajikistan","CountryCode":"TJK","GNI":990},{"CountryName":"Turkmenistan","CountryCode":"TKM","GNI":6380},{"CountryName":"Latin America & the Caribbean (IDA & IBRD countries)","CountryCode":"TLA","GNI":8179},{"CountryName":"Timor-Leste","CountryCode":"TLS","GNI":1790},{"CountryName":"Middle East & North Africa (IDA & IBRD countries)","CountryCode":"TMN","GNI":3839},{"CountryName":"Tonga","CountryCode":"TON","GNI":4010},{"CountryName":"South Asia (IDA & IBRD)","CountryCode":"TSA","GNI":1729},_x000D_
        {"CountryName":"Sub-Saharan Africa (IDA & IBRD countries)","CountryCode":"TSS","GNI":1486},{"CountryName":"Trinidad and Tobago","CountryCode":"TTO","GNI":15340},{"CountryName":"Tunisia","CountryCode":"TUN","GNI":3490},{"CountryName":"Turkey","CountryCode":"TUR","GNI":10940},{"CountryName":"Tuvalu","CountryCode":"TUV","GNI":4970},{"CountryName":"Tanzania","CountryCode":"TZA","GNI":910},{"CountryName":"Uganda","CountryCode":"UGA","GNI":600},{"CountryName":"Ukraine","CountryCode":"UKR","GNI":2390},{"CountryName":"Upper middle income","CountryCode":"UMC","GNI":8197},{"CountryName":"Uruguay","CountryCode":"URY","GNI":15250},{"CountryName":"United States","CountryCode":"USA","GNI":58270},{"CountryName":"Uzbekistan","CountryCode":"UZB","GNI":2000},{"CountryName":"St. Vincent and the Grenadines","CountryCode":"VCT","GNI":7390},{"CountryName":"Vietnam","CountryCode":"VNM","GNI":2160},{"CountryName":"Vanuatu","CountryCode":"VUT","GNI":2920},{"CountryName":"World","CountryCode":"WLD","GNI":10371},{"CountryName":"Samoa","CountryCode":"WSM","GNI":4090},{"CountryName":"Kosovo","CountryCode":"XKX","GNI":3900},_x000D_
        {"CountryName":"South Africa","CountryCode":"ZAF","GNI":5430},{"CountryName":"Zambia","CountryCode":"ZMB","GNI":1290},{"CountryName":"Zimbabwe","CountryCode":"ZWE","GNI":1170},_x000D_
        {"CountryName":"Zimbabwe","CountryCode":"ZWE","GNI":1171}];_x000D_
_x000D_
    const sortMethod = sortMethodWithDirectionMultiColumn(_x000D_
        [_x000D_
            { column: "GNI", direction: "asc" },_x000D_
            { column: "CountryCode", direction: "desc" }_x000D_
        ]_x000D_
    );_x000D_
    let sortedData = data.sort(sortMethod);  _x000D_
    _x000D_
    _x000D_
    console.log("sorted by: 1)column:GNI-asc, 2)column:CountryCode-desc") _x000D_
    console.table(sortedData);_x000D_
    console.log(sortedData);_x000D_
    
_x000D_
_x000D_
_x000D_

C++ cast to derived class

You can't cast a base object to a derived type - it isn't of that type.

If you have a base type pointer to a derived object, then you can cast that pointer around using dynamic_cast. For instance:

DerivedType D;
BaseType B;

BaseType *B_ptr=&B
BaseType *D_ptr=&D;// get a base pointer to derived type

DerivedType *derived_ptr1=dynamic_cast<DerivedType*>(D_ptr);// works fine
DerivedType *derived_ptr2=dynamic_cast<DerivedType*>(B_ptr);// returns NULL

SQL Query - how do filter by null or not null

set ansi_nulls off go select * from table t inner join otherTable o on t.statusid = o.statusid go set ansi_nulls on go

yum error "Cannot retrieve metalink for repository: epel. Please verify its path and try again" updating ContextBroker

Another possible cause is that your architecture is not supported. I ran into this because I was provided with a CentOS VM, wanted to install EPEL and couldn't for the life of me get it done.

Turns out the VM was CentOS 7 i386, which is an architecture that is apparently no longer supported by EPEL. I guess the only remedy in this case is to reinstall.

How to set response header in JAX-RS so that user sees download popup for Excel?

I figured to set HTTP response header and stream to display download-popup in browser via standard servlet. note: I'm using Excella, excel output API.

package local.test.servlet;

import java.io.IOException;
import java.net.URL;
import java.net.URLDecoder;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import local.test.jaxrs.ExcellaTestResource;
import org.apache.poi.ss.usermodel.Workbook;
import org.bbreak.excella.core.BookData;
import org.bbreak.excella.core.exception.ExportException;
import org.bbreak.excella.reports.exporter.ExcelExporter;
import org.bbreak.excella.reports.exporter.ReportBookExporter;
import org.bbreak.excella.reports.model.ConvertConfiguration;
import org.bbreak.excella.reports.model.ReportBook;
import org.bbreak.excella.reports.model.ReportSheet;
import org.bbreak.excella.reports.processor.ReportProcessor;

@WebServlet(name="ExcelServlet", urlPatterns={"/ExcelServlet"})
public class ExcelServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


        try {

            URL templateFileUrl = ExcellaTestResource.class.getResource("myTemplate.xls");
            //   /C:/Users/m-hugohugo/Documents/NetBeansProjects/KogaAlpha/build/web/WEB-INF/classes/local/test/jaxrs/myTemplate.xls
            System.out.println(templateFileUrl.getPath());
            String templateFilePath = URLDecoder.decode(templateFileUrl.getPath(), "UTF-8");
            String outputFileDir = "MasatoExcelHorizontalOutput";

            ReportProcessor reportProcessor = new ReportProcessor();
            ReportBook outputBook = new ReportBook(templateFilePath, outputFileDir, ExcelExporter.FORMAT_TYPE);

            ReportSheet outputSheet = new ReportSheet("MySheet");
            outputBook.addReportSheet(outputSheet);

            reportProcessor.addReportBookExporter(new OutputStreamExporter(response));
            System.out.println("wtf???");
            reportProcessor.process(outputBook);


            System.out.println("done!!");
        }
        catch(Exception e) {
            System.out.println(e);
        }

    } //end doGet()

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

    }

}//end class



class OutputStreamExporter extends ReportBookExporter {

    private HttpServletResponse response;

    public OutputStreamExporter(HttpServletResponse response) {
        this.response = response;
    }

    @Override
    public String getExtention() {
        return null;
    }

    @Override
    public String getFormatType() {
        return ExcelExporter.FORMAT_TYPE;
    }

    @Override
    public void output(Workbook book, BookData bookdata, ConvertConfiguration configuration) throws ExportException {

        System.out.println(book.getFirstVisibleTab());
        System.out.println(book.getSheetName(0));

        //TODO write to stream
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment; filename=masatoExample.xls");
            book.write(response.getOutputStream());
            response.getOutputStream().close();
            System.out.println("booya!!");
        }
        catch(Exception e) {
            System.out.println(e);
        }
    }
}//end class

Array initializing in Scala

If you know Array's length but you don't know its content, you can use

val length = 5
val temp = Array.ofDim[String](length)

If you want to have two dimensions array but you don't know its content, you can use

val row = 5
val column = 3
val temp = Array.ofDim[String](row, column)

Of course, you can change String to other type.

If you already know its content, you can use

val temp = Array("a", "b")

Javascript: How to generate formatted easy-to-read JSON straight from an object?

JSON.stringify takes more optional arguments.

Try:

 JSON.stringify({a:1,b:2,c:{d:1,e:[1,2]}}, null, 4); // Indented 4 spaces
 JSON.stringify({a:1,b:2,c:{d:1,e:[1,2]}}, null, "\t"); // Indented with tab

From:

How can I beautify JSON programmatically?

Should work in modern browsers, and it is included in json2.js if you need a fallback for browsers that don't support the JSON helper functions. For display purposes, put the output in a <pre> tag to get newlines to show.

Best Practice: Initialize JUnit class fields in setUp() or at declaration?

If you're wondering specifically about the examples in the JUnit FAQ, such as the basic test template, I think the best practice being shown off there is that the class under test should be instantiated in your setUp method (or in a test method).

When the JUnit examples create an ArrayList in the setUp method, they all go on to test the behavior of that ArrayList, with cases like testIndexOutOfBoundException, testEmptyCollection, and the like. The perspective there is of someone writing a class and making sure it works right.

You should probably do the same when testing your own classes: create your object in setUp or in a test method, so that you'll be able to get reasonable output if you break it later.

On the other hand, if you use a Java collection class (or other library class, for that matter) in your test code, it's probably not because you want to test it--it's just part of the test fixture. In this case, you can safely assume it works as intended, so initializing it in the declaration won't be a problem.

For what it's worth, I work on a reasonably large, several-year-old, TDD-developed code base. We habitually initialize things in their declarations in test code, and in the year and a half that I've been on this project, it has never caused a problem. So there's at least some anecdotal evidence that it's a reasonable thing to do.

Converting a String array into an int Array in java

Since you are trying to get an Integer[] array you could use:

Integer[] intarray = Stream.of(strings).mapToInt(Integer::parseInt).boxed().toArray(Integer[]::new);

Your code:

private void processLine(String[] strings) {
    Integer[] intarray = Stream.of(strings).mapToInt(Integer::parseInt).boxed().toArray(Integer[]::new);
}

Note, that this only works for Java 8 and higher.

Script for rebuilding and reindexing the fragmented index?

The real answer, in 2016 and 2017, is: Use Ola Hallengren's scripts:

https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html

That is all any of us need to know or bother with, at this point in our mutual evolution.

If '<selector>' is an Angular component, then verify that it is part of this module

Check which module the parent component is being declared in...

If your parent component is defined in the shared module, so must your child module.

The parent component could be declared in a shared module and not the module that is logical based on the file directory structure / naming, even the Angular CLI added it into the wrong module in my case.

Looping each row in datagridview

Best aproach for me was:

  private void grid_receptie_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
    {
        int X = 1;
        foreach(DataGridViewRow row in grid_receptie.Rows)
        {
            row.Cells["NR_CRT"].Value = X;
            X++;
        }
    }

A more useful statusline in vim?

set statusline=%<%f%m\ \[%{&ff}:%{&fenc}:%Y]\ %{getcwd()}\ \ \[%{strftime('%Y/%b/%d\ %a\ %I:%M\ %p')}\]\ %=\ Line:%l\/%L\ Column:%c%V\ %P

This is mine, give as a suggestion

re.sub erroring with "Expected string or bytes-like object"

As you stated in the comments, some of the values appeared to be floats, not strings. You will need to change it to strings before passing it to re.sub. The simplest way is to change location to str(location) when using re.sub. It wouldn't hurt to do it anyways even if it's already a str.

letters_only = re.sub("[^a-zA-Z]",  # Search for all non-letters
                          " ",          # Replace all non-letters with spaces
                          str(location))

SAP Crystal Reports runtime for .Net 4.0 (64-bit)

SAP is notoriously bad at making these downloads available... or in an easily accessible location so hopefully this link still works by the time you read this answer.

< original link no longer active >

http://scn.sap.com/docs/DOC-7824 Updated Link 2/6/13:

https://wiki.scn.sap.com/wiki/display/BOBJ/Crystal+Reports%2C+Developer+for+Visual+Studio+Downloads - "Updated 10/31/2017"

http://www.crystalreports.com/crvs/confirm/ - "Updated 10/31/2017"

Set up Python simpleHTTPserver on Windows

From Stack Overflow question What is the Python 3 equivalent of "python -m SimpleHTTPServer":

The following works for me:

python -m http.server [<portNo>]

Because I am using Python 3 the module SimpleHTTPServer has been replaced by http.server, at least in Windows.

How can you speed up Eclipse?

Close any open projects which are not in current use.

Try to switch off the auto publish mode during development.

How to export a Vagrant virtual machine to transfer it

The easiest way would be to package the Vagrant box and then copy (e.g. scp or rsync) it over to the other PC, add it and vagrant up ;-)

For detailed steps, check this out => Is there any way to clone a vagrant box that is already installed

How to filter rows containing a string pattern from a Pandas dataframe

In [3]: df[df['ids'].str.contains("ball")]
Out[3]:
     ids  vals
0  aball     1
1  bball     2
3  fball     4

Copy to Clipboard for all Browsers using javascript

This works on firefox 3.6.x and IE:

    function copyToClipboardCrossbrowser(s) {           
        s = document.getElementById(s).value;               

        if( window.clipboardData && clipboardData.setData )
        {
            clipboardData.setData("Text", s);
        }           
        else
        {
            // You have to sign the code to enable this or allow the action in about:config by changing
            //user_pref("signed.applets.codebase_principal_support", true);
            netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');

            var clip = Components.classes["@mozilla.org/widget/clipboard;1"].createInstance(Components.interfaces.nsIClipboard);
            if (!clip) return;

            // create a transferable

            var trans = Components.classes["@mozilla.org/widget/transferable;1"].createInstance(Components.interfaces.nsITransferable);
            if (!trans) return;

            // specify the data we wish to handle. Plaintext in this case.
            trans.addDataFlavor('text/unicode');

            // To get the data from the transferable we need two new objects
            var str = new Object();
            var len = new Object();

            var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);

            str.data= s;        

            trans.setTransferData("text/unicode",str, str.data.length * 2);

            var clipid=Components.interfaces.nsIClipboard;              
            if (!clip) return false;
            clip.setData(trans,null,clipid.kGlobalClipboard);      
        }
    }

md-table - How to update the column width

When Material creates the table it automagically applies two class-names for you which you can use to style each column. In the the example below the styles is named mat-column-userId and cdk-column-userId.

<ng-container cdkColumnDef="userId">
  <md-header-cell *cdkHeaderCellDef> ID </md-header-cell>
  <md-cell *cdkCellDef="let row"> {{row.id}} </md-cell>
</ng-container>

Now you can use those names in css:

.mat-column-userId {
  flex: 0 0 100px;
}

Similar to Rahul Patil's answer, but you don't need to add another class to your column definitions.

How can I read user input from the console?

string input = Console.ReadLine();
double d;
if (!Double.TryParse(input, out d))
    Console.WriteLine("Wrong input");
double r = d * Math.Pi;
Console.WriteLine(r);

The main reason of different input/output you're facing is that Console.Read() returns char code, not a number you typed! Learn how to use MSDN.

What is declarative programming?

Describing to a computer what you want, not how to do something.

Use multiple custom fonts using @font-face?

Check out fontsquirrel. They have a web font generator, which will also spit out a suitable stylesheet for your font (look for "@font-face kit"). This stylesheet can be included in your own, or you can use it as a template.

How to change Label Value using javascript

Based off your code, i created this Fiddle
You need to use

var cb = document.getElementsByName('field206451')[0];
var label = document.getElementsByName('label206451')[0];


if you want to use name attributes then you have to take the index since it is a list of items, not just a single one. Everything else worked good.

Describe table structure

Sql server

DECLARE @tableName nvarchar(100)
SET @tableName = N'members' -- change with table name
SELECT
    [column].*,
    COLUMNPROPERTY(object_id([column].[TABLE_NAME]), [column].[COLUMN_NAME], 'IsIdentity') AS [identity]
FROM 
    INFORMATION_SCHEMA.COLUMNS [column] 
WHERE
    [column].[Table_Name] = @tableName

Where is Android Studio layout preview?

UPDATE 2 (2020-03-16)

The newer Android Studio version changed the location of this button. Now if you want to see the layout design preview you will need to press one of the buttons at the top right of your xml. The button that looks like an image icon will open the design dashboard, while the button next to it will open the split view where the design is placed next to the XML code:

enter image description here

ORIGINAL (2013-05-21)

You should have a Design button next to the Text button under the xml text editor:

enter image description here

Or you can use the Preview button in the upper right corner to add a preview window next to the XML code:

enter image description here

UPDATE:

If you dont have it, then do this: View -> Tool Windows -> Preview

enter image description here

How to create timer events using C++ 11?

Made a simple implementation of what I believe to be what you want to achieve. You can use the class later with the following arguments:

  • int (milliseconds to wait until to run the code)
  • bool (if true it returns instantly and runs the code after specified time on another thread)
  • variable arguments (exactly what you'd feed to std::bind)

You can change std::chrono::milliseconds to std::chrono::nanoseconds or microseconds for even higher precision and add a second int and a for loop to specify for how many times to run the code.

Here you go, enjoy:

#include <functional>
#include <chrono>
#include <future>
#include <cstdio>

class later
{
public:
    template <class callable, class... arguments>
    later(int after, bool async, callable&& f, arguments&&... args)
    {
        std::function<typename std::result_of<callable(arguments...)>::type()> task(std::bind(std::forward<callable>(f), std::forward<arguments>(args)...));

        if (async)
        {
            std::thread([after, task]() {
                std::this_thread::sleep_for(std::chrono::milliseconds(after));
                task();
            }).detach();
        }
        else
        {
            std::this_thread::sleep_for(std::chrono::milliseconds(after));
            task();
        }
    }

};

void test1(void)
{
    return;
}

void test2(int a)
{
    printf("%i\n", a);
    return;
}

int main()
{
    later later_test1(1000, false, &test1);
    later later_test2(1000, false, &test2, 101);

    return 0;
}

Outputs after two seconds:

101

How to parse JSON to receive a Date object in JavaScript?

The JSON.parse function accepts an optional DateTime reviver function. You can use a function like this:

dateTimeReviver = function (key, value) {
    var a;
    if (typeof value === 'string') {
        a = /\/Date\((\d*)\)\//.exec(value);
        if (a) {
            return new Date(+a[1]);
        }
    }
    return value;
}

Then call

JSON.parse(somejsonstring, dateTimeReviver);

And your dates will come out right.

How do I create a file AND any folders, if the folders don't exist?

To summarize what has been commented in other answers:

//path = @"C:\Temp\Bar\Foo\Test.txt";
Directory.CreateDirectory(Path.GetDirectoryName(path));

Directory.CreateDirectory will create the directories recursively and if the directory already exist it will return without an error.

If there happened to be a file Foo at C:\Temp\Bar\Foo an exception will be thrown.

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

Check your compileSdkVersion on app build.gradle. Set it to 21:

compileSdkVersion 21

How can I find the last element in a List<>?

If you just want to access the last item in the list you can do

if(integerList.Count>0)
{
   var item = integerList[integerList.Count - 1];
}

to get the total number of items in the list you can use the Count property

var itemCount = integerList.Count;

How to check Oracle database for long running queries

This one shows SQL that is currently "ACTIVE":-

select S.USERNAME, s.sid, s.osuser, t.sql_id, sql_text
from v$sqltext_with_newlines t,V$SESSION s
where t.address =s.sql_address
and t.hash_value = s.sql_hash_value
and s.status = 'ACTIVE'
and s.username <> 'SYSTEM'
order by s.sid,t.piece
/

This shows locks. Sometimes things are going slow, but it's because it is blocked waiting for a lock:

select
  object_name, 
  object_type, 
  session_id, 
  type,         -- Type or system/user lock
  lmode,        -- lock mode in which session holds lock
  request, 
  block, 
  ctime         -- Time since current mode was granted
from
  v$locked_object, all_objects, v$lock
where
  v$locked_object.object_id = all_objects.object_id AND
  v$lock.id1 = all_objects.object_id AND
  v$lock.sid = v$locked_object.session_id
order by
  session_id, ctime desc, object_name
/

This is a good one for finding long operations (e.g. full table scans). If it is because of lots of short operations, nothing will show up.

COLUMN percent FORMAT 999.99 

SELECT sid, to_char(start_time,'hh24:mi:ss') stime, 
message,( sofar/totalwork)* 100 percent 
FROM v$session_longops
WHERE sofar/totalwork < 1
/

Is there any sizeof-like method in Java?

The Instrumentation class has a getObjectSize() method however, you shouldn't need to use it at runtime. The easiest way to examine memory usage is to use a profiler which is designed to help you track memory usage.

Find out time it took for a python script to complete execution

import sys
import timeit

start = timeit.default_timer()

#do some nice things...

stop = timeit.default_timer()
total_time = stop - start

# output running time in a nice format.
mins, secs = divmod(total_time, 60)
hours, mins = divmod(mins, 60)

sys.stdout.write("Total running time: %d:%d:%d.\n" % (hours, mins, secs))

Find files and tar them (with spaces)

Why not give something like this a try: tar cvf scala.tar `find src -name *.scala`

is there something like isset of php in javascript/jQuery?

typeof will serve the purpose I think

if(typeof foo != "undefined"){}

Split string with string as delimiter

Try this:

for /F "tokens=1,3 delims=. " %%a in ("%string%") do (
   echo %%a
   echo %%b
)

that is, take the first and third tokens delimited by space or point...

Repeat String - Javascript

Here's the JSLint safe version

String.prototype.repeat = function (num) {
  var a = [];
  a.length = num << 0 + 1;
  return a.join(this);
};

Squash the first two commits in Git?

There is an easier way to do this. Let's assume you're on the master branch

Create a new orphaned branch which will remove all commit history:

$ git checkout --orphan new_branch

Add your initial commit message:

$ git commit -a

Get rid of the old unmerged master branch:

$ git branch -D master

Rename your current branch new_branch to master:

$ git branch -m master

What's the difference between ClusterIP, NodePort and LoadBalancer service types in Kubernetes?

A ClusterIP exposes the following:

  • spec.clusterIp:spec.ports[*].port

You can only access this service while inside the cluster. It is accessible from its spec.clusterIp port. If a spec.ports[*].targetPort is set it will route from the port to the targetPort. The CLUSTER-IP you get when calling kubectl get services is the IP assigned to this service within the cluster internally.

A NodePort exposes the following:

  • <NodeIP>:spec.ports[*].nodePort
  • spec.clusterIp:spec.ports[*].port

If you access this service on a nodePort from the node's external IP, it will route the request to spec.clusterIp:spec.ports[*].port, which will in turn route it to your spec.ports[*].targetPort, if set. This service can also be accessed in the same way as ClusterIP.

Your NodeIPs are the external IP addresses of the nodes. You cannot access your service from spec.clusterIp:spec.ports[*].nodePort.

A LoadBalancer exposes the following:

  • spec.loadBalancerIp:spec.ports[*].port
  • <NodeIP>:spec.ports[*].nodePort
  • spec.clusterIp:spec.ports[*].port

You can access this service from your load balancer's IP address, which routes your request to a nodePort, which in turn routes the request to the clusterIP port. You can access this service as you would a NodePort or a ClusterIP service as well.

How do you round a float to 2 decimal places in JRuby?

Try this:

module Util
module MyUtil



    def self.redondear_up(suma,cantidad, decimales=0)

        unless suma.present?
            return nil
        end


        if suma>0
            resultado= (suma.to_f/cantidad)
            return resultado.round(decimales)
        end


        return nil


    end

end 
end 

Write to custom log file from a Bash script

If you see the man page of logger:

$ man logger

LOGGER(1) BSD General Commands Manual LOGGER(1)

NAME logger — a shell command interface to the syslog(3) system log module

SYNOPSIS logger [-isd] [-f file] [-p pri] [-t tag] [-u socket] [message ...]

DESCRIPTION Logger makes entries in the system log. It provides a shell command interface to the syslog(3) system log module.

It Clearly says that it will log to system log. If you want to log to file, you can use ">>" to redirect to log file.

initialize a const array in a class initializer in C++

std::vector uses the heap. Geez, what a waste that would be just for the sake of a const sanity-check. The point of std::vector is dynamic growth at run-time, not any old syntax checking that should be done at compile-time. If you're not going to grow then create a class to wrap a normal array.

#include <stdio.h>


template <class Type, size_t MaxLength>
class ConstFixedSizeArrayFiller {
private:
    size_t length;

public:
    ConstFixedSizeArrayFiller() : length(0) {
    }

    virtual ~ConstFixedSizeArrayFiller() {
    }

    virtual void Fill(Type *array) = 0;

protected:
    void add_element(Type *array, const Type & element)
    {
        if(length >= MaxLength) {
            // todo: throw more appropriate out-of-bounds exception
            throw 0;
        }
        array[length] = element;
        length++;
    }
};


template <class Type, size_t Length>
class ConstFixedSizeArray {
private:
    Type array[Length];

public:
    explicit ConstFixedSizeArray(
        ConstFixedSizeArrayFiller<Type, Length> & filler
    ) {
        filler.Fill(array);
    }

    const Type *Array() const {
        return array;
    }

    size_t ArrayLength() const {
        return Length;
    }
};


class a {
private:
    class b_filler : public ConstFixedSizeArrayFiller<int, 2> {
    public:
        virtual ~b_filler() {
        }

        virtual void Fill(int *array) {
            add_element(array, 87);
            add_element(array, 96);
        }
    };

    const ConstFixedSizeArray<int, 2> b;

public:
    a(void) : b(b_filler()) {
    }

    void print_items() {
        size_t i;
        for(i = 0; i < b.ArrayLength(); i++)
        {
            printf("%d\n", b.Array()[i]);
        }
    }
};


int main()
{
    a x;
    x.print_items();
    return 0;
}

ConstFixedSizeArrayFiller and ConstFixedSizeArray are reusable.

The first allows run-time bounds checking while initializing the array (same as a vector might), which can later become const after this initialization.

The second allows the array to be allocated inside another object, which could be on the heap or simply the stack if that's where the object is. There's no waste of time allocating from the heap. It also performs compile-time const checking on the array.

b_filler is a tiny private class to provide the initialization values. The size of the array is checked at compile-time with the template arguments, so there's no chance of going out of bounds.

I'm sure there are more exotic ways to modify this. This is an initial stab. I think you can pretty much make up for any of the compiler's shortcoming with classes.

Open Popup window using javascript

To create a popup you'll need the following script:

<script language="javascript" type="text/javascript">

function popitup(url) {
newwindow=window.open(url,'name','height=200,width=150');
if (window.focus) {newwindow.focus()}
return false;
}


</script>

Then, you link to it by:

  <a href="popupex.html" onclick="return popitup('popupex.html')">Link to popup</a>

If you want you can call the function directly from document.ready also. Or maybe from another function.

node.js: read a text file into an array. (Each line an item in the array.)

Using the Node.js readline module.

var fs = require('fs');
var readline = require('readline');

var filename = process.argv[2];
readline.createInterface({
    input: fs.createReadStream(filename),
    terminal: false
}).on('line', function(line) {
   console.log('Line: ' + line);
});

jquery click event not firing?

You need to prevent the default event (following the link), otherwise your link will load a new page:

    $(document).ready(function(){
        $('.play_navigation a').click(function(e){
            e.preventDefault();
            console.log("this is the click");
        });
    });

As pointed out in comments, if your link has no href, then it's not a link, use something else.

Not working? Your code is A MESS! and ready() events everywhere... clean it, put all your scripts in ONE ready event and then try again, it will very likely sort things out.

Rounding a number to the nearest 5 or 10 or X

For a strict Visual Basic approach, you can convert the floating-point value to an integer to round to said integer. VB is one of the rare languages that rounds on type conversion (most others simply truncate.)

Multiples of 5 or x can be done simply by dividing before and multiplying after the round.

If you want to round and keep decimal places, Math.round(n, d) would work.

Remove trailing zeros

You can just set as:

decimal decNumber = 23.45600000m;
Console.WriteLine(decNumber.ToString("0.##"));

newline character in c# string

They might be just a \r or a \n. I just checked and the text visualizer in VS 2010 displays both as newlines as well as \r\n.

This string

string test = "blah\r\nblah\rblah\nblah";

Shows up as

blah
blah
blah
blah

in the text visualizer.

So you could try

string modifiedString = originalString
    .Replace(Environment.NewLine, "<br />")
    .Replace("\r", "<br />")
    .Replace("\n", "<br />");

Cannot read property 'addEventListener' of null

I had the same problem, but my id was present. So I tried adding "window.onload = init;" Then I wrapped my original JS code with an init function (call it what you want). This worked, so at least in my case, I was adding an event listener before my document loaded. This could be what you are experiencing as well.

Add placeholder text inside UITextView in Swift?

I believe this is a very clean solution. It adds a dummy text view underneath the actual text view and shows or hides it depending on the text in the actual text view:

import Foundation
import UIKit

class TextViewWithPlaceholder: UITextView {

    private var placeholderTextView: UITextView = UITextView()

    var placeholder: String? {
        didSet {
            placeholderTextView.text = placeholder
        }
    }

    override var text: String! {
        didSet {
            placeholderTextView.isHidden = text.isEmpty == false
        }
    }

    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        commonInit()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        commonInit()
    }

    private func commonInit() {
        applyCommonTextViewAttributes(to: self)
        configureMainTextView()
        addPlaceholderTextView()
        NotificationCenter.default.addObserver(self,
                                               selector: #selector(textDidChange),
                                               name: UITextView.textDidChangeNotification,
                                               object: nil)
    }

    func addPlaceholderTextView() {
        applyCommonTextViewAttributes(to: placeholderTextView)
        configurePlaceholderTextView()
        insertSubview(placeholderTextView, at: 0)
    }

    private func applyCommonTextViewAttributes(to textView: UITextView) {
        textView.translatesAutoresizingMaskIntoConstraints = false
        textView.textContainer.lineFragmentPadding = 0
        textView.textContainerInset = UIEdgeInsets(top: 10,
                                                   left: 10,
                                                   bottom: 10,
                                                   right: 10)
    }

    private func configureMainTextView() {
        // Do any configuration of the actual text view here
    }

    private func configurePlaceholderTextView() {
        placeholderTextView.text = placeholder
        placeholderTextView.font = font
        placeholderTextView.textColor = UIColor.lightGray
        placeholderTextView.frame = bounds
        placeholderTextView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        placeholderTextView.frame = bounds
    }

    @objc func textDidChange() {
        placeholderTextView.isHidden = !text.isEmpty
    }

}

How to prettyprint a JSON file?

def saveJson(date,fileToSave):
    with open(fileToSave, 'w+') as fileToSave:
        json.dump(date, fileToSave, ensure_ascii=True, indent=4, sort_keys=True)

It works to display or save it to a file.

Where is the correct location to put Log4j.properties in an Eclipse project?

Add the log4j.properties file to the runtime class path of the project. Some people add this to the root of the source tree (so that it gets copied to the root of the compiled classes).

Edit: If your project is a maven project, you can put the log4j.properties in the src/main/resources folder (and the src/test/resources for your unit tests).

If you have multiple environments (for example development and production), want different logging for each environment, and want to deploy the same jar (or war, or ear) file to each environment (as in one build for all environments) then store the log4j.properties file outside of the jar file and put it in the class path for each environment (configurable by environment). Historically, I would include some known directory in each environment in the classpath and deploy environment specific stuff there. For example, ~tomcat_user/localclasspath where ~tomcat_user is the home directory of the user that will be running the tomcat instance to which my war file will be deployed.

How to find specified name and its value in JSON-string from Java?

I agree that Google's Gson is clear and easy to use. But you should create a result class for getting an instance from JSON string. If you can't clarify the result class, use json-simple:

// import static org.hamcrest.CoreMatchers.is;
// import static org.junit.Assert.assertThat;
// import org.json.simple.JSONObject;
// import org.json.simple.JSONValue;
// import org.junit.Test;

@Test
public void json2Object() {
    // given
    String jsonString = "{\"name\" : \"John\",\"age\" : \"20\","
            + "\"address\" : \"some address\","
            + "\"someobject\" : {\"field\" : \"value\"}}";

    // when
    JSONObject object = (JSONObject) JSONValue.parse(jsonString);

    // then
    @SuppressWarnings("unchecked")
    Set<String> keySet = object.keySet();
    for (String key : keySet) {
        Object value = object.get(key);
        System.out.printf("%s=%s (%s)\n", key, value, value.getClass()
                .getSimpleName());
    }

    assertThat(object.get("age").toString(), is("20"));
}

Pros and cons of Gson and json-simple is pretty much like pros and cons of user-defined Java Object and Map. The object you define is clear for all fields (name and type), but less flexible than Map.

Angularjs on page load call function

It's not the angular way, remove the function from html body and use it in controller, or use

angular.element(document).ready

More details are available here: https://stackoverflow.com/a/18646795/4301583

SQL injection that gets around mysql_real_escape_string()

Consider the following query:

$iId = mysql_real_escape_string("1 OR 1=1");    
$sSql = "SELECT * FROM table WHERE id = $iId";

mysql_real_escape_string() will not protect you against this. The fact that you use single quotes (' ') around your variables inside your query is what protects you against this. The following is also an option:

$iId = (int)"1 OR 1=1";
$sSql = "SELECT * FROM table WHERE id = $iId";

LoDash: Get an array of values from an array of object properties

With pure JS:

var userIds = users.map( function(obj) { return obj.id; } );

How to make HTML table cell editable?

HTML5 supports contenteditable,

<table border="3">
<thead>
<tr>Heading 1</tr>
<tr>Heading 2</tr>
</thead>
<tbody>
<tr>
<td contenteditable='true'></td>
<td contenteditable='true'></td>
</tr>
<tr>
<td contenteditable='true'></td>
<td contenteditable='true'></td>
</tr>
</tbody>
</table>

3rd party edit

To quote the mdn entry on contenteditable

The attribute must take one of the following values:

  • true or the empty string, which indicates that the element must be editable;

  • false, which indicates that the element must not be editable.

If this attribute is not set, its default value is inherited from its parent element.

This attribute is an enumerated one and not a Boolean one. This means that the explicit usage of one of the values true, false or the empty string is mandatory and that a shorthand ... is not allowed.

// wrong not allowed
<label contenteditable>Example Label</label> 

// correct usage
<label contenteditable="true">Example Label</label>.

Dropping connected users in Oracle database

Here's how I "automate" Dropping connected users in Oracle database:

# A shell script to Drop a Database Schema, forcing off any Connected Sessions (for example, before an Import) 
# Warning! With great power comes great responsibility.
# It is often advisable to take an Export before Dropping a Schema

if [ "$1" = "" ] 
then
    echo "Which Schema?"
    read schema
else
    echo "Are you sure? (y/n)"
    read reply
    [ ! $reply = y ] && return 1
    schema=$1
fi

sqlplus / as sysdba <<EOF
set echo on
alter user $schema account lock;
-- Exterminate all sessions!
begin     
  for x in ( select sid, serial# from v\$session where username=upper('$schema') )
  loop  
   execute immediate ( 'alter system kill session '''|| x.Sid || ',' || x.Serial# || ''' immediate' );  
  end loop;  
  dbms_lock.sleep( seconds => 2 ); -- Prevent ORA-01940: cannot drop a user that is currently connected
end;
/
drop user $schema cascade;
quit
EOF

Twitter Bootstrap: div in container with 100% height

Update 2019

In Bootstrap 4, flexbox can be used to get a full height layout that fills the remaining space.

First of all, the container (parent) needs to be full height:

Option 1_ Add a class for min-height: 100%;. Remember that min-height will only work if the parent has a defined height:

html, body {
  height: 100%;
}

.min-100 {
    min-height: 100%;
}

https://codeply.com/go/dTaVyMah1U

Option 2_ Use vh units:

.vh-100 {
    min-height: 100vh;
}

https://codeply.com/go/kMahVdZyGj

Also of Bootstrap 4.1, the vh-100 and min-vh-100 classes are included in Bootstrap so there is no need to for the extra CSS

Then, use flexbox direction column d-flex flex-column on the container, and flex-grow-1 on any child divs (ie: row) that you want to fill the remaining height.

Also see:
Bootstrap 4 Navbar and content fill height flexbox
Bootstrap - Fill fluid container between header and footer
How to make the row stretch remaining height

" app-release.apk" how to change this default generated apk name

I think this will be helpful.

buildTypes {
    release {
        shrinkResources true
        minifyEnabled true
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        applicationVariants.all { variant ->
            variant.outputs.each { output ->
                project.ext { appName = 'MyAppName' }
                def formattedDate = new Date().format('yyyyMMddHHmmss')
                def newName = output.outputFile.name
                newName = newName.replace("app-", "$project.ext.appName-")
                newName = newName.replace("-release", "-release" + formattedDate)
                output.outputFile = new File(output.outputFile.parent, newName)
            }
        }
    }
}
productFlavors {
    flavor1 {
    }
    flavor2 {
        proguardFile 'flavor2-rules.pro'
    }
}

How to change button color with tkinter

Another way to change color of a button if you want to do multiple operations along with color change. Using the Tk().after method and binding a change method allows you to change color and do other operations.

Label.destroy is another example of the after method.

    def export_win():
        //Some Operation
        orig_color = export_finding_graph.cget("background")
        export_finding_graph.configure(background = "green")

        tt = "Exported"
        label = Label(tab1_closed_observations, text=tt, font=("Helvetica", 12))
        label.grid(row=0,column=0,padx=10,pady=5,columnspan=3)

        def change(orig_color):
            export_finding_graph.configure(background = orig_color)

        tab1_closed_observations.after(1000, lambda: change(orig_color))
        tab1_closed_observations.after(500, label.destroy)


    export_finding_graph = Button(tab1_closed_observations, text='Export', command=export_win)
    export_finding_graph.grid(row=6,column=4,padx=70,pady=20,sticky='we',columnspan=3)

You can also revert to the original color.

How to get current formatted date dd/mm/yyyy in Javascript and append it to an input

I honestly suggest that you use moment.js. Just download moment.min.js and then use this snippet to get your date in whatever format you want:

<script>
$(document).ready(function() {

     // set an element
     $("#date").val( moment().format('MMM D, YYYY') );

     // set a variable
     var today = moment().format('D MMM, YYYY');

});
</script>

Use following chart for date formats:

enter image description here

Jasmine JavaScript Testing - toBe vs toEqual

Looking at the Jasmine source code sheds more light on the issue.

toBe is very simple and just uses the identity/strict equality operator, ===:

  function(actual, expected) {
    return {
      pass: actual === expected
    };
  }

toEqual, on the other hand, is nearly 150 lines long and has special handling for built in objects like String, Number, Boolean, Date, Error, Element and RegExp. For other objects it recursively compares properties.

This is very different from the behavior of the equality operator, ==. For example:

var simpleObject = {foo: 'bar'};
expect(simpleObject).toEqual({foo: 'bar'}); //true
simpleObject == {foo: 'bar'}; //false

var castableObject = {toString: function(){return 'bar'}};
expect(castableObject).toEqual('bar'); //false
castableObject == 'bar'; //true

WordPress: get author info from post id

I figured it out.

<?php $author_id=$post->post_author; ?>
<img src="<?php the_author_meta( 'avatar' , $author_id ); ?> " width="140" height="140" class="avatar" alt="<?php echo the_author_meta( 'display_name' , $author_id ); ?>" />
<?php the_author_meta( 'user_nicename' , $author_id ); ?> 

Node.js: for each … in not working

https://github.com/cscott/jsshaper implements a translator from JavaScript 1.8 to ECMAScript 5.1, which would allow you to use 'for each' in code running on webkit or node.

Is there a way to iterate over a range of integers?

You can also check out github.com/wushilin/stream

It is a lazy stream like concept of java.util.stream.

// It doesn't really allocate the 10 elements.
stream1 := stream.Range(0, 10)

// Print each element.
stream1.Each(print)

// Add 3 to each element, but it is a lazy add.
// You only add when consume the stream
stream2 := stream1.Map(func(i int) int {
    return i + 3
})

// Well, this consumes the stream => return sum of stream2.
stream2.Reduce(func(i, j int) int {
    return i + j
})

// Create stream with 5 elements
stream3 := stream.Of(1, 2, 3, 4, 5)

// Create stream from array
stream4 := stream.FromArray(arrayInput)

// Filter stream3, keep only elements that is bigger than 2,
// and return the Sum, which is 12
stream3.Filter(func(i int) bool {
    return i > 2
}).Sum()

Hope this helps

How do I obtain a Query Execution Plan in SQL Server?

Estimated execution plan

The estimated execution plan is generated by the Optimizer without running the SQL query.

In order to get the estimated execution plan, you need to enable the SHOWPLAN_ALL setting prior to executing the query.

SET SHOWPLAN_ALL ON

Now, when executing the following SQL query:

SELECT p.id
FROM post p
WHERE EXISTS (
  SELECT 1
  FROM post_comment pc
  WHERE
    pc.post_id = p.id AND
    pc.review = 'Bingo'
)
ORDER BY p.title
OFFSET 20 ROWS
FETCH NEXT 10 ROWS ONLY

SQL Server will generate the following estimated execution plan:

| NodeId | Parent | LogicalOp            | EstimateRows | EstimateIO  | EstimateCPU | AvgRowSize | TotalSubtreeCost | EstimateExecutions |
|--------|--------|----------------------|--------------|-------------|-------------|------------|------------------|--------------------|
| 1      | 0      | NULL                 | 10           | NULL        | NULL        | NULL       | 0.03374284       | NULL               |
| 2      | 1      | Top                  | 10           | 0           | 3.00E-06    | 15         | 0.03374284       | 1                  |
| 4      | 2      | Distinct Sort        | 30           | 0.01126126  | 0.000504114 | 146        | 0.03373984       | 1                  |
| 5      | 4      | Inner Join           | 46.698       | 0           | 0.00017974  | 146        | 0.02197446       | 1                  |
| 6      | 5      | Clustered Index Scan | 43           | 0.004606482 | 0.0007543   | 31         | 0.005360782      | 1                  |
| 7      | 5      | Clustered Index Seek | 1            | 0.003125    | 0.0001581   | 146        | 0.0161733        | 43                 |

After running the query we are interested in getting the estimated execution plan, you need to disable the SHOWPLAN_ALL as, otherwise, the current database session will only generate estimated execution plan instead of executing the provided SQL queries.

SET SHOWPLAN_ALL OFF

SQL Server Management Studio estimated plan

In the SQL Server Management Studio application, you can easily get the estimated execution plan for any SQL query by hitting the CTRL+L key shortcut.

SQL Server Management Studio estimated plan

Actual execution plan

The actual SQL execution plan is generated by the Optimizer when running the SQL query. If the database table statistics are accurate, the actual plan should not differ significantly from the estimated one.

To get the actual execution plan on SQL Server, you need to enable the STATISTICS IO, TIME, PROFILE settings, as illustrated by the following SQL command:

SET STATISTICS IO, TIME, PROFILE ON

Now, when running the previous query, SQL Server is going to generate the following execution plan:

| Rows | Executes | NodeId | Parent | LogicalOp            | EstimateRows | EstimateIO  | EstimateCPU | AvgRowSize | TotalSubtreeCost |
|------|----------|--------|--------|----------------------|--------------|-------------|-------------|------------|------------------|
| 10   | 1        | 1      | 0      | NULL                 | 10           | NULL        | NULL        | NULL       | 0.03338978       |
| 10   | 1        | 2      | 1      | Top                  | 1.00E+01     | 0           | 3.00E-06    | 15         | 0.03338978       |
| 30   | 1        | 4      | 2      | Distinct Sort        | 30           | 0.01126126  | 0.000478783 | 146        | 0.03338679       |
| 41   | 1        | 5      | 4      | Inner Join           | 44.362       | 0           | 0.00017138  | 146        | 0.02164674       |
| 41   | 1        | 6      | 5      | Clustered Index Scan | 41           | 0.004606482 | 0.0007521   | 31         | 0.005358581      |
| 41   | 41       | 7      | 5      | Clustered Index Seek | 1            | 0.003125    | 0.0001581   | 146        | 0.0158571        |
 
SQL Server parse and compile time:
   CPU time = 8 ms, elapsed time = 8 ms.
 
(10 row(s) affected)
Table 'Worktable'. Scan count 0, logical reads 0, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
Table 'post'. Scan count 0, logical reads 116, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
Table 'post_comment'. Scan count 1, logical reads 5, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
 
(6 row(s) affected)
 
SQL Server Execution Times:
   CPU time = 0 ms,  elapsed time = 1 ms.

After running the query we are interested in getting the actual execution plan, you need to disable the STATISTICS IO, TIME, PROFILE ON settings like this:

SET STATISTICS IO, TIME, PROFILE OFF

SQL Server Management Studio actual plan

In the SQL Server Management Studio application, you can easily get the estimated execution plan for any SQL query by hitting the CTRL+M key shortcut.

SQL Server Management Studio actual plan

Upload a file to Amazon S3 with NodeJS

I found the following to be a working solution::

npm install aws-sdk


Once you've installed the aws-sdk , use the following code replacing values with your where needed.

var AWS = require('aws-sdk');
var fs =  require('fs');

var s3 = new AWS.S3();

// Bucket names must be unique across all S3 users

var myBucket = 'njera';

var myKey = 'jpeg';
//for text file
//fs.readFile('demo.txt', function (err, data) {
//for Video file
//fs.readFile('demo.avi', function (err, data) {
//for image file                
fs.readFile('demo.jpg', function (err, data) {
  if (err) { throw err; }



     params = {Bucket: myBucket, Key: myKey, Body: data };

     s3.putObject(params, function(err, data) {

         if (err) {

             console.log(err)

         } else {

             console.log("Successfully uploaded data to myBucket/myKey");

         }

      });

});

I found the complete tutorial on the subject here in case you're looking for references ::


How to upload files (text/image/video) in amazon s3 using node.js

Is there a way to get element by XPath using JavaScript in Selenium WebDriver?

To identify a WebElement using and you have to use the evaluate() method which evaluates an xpath expression and returns a result.


document.evaluate()

document.evaluate() returns an XPathResult based on an XPath expression and other given parameters.

The syntax is:

var xpathResult = document.evaluate(
  xpathExpression,
  contextNode,
  namespaceResolver,
  resultType,
  result
);

Where:

  • xpathExpression: The string representing the XPath to be evaluated.
  • contextNode: Specifies the context node for the query. Common practice is to pass document as the context node.
  • namespaceResolver: The function that will be passed any namespace prefixes and should return a string representing the namespace URI associated with that prefix. It will be used to resolve prefixes within the XPath itself, so that they can be matched with the document. null is common for HTML documents or when no namespace prefixes are used.
  • resultType: An integer that corresponds to the type of result XPathResult to return using named constant properties, such as XPathResult.ANY_TYPE, of the XPathResult constructor, which correspond to integers from 0 to 9.
  • result: An existing XPathResult to use for the results. null is the most common and will create a new XPathResult

Demonstration

As an example the Search Box within the Google Home Page which can be identified uniquely using the xpath as //*[@name='q'] can also be identified using the Console by the following command:

$x("//*[@name='q']")

Snapshot:

googlesearchbox_xpath

The same element can can also be identified using document.evaluate() and the xpath expression as follows:

document.evaluate("//*[@name='q']", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;

Snapshot:

document_evalute_xpath

Find and replace entire mysql database

I had the same issue on MySQL. I took the procedure from symcbean and adapted her to my needs.

Mine is only replacing textual values (or any type you put in the SELECT FROM information_schema) so if you have date fields, you will not have an error in execution.

Mind the collate in SET @stmt, it must match you database collation.

I used a template request in a variable with multiple replaces but if you have motivation, you could have done it with one CONCAT().

Anyway, if you have serialized data in your database, don't use this. It will not work unless you replace your string with a string with the same lenght.

Hope it helps someone.

DELIMITER $$

DROP PROCEDURE IF EXISTS replace_all_occurences_in_database$$
CREATE PROCEDURE replace_all_occurences_in_database (find_string varchar(255), replace_string varchar(255))
BEGIN
  DECLARE loop_done integer DEFAULT 0;
  DECLARE current_table varchar(255);
  DECLARE current_column varchar(255);
  DECLARE all_columns CURSOR FOR
  SELECT
    t.table_name,
    c.column_name
  FROM information_schema.tables t,
       information_schema.columns c
  WHERE t.table_schema = DATABASE()
  AND c.table_schema = DATABASE()
  AND t.table_name = c.table_name
  AND c.DATA_TYPE IN('varchar', 'text', 'longtext');

  DECLARE CONTINUE HANDLER FOR NOT FOUND
  SET loop_done = 1;

  OPEN all_columns;

table_loop:
LOOP
  FETCH all_columns INTO current_table, current_column;
  IF (loop_done > 0) THEN
    LEAVE table_loop;
  END IF;
  SET @stmt = 'UPDATE `|table|` SET `|column|` = REPLACE(`|column|`, "|find|", "|replace|") WHERE `|column|` LIKE "%|find|%"' COLLATE `utf8mb4_unicode_ci`;
  SET @stmt = REPLACE(@stmt, '|table|', current_table);
  SET @stmt = REPLACE(@stmt, '|column|', current_column);
  SET @stmt = REPLACE(@stmt, '|find|', find_string);
  SET @stmt = REPLACE(@stmt, '|replace|', replace_string);
  PREPARE s1 FROM @stmt;
  EXECUTE s1;
  DEALLOCATE PREPARE s1;
END LOOP;
END
$$

DELIMITER ;

Scale iFrame css width 100% like an image

None of these solutions worked for me inside a Weebly "add your own html" box. Not sure what they are doing with their code. But I found this solution at https://benmarshall.me/responsive-iframes/ and it works perfectly.

CSS

.iframe-container {
  overflow: hidden;
  padding-top: 56.25%;
  position: relative;
}

.iframe-container iframe {
   border: 0;
   height: 100%;
   left: 0;
   position: absolute;
   top: 0;
   width: 100%;
}

/* 4x3 Aspect Ratio */
.iframe-container-4x3 {
  padding-top: 75%;
}

HTML

<div class="iframe-container">
  <iframe src="https://player.vimeo.com/video/106466360" allowfullscreen></iframe>
</div>

How to add an extra column to a NumPy array

In my case, I had to add a column of ones to a NumPy array

X = array([ 6.1101, 5.5277, ... ])
X.shape => (97,)
X = np.concatenate((np.ones((m,1), dtype=np.int), X.reshape(m,1)), axis=1)

After X.shape => (97, 2)

array([[ 1. , 6.1101],
       [ 1. , 5.5277],
...

How to change active class while click to another link in bootstrap use jquery?

_x000D_
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
$(document).ready(function () {_x000D_
        var url = window.location;_x000D_
        $('ul.nav a[href="' + url + '"]').parent().addClass('active');_x000D_
        $('ul.nav a').filter(function () {_x000D_
            return this.href == url;_x000D_
        }).parent().addClass('active').parent().parent().addClass('active');_x000D_
    });_x000D_
    _x000D_
    This works perfectly
_x000D_
_x000D_
_x000D_

Looking for a 'cmake clean' command to clear up CMake output

In these days of Git everywhere, you may forget CMake and use git clean -d -f -x, that will remove all files not under source control.

how to generate a unique token which expires after 24 hours?

I like Guffa's answer and since I can't comment I will provide the answer Udil's question here.

I needed something similar but I wanted certein logic in my token, I wanted to:

  1. See the expiration of a token
  2. Use a guid to mask validate (global application guid or user guid)
  3. See if the token was provided for the purpose I created it (no reuse..)
  4. See if the user I send the token to is the user that I am validating it for

Now points 1-3 are fixed length so it was easy, here is my code:

Here is my code to generate the token:

public string GenerateToken(string reason, MyUser user)
{
    byte[] _time     = BitConverter.GetBytes(DateTime.UtcNow.ToBinary());
    byte[] _key      = Guid.Parse(user.SecurityStamp).ToByteArray();
    byte[] _Id       = GetBytes(user.Id.ToString());
    byte[] _reason   = GetBytes(reason);
    byte[] data       = new byte[_time.Length + _key.Length + _reason.Length+_Id.Length];

    System.Buffer.BlockCopy(_time, 0, data, 0, _time.Length);
    System.Buffer.BlockCopy(_key , 0, data, _time.Length, _key.Length);
    System.Buffer.BlockCopy(_reason, 0, data, _time.Length + _key.Length, _reason.Length);
    System.Buffer.BlockCopy(_Id, 0, data, _time.Length + _key.Length + _reason.Length, _Id.Length);

    return Convert.ToBase64String(data.ToArray());
}

Here is my Code to take the generated token string and validate it:

public TokenValidation ValidateToken(string reason, MyUser user, string token)
{
    var result = new TokenValidation();
    byte[] data     = Convert.FromBase64String(token);
    byte[] _time     = data.Take(8).ToArray();
    byte[] _key      = data.Skip(8).Take(16).ToArray();
    byte[] _reason   = data.Skip(24).Take(2).ToArray();
    byte[] _Id       = data.Skip(26).ToArray();

    DateTime when = DateTime.FromBinary(BitConverter.ToInt64(_time, 0));
    if (when < DateTime.UtcNow.AddHours(-24))
    {
        result.Errors.Add( TokenValidationStatus.Expired);
    }
    
    Guid gKey = new Guid(_key);
    if (gKey.ToString() != user.SecurityStamp)
    {
        result.Errors.Add(TokenValidationStatus.WrongGuid);
    }

    if (reason != GetString(_reason))
    {
        result.Errors.Add(TokenValidationStatus.WrongPurpose);
    }

    if (user.Id.ToString() != GetString(_Id))
    {
        result.Errors.Add(TokenValidationStatus.WrongUser);
    }
    
    return result;
}

private static string GetString(byte[] reason) => Encoding.ASCII.GetString(reason);

private static byte[] GetBytes(string reason) => Encoding.ASCII.GetBytes(reason);

The TokenValidation class looks like this:

public class TokenValidation
{
    public bool Validated { get { return Errors.Count == 0; } }
    public readonly List<TokenValidationStatus> Errors = new List<TokenValidationStatus>();
}

public enum TokenValidationStatus
{
    Expired,
    WrongUser,
    WrongPurpose,
    WrongGuid
}

Now I have an easy way to validate a token, no Need to Keep it in a list for 24 hours or so. Here is my Good-Case Unit test:

private const string ResetPasswordTokenPurpose = "RP";
private const string ConfirmEmailTokenPurpose  = "EC";//change here change bit length for reason  section (2 per char)

[TestMethod]
public void GenerateTokenTest()
{
    MyUser user         = CreateTestUser("name");
    user.Id             = 123;
    user.SecurityStamp  = Guid.NewGuid().ToString();
    var token   = sit.GenerateToken(ConfirmEmailTokenPurpose, user);
    var validation    = sit.ValidateToken(ConfirmEmailTokenPurpose, user, token);
    Assert.IsTrue(validation.Validated,"Token validated for user 123");
}

One can adapt the code for other business cases easely.

Happy Coding

Walter

Get HTML inside iframe using jQuery

This can be another solution if jquery is loaded in iframe.html.

$('#iframe')[0].contentWindow.$("html").html()

Using ffmpeg to encode a high quality video

Unless you do some kind of post-processing work, the video will never be better than the original frames. Also just like a flip-book, if you have a big "jump" between keyframes it will look funny. You generally need enough "tweens" in between the keyframes to give smooth animation. HTH

How to set cache: false in jQuery.get call

I think you have to use the AJAX method instead which allows you to turn caching off:

$.ajax({
  url: "test.html",
  data: 'foo',
  success: function(){
    alert('bar');
  },
  cache: false
});

Save a subplot in matplotlib

While @Eli is quite correct that there usually isn't much of a need to do it, it is possible. savefig takes a bbox_inches argument that can be used to selectively save only a portion of a figure to an image.

Here's a quick example:

import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np

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

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

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

# Save just the portion _inside_ the second axis's boundaries
extent = ax2.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
fig.savefig('ax2_figure.png', bbox_inches=extent)

# Pad the saved area by 10% in the x-direction and 20% in the y-direction
fig.savefig('ax2_figure_expanded.png', bbox_inches=extent.expanded(1.1, 1.2))

The full figure: Full Example Figure


Area inside the second subplot: Inside second subplot


Area around the second subplot padded by 10% in the x-direction and 20% in the y-direction: Full second subplot

php - insert a variable in an echo string

$i = 1;

echo "<p class='paragraph{$i}'></p>"; 

$i++;

launch sms application with an intent

Intent smsIntent = new Intent(Intent.ACTION_VIEW);
smsIntent.setType("vnd.android-dir/mms-sms");
smsIntent.putExtra("address", "12125551212");
smsIntent.putExtra("sms_body","Body of Message");
startActivity(smsIntent);

Differences between contentType and dataType in jQuery ajax function

From the documentation:

contentType (default: 'application/x-www-form-urlencoded; charset=UTF-8')

Type: String

When sending data to the server, use this content type. Default is "application/x-www-form-urlencoded; charset=UTF-8", which is fine for most cases. If you explicitly pass in a content-type to $.ajax(), then it'll always be sent to the server (even if no data is sent). If no charset is specified, data will be transmitted to the server using the server's default charset; you must decode this appropriately on the server side.

and:

dataType (default: Intelligent Guess (xml, json, script, or html))

Type: String

The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string).

They're essentially the opposite of what you thought they were.

Detect viewport orientation, if orientation is Portrait display alert message advising user of instructions

I combined two solutions and it works fine for me.

window.addEventListener("orientationchange", function() {                   
    if (window.matchMedia("(orientation: portrait)").matches) {
       alert("PORTRAIT")
     }
    if (window.matchMedia("(orientation: landscape)").matches) {
      alert("LANSCAPE")
     }
}, false);

How to order events bound with jQuery

Dowski's method is good if all of your callbacks are always going to be present and you are happy with them being dependant on each other.

If you want the callbacks to be independent of each other, though, you could be to take advantage of bubbling and attach subsequent events as delegates to parent elements. The handlers on a parent elements will be triggered after the handlers on the element, continuing right up to the document. This is quite good as you can use event.stopPropagation(), event.preventDefault(), etc to skip handlers and cancel or un-cancel the action.

$( '#mybutton' ).click( function(e) { 
    // Do stuff first
} );

$( '#mybutton' ).click( function(e) { 
    // Do other stuff first
} );

$( document ).delegate( '#mybutton', 'click', function(e) {
    // Do stuff last
} );

Or, if you don't like this, you could use Nick Leaches bindLast plugin to force an event to be bound last: https://github.com/nickyleach/jQuery.bindLast.

Or, if you are using jQuery 1.5, you could also potentially do something clever with the new Deferred object.

What is the simplest and most robust way to get the user's current location on Android?

Here's what I do:

  1. First of all I check what providers are enabled. Some may be disabled on the device, some may be disabled in application manifest.
  2. If any provider is available I start location listeners and timeout timer. It's 20 seconds in my example, may not be enough for GPS so you can enlarge it.
  3. If I get update from location listener I use the provided value. I stop listeners and timer.
  4. If I don't get any updates and timer elapses I have to use last known values.
  5. I grab last known values from available providers and choose the most recent of them.

Here's how I use my class:

LocationResult locationResult = new LocationResult(){
    @Override
    public void gotLocation(Location location){
        //Got the location!
    }
};
MyLocation myLocation = new MyLocation();
myLocation.getLocation(this, locationResult);

And here's MyLocation class:

import java.util.Timer;
import java.util.TimerTask;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;

public class MyLocation {
    Timer timer1;
    LocationManager lm;
    LocationResult locationResult;
    boolean gps_enabled=false;
    boolean network_enabled=false;

    public boolean getLocation(Context context, LocationResult result)
    {
        //I use LocationResult callback class to pass location value from MyLocation to user code.
        locationResult=result;
        if(lm==null)
            lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);

        //exceptions will be thrown if provider is not permitted.
        try{gps_enabled=lm.isProviderEnabled(LocationManager.GPS_PROVIDER);}catch(Exception ex){}
        try{network_enabled=lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);}catch(Exception ex){}

        //don't start listeners if no provider is enabled
        if(!gps_enabled && !network_enabled)
            return false;

        if(gps_enabled)
            lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListenerGps);
        if(network_enabled)
            lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListenerNetwork);
        timer1=new Timer();
        timer1.schedule(new GetLastLocation(), 20000);
        return true;
    }

    LocationListener locationListenerGps = new LocationListener() {
        public void onLocationChanged(Location location) {
            timer1.cancel();
            locationResult.gotLocation(location);
            lm.removeUpdates(this);
            lm.removeUpdates(locationListenerNetwork);
        }
        public void onProviderDisabled(String provider) {}
        public void onProviderEnabled(String provider) {}
        public void onStatusChanged(String provider, int status, Bundle extras) {}
    };

    LocationListener locationListenerNetwork = new LocationListener() {
        public void onLocationChanged(Location location) {
            timer1.cancel();
            locationResult.gotLocation(location);
            lm.removeUpdates(this);
            lm.removeUpdates(locationListenerGps);
        }
        public void onProviderDisabled(String provider) {}
        public void onProviderEnabled(String provider) {}
        public void onStatusChanged(String provider, int status, Bundle extras) {}
    };

    class GetLastLocation extends TimerTask {
        @Override
        public void run() {
             lm.removeUpdates(locationListenerGps);
             lm.removeUpdates(locationListenerNetwork);

             Location net_loc=null, gps_loc=null;
             if(gps_enabled)
                 gps_loc=lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
             if(network_enabled)
                 net_loc=lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

             //if there are both values use the latest one
             if(gps_loc!=null && net_loc!=null){
                 if(gps_loc.getTime()>net_loc.getTime())
                     locationResult.gotLocation(gps_loc);
                 else
                     locationResult.gotLocation(net_loc);
                 return;
             }

             if(gps_loc!=null){
                 locationResult.gotLocation(gps_loc);
                 return;
             }
             if(net_loc!=null){
                 locationResult.gotLocation(net_loc);
                 return;
             }
             locationResult.gotLocation(null);
        }
    }

    public static abstract class LocationResult{
        public abstract void gotLocation(Location location);
    }
}

Somebody may also want to modify my logic. For example if you get update from Network provider don't stop listeners but continue waiting. GPS gives more accurate data so it's worth waiting for it. If timer elapses and you've got update from Network but not from GPS then you can use value provided from Network.

One more approach is to use LocationClient http://developer.android.com/training/location/retrieve-current.html. But it requires Google Play Services apk to be installed on user device.

Start an external application from a Google Chrome Extension?

I go for hypothesys since I can't verify now.

With Apache, if you make a php script on your local machine calling your executable, and then call this script via POST or GET via html/javascript?

would it function?

let me know.

How to Split Image Into Multiple Pieces in Python

from PIL import Image

def crop(path, input, height, width, k, page, area):
    im = Image.open(input)
    imgwidth, imgheight = im.size
    for i in range(0,imgheight,height):
        for j in range(0,imgwidth,width):
            box = (j, i, j+width, i+height)
            a = im.crop(box)
            try:
                o = a.crop(area)
                o.save(os.path.join(path,"PNG","%s" % page,"IMG-%s.png" % k))
            except:
                pass
            k +=1

Combine Date and Time columns using python pandas

Use the combine function:

datetime.datetime.combine(date, time)

Best practice for instantiating a new Android Fragment

The only benefit in using the newInstance() that I see are the following:

  1. You will have a single place where all the arguments used by the fragment could be bundled up and you don't have to write the code below everytime you instantiate a fragment.

    Bundle args = new Bundle();
    args.putInt("someInt", someInt);
    args.putString("someString", someString);
    // Put any other arguments
    myFragment.setArguments(args);
    
  2. Its a good way to tell other classes what arguments it expects to work faithfully(though you should be able to handle cases if no arguments are bundled in the fragment instance).

So, my take is that using a static newInstance() to instantiate a fragment is a good practice.

How to use onSaveInstanceState() and onRestoreInstanceState()?

When your activity is recreated after it was previously destroyed, you can recover your saved state from the Bundle that the system passes your activity. Both the onCreate() and onRestoreInstanceState() callback methods receive the same Bundle that contains the instance state information.

Because the onCreate() method is called whether the system is creating a new instance of your activity or recreating a previous one, you must check whether the state Bundle is null before you attempt to read it. If it is null, then the system is creating a new instance of the activity, instead of restoring a previous one that was destroyed.

static final String STATE_USER = "user";
private String mUser;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Check whether we're recreating a previously destroyed instance
    if (savedInstanceState != null) {
        // Restore value of members from saved state
        mUser = savedInstanceState.getString(STATE_USER);
    } else {
        // Probably initialize members with default values for a new instance
        mUser = "NewUser";
    }
}

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
    savedInstanceState.putString(STATE_USER, mUser);
    // Always call the superclass so it can save the view hierarchy state
    super.onSaveInstanceState(savedInstanceState);
}

http://developer.android.com/training/basics/activity-lifecycle/recreating.html

Object does not support item assignment error

The error seems clear: model objects do not support item assignment. MyModel.objects.latest('id')['foo'] = 'bar' will throw this same error.

It's a little confusing that your model instance is called projectForm...

To reproduce your first block of code in a loop, you need to use setattr

for k,v in session_results.iteritems():
    setattr(projectForm, k, v)

How to remove focus without setting focus to another control?

You could try turning off the main Activity's ability to save its state (thus making it forget what control had text and what had focus). You will need to have some other way of remembering what your EditText's have and repopulating them onResume(). Launch your sub-Activities with startActivityForResult() and create an onActivityResult() handler in your main Activity that will update the EditText's correctly. This way you can set the proper button you want focused onResume() at the same time you repopulate the EditText's by using a myButton.post(new Runnable(){ run() { myButton.requestFocus(); } });

The View.post() method is useful for setting focus initially because that runnable will be executed after the window is created and things settle down, allowing the focus mechanism to function properly by that time. Trying to set focus during onCreate/Start/Resume() usually has issues, I've found.

Please note this is pseudo-code and non-tested, but it's a possible direction you could try.

Compare two files line by line and generate the difference in another file

If you need to solve this with coreutils the accepted answer is good:

comm -23 <(sort file1) <(sort file2) > file3

You can also use sd (stream diff), which doesn't require sorting nor process substitution and supports infinite streams, like so:

cat file1 | sd 'cat file2' > file3

Probably not that much of a benefit on this example, but still consider it; in some cases you won't be able to use comm nor grep -F nor diff.

Here's a blogpost I wrote about diffing streams on the terminal, which introduces sd.

POST JSON fails with 415 Unsupported media type, Spring 3 mvc

I believe I ran exactly into the same issue. After countless hours of fighting with the JSON, the JavaScript and the Server, I found the culprit: In my case I had a Date object in the DTO, this Date object was converted to a String so we could show it in the view with the format: HH:mm.

When JSON information was being sent back, this Date String object had to be converted back into a full Date Object, therefore we also need a method to set it in the DTO. The big BUT is you cannot have 2 methods with the same name (Overload) in the DTO even if they have different type of parameter (String vs Date) because this will give you also the 415 Unsupported Media type error.

This was my controller method

  @RequestMapping(value = "/alarmdownload/update", produces = "application/json", method = RequestMethod.POST)
  public @ResponseBody
  StatusResponse update(@RequestBody AlarmDownloadDTO[] rowList) {
    System.out.println("hola");
    return new StatusResponse();
  }

This was my DTO example (id get/set and preAlarm get Methods are not included for code shortness):

@JsonIgnoreProperties(ignoreUnknown = true)
public class AlarmDownloadDTO implements Serializable {

  private static final SimpleDateFormat formatHHmm = new SimpleDateFormat("HH:mm");

  private String id;
  private Date preAlarm;

  public void setPreAlarm(Date date) { 
    this.preAlarm == date;
  }
  public void setPreAlarm(String date) {    
    try {
      this.preAlarm = formatHHmm.parse(date);
    } catch (ParseException e) {
      this.preAlarm = null;
    } catch (NullPointerException e){
      this.preAlarm = null;
    }
  }
}

To make everything work you need to remove the method with Date type parameter. This error is very frustrating. Hope this can save someone hours of debugging.

Push method in React Hooks (useState)?

The same way you do it with "normal" state in React class components.

example:

function App() {
  const [state, setState] = useState([]);

  return (
    <div>
      <p>You clicked {state.join(" and ")}</p>
      //destructuring
      <button onClick={() => setState([...state, "again"])}>Click me</button>
      //old way
      <button onClick={() => setState(state.concat("again"))}>Click me</button>
    </div>
  );
}

How to see an HTML page on Github as a normal rendered HTML page to see preview in browser, without downloading?

This isn't a direct answer, but I think it is a pretty sweet alternative.

http://www.s3auth.com/

It allows you to host your pages behind basic auth. Great for things like api docs in your private github repo. just ad a s3 put as part of your api build.

Postman - How to see request with headers and body data with variables substituted

As of now, Postman comes with its own "Console." Click the terminal-like icon on the bottom left to open the console. Send a request, and you can inspect the request from within Postman's console.

enter image description here

Shell script to send email

Yes it works fine and is commonly used:

$ echo "hello world" | mail -s "a subject" [email protected]

Splitting templated C++ classes into .hpp/.cpp files--is it possible?

Another possibility is to do something like:

#ifndef _STACK_HPP
#define _STACK_HPP

template <typename Type>
class stack {
    public:
            stack();
            ~stack();
};

#include "stack.cpp"  // Note the include.  The inclusion
                      // of stack.h in stack.cpp must be 
                      // removed to avoid a circular include.

#endif

I dislike this suggestion as a matter of style, but it may suit you.

Python: Total sum of a list of numbers with the for loop

l = [1,2,3,4,5]
sum = 0
for x in l:
    sum = sum + x

And you can change l for any list you want.

How to avoid precompiled headers

You can create an empty project by selecting the "Empty Project" from the "General" group of Visual C++ projects (maybe that project template isn't included in Express?).

To fix the problem in the project you already have, open the project properties and navigate to:

Configuration Properties | C/C++ | Precompiled Headers

And choose "Not using Precompiled Headers" for the "Precompiled Header" option.

Web Application Problems (web.config errors) HTTP 500.19 with IIS7.5 and ASP.NET v2

Aha! I beat this problem! My god, it was a beast for someone like me with limited IIS experience. I really thought I was going to be spending all weekend fixing it.

Here's the solution for anyone else who ever comes this evil problem.

First thing to be aware of: If you're hoping this is your solution, make sure that you have the same Error Code (0x8007000d) and Config Source (-1: 0:). If not, this isn't your solution.

Next thing to be aware of: AJAX is not properly installed in your web.config!

Fix that by following this guide:
http://www.asp.net/AJAX/documentation/live/ConfiguringASPNETAJAX.aspx

Then, install the AJAX 1.0 extensions on your production server, from this link:

http://www.asp.net/ajax/downloads/archive/
Update: Microsoft seems to have removed the above page :(

That's it!

Button background as transparent

Selectors work only for drawables, not styles. Reference


First, to make the button background transparent use the following attribute as this will not affect the material design animations:

style="?attr/buttonBarButtonStyle"

There are many ways to style your button. Check out this tutorial.

Second, to make the text bold on pressed, use this java code:

btn.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {

        switch (event.getAction()) {
            // When the user clicks the Button
            case MotionEvent.ACTION_DOWN:
                btn.setTypeface(Typeface.DEFAULT_BOLD);
                break;

            // When the user releases the Button
            case MotionEvent.ACTION_UP:
                btn.setTypeface(Typeface.DEFAULT);
                break;
        }
        return false;
    }
});

How to avoid "cannot load such file -- utils/popen" from homebrew on OSX

This issue should be fixed in the newest version of Homebrew. Try reinstalling it, which is described on the Homebrew home page.

How do I convert datetime to ISO 8601 in PHP

Object Oriented

This is the recommended way.

$datetime = new DateTime('2010-12-30 23:21:46');

echo $datetime->format(DateTime::ATOM); // Updated ISO8601

Procedural

For older versions of PHP, or if you are more comfortable with procedural code.

echo date(DATE_ISO8601, strtotime('2010-12-30 23:21:46'));

HTML - Change\Update page contents without refreshing\reloading the page

jQuery will do the job. You can use either jQuery.ajax function, which is general one for performing ajax calls, or its wrappers: jQuery.get, jQuery.post for getting/posting data. Its very easy to use, for example, check out this tutorial, which shows how to use jQuery with PHP.

Regex, every non-alphanumeric character except white space or colon

In JavaScript:

/[^\w_]/g

^ negation, i.e. select anything not in the following set

\w any word character (i.e. any alphanumeric character, plus underscore)

_ negate the underscore, as it's considered a 'word' character

Usage example - const nonAlphaNumericChars = /[^\w_]/g;

Tab key == 4 spaces and auto-indent after curly braces in Vim

The auto-indent is based on the current syntax mode. I know that if you are editing Foo.java, then entering a { and hitting Enter indents the following line.

As for tabs, there are two settings. Within Vim, type a colon and then "set tabstop=4" which will set the tabs to display as four spaces. Hit colon again and type "set expandtab" which will insert spaces for tabs.

You can put these settings in a .vimrc (or _vimrc on Windows) in your home directory, so you only have to type them once.

Calculate row means on subset of columns

Calculate row means on a subset of columns:

Create a new data.frame which specifies the first column from DF as an column called ID and calculates the mean of all the other fields on that row, and puts that into column entitled 'Means':

data.frame(ID=DF[,1], Means=rowMeans(DF[,-1]))
  ID    Means
1  A 3.666667
2  B 4.333333
3  C 3.333333
4  D 4.666667
5  E 4.333333

Floating point exception( core dump

You are getting Floating point exception because Number % i, when i is 0:

int Is_Prime( int Number ){

  int i ;

  for( i = 0 ; i < Number / 2 ; i++ ){

    if( Number % i != 0 ) return -1 ;

  }

  return Number ;

}

Just start the loop at i = 2. Since i = 1 in Number % i it always be equal to zero, since Number is a int.

Check substring exists in a string in C

My code to find out if substring is exist in string or not 
// input ( first line -->> string , 2nd lin ->>> no. of queries for substring
following n lines -->> string to check if substring or not..

#include <stdio.h>
int len,len1;
int isSubstring(char *s, char *sub,int i,int j)
{

        int ans =0;
         for(;i<len,j<len1;i++,j++)
        {
                if(s[i] != sub[j])
                {
                    ans =1;
                    break;
                }
        }
        if(j == len1 && ans ==0)
        {
            return 1;
        }
        else if(ans==1)
            return 0;
return 0;
}
int main(){
    char s[100001];
    char sub[100001];
    scanf("%s", &s);// Reading input from STDIN
    int no;
    scanf("%d",&no);
    int i ,j;
    i=0;
    j=0;
    int ans =0;
    len = strlen(s);
    while(no--)
    {
        i=0;
        j=0;
        ans=0;
        scanf("%s",&sub);
        len1=strlen(sub);
        int value;
        for(i=0;i<len;i++)
        {
                if(s[i]==sub[j])
                {
                    value = isSubstring(s,sub,i,j);
                    if(value)
                    {
                        printf("Yes\n");
                        ans = 1;
                        break;
                    }
                }
        }
        if(ans==0)
            printf("No\n");

    }
}

The proxy server received an invalid response from an upstream server

This is not mentioned in you post but I suspect you are initiating an SSL connection from the browser to Apache, where VirtualHosts are configured, and Apache does a revese proxy to your Tomcat.

There is a serious bug in (some versions ?) of IE that sends the 'wrong' host information in an SSL connection (see EDIT below) and confuses the Apache VirtualHosts. In short the server name presented is the one of the reverse DNS resolution of the IP, not the one in the URL.

The workaround is to have one IP address per SSL virtual hosts/server name. Is short, you must end up with something like

1 server name == 1 IP address == 1 certificate == 1 Apache Virtual Host

EDIT

Though the conclusion is correct, the identification of the problem is better described here http://en.wikipedia.org/wiki/Server_Name_Indication

Reading file input from a multipart/form-data POST

I open-sourced a C# Http form parser here.

This is slightly more flexible than the other one mentioned which is on CodePlex, since you can use it for both Multipart and non-Multipart form-data, and also it gives you other form parameters formatted in a Dictionary object.

This can be used as follows:

non-multipart

public void Login(Stream stream)
{
    string username = null;
    string password = null;

    HttpContentParser parser = new HttpContentParser(stream);
    if (parser.Success)
    {
        username = HttpUtility.UrlDecode(parser.Parameters["username"]);
        password = HttpUtility.UrlDecode(parser.Parameters["password"]);
    }
}

multipart

public void Upload(Stream stream)
{
    HttpMultipartParser parser = new HttpMultipartParser(stream, "image");

    if (parser.Success)
    {
        string user = HttpUtility.UrlDecode(parser.Parameters["user"]);
        string title = HttpUtility.UrlDecode(parser.Parameters["title"]);

        // Save the file somewhere
        File.WriteAllBytes(FILE_PATH + title + FILE_EXT, parser.FileContents);
    }
}

How to do error logging in CodeIgniter (PHP)

CodeIgniter has some error logging functions built in.

  • Make your /application/logs folder writable
  • In /application/config/config.php set
    $config['log_threshold'] = 1;
    or use a higher number, depending on how much detail you want in your logs
  • Use log_message('error', 'Some variable did not contain a value.');
  • To send an email you need to extend the core CI_Exceptions class method log_exceptions(). You can do this yourself or use this. More info on extending the core here

See http://www.codeigniter.com/user_guide/general/errors.html

Representing null in JSON

According to the JSON spec, the outermost container does not have to be a dictionary (or 'object') as implied in most of the comments above. It can also be a list or a bare value (i.e. string, number, boolean or null). If you want to represent a null value in JSON, the entire JSON string (excluding the quotes containing the JSON string) is simply null. No braces, no brackets, no quotes. You could specify a dictionary containing a key with a null value ({"key1":null}), or a list with a null value ([null]), but these are not null values themselves - they are proper dictionaries and lists. Similarly, an empty dictionary ({}) or an empty list ([]) are perfectly fine, but aren't null either.

In Python:

>>> print json.loads('{"key1":null}')
{u'key1': None}
>>> print json.loads('[null]')
[None]
>>> print json.loads('[]')
[]
>>> print json.loads('{}')
{}
>>> print json.loads('null')
None

How Can I Set the Default Value of a Timestamp Column to the Current Timestamp with Laravel Migrations?

In laravel 7, to set current time use following:

$table->timestamp('column_name')->useCurrent();

Transaction marked as rollback only: How do I find the cause

Look for exceptions being thrown and caught in the ... sections of your code. Runtime and rollbacking application exceptions cause rollback when thrown out of a business method even if caught on some other place.

You can use context to find out whether the transaction is marked for rollback.

@Resource
private SessionContext context;

context.getRollbackOnly();

displaying a string on the textview when clicking a button in android

public void onCreate(Bundle savedInstanceState) 
{
    setContentView(R.layout.main);
    super.onCreate(savedInstanceState);

    mybtn = (Button)findViewById(R.id.mybtn);
    txtView=(TextView)findViewById(R.id.txtView);

    mybtn .setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            txtView.SetText("Your Message");
        }
    });
}

Convert Json string to Json object in Swift 4

I tried the solutions here, and as? [String:AnyObject] worked for me:

do{
    if let json = stringToParse.data(using: String.Encoding.utf8){
        if let jsonData = try JSONSerialization.jsonObject(with: json, options: .allowFragments) as? [String:AnyObject]{
            let id = jsonData["id"] as! String
            ...
        }
    }
}catch {
    print(error.localizedDescription)

}

How to save LogCat contents to file?

Use logcat tool with -d or -f switch and exec() method.

Saving to a file on the host computer:

exec( "adb logcat -d > logcat.log" ) // logcat is written to logcat.log file on the host.

If you are just saving to a file on the device itself, you can use:

exec( "adb logcat -f logcat.log" ) // logcat is written to logcat.log file on the device.

Fastest way to download a GitHub project

Use

git clone https://github.com/<path>/repository
or
git clone https://github.com/<path>/<master>.git

examples

git clone https://github.com/spring-projects/spring-data-graph-examples
git clone https://github.com/spring-projects/spring-data-graph-examples.git

update listview dynamically with adapter

add and remove methods are easier to use. They update the data in the list and call notifyDataSetChanged in background.

Sample code:

adapter.add("your object");
adapter.remove("your object");

Why use #ifndef CLASS_H and #define CLASS_H in .h file but not in .cpp?

The CLASS_H is an include guard; it's used to avoid the same header file being included multiple times (via different routes) within the same CPP file (or, more accurately, the same translation unit), which would lead to multiple-definition errors.

Include guards aren't needed on CPP files because, by definition, the contents of the CPP file are only read once.

You seem to have interpreted the include guards as having the same function as import statements in other languages (such as Java); that's not the case, however. The #include itself is roughly equivalent to the import in other languages.

What is the difference between the GNU Makefile variable assignments =, ?=, := and +=?

Lazy Set

VARIABLE = value

Normal setting of a variable, but any other variables mentioned with the value field are recursively expanded with their value at the point at which the variable is used, not the one it had when it was declared

Immediate Set

VARIABLE := value

Setting of a variable with simple expansion of the values inside - values within it are expanded at declaration time.

Lazy Set If Absent

VARIABLE ?= value

Setting of a variable only if it doesn't have a value. value is always evaluated when VARIABLE is accessed. It is equivalent to

ifeq ($(origin FOO), undefined)
  FOO = bar
endif

See the documentation for more details.

Append

VARIABLE += value

Appending the supplied value to the existing value (or setting to that value if the variable didn't exist)

MVC 4 @Scripts "does not exist"

If you added to your web.config and it still shows message, then you need to close your project and reopen it, now it will exist and @Styles.Render("") and @Scripts.Render() will work fine.

How to add and remove item from array in components in Vue 2

There are few mistakes you are doing:

  1. You need to add proper object in the array in addRow method
  2. You can use splice method to remove an element from an array at particular index.
  3. You need to pass the current row as prop to my-item component, where this can be modified.

You can see working code here.

addRow(){
   this.rows.push({description: '', unitprice: '' , code: ''}); // what to push unto the rows array?
},
removeRow(index){
   this. itemList.splice(index, 1)
}

What is the best way to compare 2 folder trees on windows?

Beyond compare allows you to do that and much more.

It's one of those tools I can't live without.
Take a look here for a reference on the scripting options

jquery disable form submit on enter

When the file is finished (load complete), the script detect each event for " Entry " key and he disable the event behind.

<script>
            $(document).ready(function () {
                $(window).keydown(function(event){
                    if(event.keyCode == 13) {
                        e.preventDefault(); // Disable the " Entry " key
                        return false;               
                    }
                });
            });
        </script>

How to add property to object in PHP >= 5.3 strict mode without generating error

you should use magic methods __Set and __get. Simple example:

class Foo
{
    //This array stores your properties
private $content = array();

public function __set($key, $value)
{
            //Perform data validation here before inserting data
    $this->content[$key] = $value;
    return $this;
}

public function __get($value)
{       //You might want to check that the data exists here
    return $this->$content[$value];
}

}

Of course, don't use this example as this : no security at all :)

EDIT : seen your comments, here could be an alternative based on reflection and a decorator :

 class Foo
 {
private $content = array();
private $stdInstance;

public function __construct($stdInstance)
{
    $this->stdInstance = $stdInstance;
}

public function __set($key, $value)
{
    //Reflection for the stdClass object
    $ref = new ReflectionClass($this->stdInstance);
    //Fetch the props of the object

    $props = $ref->getProperties();

    if (in_array($key, $props)) {
        $this->stdInstance->$key = $value;
    } else {
        $this->content[$key] = $value;
    }
    return $this;
}

public function __get($value)
{
    //Search first your array as it is faster than using reflection
    if (array_key_exists($value, $this->content))
    {
        return $this->content[$value];
    } else {
        $ref = new ReflectionClass($this->stdInstance);

        //Fetch the props of the object
        $props = $ref->getProperties();

        if (in_array($value, $props)) {

        return $this->stdInstance->$value;
    } else {
        throw new \Exception('No prop in here...');
    }
}
 }
}

PS : I didn't test my code, just the general idea...