Programs & Examples On #Selectall

How to implement "select all" check box in HTML?

html

<input class='all' type='checkbox'> All
<input class='item' type='checkbox' value='1'> 1
<input class='item' type='checkbox' value='2'> 2
<input class='item' type='checkbox' value='3'> 3

javascript

$(':checkbox.all').change(function(){
  $(':checkbox.item').prop('checked', this.checked);
});

Setting environment variables on OS X

Sometimes all of the previous answers simply don't work. If you want to have access to a system variable (like M2_HOME) in Eclipse or in IntelliJ IDEA the only thing that works for me in this case is:

First (step 1) edit /etc/launchd.conf to contain a line like this: "setenv VAR value" and then (step 2) reboot.

Simply modifying .bash_profile won't work because in OS X the applications are not started as in other Unix'es; they don't inherit the parent's shell variables. All the other modifications won't work for a reason that is unknown to me. Maybe someone else can clarify about this.

pandas: multiple conditions while indexing data frame - unexpected behavior

A little mathematical logic theory here:

"NOT a AND NOT b" is the same as "NOT (a OR b)", so:

"a NOT -1 AND b NOT -1" is equivalent of "NOT (a is -1 OR b is -1)", which is opposite (Complement) of "(a is -1 OR b is -1)".

So if you want exact opposite result, df1 and df2 should be as below:

df1 = df[(df.a != -1) & (df.b != -1)]
df2 = df[(df.a == -1) | (df.b == -1)]

Display date/time in user's locale format and time offset

With date from PHP code I used something like this..

function getLocalDate(php_date) {
  var dt = new Date(php_date);
  var minutes = dt.getTimezoneOffset();
  dt = new Date(dt.getTime() + minutes*60000);
  return dt;
}

We can call it like this

var localdateObj = getLocalDate('2015-09-25T02:57:46');

How can I get a list of locally installed Python modules?

For anyone wondering how to call pip list from a Python program you can use the following:

import pip
pip.main(['list])  # this will print all the packages

How to set a background image in Xcode using swift?

Background Image from API in swift 4 (with Kingfisher) :

import UIKit
import Kingfisher

extension UIView {

func addBackgroundImage(imgUrl: String, placeHolder: String){
    let backgroundImage = UIImageView(frame: self.bounds)
    backgroundImage.kf.setImage(with: URL(string: imgUrl), placeholder: UIImage(named: placeHolder))
    backgroundImage.contentMode = UIViewContentMode.scaleAspectFill
    self.insertSubview(backgroundImage, at: 0)

}
}

Usage:

someview.addBackgroundImage(imgUrl: "yourImgUrl", placeHolder: "placeHolderName")

Passing parameters in rails redirect_to

routes.rb

 match 'controller_name/action_name' => 'controller_name#action_name', via: [:get, :post], :as => :abc

Any controller you want to redirect with parameters are given below:

redirect_to abc_path(@abc, id: @id), :notice => "message fine" 

bundle install fails with SSL certificate verification error

I get a slightly different error, though perhaps related, on Ubuntu 12.04:

Gem::RemoteFetcher::FetchError: SSL_connect returned=1 errno=0 state=unknown state: sslv3 alert handshake failure (https://d2chzxaqi4y7f8.cloudfront.net/gems/activesupport-3.2.3.gem)
An error occured while installing activesupport (3.2.3), and Bundler cannot continue.
Make sure that `gem install activesupport -v '3.2.3'` succeeds before bundling.

It happens when I run bundle install with source 'https://rubygems.org' in a Gemfile.

This is an issue with OpenSSL on Ubuntu 12.04. See Rubygems issue #319.

To fix this, run apt-get update && apt-get upgrade on Ubuntu 12.04 to upgrade your OpenSSL.

How do I calculate r-squared using Python and Numpy?

A very late reply, but just in case someone needs a ready function for this:

scipy.stats.linregress

i.e.

slope, intercept, r_value, p_value, std_err = scipy.stats.linregress(x, y)

as in @Adam Marples's answer.

C99 stdint.h header and MS Visual Studio

Just define them yourself.

#ifdef _MSC_VER

typedef __int32 int32_t;
typedef unsigned __int32 uint32_t;
typedef __int64 int64_t;
typedef unsigned __int64 uint64_t;

#else
#include <stdint.h>
#endif

How to get values and keys from HashMap?

Map is internally made up of Map.Entry objects. Each Entry contains key and value. To get key and value from the entry you use accessor and modifier methods.

If you want to get values with given key, use get() method and to insert value, use put() method.

#Define and initialize map;
Map map = new HashMap();
map.put("USA",1)
map.put("Japan",3)
map.put("China",2)
map.put("India",5)
map.put("Germany",4)

map.get("Germany") // returns 4

If you want to get the set of keys from map, you can use keySet() method

Set keys = map.keySet();
System.out.println("All keys are: " + keys);
// To get all key: value
for(String key: keys){
    System.out.println(key + ": " + map.get(key));
}

Generally, To get all keys and values from the map, you have to follow the sequence in the following order:

  • Convert Hashmap to MapSet to get set of entries in Map with entryset() method.:
    Set st = map.entrySet();
  • Get the iterator of this set:
    Iterator it = st.iterator();
  • Get Map.Entry from the iterator:
    Map.Entry entry = it.next();
  • use getKey() and getValue() methods of the Map.Entry to get keys and values.
// Now access it
Set st = (Set) map.entrySet();
Iterator it = st.iterator();
while(it.hasNext()){
    Map.Entry entry = mapIterator.next();
    System.out.print(entry.getKey() + " : " + entry.getValue());
}

In short, use iterator directly in for

for(Map.Entry entry:map.entrySet()){
    System.out.print(entry.getKey() + " : " + entry.getValue());
}

When should iteritems() be used instead of items()?

Just as @Wessie noted, dict.iteritems, dict.iterkeys and dict.itervalues (which return an iterator in Python2.x) as well as dict.viewitems, dict.viewkeys and dict.viewvalues (which return view objects in Python2.x) were all removed in Python3.x

And dict.items, dict.keys and dict.values used to return a copy of the dictionary's list in Python2.x now return view objects in Python3.x, but they are still not the same as iterator.

If you want to return an iterator in Python3.x, use iter(dictview) :

$ python3.3

>>> d = {'one':'1', 'two':'2'}
>>> type(d.items())
<class 'dict_items'>
>>>
>>> type(d.keys())
<class 'dict_keys'>
>>>
>>>
>>> ii = iter(d.items())
>>> type(ii)
<class 'dict_itemiterator'>
>>>
>>> ik = iter(d.keys())
>>> type(ik)
<class 'dict_keyiterator'>

Print an ArrayList with a for-each loop

Your code works. If you don't have any output, you may have "forgotten" to add some values to the list:

// add values
list.add("one");
list.add("two");

// your code
for (String object: list) {
    System.out.println(object);
}

Delete cookie by name?

You should define the path on which the cookie exists to ensure that you are deleting the correct cookie.

function set_cookie(name, value) {
  document.cookie = name +'='+ value +'; Path=/;';
}
function delete_cookie(name) {
  document.cookie = name +'=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;';
}

If you don't specify the path, the browser will set a cookie relative to the page you are currently on, so if you delete the cookie while on a different page, the other cookie continues its existence.

Edit based on @Evan Morrison's comment.
Be aware that in some cases to identify the correct cookie, the Domain parameter is required.
Usually it's defined as Domain=.yourdomain.com.
Placing a dot in front of your domain name means that this cookie may exist on any sub-domain (www also counts as sub-domain).

Also, as mentioned in @RobertT's answer, HttpOnly cookies cannot be deleted with JavaScript on the client side.

What’s the best way to reload / refresh an iframe?

If using jQuery, this seems to work:

$('#your_iframe').attr('src', $('#your_iframe').attr('src'));

I hope it's not too ugly for stackoverflow.

Colorizing text in the console with C++

I'm not sure what you really want to do, but my guess is you want your C++ program to output colored text in the console, right ? Don't know about Windows, but on all Unices (including Mac OS X), you'd simply use ANSI escape sequences for that.

Stop a youtube video with jquery?

Actually you only need javascript and build the embed of the youtube video correctly with swfobject google library

This is an example

<script type="text/javascript" src="swfobject.js"></script>    
<div style="width: 425; height: 356px;">
  <div id="ytapiplayer">
    You need Flash player 8+ and JavaScript enabled to view this video.
  </div>      
  <script type="text/javascript">
    var params = { allowScriptAccess: "always" };
    var atts = { id: "myytplayer" };
    swfobject.embedSWF("http://www.youtube.com/v/y5whWXxGHUA?enablejsapi=1&playerapiid=ytplayer&version=3",
    "ytapiplayer", "425", "356", "8", null, null, params, atts);
  </script>
</div> 

After that you can call this functions:

ytplayer = document.getElementById("myytplayer");
ytplayer.playVideo();
ytplayer.pauseVideo();
ytplayer.stopVideo();

How do I tell if a variable has a numeric value in Perl?

rexep not perfect... this is:

use Try::Tiny;

sub is_numeric {
  my ($x) = @_;
  my $numeric = 1;
  try {
    use warnings FATAL => qw/numeric/;
    0 + $x;
  }
  catch {
    $numeric = 0;
  };
  return $numeric;
}

How to use '-prune' option of 'find' in sh?

There are quite a few answers; some of them are a bit too much theory-heavy. I'll leave why I needed prune once so maybe the need-first/example kind of explanation is useful to someone :)

Problem

I had a folder with about 20 node directories, each having its node_modules directory as expected.

Once you get into any project, you see each ../node_modules/module. But you know how it is. Almost every module has dependencies, so what you are looking at is more like projectN/node_modules/moduleX/node_modules/moduleZ...

I didn't want to drown with a list with the dependency of the dependency of...

Knowing -d n / -depth n, it wouldn't have helped me, as the main/first node_modules directory I wanted of each project was at a different depth, like this:

Projects/MysuperProjectName/project/node_modules/...
Projects/Whatshisname/version3/project/node_modules/...
Projects/project/node_modules/...
Projects/MysuperProjectName/testProject/november2015Copy/project/node_modules/...
[...]

How can I get the first a list of paths ending at the first node_modules and move to the next project to get the same?

Enter -prune

When you add -prune, you'll still have a standard recursive search. Each "path" is analyzed, and every find gets spit out and find keeps digging down like a good chap. But it's the digging down for more node_modules what I didn't want.

So, the difference is that in any of those different paths, -prune will find to stop digging further down that particular avenue when it has found your item. In my case, the node_modules folder.

"error: assignment to expression with array type error" when I assign a struct field (C)

Please check this example here: Accessing Structure Members

There is explained that the right way to do it is like this:

strcpy(s1.name , "Egzona");
printf( "Name : %s\n", s1.name);

Convert string to JSON Object

try:

var myjson = '{"TeamList" : [{"teamid" : "1","teamname" : "Barcelona"}]}';
var newJ= $.parseJSON(myjson);
    alert(newJ.TeamList[0].teamname);

What does (function($) {})(jQuery); mean?

Actually, this example helped me to understand what does (function($) {})(jQuery); mean.

Consider this:

// Clousure declaration (aka anonymous function)
var f = function(x) { return x*x; };
// And use of it
console.log( f(2) ); // Gives: 4

// An inline version (immediately invoked)
console.log( (function(x) { return x*x; })(2) ); // Gives: 4

And now consider this:

  • jQuery is a variable holding jQuery object.
  • $ is a variable name like any other (a, $b, a$b etc.) and it doesn't have any special meaning like in PHP.

Knowing that we can take another look at our example:

var $f = function($) { return $*$; };
var jQuery = 2;
console.log( $f(jQuery) ); // Gives: 4

// An inline version (immediately invoked)
console.log( (function($) { return $*$; })(jQuery) ); // Gives: 4

Escaping ampersand character in SQL string

I wrote a regex to help find and replace "&" within an INSERT, I hope that this helps someone.

The trick was to make sure that the "&" was with other text.

Find “(\'[^\']*(?=\&))(\&)([^\']*\')”

Replace “$1' || chr(38) || '$3”

Including one C source file in another?

The extension of the file does not matter to most C compilers, so it will work.

However, depending on your makefile or project settings the included c file might generate a separate object file. When linking that might lead to double defined symbols.

Python - difference between two strings

You can look into the regex module (the fuzzy section). I don't know if you can get the actual differences, but at least you can specify allowed number of different types of changes like insert, delete, and substitutions:

import regex
sequence = 'afrykanerskojezyczny'
queries = [ 'afrykanerskojezycznym', 'afrykanerskojezyczni', 
            'nieafrykanerskojezyczni' ]
for q in queries:
    m = regex.search(r'(%s){e<=2}'%q, sequence)
    print 'match' if m else 'nomatch'

How to fix corrupted git repository?

In my case, I was creating the repository from source code already in my pc and that error appeared. I deleted the .git folder and did everything again and it worked :)

Intel X86 emulator accelerator (HAXM installer) VT/NX not enabled

Version 1.1.1 is the correct version for Yosemite. You need to download this directly from intel's site: https://software.intel.com/en-us/android/articles/intel-hardware-accelerated-execution-manager.

The one downloaded by SDK Manager is the older version (1.1.0). If you still want to run with version 1.1.0 - refer to the solution here - http://www.csell.net/2014/09/03/VTNX_Not_Enabled/

What is the best way to add a value to an array in state

If you want to keep adding a new object to the array i've been using:

_methodName = (para1, para2) => {
  this.setState({
    arr: this.state.arr.concat({para1, para2})
  })
}

How to connect to LocalDb

Suppose: SqlConnection connectionObj = new SqlConnection()

for : connectionObj.ConnectionString -> use server name : (localdb)\\MSSQLLocalDB.

Note: Double back slash

for : App.config -> use server name : (localdb)\MSSQLLocalDB

Note: Single back slash

Run a mySQL query as a cron job?

It depends on what runs cron on your system, but all you have to do to run a php script from cron is to do call the location of the php installation followed by the script location. An example with crontab running every hour:

# crontab -e
00 * * * * /usr/local/bin/php /home/path/script.php

On my system, I don't even have to put the path to the php installation:

00 * * * * php /home/path/script.php

On another note, you should not be using mysql extension because it is deprecated, unless you are using an older installation of php. Read here for a comparison.

curl: (35) SSL connect error

curl 7.19.7 (x86_64-redhat-linux-gnu) libcurl/7.19.7 NSS/3.19.1 Basic ECC zlib/1.2.3 libidn/1.18 libssh2/1.4.2

You are using a very old version of curl. My guess is that you run into the bug described 6 years ago. Fix is to update your curl.

How do I make a div full screen?

Use document height if you want to show it beyond the visible area of browser(scrollable area).

CSS Portion

#foo {
    position:absolute;
    top:0;
    left:0;
}

JQuery Portion

$(document).ready(function() {
   $('#foo').css({
       width: $(document).width(),
       height: $(document).height()
   });
});

How to create id with AUTO_INCREMENT on Oracle?

it is called Identity Columns and it is available only from oracle Oracle 12c

CREATE TABLE identity_test_tab
(
   id            NUMBER GENERATED ALWAYS AS IDENTITY,
   description   VARCHAR2 (30)
);

example of insert into Identity Columns as below

INSERT INTO identity_test_tab (description) VALUES ('Just DESCRIPTION');

1 row created.

you can NOT do insert like below

INSERT INTO identity_test_tab (id, description) VALUES (NULL, 'ID=NULL and DESCRIPTION');

ERROR at line 1: ORA-32795: cannot insert into a generated always identity column

INSERT INTO identity_test_tab (id, description) VALUES (999, 'ID=999 and DESCRIPTION');

ERROR at line 1: ORA-32795: cannot insert into a generated always identity column

useful link

How to use andWhere and orWhere in Doctrine?

Here's an example for those who have more complicated conditions and using Doctrine 2.* with QueryBuilder:

$qb->where('o.foo = 1')
   ->andWhere($qb->expr()->orX(
      $qb->expr()->eq('o.bar', 1),
      $qb->expr()->eq('o.bar', 2)
   ))
  ;

Those are expressions mentioned in Czechnology answer.

How to add files/folders to .gitignore in IntelliJ IDEA?

Here is the screen print showing the options to ignore the file or folder after the installation of the .ignore plugin. The generated file name would be .gitignore enter image description here

pandas unique values multiple columns

pd.unique returns the unique values from an input array, or DataFrame column or index.

The input to this function needs to be one-dimensional, so multiple columns will need to be combined. The simplest way is to select the columns you want and then view the values in a flattened NumPy array. The whole operation looks like this:

>>> pd.unique(df[['Col1', 'Col2']].values.ravel('K'))
array(['Bob', 'Joe', 'Bill', 'Mary', 'Steve'], dtype=object)

Note that ravel() is an array method that returns a view (if possible) of a multidimensional array. The argument 'K' tells the method to flatten the array in the order the elements are stored in the memory (pandas typically stores underlying arrays in Fortran-contiguous order; columns before rows). This can be significantly faster than using the method's default 'C' order.


An alternative way is to select the columns and pass them to np.unique:

>>> np.unique(df[['Col1', 'Col2']].values)
array(['Bill', 'Bob', 'Joe', 'Mary', 'Steve'], dtype=object)

There is no need to use ravel() here as the method handles multidimensional arrays. Even so, this is likely to be slower than pd.unique as it uses a sort-based algorithm rather than a hashtable to identify unique values.

The difference in speed is significant for larger DataFrames (especially if there are only a handful of unique values):

>>> df1 = pd.concat([df]*100000, ignore_index=True) # DataFrame with 500000 rows
>>> %timeit np.unique(df1[['Col1', 'Col2']].values)
1 loop, best of 3: 1.12 s per loop

>>> %timeit pd.unique(df1[['Col1', 'Col2']].values.ravel('K'))
10 loops, best of 3: 38.9 ms per loop

>>> %timeit pd.unique(df1[['Col1', 'Col2']].values.ravel()) # ravel using C order
10 loops, best of 3: 49.9 ms per loop

How to specify multiple conditions in an if statement in javascript

if((Type == 2 && PageCount == 0) || (Type == 2 && PageCount == '')) {

        PageCount= document.getElementById('<%=hfPageCount.ClientID %>').value;
}

This could be one of possible solutions, so 'or' is || not !!

Open a folder using Process.Start

Strange.

If it can't find explorer.exe, you should get an exception. If it can't find the folder, it should still open some folder (eg my Documents)

You say another copy of Explorer appears in the taskmanager, but you can't see it.

Is it possible that it is opening offscreen (ie another monitor)?

Or are you by any chance doing this in a non-interactive service?

form_for but to post to a different action

Alternatively the same can be reached using form_tag with the syntax:

form_tag({controller: "people", action: "search"}, method: "get", class: "nifty_form")
# => '<form accept-charset="UTF-8" action="/people/search" method="get" class="nifty_form">'

As described in http://guides.rubyonrails.org/form_helpers.html#multiple-hashes-in-form-helper-calls

SQL Insert into table only if record doesn't exist

This might be a simple solution to achieve this:

INSERT INTO funds (ID, date, price)
SELECT 23, DATE('2013-02-12'), 22.5
  FROM dual
 WHERE NOT EXISTS (SELECT 1 
                     FROM funds 
                    WHERE ID = 23
                      AND date = DATE('2013-02-12'));

p.s. alternatively (if ID a primary key):

 INSERT INTO funds (ID, date, price)
    VALUES (23, DATE('2013-02-12'), 22.5)
        ON DUPLICATE KEY UPDATE ID = 23; -- or whatever you need

see this Fiddle.

Passing a Bundle on startActivity()?

You have a few options:

1) Use the Bundle from the Intent:

Intent mIntent = new Intent(this, Example.class);
Bundle extras = mIntent.getExtras();
extras.putString(key, value);  

2) Create a new Bundle

Intent mIntent = new Intent(this, Example.class);
Bundle mBundle = new Bundle();
mBundle.putString(key, value);
mIntent.putExtras(mBundle);

3) Use the putExtra() shortcut method of the Intent

Intent mIntent = new Intent(this, Example.class);
mIntent.putExtra(key, value);


Then, in the launched Activity, you would read them via:

String value = getIntent().getExtras().getString(key)

NOTE: Bundles have "get" and "put" methods for all the primitive types, Parcelables, and Serializables. I just used Strings for demonstrational purposes.

How to fix java.lang.UnsupportedClassVersionError: Unsupported major.minor version

You have used a higher version of the JDK to compile and trying to run from a lower version of JDK/JRE.

To check this, see the version information:

javac -version

java -version

They will be different and javac will have a higher version number.

To get around this, run using java from the JDK version or if you have a newer JRE/JDK that will work as well.

which javac will tell you the location, for example, /usr/bin/javac. Just run directly using /usr/bin/java <program>.

OR you can set the environment variable as a permanent solution.

MySQL - force not to use cache for testing speed of query

You can also run the follow command to reset the query cache.

RESET QUERY CACHE

How to properly overload the << operator for an ostream?

To add to Mehrdad answer ,

namespace Math
{
    class Matrix
    {
       public:

       [...]


    }   
    std::ostream& operator<< (std::ostream& stream, const Math::Matrix& matrix);
}

In your implementation

std::ostream& operator<<(std::ostream& stream, 
                     const Math::Matrix& matrix) {
    matrix.print(stream); //assuming you define print for matrix 
    return stream;
 }

How to create a GUID / UUID

Based on the work of broofa, I've added some more randomness by adding the timestamp to math.random()

Hope it might help

function uuidv4() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        var r = parseFloat('0.' + Math.random().toString().replace('0.', '') + new Date().getTime()) * 16 | 0,
            v = c == 'x' ? r : (r & 0x3 | 0x8);
        return v.toString(16);
    });
}

Can I simultaneously declare and assign a variable in VBA?

In some cases the whole need for declaring a variable can be avoided by using With statement.

For example,

    Dim fd As Office.FileDialog
    Set fd = Application.FileDialog(msoFileDialogSaveAs)
    If fd.Show Then
        'use fd.SelectedItems(1)
    End If

this can be rewritten as

    With Application.FileDialog(msoFileDialogSaveAs)
      If .Show Then
        'use .SelectedItems(1)
      End If
    End With

Counting null and non-null values in a single query

This is little tricky. Assume the table has just one column, then the Count(1) and Count(*) will give different values.

set nocount on
    declare @table1 table (empid int)
    insert @table1 values (1),(2),(3),(4),(5),(6),(7),(8),(9),(10),(NULL),(11),(12),(NULL),(13),(14);

    select * from @table1
    select COUNT(1) as "COUNT(1)" from @table1
    select COUNT(empid) "Count(empid)" from @table1

Query Results

As you can see in the image, The first result shows the table has 16 rows. out of which two rows are NULL. So when we use Count(*) the query engine counts the number of rows, So we got count result as 16. But in case of Count(empid) it counted the non-NULL-values in the column empid. So we got the result as 14.

so whenever we are using COUNT(Column) make sure we take care of NULL values as shown below.

select COUNT(isnull(empid,1)) from @table1

will count both NULL and Non-NULL values.

Note: Same thing applies even when the table is made up of more than one column. Count(1) will give total number of rows irrespective of NULL/Non-NULL values. Only when the column values are counted using Count(Column) we need to take care of NULL values.

nodejs - first argument must be a string or Buffer - when using response.write with http.request

And there is another possibility (not in this case) when working with ajax(XMLhttpRequest), while sending information back to the client end you should use res.send(responsetext) instead of res.end(responsetext)

JavaScript loop through json array?

Your JSON should look like this:

var json = [{
    "id" : "1", 
    "msg"   : "hi",
    "tid" : "2013-05-05 23:35",
    "fromWho": "[email protected]"
},
{
    "id" : "2", 
    "msg"   : "there",
    "tid" : "2013-05-05 23:45",
    "fromWho": "[email protected]"
}];

You can loop over the Array like this:

for(var i = 0; i < json.length; i++) {
    var obj = json[i];

    console.log(obj.id);
}

Or like this (suggested from Eric) be careful with IE support

json.forEach(function(obj) { console.log(obj.id); });

How to get an isoformat datetime string including the default timezone?

With arrow:

>>> import arrow
>>> arrow.now().isoformat()
'2015-04-17T06:36:49.463207-05:00'
>>> arrow.utcnow().isoformat()
'2015-04-17T11:37:17.042330+00:00'

How do you clear a stringstream variable?

This should be the most reliable way regardless of the compiler:

m=std::stringstream();

Import Package Error - Cannot Convert between Unicode and Non Unicode String Data Type

Get to the registry to configuration of the client and change the LANG. For Oracle, go to HLM\SOFTWARE\ORACLE\KEY_ORACLIENT...HOME\NLS_LANG and change to appropriate language.

How to return first 5 objects of Array in Swift?

Update for swift 4:

[0,1,2,3,4,5].enumerated().compactMap{ $0 < 10000 ? $1 : nil }

For swift 3:

[0,1,2,3,4,5].enumerated().flatMap{ $0 < 10000 ? $1 : nil }

How to scan a folder in Java?

Visualizing the tree structure was the most convenient way for me :

public static void main(String[] args) throws IOException {
    printTree(0, new File("START/FROM/DIR"));
}

static void printTree(int depth, File file) throws IOException { 
    StringBuilder indent = new StringBuilder();
    String name = file.getName();

    for (int i = 0; i < depth; i++) {
        indent.append(".");
    }

    //Pretty print for directories
    if (file.isDirectory()) { 
        System.out.println(indent.toString() + "|");
        if(isPrintName(name)){
            System.out.println(indent.toString() + "*" + file.getName() + "*");
        }
    }
    //Print file name
    else if(isPrintName(name)) {
        System.out.println(indent.toString() + file.getName()); 
    }
    //Recurse children
    if (file.isDirectory()) { 
        File[] files = file.listFiles(); 
        for (int i = 0; i < files.length; i++){
            printTree(depth + 4, files[i]);
        } 
    }
}

//Exclude some file names
static boolean isPrintName(String name){
    if (name.charAt(0) == '.') {
        return false;
    }
    if (name.contains("svn")) {
        return false;
    }
    //.
    //. Some more exclusions
    //.
    return true;
}

Escape double quotes in parameter

Another way to escape quotes (though probably not preferable), which I've found used in certain places is to use multiple double-quotes. For the purpose of making other people's code legible, I'll explain.

Here's a set of basic rules:

  1. When not wrapped in double-quoted groups, spaces separate parameters:
    program param1 param2 param 3 will pass four parameters to program.exe:
         param1, param2, param, and 3.
  2. A double-quoted group ignores spaces as value separators when passing parameters to programs:
    program one two "three and more" will pass three parameters to program.exe:
         one, two, and three and more.
  3. Now to explain some of the confusion:
  4. Double-quoted groups that appear directly adjacent to text not wrapped with double-quotes join into one parameter:
    hello"to the entire"world acts as one parameter: helloto the entireworld.
  5. Note: The previous rule does NOT imply that two double-quoted groups can appear directly adjacent to one another.
  6. Any double-quote directly following a closing quote is treated as (or as part of) plain unwrapped text that is adjacent to the double-quoted group, but only one double-quote:
    "Tim says, ""Hi!""" will act as one parameter: Tim says, "Hi!"

Thus there are three different types of double-quotes: quotes that open, quotes that close, and quotes that act as plain-text.
Here's the breakdown of that last confusing line:

"   open double-quote group
T   inside ""s
i   inside ""s
m   inside ""s
    inside ""s - space doesn't separate
s   inside ""s
a   inside ""s
y   inside ""s
s   inside ""s
,   inside ""s
    inside ""s - space doesn't separate
"   close double-quoted group
"   quote directly follows closer - acts as plain unwrapped text: "
H   outside ""s - gets joined to previous adjacent group
i   outside ""s - ...
!   outside ""s - ...
"   open double-quote group
"   close double-quote group
"   quote directly follows closer - acts as plain unwrapped text: "

Thus, the text effectively joins four groups of characters (one with nothing, however):
Tim says,  is the first, wrapped to escape the spaces
"Hi! is the second, not wrapped (there are no spaces)
 is the third, a double-quote group wrapping nothing
" is the fourth, the unwrapped close quote.

As you can see, the double-quote group wrapping nothing is still necessary since, without it, the following double-quote would open up a double-quoted group instead of acting as plain-text.

From this, it should be recognizable that therefore, inside and outside quotes, three double-quotes act as a plain-text unescaped double-quote:

"Tim said to him, """What's been happening lately?""""

will print Tim said to him, "What's been happening lately?" as expected. Therefore, three quotes can always be reliably used as an escape.
However, in understanding it, you may note that the four quotes at the end can be reduced to a mere two since it technically is adding another unnecessary empty double-quoted group.

Here are a few examples to close it off:

program a b                       REM sends (a) and (b)
program """a"""                   REM sends ("a")
program """a b"""                 REM sends ("a) and (b")
program """"Hello,""" Mike said." REM sends ("Hello," Mike said.)
program ""a""b""c""d""            REM sends (abcd) since the "" groups wrap nothing
program "hello to """quotes""     REM sends (hello to "quotes")
program """"hello world""         REM sends ("hello world")
program """hello" world""         REM sends ("hello world")
program """hello "world""         REM sends ("hello) and (world")
program "hello ""world"""         REM sends (hello "world")
program "hello """world""         REM sends (hello "world")

Final note: I did not read any of this from any tutorial - I came up with all of it by experimenting. Therefore, my explanation may not be true internally. Nonetheless all the examples above evaluate as given, thus validating (but not proving) my theory.

I tested this on Windows 7, 64bit using only *.exe calls with parameter passing (not *.bat, but I would suppose it works the same).

Where to get this Java.exe file for a SQL Developer installation

Hhere is what what I did to fix it:

Prerequisite

  • Make sure JDK is installed (Not JRE).
  • Make sure Oracle is installed

After

  1. Open the file ..\sqldeveloper\sqldeveloper\bin\sqldevloper.conf and add the following line to set jdk path:

    SetJavaHome C:\Program Files\Oracle\11g\product\11.1.0\client_1\jdk

    If it dont allow you to save the file, copy whole sqldeveloper folder to a different location where you have write access to modify this file.

  2. Run sqldeveloper.exe (from the new place if you moved the folder out from oracle folders) as administrator and enter the jdk path that comes with your oracle installation: e.g. C:\Program Files\Oracle\11g\product\11.1.0\client_1\jdk\bin

Python webbrowser.open() to open Chrome browser

In Selenium to get the URL of the active tab try,

from selenium import webdriver

driver = webdriver.Firefox()
print driver.current_url # This will print the URL of the Active link

Sending a signal to change the tab

driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + Keys.TAB)

and again use

print driver.current_url

I am here just providing a pseudo code for you.

You can put this in a loop and create your own flow.

I new to Stackoverflow so still learning how to write proper answers.

How do I print to the debug output window in a Win32 app?

You can also use WriteConsole method to print on console.

AllocConsole();
LPSTR lpBuff = "Hello Win32 API";
DWORD dwSize = 0;
WriteConsole(GetStdHandle(STD_OUTPUT_HANDLE), lpBuff, lstrlen(lpBuff), &dwSize, NULL);

Can't use modulus on doubles?

The % operator is for integers. You're looking for the fmod() function.

#include <cmath>

int main()
{
    double x = 6.3;
    double y = 2.0;
    double z = std::fmod(x,y);

}

print memory address of Python variable

id is the method you want to use: to convert it to hex:

hex(id(variable_here))

For instance:

x = 4
print hex(id(x))

Gave me:

0x9cf10c

Which is what you want, right?

(Fun fact, binding two variables to the same int may result in the same memory address being used.)
Try:

x = 4
y = 4
w = 9999
v = 9999
a = 12345678
b = 12345678
print hex(id(x))
print hex(id(y))
print hex(id(w))
print hex(id(v))
print hex(id(a))
print hex(id(b))

This gave me identical pairs, even for the large integers.

Are HTTPS URLs encrypted?

Since nobody provided a wire capture, here's one.
Server Name (the domain part of the URL) is presented in the ClientHello packet, in plain text.

The following shows a browser request to:
https://i.stack.imgur.com/path/?some=parameters&go=here

ClientHello SNI See this answer for more on TLS version fields (there are 3 of them - not versions, fields that each contain a version number!)

From https://www.ietf.org/rfc/rfc3546.txt:

3.1. Server Name Indication

[TLS] does not provide a mechanism for a client to tell a server the name of the server it is contacting. It may be desirable for clients to provide this information to facilitate secure connections to servers that host multiple 'virtual' servers at a single underlying network address.

In order to provide the server name, clients MAY include an extension of type "server_name" in the (extended) client hello.


In short:

  • FQDN (the domain part of the URL) MAY be transmitted in clear inside the ClientHello packet if SNI extension is used

  • The rest of the URL (/path/?some=parameters&go=here) has no business being inside ClientHello since the request URL is a HTTP thing (OSI Layer 7), therefore it will never show up in a TLS handshake (Layer 4 or 5). That will come later on in a GET /path/?some=parameters&go=here HTTP/1.1 HTTP request, AFTER the secure TLS channel is established.


EXECUTIVE SUMMARY

Domain name MAY be transmitted in clear (if SNI extension is used in the TLS handshake) but URL (path and parameters) is always encrypted.


MARCH 2019 UPDATE

Thank you carlin.scott for bringing this one up.

The payload in the SNI extension can now be encrypted via this draft RFC proposal. This capability only exists in TLS 1.3 (as an option and it's up to both ends to implement it) and there is no backwards compatibility with TLS 1.2 and below.

CloudFlare is doing it and you can read more about the internals here — If the chicken must come before the egg, where do you put the chicken?

In practice this means that instead of transmitting the FQDN in plain text (like the Wireshark capture shows), it is now encrypted.

NOTE: This addresses the privacy aspect more than the security one since a reverse DNS lookup MAY reveal the intended destination host anyway.

SEPTEMBER 2020 UPDATE

There's now a draft RFC for encrypting the entire Client Hello message, not just the SNI part: https://datatracker.ietf.org/doc/draft-ietf-tls-esni/?include_text=1

At the time of writing this browser support is VERY limited.

Control cannot fall through from one case label

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

namespace Case_example_1
{
    class Program
    {
        static void Main(string[] args)
        {
            Char ch;
            Console.WriteLine("Enter a character");
            ch =Convert.ToChar(Console.ReadLine());
            switch (ch)
            {
                case 'a':
                case 'e':
                case 'i':
                case 'o':
                case 'u':
                case 'A':
                case 'E':
                case 'I':
                case 'O':
                case 'U':

                    Console.WriteLine("Character is alphabet");
                    break;

                default:
                    Console.WriteLine("Character is constant");
                    break;

            }

            Console.ReadLine();

        }
    }
}

Creating a constant Dictionary in C#

If using 4.5+ Framework I would use ReadOnlyDictionary (also ReadOnly Collection for lists) to do readonly mappings/constants. It's implemented in the following way.

static class SomeClass
{
    static readonly ReadOnlyDictionary<string,int> SOME_MAPPING 
        = new ReadOnlyDictionary<string,int>(
            new Dictionary<string,int>()
            {
                { "One", 1 },
                { "Two", 2 }
            }
        )
}        

KnockoutJs v2.3.0 : Error You cannot apply bindings multiple times to the same element

I finally solved mine by returning { controlsDescendantBindings: true } in the init function of the binding handler. See this

Printing without newline (print 'a',) prints a space, how to remove?

From PEP 3105: print As a Function in the What’s New in Python 2.6 document:

>>> from __future__ import print_function
>>> print('a', end='')

Obviously that only works with python 3.0 or higher (or 2.6+ with a from __future__ import print_function at the beginning). The print statement was removed and became the print() function by default in Python 3.0.

Do Git tags only apply to the current branch?

If you create a tag by e.g.

git tag v1.0

the tag will refer to the most recent commit of the branch you are currently on. You can change branch and create a tag there.

You can also just refer to the other branch while tagging,

git tag v1.0 name_of_other_branch

which will create the tag to the most recent commit of the other branch.

Or you can just put the tag anywhere, no matter which branch, by directly referencing to the SHA1 of some commit

git tag v1.0 <sha1>

Removing empty rows of a data file in R

Here are some dplyr options:

# sample data
df <- data.frame(a = c('1', NA, '3', NA), b = c('a', 'b', 'c', NA), c = c('e', 'f', 'g', NA))

library(dplyr)

# remove rows where all values are NA:
df %>% filter_all(any_vars(!is.na(.)))
df %>% filter_all(any_vars(complete.cases(.)))  


# remove rows where only some values are NA:
df %>% filter_all(all_vars(!is.na(.)))
df %>% filter_all(all_vars(complete.cases(.)))  

# or more succinctly:
df %>% filter(complete.cases(.))  
df %>% na.omit

# dplyr and tidyr:
library(tidyr)
df %>% drop_na

How to force NSLocalizedString to use a specific language

NSLocalizedString() reads the value for the key AppleLanguages from the standard user defaults ([NSUserDefaults standardUserDefaults]). It uses that value to choose an appropriate localization among all existing localizations at runtime. When Apple builds the user defaults dictionary at app launch, they look up the preferred language(s) key in the system preferences and copy the value from there. This also explains for example why changing the language settings in OS X has no effect on running apps, only on apps started thereafter. Once copied, the value is not updated just because the settings change. That's why iOS restarts all apps if you change then language.

However, all values of the user defaults dictionary can be overwritten by command line arguments. See NSUserDefaults documentation on the NSArgumentDomain. This even includes those values that are loaded from the app preferences (.plist) file. This is really good to know if you want to change a value just once for testing.

So if you want to change the language just for testing, you probably don't want to alter your code (if you forget to remove this code later on ...), instead tell Xcode to start your app with a command line parameters (e.g. use Spanish localization):

enter image description here

No need to touch your code at all. Just create different schemes for different languages and you can quickly start the app once in one language and once in another one by just switching the scheme.

How to gracefully handle the SIGKILL signal in Java

There is one way to react to a kill -9: that is to have a separate process that monitors the process being killed and cleans up after it if necessary. This would probably involve IPC and would be quite a bit of work, and you can still override it by killing both processes at the same time. I assume it will not be worth the trouble in most cases.

Whoever kills a process with -9 should theoretically know what he/she is doing and that it may leave things in an inconsistent state.

Vue.js : How to set a unique ID for each component instance?

If you're using TypeScript, without any plugin, you could simply add a static id in your class component and increment it in the created() method. Each component will have a unique id (add a string prefix to avoid collision with another components which use the same tip)

<template>
  <div>
    <label :for="id">Label text for {{id}}</label>
    <input :id="id" type="text" />
  </div>
</template>

<script lang="ts">
  ...
  @Component
  export default class MyComponent extends Vue {
    private id!: string;
    private static componentId = 0;
    ...
    created() {
      MyComponent.componentId += 1;
      this.id = `my-component-${MyComponent.componentId}`;
    }
 </script>

Extract the filename from a path

Find a file using wildcard and getting filename:

Resolve-Path "Package.1.0.191.*.zip" | Split-Path -leaf

“Unable to find manifest signing certificate in the certificate store” - even when add new key

It is not enough to manually add keys to the Windows certificate store. The certificate only contains the signed public key. You must also import the private key that is associated with the public key in the certificate. A .pfx file contains both public and private keys in a single file. That is what you need to import.

Open directory using C

You should really post your code(a), but here goes. Start with something like:

    #include <stdio.h>
    #include <dirent.h>

    int main (int argc, char *argv[]) {
        struct dirent *pDirent;
        DIR *pDir;

        // Ensure correct argument count.

        if (argc != 2) {
            printf ("Usage: testprog <dirname>\n");
            return 1;
        }

        // Ensure we can open directory.

        pDir = opendir (argv[1]);
        if (pDir == NULL) {
            printf ("Cannot open directory '%s'\n", argv[1]);
            return 1;
        }

        // Process each entry.

        while ((pDirent = readdir(pDir)) != NULL) {
            printf ("[%s]\n", pDirent->d_name);
        }

        // Close directory and exit.

        closedir (pDir);
        return 0;
    }

You need to check in your case that args[1] is both set and refers to an actual directory. A sample run, with tmp is a subdirectory off my current directory but you can use any valid directory, gives me: testprog tmp

[.]
[..]
[file1.txt]
[file1_file1.txt]
[file2.avi]
[file2_file2.avi]
[file3.b.txt]
[file3_file3.b.txt]

Note also that you have to pass a directory in, not a file. When I execute:

testprog tmp/file1.txt

I get:

Cannot open directory 'tmp/file1.txt'

That's because it's a file rather than a directory (though, if you're sneaky, you can attempt to use diropen(dirname(argv[1])) if the initial diropen fails).


(a) This has now been rectified but, since this answer has been accepted, I'm going to assume it was the issue of whatever you were passing in.

Find out free space on tablespace

The following query will help to find out free space of tablespaces in MB:

select tablespace_name , sum(bytes)/1024/1024 from dba_free_space group by tablespacE_name order by 1;

How to give a pandas/matplotlib bar graph custom colors

You can specify the color option as a list directly to the plot function.

from matplotlib import pyplot as plt
from itertools import cycle, islice
import pandas, numpy as np  # I find np.random.randint to be better

# Make the data
x = [{i:np.random.randint(1,5)} for i in range(10)]
df = pandas.DataFrame(x)

# Make a list by cycling through the colors you care about
# to match the length of your data.
my_colors = list(islice(cycle(['b', 'r', 'g', 'y', 'k']), None, len(df)))

# Specify this list of colors as the `color` option to `plot`.
df.plot(kind='bar', stacked=True, color=my_colors)

To define your own custom list, you can do a few of the following, or just look up the Matplotlib techniques for defining a color item by its RGB values, etc. You can get as complicated as you want with this.

my_colors = ['g', 'b']*5 # <-- this concatenates the list to itself 5 times.
my_colors = [(0.5,0.4,0.5), (0.75, 0.75, 0.25)]*5 # <-- make two custom RGBs and repeat/alternate them over all the bar elements.
my_colors = [(x/10.0, x/20.0, 0.75) for x in range(len(df))] # <-- Quick gradient example along the Red/Green dimensions.

The last example yields the follow simple gradient of colors for me:

enter image description here

I didn't play with it long enough to figure out how to force the legend to pick up the defined colors, but I'm sure you can do it.

In general, though, a big piece of advice is to just use the functions from Matplotlib directly. Calling them from Pandas is OK, but I find you get better options and performance calling them straight from Matplotlib.

How to do perspective fixing?

The simple solution is to just remap coordinates from the original to the final image, copying pixels from one coordinate space to the other, rounding off as necessary -- which may result in some pixels being copied several times adjacent to each other, and other pixels being skipped, depending on whether you're stretching or shrinking (or both) in either dimension. Make sure your copying iterates through the destination space, so all pixels are covered there even if they're painted more than once, rather than thru the source which may skip pixels in the output.

The better solution involves calculating the corresponding source coordinate without rounding, and then using its fractional position between pixels to compute an appropriate average of the (typically) four pixels surrounding that location. This is essentially a filtering operation, so you lose some resolution -- but the result looks a LOT better to the human eye; it does a much better job of retaining small details and avoids creating straight-line artifacts which humans find objectionable.

Note that the same basic approach can be used to remap flat images onto any other shape, including 3D surface mapping.

How to correct "TypeError: 'NoneType' object is not subscriptable" in recursive function?

What is a when you call Ancestors('A',a)? If a['A'] is None, or if a['A'][0] is None, you'd receive that exception.

How to emulate a BEFORE INSERT trigger in T-SQL / SQL Server for super/subtype (Inheritance) entities?

While Andriy's proposal will work well for INSERTs of a small number of records, full table scans will be done on the final join as both 'enumerated' and '@new_super' are not indexed, resulting in poor performance for large inserts.

This can be resolved by specifying a primary key on the @new_super table, as follows:

DECLARE @new_super TABLE (
  row_num INT IDENTITY(1,1) PRIMARY KEY CLUSTERED,
  super_id   int
);

This will result in the SQL optimizer scanning through the 'enumerated' table but doing an indexed join on @new_super to get the new key.

See changes to a specific file using git

to list only commits details for specific file changes,

git log --follow file_1.rb

to list difference among various commits for same file,

git log -p file_1.rb

to list only commit and its message,

git log --follow --oneline file_1.rb

Best way to represent a Grid or Table in AngularJS with Bootstrap 3?

For anyone reading this post: Do yourself a favor and stay away of ng-grid. Is full of bugs (really..almost every part of the lib is broken somehow), the devs has abandoned the support of 2.0.x branch in order to work in 3.0 which is very far of being ready. Fixing the problems by yourself is not an easy task, ng-grid code is not small and is not simple, unless you have a lot of time and a deep knowledge of angular and js in general, its going to be a hard task.

Bottom Line: is full of bugs, and the last stable version has been abandoned.

The github is full of PRs, but they are being ignored. And if you report a bug in the 2.x branch, it's get closed.

I know is an open source proyect and the complains may sound a little bit out of place, but from the perspective of a developer looking for a library, that's my opinion. I spent many hours working with ng-grid in a large proyect and the headcaches are never ending

Set form backcolor to custom color

If you want to set the form's back color to some arbitrary RGB value, you can do this:

this.BackColor = Color.FromArgb(255, 232, 232); // this should be pink-ish

Android Studio: Unable to start the daemon process

Error:Unable to start the daemon process.

This problem might be caused by incorrect configuration of the daemon. For example, an unrecognized JVM option is used.

Please refer to the user guide chapter on the daemon at https://docs.gradle.org/3.3/userguide/gradle_daemon.html

How to add custom html attributes in JSX

Depending on what version of React you are using, you may need to use something like this. I know Facebook is thinking about deprecating string refs in the somewhat near future.

var Hello = React.createClass({
    componentDidMount: function() {
        ReactDOM.findDOMNode(this.test).setAttribute('custom-attribute', 'some value');
    },
    render: function() {
        return <div>
            <span ref={(ref) => this.test = ref}>Element with a custom attribute</span>
        </div>;
    }
});

React.render(<Hello />, document.getElementById('container'));

Facebook's ref documentation

Variables declared outside function

Unlike languages that employ 'true' lexical scoping, Python opts to have specific 'namespaces' for variables, whether it be global, nonlocal, or local. It could be argued that making developers consciously code with such namespaces in mind is more explicit, thus more understandable. I would argue that such complexities make the language more unwieldy, but I guess it's all down to personal preference.

Here are some examples regarding global:-

>>> global_var = 5
>>> def fn():
...     print(global_var)
... 
>>> fn()
5
>>> def fn_2():
...     global_var += 2
...     print(global_var)
... 
>>> fn_2()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in fn_2
UnboundLocalError: local variable 'global_var' referenced before assignment
>>> def fn_3():
...     global global_var
...     global_var += 2
...     print(global_var)
... 
>>> fn_3()
7

The same patterns can be applied to nonlocal variables too, but this keyword is only available to the latter Python versions.

In case you're wondering, nonlocal is used where a variable isn't global, but isn't within the function definition it's being used. For example, a def within a def, which is a common occurrence partially due to a lack of multi-statement lambdas. There's a hack to bypass the lack of this feature in the earlier Pythons though, I vaguely remember it involving the use of a single-element list...

Note that writing to variables is where these keywords are needed. Just reading from them isn't ambiguous, thus not needed. Unless you have inner defs using the same variable names as the outer ones, which just should just be avoided to be honest.

How to set the current working directory?

import os
print os.getcwd()  # Prints the current working directory

To set the working directory:

os.chdir('c:\\Users\\uname\\desktop\\python')  # Provide the new path here

Read file-contents into a string in C++

The most efficient is to create a buffer of the correct size and then read the file into the buffer.

#include <fstream>
#include <vector>

int main()
{
    std::ifstream       file("Plop");
    if (file)
    {
        /*
         * Get the size of the file
         */
        file.seekg(0,std::ios::end);
        std::streampos          length = file.tellg();
        file.seekg(0,std::ios::beg);

        /*
         * Use a vector as the buffer.
         * It is exception safe and will be tidied up correctly.
         * This constructor creates a buffer of the correct length.
         * Because char is a POD data type it is not initialized.
         *
         * Then read the whole file into the buffer.
         */
        std::vector<char>       buffer(length);
        file.read(&buffer[0],length);
    }
}

Tkinter module not found on Ubuntu

The answer to your question is that Tkinter is renamed to tkinter in python3

that is with lowercase t

C++ variable has initializer but incomplete type?

You use a forward declaration when you need a complete type.

You must have a full definition of the class in order to use it.

The usual way to go about this is:

1) create a file Cat_main.h

2) move

#include <string>

class Cat
{
    public:
        Cat(std::string str);
    // Variables
        std::string name;
    // Functions
        void Meow();
};

to Cat_main.h. Note that inside the header I removed using namespace std; and qualified string with std::string.

3) include this file in both Cat_main.cpp and Cat.cpp:

#include "Cat_main.h"

How to get the path of running java program

Use

System.getProperty("java.class.path")

see http://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html

You can also split it into it's elements easily

String classpath = System.getProperty("java.class.path");
String[] classpathEntries = classpath.split(File.pathSeparator);

Determining complexity for recursive functions (Big O notation)

The key here is to visualise the call tree. Once done that, the complexity is:

nodes of the call tree * complexity of other code in the function

the latter term can be computed the same way we do for a normal iterative function.

Instead, the total nodes of a complete tree are computed as

                  C^L - 1
                  -------  , when C>1
               /   C - 1
              /
 # of nodes =
              \    
               \ 
                  L        , when C=1

Where C is number of children of each node and L is the number of levels of the tree (root included).

It is easy to visualise the tree. Start from the first call (root node) then draw a number of children same as the number of recursive calls in the function. It is also useful to write the parameter passed to the sub-call as "value of the node".

So, in the examples above:

  1. the call tree here is C = 1, L = n+1. Complexity of the rest of function is O(1). Therefore total complexity is L * O(1) = (n+1) * O(1) = O(n)
n     level 1
n-1   level 2
n-2   level 3
n-3   level 4
... ~ n levels -> L = n
  1. call tree here is C = 1, L = n/5. Complexity of the rest of function is O(1). Therefore total complexity is L * O(1) = (n/5) * O(1) = O(n)
n
n-5
n-10
n-15
... ~ n/5 levels -> L = n/5
  1. call tree here is C = 1, L = log(n). Complexity of the rest of function is O(1). Therefore total complexity is L * O(1) = log5(n) * O(1) = O(log(n))
n
n/5
n/5^2
n/5^3
... ~ log5(n) levels -> L = log5(n)
  1. call tree here is C = 2, L = n. Complexity of the rest of function is O(1). This time we use the full formula for the number of nodes in the call tree because C > 1. Therefore total complexity is (C^L-1)/(C-1) * O(1) = (2^n - 1) * O(1) = O(2^n).
               n                   level 1
      n-1             n-1          level 2
  n-2     n-2     n-2     n-2      ...
n-3 n-3 n-3 n-3 n-3 n-3 n-3 n-3    ...     
              ...                ~ n levels -> L = n
  1. call tree here is C = 1, L = n/5. Complexity of the rest of function is O(n). Therefore total complexity is L * O(1) = (n/5) * O(n) = O(n^2)
n
n-5
n-10
n-15
... ~ n/5 levels -> L = n/5

Android: Create spinner programmatically from array

In the same way with Array

// Array of choices
String colors[] = {"Red","Blue","White","Yellow","Black", "Green","Purple","Orange","Grey"};

// Selection of the spinner
Spinner spinner = (Spinner) findViewById(R.id.myspinner);

// Application of the Array to the Spinner
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(this,   android.R.layout.simple_spinner_item, colors);
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down view
spinner.setAdapter(spinnerArrayAdapter);

Scatter plots in Pandas/Pyplot: How to plot by category

You can use df.plot.scatter, and pass an array to c= argument defining the color of each point:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame(np.random.normal(10,1,30).reshape(10,3), index = pd.date_range('2010-01-01', freq = 'M', periods = 10), columns = ('one', 'two', 'three'))
df['key1'] = (4,4,4,6,6,6,8,8,8,8)
colors = np.where(df["key1"]==4,'r','-')
colors[df["key1"]==6] = 'g'
colors[df["key1"]==8] = 'b'
print(colors)
df.plot.scatter(x="one",y="two",c=colors)
plt.show()

enter image description here

Python socket connection timeout

If you are using Python2.6 or newer, it's convenient to use socket.create_connection

sock = socket.create_connection(address, timeout=10)
sock.settimeout(None)
fileobj = sock.makefile('rb', 0)

Excel Macro : How can I get the timestamp in "yyyy-MM-dd hh:mm:ss" format?

Copy and paste this format yyyy-mm-dd hh:MM:ss in format cells by clicking customs category under Type

Set value of textarea in jQuery

i had the same question so i decided to try it in the current browsers (we're one and a half year later in time after this question), and this (.val) works

$("textarea#ExampleMessage").val(result.exampleMessage); 

for

  • IE8
  • FF 3.6
  • FF4
  • Opera 11
  • Chrome 10

How to my "exe" from PyCharm project

You cannot directly save a Python file as an exe and expect it to work -- the computer cannot automatically understand whatever code you happened to type in a text file. Instead, you need to use another program to transform your Python code into an exe.

I recommend using a program like Pyinstaller. It essentially takes the Python interpreter and bundles it with your script to turn it into a standalone exe that can be run on arbitrary computers that don't have Python installed (typically Windows computers, since Linux tends to come pre-installed with Python).

To install it, you can either download it from the linked website or use the command:

pip install pyinstaller

...from the command line. Then, for the most part, you simply navigate to the folder containing your source code via the command line and run:

pyinstaller myscript.py

You can find more information about how to use Pyinstaller and customize the build process via the documentation.


You don't necessarily have to use Pyinstaller, though. Here's a comparison of different programs that can be used to turn your Python code into an executable.

How to check if PHP array is associative or sequential?

Checking if array has all assoc-keys. With using stdClass & get_object_vars ^):

$assocArray = array('fruit1' => 'apple', 
                    'fruit2' => 'orange', 
                    'veg1' => 'tomato', 
                    'veg2' => 'carrot');

$assoc_object = (object) $assocArray;
$isAssoc = (count($assocArray) === count (get_object_vars($assoc_object)));  
var_dump($isAssoc); // true

Why? Function get_object_vars returns only accessible properties (see more about what is occuring during converting array to object here). Then, just logically: if count of basic array's elements equals count of object's accessible properties - all keys are assoc.

Few tests:

$assocArray = array('apple', 'orange', 'tomato', 'carrot');
$assoc_object = (object) $assocArray; 
$isAssoc = (count($assocArray) === count (get_object_vars($assoc_object)));
var_dump($isAssoc); // false 
//...

$assocArray = array( 0 => 'apple', 'orange', 'tomato', '4' => 'carrot');
$assoc_object = (object) $assocArray; 
$isAssoc = (count($assocArray) === count (get_object_vars($assoc_object)));
var_dump($isAssoc); // false 

//... 
$assocArray = array('fruit1' => 'apple', 
                    NULL => 'orange', 
                    'veg1' => 'tomato', 
                    'veg2' => 'carrot');

$assoc_object = (object) $assocArray;
$isAssoc = (count($assocArray) === count (get_object_vars($assoc_object)));  
var_dump($isAssoc); //false

Etc.

Why is there extra padding at the top of my UITableView with style UITableViewStyleGrouped in iOS7

This code worked for me, The best answer for me that was written in objective-C at up-side so I converted it into Swift.

For Swift 4.0+

self.tableView.tableHeaderView = UIView(frame: CGRect(x: 0, y: 0, width: self.tableView.bounds.size.width, height: 0.01))

Just write this into viewDidLoad() and it will work like a charm.

ES6 class variable alternatives

You can mimic es6 classes behaviour... and use your class variables :)

Look mum... no classes!

// Helper
const $constructor = Symbol();
const $extends = (parent, child) =>
  Object.assign(Object.create(parent), child);
const $new = (object, ...args) => {
  let instance = Object.create(object);
  instance[$constructor].call(instance, ...args);
  return instance;
}
const $super = (parent, context, ...args) => {
  parent[$constructor].call(context, ...args)
}
// class
var Foo = {
  classVariable: true,

  // constructor
  [$constructor](who){
    this.me = who;
    this.species = 'fufel';
  },

  // methods
  identify(){
    return 'I am ' + this.me;
  }
}

// class extends Foo
var Bar = $extends(Foo, {

  // constructor
  [$constructor](who){
    $super(Foo, this, who);
    this.subtype = 'barashek';
  },

  // methods
  speak(){
    console.log('Hello, ' + this.identify());
  },
  bark(num){
    console.log('Woof');
  }
});

var a1 = $new(Foo, 'a1');
var b1 = $new(Bar, 'b1');
console.log(a1, b1);
console.log('b1.classVariable', b1.classVariable);

I put it on GitHub

how to get bounding box for div element in jquery

You can get the bounding box of any element by calling getBoundingClientRect

var rect = document.getElementById("myElement").getBoundingClientRect();

That will return an object with left, top, width and height fields.

Can I pass column name as input parameter in SQL stored Procedure

You can pass the column name but you cannot use it in a sql statemnt like

Select @Columnname From Table

One could build a dynamic sql string and execute it like EXEC (@SQL)

For more information see this answer on dynamic sql.

Dynamic SQL Pros and Cons

Detect if an input has text in it using CSS -- on a page I am visiting and do not control?

Simple Trick with jQuery and CSS Like so:

JQuery:

$('input[value=""]').addClass('empty');
        $('input').keyup(function(){
            if( $(this).val() == ""){
                $(this).addClass("empty");
            }else{
                $(this).removeClass("empty");
            }
        });

CSS:

input.empty:valid{
        box-shadow: none;
        background-image: none;
        border: 1px solid #000;
    }

    input:invalid,
    input:required {
        box-shadow: 3px 1px 5px rgba(200, 0, 0, 0.85);
        border: 1px solid rgb(200,0,0);
    }




    input:valid{
        box-shadow: none;
        border: 1px solid #0f0;
    }

how to download file in react js

browsers are smart enough to detect the link and downloading it directly when clicking on an anchor tag without using the download attribute.

after getting your file link from the api, just use plain javascript by creating anchor tag and delete it after clicking on it dynamically immediately on the fly.

const link = document.createElement('a');
link.href = `your_link.pdf`;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);

How to declare a global variable in JavaScript

If you have to generate global variables in production code (which should be avoided) always declare them explicitly:

window.globalVar = "This is global!";

While it is possible to define a global variable by just omitting var (assuming there is no local variable of the same name), doing so generates an implicit global, which is a bad thing to do and would generate an error in strict mode.

How can I schedule a job to run a SQL query daily?

  1. Expand the SQL Server Agent node and right click the Jobs node in SQL Server Agent and select 'New Job'

  2. In the 'New Job' window enter the name of the job and a description on the 'General' tab.

  3. Select 'Steps' on the left hand side of the window and click 'New' at the bottom.

  4. In the 'Steps' window enter a step name and select the database you want the query to run against.

  5. Paste in the T-SQL command you want to run into the Command window and click 'OK'.

  6. Click on the 'Schedule' menu on the left of the New Job window and enter the schedule information (e.g. daily and a time).

  7. Click 'OK' - and that should be it.

(There are of course other options you can add - but I would say that is the bare minimum you need to get a job set up and scheduled)

@import vs #import - iOS 7

There is a few benefits of using modules. You can use it only with Apple's framework unless module map is created. @import is a bit similar to pre-compiling headers files when added to .pch file which is a way to tune app the compilation process. Additionally you do not have to add libraries in the old way, using @import is much faster and efficient in fact. If you still look for a nice reference I will highly recommend you reading this article.

how to get the last character of a string?

Try this...

const str = "linto.yahoo.com."
console.log(str.charAt(str.length-1));

Deep cloning objects

I have created a version of the accepted answer that works with both '[Serializable]' and '[DataContract]'. It has been a while since I wrote it, but if I remember correctly [DataContract] needed a different serializer.

Requires System, System.IO, System.Runtime.Serialization, System.Runtime.Serialization.Formatters.Binary, System.Xml;

public static class ObjectCopier
{

    /// <summary>
    /// Perform a deep Copy of an object that is marked with '[Serializable]' or '[DataContract]'
    /// </summary>
    /// <typeparam name="T">The type of object being copied.</typeparam>
    /// <param name="source">The object instance to copy.</param>
    /// <returns>The copied object.</returns>
    public static T Clone<T>(T source)
    {
        if (typeof(T).IsSerializable == true)
        {
            return CloneUsingSerializable<T>(source);
        }

        if (IsDataContract(typeof(T)) == true)
        {
            return CloneUsingDataContracts<T>(source);
        }

        throw new ArgumentException("The type must be Serializable or use DataContracts.", "source");
    }


    /// <summary>
    /// Perform a deep Copy of an object that is marked with '[Serializable]'
    /// </summary>
    /// <remarks>
    /// Found on http://stackoverflow.com/questions/78536/cloning-objects-in-c-sharp
    /// Uses code found on CodeProject, which allows free use in third party apps
    /// - http://www.codeproject.com/KB/tips/SerializedObjectCloner.aspx
    /// </remarks>
    /// <typeparam name="T">The type of object being copied.</typeparam>
    /// <param name="source">The object instance to copy.</param>
    /// <returns>The copied object.</returns>
    public static T CloneUsingSerializable<T>(T source)
    {
        if (!typeof(T).IsSerializable)
        {
            throw new ArgumentException("The type must be serializable.", "source");
        }

        // Don't serialize a null object, simply return the default for that object
        if (Object.ReferenceEquals(source, null))
        {
            return default(T);
        }

        IFormatter formatter = new BinaryFormatter();
        Stream stream = new MemoryStream();
        using (stream)
        {
            formatter.Serialize(stream, source);
            stream.Seek(0, SeekOrigin.Begin);
            return (T)formatter.Deserialize(stream);
        }
    }


    /// <summary>
    /// Perform a deep Copy of an object that is marked with '[DataContract]'
    /// </summary>
    /// <typeparam name="T">The type of object being copied.</typeparam>
    /// <param name="source">The object instance to copy.</param>
    /// <returns>The copied object.</returns>
    public static T CloneUsingDataContracts<T>(T source)
    {
        if (IsDataContract(typeof(T)) == false)
        {
            throw new ArgumentException("The type must be a data contract.", "source");
        }

        // ** Don't serialize a null object, simply return the default for that object
        if (Object.ReferenceEquals(source, null))
        {
            return default(T);
        }

        DataContractSerializer dcs = new DataContractSerializer(typeof(T));
        using(Stream stream = new MemoryStream())
        {
            using (XmlDictionaryWriter writer = XmlDictionaryWriter.CreateBinaryWriter(stream))
            {
                dcs.WriteObject(writer, source);
                writer.Flush();
                stream.Seek(0, SeekOrigin.Begin);
                using (XmlDictionaryReader reader = XmlDictionaryReader.CreateBinaryReader(stream, XmlDictionaryReaderQuotas.Max))
                {
                    return (T)dcs.ReadObject(reader);
                }
            }
        }
    }


    /// <summary>
    /// Helper function to check if a class is a [DataContract]
    /// </summary>
    /// <param name="type">The type of the object to check.</param>
    /// <returns>Boolean flag indicating if the class is a DataContract (true) or not (false) </returns>
    public static bool IsDataContract(Type type)
    {
        object[] attributes = type.GetCustomAttributes(typeof(DataContractAttribute), false);
        return attributes.Length == 1;
    }

} 

Powershell folder size of folders without listing Subdirectories

You need to get the total contents size of each directory recursively to output. Also, you need to specify that the contents you're grabbing to measure are not directories, or you risk errors (as directories do not have a Length parameter).

Here's your script modified for the output you're looking for:

$colItems = Get-ChildItem $startFolder | Where-Object {$_.PSIsContainer -eq $true} | Sort-Object
foreach ($i in $colItems)
{
    $subFolderItems = Get-ChildItem $i.FullName -recurse -force | Where-Object {$_.PSIsContainer -eq $false} | Measure-Object -property Length -sum | Select-Object Sum
    $i.FullName + " -- " + "{0:N2}" -f ($subFolderItems.sum / 1MB) + " MB"
}

Passing Parameters JavaFX FXML

I realize this is a very old post and has some great answers already, but I wanted to make a simple MCVE to demonstrate one such approach and allow new coders a way to quickly see the concept in action.

In this example, we will use 5 files:

  1. Main.java - Simply used to start the application and call the first controller.
  2. Controller1.java - The controller for the first FXML layout.
  3. Controller2.java - The controller for the second FXML layout.
  4. Layout1.fxml - The FXML layout for the first scene.
  5. Layout2.fxml - The FXML layout for the second scene.

All files are listed in their entirety at the bottom of this post.

The Goal: To demonstrate passing values from Controller1 to Controller2 and vice versa.

The Program Flow:

  • The first scene contains a TextField, a Button, and a Label. When the Button is clicked, the second window is loaded and displayed, including the text entered in the TextField.
  • Within the second scene, there is also a TextField, a Button, and a Label. The Label will display the text entered in the TextField on the first scene.
  • Upon entering text in the second scene's TextField and clicking its Button, the first scene's Label is updated to show the entered text.

This is a very simple demonstration and could surely stand for some improvement, but should make the concept very clear.

The code itself is also commented with some details of what is happening and how.

THE CODE

Main.java:

import javafx.application.Application;
import javafx.stage.Stage;

public class Main extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) {

        // Create the first controller, which loads Layout1.fxml within its own constructor
        Controller1 controller1 = new Controller1();

        // Show the new stage
        controller1.showStage();

    }
}

Controller1.java:

import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.stage.Stage;

import java.io.IOException;

public class Controller1 {

    // Holds this controller's Stage
    private final Stage thisStage;

    // Define the nodes from the Layout1.fxml file. This allows them to be referenced within the controller
    @FXML
    private TextField txtToSecondController;
    @FXML
    private Button btnOpenLayout2;
    @FXML
    private Label lblFromController2;

    public Controller1() {

        // Create the new stage
        thisStage = new Stage();

        // Load the FXML file
        try {
            FXMLLoader loader = new FXMLLoader(getClass().getResource("Layout1.fxml"));

            // Set this class as the controller
            loader.setController(this);

            // Load the scene
            thisStage.setScene(new Scene(loader.load()));

            // Setup the window/stage
            thisStage.setTitle("Passing Controllers Example - Layout1");

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * Show the stage that was loaded in the constructor
     */
    public void showStage() {
        thisStage.showAndWait();
    }

    /**
     * The initialize() method allows you set setup your scene, adding actions, configuring nodes, etc.
     */
    @FXML
    private void initialize() {

        // Add an action for the "Open Layout2" button
        btnOpenLayout2.setOnAction(event -> openLayout2());
    }

    /**
     * Performs the action of loading and showing Layout2
     */
    private void openLayout2() {

        // Create the second controller, which loads its own FXML file. We pass a reference to this controller
        // using the keyword [this]; that allows the second controller to access the methods contained in here.
        Controller2 controller2 = new Controller2(this);

        // Show the new stage/window
        controller2.showStage();

    }

    /**
     * Returns the text entered into txtToSecondController. This allows other controllers/classes to view that data.
     */
    public String getEnteredText() {
        return txtToSecondController.getText();
    }

    /**
     * Allows other controllers to set the text of this layout's Label
     */
    public void setTextFromController2(String text) {
        lblFromController2.setText(text);
    }
}

Controller2.java:

import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.stage.Stage;

import java.io.IOException;

public class Controller2 {

    // Holds this controller's Stage
    private Stage thisStage;

    // Will hold a reference to the first controller, allowing us to access the methods found there.
    private final Controller1 controller1;

    // Add references to the controls in Layout2.fxml
    @FXML
    private Label lblFromController1;
    @FXML
    private TextField txtToFirstController;
    @FXML
    private Button btnSetLayout1Text;

    public Controller2(Controller1 controller1) {
        // We received the first controller, now let's make it usable throughout this controller.
        this.controller1 = controller1;

        // Create the new stage
        thisStage = new Stage();

        // Load the FXML file
        try {
            FXMLLoader loader = new FXMLLoader(getClass().getResource("Layout2.fxml"));

            // Set this class as the controller
            loader.setController(this);

            // Load the scene
            thisStage.setScene(new Scene(loader.load()));

            // Setup the window/stage
            thisStage.setTitle("Passing Controllers Example - Layout2");

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * Show the stage that was loaded in the constructor
     */
    public void showStage() {
        thisStage.showAndWait();
    }

    @FXML
    private void initialize() {

        // Set the label to whatever the text entered on Layout1 is
        lblFromController1.setText(controller1.getEnteredText());

        // Set the action for the button
        btnSetLayout1Text.setOnAction(event -> setTextOnLayout1());
    }

    /**
     * Calls the "setTextFromController2()" method on the first controller to update its Label
     */
    private void setTextOnLayout1() {
        controller1.setTextFromController2(txtToFirstController.getText());
    }

}

Layout1.fxml:

<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.geometry.Insets?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.HBox?>
<?import javafx.scene.layout.VBox?>
<AnchorPane xmlns="http://javafx.com/javafx/9.0.1" xmlns:fx="http://javafx.com/fxml/1">
    <VBox alignment="CENTER" spacing="10.0">
        <padding>
            <Insets bottom="10.0" left="10.0" right="10.0" top="10.0"/>
        </padding>
        <Label style="-fx-font-weight: bold;" text="This is Layout1!"/>
        <HBox alignment="CENTER_LEFT" spacing="10.0">
            <Label text="Enter Text:"/>
            <TextField fx:id="txtToSecondController"/>
            <Button fx:id="btnOpenLayout2" mnemonicParsing="false" text="Open Layout2"/>
        </HBox>
        <VBox alignment="CENTER">
            <Label text="Text From Controller2:"/>
            <Label fx:id="lblFromController2" text="Nothing Yet!"/>
        </VBox>
    </VBox>
</AnchorPane>

Layout2.fxml:

<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.geometry.Insets?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.HBox?>
<?import javafx.scene.layout.VBox?>
<AnchorPane xmlns="http://javafx.com/javafx/9.0.1" xmlns:fx="http://javafx.com/fxml/1">
    <VBox alignment="CENTER" spacing="10.0">
        <padding>
            <Insets bottom="10.0" left="10.0" right="10.0" top="10.0"/>
        </padding>
        <Label style="-fx-font-weight: bold;" text="Welcome to Layout 2!"/>
        <VBox alignment="CENTER">
            <Label text="Text From Controller1:"/>
            <Label fx:id="lblFromController1" text="Nothing Yet!"/>
        </VBox>
        <HBox alignment="CENTER_LEFT" spacing="10.0">
            <Label text="Enter Text:"/>
            <TextField fx:id="txtToFirstController"/>
            <Button fx:id="btnSetLayout1Text" mnemonicParsing="false" text="Set Text on Layout1"/>
        </HBox>
    </VBox>
</AnchorPane>

Multiple variables in a 'with' statement?

You can also separate creating a context manager (the __init__ method) and entering the context (the __enter__ method) to increase readability. So instead of writing this code:

with Company(name, id) as company, Person(name, age, gender) as person, Vehicle(brand) as vehicle:
    pass

you can write this code:

company = Company(name, id)
person = Person(name, age, gender)
vehicle = Vehicle(brand)

with company, person, vehicle:
    pass

Note that creating the context manager outside of the with statement makes an impression that the created object can also be further used outside of the statement. If this is not true for your context manager, the false impression may counterpart the readability attempt.

The documentation says:

Most context managers are written in a way that means they can only be used effectively in a with statement once. These single use context managers must be created afresh each time they’re used - attempting to use them a second time will trigger an exception or otherwise not work correctly.

This common limitation means that it is generally advisable to create context managers directly in the header of the with statement where they are used.

How do I find the index of a character within a string in C?

Just subtract the string address from what strchr returns:

char *string = "qwerty";
char *e;
int index;

e = strchr(string, 'e');
index = (int)(e - string);

Note that the result is zero based, so in above example it will be 2.

Python, how to check if a result set is empty?

cursor.rowcount will usually be set to 0.

If, however, you are running a statement that would never return a result set (such as INSERT without RETURNING, or SELECT ... INTO), then you do not need to call .fetchall(); there won't be a result set for such statements. Calling .execute() is enough to run the statement.


Note that database adapters are also allowed to set the rowcount to -1 if the database adapter can't determine the exact affected count. See the PEP 249 Cursor.rowcount specification:

The attribute is -1 in case no .execute*() has been performed on the cursor or the rowcount of the last operation is cannot be determined by the interface.

The sqlite3 library is prone to doing this. In all such cases, if you must know the affected rowcount up front, execute a COUNT() select in the same transaction first.

SyntaxError: Use of const in strict mode?

The const and let are part of ECMAScript 2015 (a.k.a. ES6 and Harmony), and was not enabled by default in Node.js 0.10 or 0.12. Since Node.js 4.x, “All shipping [ES2015] features, which V8 considers stable, are turned on by default on Node.js and do NOT require any kind of runtime flag.”. Node.js docs has an overview of what ES2015 features are enabled by default, and which who require a runtime flag. So by upgrading to Node.js 4.x or newer the error should disappear.

To enable some of the ECMAScript 2015 features (including const and let) in Node.js 0.10 and 0.12; start your node program with a harmony flag, otherwise you will get a syntax error. For example:

node --harmony app.js

It all depends on which side your strict js is located. I would recommend using strict mode with const declarations on your server side and start the server with the harmony flag. For the client side, you should use Babel or similar tool to convert ES2015 to ES5, since not all client browsers support the const declarations.

$apply already in progress error

If scope must be applied in some cases, then you can set a timeout so that the $apply is deferred until the next tick

setTimeout(function(){ scope.$apply(); });

or wrap your code in a $timeout(function(){ .. }); because it will automatically $apply the scope at the end of execution. If you need your function to behave synchronously, I'd do the first.

SQL: How to perform string does not equal

Another way of getting the results

SELECT * from table WHERE SUBSTRING(tester, 1, 8)  <> 'username' or tester is null

"Missing return statement" within if / for / while

You have to add a return statement if the condition is false.

public String myMethod() {
    if(condition) {
        return x;
    }

//  if condition is false you HAVE TO return a string
//  you could return a string, a empty string or null
    return otherCondition;  
}

FYI:

Oracle docs for return statement

Replace words in the body text

Try to apply the above suggested solution on pretty big document, replacing pretty short strings which might be present in innerHTML or even innerText, and your html design becomes broken at best

Therefore I firstly pickup only text node elements via HTML DOM nodes, like this

function textNodesUnder(node){
  var all = [];
  for (node=node.firstChild;node;node=node.nextSibling){
    if (node.nodeType==3) all.push(node);
    else all = all.concat(textNodesUnder(node));
  }
  return all;
}

textNodes=textNodesUnder(document.body)
for (i in textNodes) { textNodes[i].nodeValue = textNodes[i].nodeValue.replace(/hello/g, 'hi');    

`and followingly I applied the replacement on all of them in cycle

Python: Binding Socket: "Address already in use"

You need to set the allow_reuse_address before binding. Instead of the SimpleHTTPServer run this snippet:

Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
httpd = SocketServer.TCPServer(("", PORT), Handler, bind_and_activate=False)
httpd.allow_reuse_address = True
httpd.server_bind()
httpd.server_activate()
httpd.serve_forever()

This prevents the server from binding before we got a chance to set the flags.

Py_Initialize fails - unable to load the file system codec

Check the PYTHONPATH and PYTHONHOME environment variables and make sure they don't point to Python 2.x.

http://bugs.python.org/issue11288

How update the _id of one MongoDB Document?

You cannot update it. You'll have to save the document using a new _id, and then remove the old document.

// store the document in a variable
doc = db.clients.findOne({_id: ObjectId("4cc45467c55f4d2d2a000002")})

// set a new _id on the document
doc._id = ObjectId("4c8a331bda76c559ef000004")

// insert the document, using the new _id
db.clients.insert(doc)

// remove the document with the old _id
db.clients.remove({_id: ObjectId("4cc45467c55f4d2d2a000002")})

How to set a Fragment tag by code?

You can provide a tag inside your activity layout xml file.

Supply the android:tag attribute with a unique string.

Just as you would assign an id in a layout xml.

    android:tag="unique_tag"

link to developer guide

make an ID in a mysql table auto_increment (after the fact)

None of the above worked for my table. I have a table with an unsigned integer as the primary key with values ranging from 0 to 31543. Currently there are over 19 thousand records. I had to modify the column to AUTO_INCREMENT (MODIFY COLUMN'id'INTEGER UNSIGNED NOT NULL AUTO_INCREMENT) and set the seed(AUTO_INCREMENT = 31544) in the same statement.

ALTER TABLE `'TableName'` MODIFY COLUMN `'id'` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT = 31544;

How to clear jQuery validation error messages?

If you want to simply hide the errors:

$("#clearButton").click(function() {
  $("label.error").hide();
  $(".error").removeClass("error");
});

If you specified the errorClass, call that class to hide instead error (the default) I used above.

Array vs. Object efficiency in JavaScript

In NodeJS if you know the ID, the looping through the array is very slow compared to object[ID].

const uniqueString = require('unique-string');
const obj = {};
const arr = [];
var seeking;

//create data
for(var i=0;i<1000000;i++){
  var getUnique = `${uniqueString()}`;
  if(i===888555) seeking = getUnique;
  arr.push(getUnique);
  obj[getUnique] = true;
}

//retrieve item from array
console.time('arrTimer');
for(var x=0;x<arr.length;x++){
  if(arr[x]===seeking){
    console.log('Array result:');
    console.timeEnd('arrTimer');
    break;
  }
}

//retrieve item from object
console.time('objTimer');
var hasKey = !!obj[seeking];
console.log('Object result:');
console.timeEnd('objTimer');

And the results:

Array result:
arrTimer: 12.857ms
Object result:
objTimer: 0.051ms

Even if the seeking ID is the first one in the array/object:

Array result:
arrTimer: 2.975ms
Object result:
objTimer: 0.068ms

Convert LocalDate to LocalDateTime or java.sql.Timestamp

Java8 +

import java.time.Instant;
Instant.now().getEpochSecond(); //timestamp in seconds format (int)
Instant.now().toEpochMilli(); // timestamp in milliseconds format (long)

How to remove part of a string?

I wanted to remove "www." from a href so I did this:

const str = "https://www.example.com/path";

str.split("www.").join("");

// https://example.com/path

How to add jQuery to an HTML page?

Including the jQuery Library

That is jQuery code. You'll first need to make sure the jQuery library is loaded. If you don't host the library file yourself, you can hotlink one from the jQuery CDN:

<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>

You can do this within the <head> section, but it's fine as long as it's loaded before your jQuery code.

Further reading:


Placing Your Code in the Page

Place your code inside <script> tags. It can be inserted anywhere within either <head> or <body>. If you place it before the <input> and <tr> tags (as referenced in your code), you have to use $(document).ready() to make sure those elements are present before the code is run:

$(document).ready(function() {
    // put your jQuery code here.
});

If you want your page content to be loaded as soon as possible, you might want to place it as close as the </body> close tag as possible. But another common practice is to place all JavaScript code in the <head> section. This is your choice, based on your coding style and needs.

Suggestion: Instead of embedding JS/jQuery code directly into an HTML page, consider placing the code in a separate .js file. This will allow you to reuse the same code on other pages:

<script src="/path/to/your/code.js"></script>

Further reading:

Temporary table in SQL server causing ' There is already an object named' error

Some times you may make silly mistakes like writing insert query on the same .sql file (in the same workspace/tab) so once you execute the insert query where your create query was written just above and already executed, it will again start executing along with the insert query.

This is the reason why we are getting the object name (table name) exists already, since it's getting executed for the second time.

So go to a separate tab to write the insert or drop or whatever queries you are about to execute.

Or else use comment lines preceding all queries in the same workspace like

CREATE -- …
-- Insert query
INSERT INTO -- …

Find closing HTML tag in Sublime Text

There is a shortcut (Ctrl+Shift+A for Windows and Linux users, Command+Shift+A for Mac users) to select the whole block within the currently selected tag.

For example, if you pressed this while your text cursor was within the outer div tag in the code below, all the divs with class selected would be selected.

<div class='current_tag_block'>
  <div class='selected'></div>
  <div class='selected'></div>
  <div class='selected'></div>
  <div class='selected'></div>
</div>

What is the maximum recursion depth in Python, and how to increase it?

We can do that using @lru_cache decorator and setrecursionlimit() method:

import sys
from functools import lru_cache

sys.setrecursionlimit(15000)


@lru_cache(128)
def fib(n: int) -> int:
    if n == 0:
        return 0
    if n == 1:
        return 1

    return fib(n - 2) + fib(n - 1)


print(fib(14000))

Output

3002468761178461090995494179715025648692747937490792943468375429502230242942284835863402333575216217865811638730389352239181342307756720414619391217798542575996541081060501905302157019002614964717310808809478675602711440361241500732699145834377856326394037071666274321657305320804055307021019793251762830816701587386994888032362232198219843549865275880699612359275125243457132496772854886508703396643365042454333009802006384286859581649296390803003232654898464561589234445139863242606285711591746222880807391057211912655818499798720987302540712067959840802106849776547522247429904618357394771725653253559346195282601285019169360207355179223814857106405285007997547692546378757062999581657867188420995770650565521377874333085963123444258953052751461206977615079511435862879678439081175536265576977106865074099512897235100538241196445815568291377846656352979228098911566675956525644182645608178603837172227838896725425605719942300037650526231486881066037397866942013838296769284745527778439272995067231492069369130289154753132313883294398593507873555667211005422003204156154859031529462152953119957597195735953686798871131148255050140450845034240095305094449911578598539658855704158240221809528010179414493499583473568873253067921639513996596738275817909624857593693291980841303291145613566466575233283651420134915764961372875933822262953420444548349180436583183291944875599477240814774580187144637965487250578134990402443365677985388481961492444981994523034245619781853365476552719460960795929666883665704293897310201276011658074359194189359660792496027472226428571547971602259808697441435358578480589837766911684200275636889192254762678512597000452676191374475932796663842865744658264924913771676415404179920096074751516422872997665425047457428327276230059296132722787915300105002019006293320082955378715908263653377755031155794063450515731009402407584683132870206376994025920790298591144213659942668622062191441346200098342943955169522532574271644954360217472458521489671859465232568419404182043966092211744372699797375966048010775453444600153524772238401414789562651410289808994960533132759532092895779406940925252906166612153699850759933762897947175972147868784008320247586210378556711332739463277940255289047962323306946068381887446046387745247925675240182981190836264964640612069909458682443392729946084099312047752966806439331403663934969942958022237945205992581178803606156982034385347182766573351768749665172549908638337611953199808161937885366709285043276595726484068138091188914698151703122773726725261370542355162118164302728812259192476428938730724109825922331973256105091200551566581350508061922762910078528219869913214146575557249199263634241165352226570749618907050553115468306669184485910269806225894530809823102279231750061652042560772530576713148647858705369649642907780603247428680176236527220826640665659902650188140474762163503557640566711903907798932853656216227739411210513756695569391593763704981001125

Source

functools lru_cache

how to set width for PdfPCell in ItextSharp

Why not use a PdfPTable object for this? Create a fixed width table and use a float array to set the widths of the columns

PdfPTable table = new PdfPTable(10);
table.HorizontalAlignment = 0;
table.TotalWidth = 500f;
table.LockedWidth = true;
float[] widths = new float[] { 20f, 60f, 60f, 30f, 50f, 80f, 50f, 50f, 50f, 50f };
table.SetWidths(widths);

addCell(table, "SER.\nNO.", 2);

addCell(table, "TYPE OF SHIPPING", 1);
addCell(table, "ORDER NO.", 1);
addCell(table, "QTY.", 1);
addCell(table, "DISCHARGE PPORT", 1);

addCell(table, "DESCRIPTION OF GOODS", 2);

addCell(table, "LINE DOC. RECL DATE", 1);

addCell(table, "CLEARANCE DATE", 2);
addCell(table, "CUSTOM PERMIT NO.", 2);
addCell(table, "DISPATCH DATE", 2);

addCell(table, "AWB/BL NO.", 1);
addCell(table, "COMPLEX NAME", 1);
addCell(table, "G. W. Kgs.", 1);
addCell(table, "DESTINATION", 1);
addCell(table, "OWNER DOC. RECL DATE", 1);

....

private static void addCell(PdfPTable table, string text, int rowspan)
{
    BaseFont bfTimes = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, false);
    iTextSharp.text.Font times = new iTextSharp.text.Font(bfTimes, 6, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLACK);

    PdfPCell cell = new PdfPCell(new Phrase(text, times));
    cell.Rowspan = rowspan;
    cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
    cell.VerticalAlignment = PdfPCell.ALIGN_MIDDLE;
    table.AddCell(cell);
}

have a look at this tutorial too...

React-router urls don't work when refreshing or writing manually

We used express' 404 handling approach

// path to the static react build directory    
const frontend = path.join(__dirname, 'react-app/build');

// map the requests to the static react build directory
app.use('/', express.static(frontend));

// all the unknown requests are redirected to the react SPA
app.use(function (req, res, next) {
    res.sendFile(path.join(frontend, 'index.html'));
});

Works like a charm. A live demo is our site

org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'customerService' is defined

Please make sure that your applicationContext.xml file is loaded by specifying it in your web.xml file:

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationContext.xml</param-value>
    </context-param>

what is the most efficient way of counting occurrences in pandas?

I think df['word'].value_counts() should serve. By skipping the groupby machinery, you'll save some time. I'm not sure why count should be much slower than max. Both take some time to avoid missing values. (Compare with size.)

In any case, value_counts has been specifically optimized to handle object type, like your words, so I doubt you'll do much better than that.

How to configure Docker port mapping to use Nginx as an upstream proxy?

AJB's "Option B" can be made to work by using the base Ubuntu image and setting up nginx on your own. (It didn't work when I used the Nginx image from Docker Hub.)

Here is the Docker file I used:

FROM ubuntu
RUN apt-get update && apt-get install -y nginx
RUN ln -sf /dev/stdout /var/log/nginx/access.log
RUN ln -sf /dev/stderr /var/log/nginx/error.log
RUN rm -rf /etc/nginx/sites-enabled/default
EXPOSE 80 443
COPY conf/mysite.com /etc/nginx/sites-enabled/mysite.com
CMD ["nginx", "-g", "daemon off;"]

My nginx config (aka: conf/mysite.com):

server {
    listen 80 default;
    server_name mysite.com;

    location / {
        proxy_pass http://website;
    }
}

upstream website {
    server website:3000;
}

And finally, how I start my containers:

$ docker run -dP --name website website
$ docker run -dP --name nginx --link website:website nginx

This got me up and running so my nginx pointed the upstream to the second docker container which exposed port 3000.

Prepend line to beginning of a file

There's no way to do this with any built-in functions, because it would be terribly inefficient. You'd need to shift the existing contents of the file down each time you add a line at the front.

There's a Unix/Linux utility tail which can read from the end of a file. Perhaps you can find that useful in your application.

Javascript Equivalent to C# LINQ Select

Since you're using knockout, you should consider using the knockout utility function arrayMap() and it's other array utility functions.

Here's a listing of array utility functions and their equivalent LINQ methods:

arrayFilter() -> Where()
arrayFirst() -> First()
arrayForEach() -> (no direct equivalent)
arrayGetDistictValues() -> Distinct()
arrayIndexOf() -> IndexOf()
arrayMap() -> Select()
arrayPushAll() -> (no direct equivalent)
arrayRemoveItem() -> (no direct equivalent)
compareArrays() -> (no direct equivalent)

So what you could do in your example is this:

var mapped = ko.utils.arrayMap(selectedFruits, function (fruit) {
    return fruit.id;
});

If you want a LINQ like interface in javascript, you could use a library such as linq.js which offers a nice interface to many of the LINQ methods.

var mapped = Enumerable.From(selectedFruits)
    .Select("$.id") // 1 of 3 different ways to specify a selector function
    .ToArray();

How to display a Yes/No dialog box on Android?

1.Create AlertDialog set message,title and Positive,Negative Button:

final AlertDialog alertDialog = new AlertDialog.Builder(this)
                        .setCancelable(false)
                        .setTitle("Confirmation")
                        .setMessage("Do you want to remove this Picture?")
                        .setPositiveButton("Yes",null)
                        .setNegativeButton("No",null)
                        .create();

2.Now find both buttons on DialogInterface Click then setOnClickListener():

alertDialog.setOnShowListener(new DialogInterface.OnShowListener() {
            @Override
            public void onShow(DialogInterface dialogInterface) {
                Button yesButton = (alertDialog).getButton(android.app.AlertDialog.BUTTON_POSITIVE);
                Button noButton = (alertDialog).getButton(android.app.AlertDialog.BUTTON_NEGATIVE);
                yesButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        //Now Background Class To Update Operator State
                        alertDialog.dismiss();
                        Toast.makeText(GroundEditActivity.this, "Click on Yes", Toast.LENGTH_SHORT).show();
                        //Do Something here 
                    }
                });

                noButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        alertDialog.dismiss();
                        Toast.makeText(GroundEditActivity.this, "Click on No", Toast.LENGTH_SHORT).show();
                        //Do Some Thing Here 
                    }
                });
            }
        });

3.To Show Alertdialog:

alertDialog.show();

Note: Don't forget Final Keyword with AlertDialog.

Split page vertically using CSS

I guess your elements on the page messes up because you don't clear out your floats, check this out

Demo

HTML

<div class="wrap">
    <div class="floatleft"></div>
    <div class="floatright"></div>
    <div style="clear: both;"></div>
</div>

CSS

.wrap {
    width: 100%;
}

.floatleft {
    float:left; 
    width: 80%;
    background-color: #ff0000;
    height: 400px;
}

.floatright {
float: right;
    background-color: #00ff00;
    height: 400px;
    width: 20%;
}

Git Bash is extremely slow on Windows 7 x64

Combined answers:

  1. Wilbert's - what info to include in PS1
  2. sinelaw's - (<branch_name>) or (<sha>)
# https://unix.stackexchange.com/questions/140610/using-variables-to-store-terminal-color-codes-for-ps1/140618#140618
# https://unix.stackexchange.com/questions/124407/what-color-codes-can-i-use-in-my-ps1-prompt
# \033 is the same as \e
# 0;32 is the same as 32
CYAN="$(echo -e "\e[1;36m")"
GREEN="$(echo -e "\e[32m")"
YELLOW="$(echo -e "\e[33m")"
RESET="$(echo -e "\e[0m")"

# https://stackoverflow.com/questions/4485059/git-bash-is-extremely-slow-in-windows-7-x64/19500237#19500237
# https://stackoverflow.com/questions/4485059/git-bash-is-extremely-slow-in-windows-7-x64/13476961#13476961
# https://stackoverflow.com/questions/39518124/check-if-directory-is-git-repository-without-having-to-cd-into-it/39518382#39518382
fast_git_ps1 ()
{
    git -C . rev-parse 2>/dev/null && echo " ($((git symbolic-ref --short -q HEAD || git rev-parse -q --short HEAD) 2> /dev/null))"
}

# you need \] at the end for colors
# Don't set \[ at the beginning or ctrl+up for history will work strangely
PS1='${GREEN}\u@\h ${YELLOW}\w${CYAN}$(fast_git_ps1)${RESET}\] $ '

Result:

frolowr@RWAMW36650 /c/projects/elm-math-kids (master) $

Does "\d" in regex mean a digit?

[0-9] is not always equivalent to \d. In python3, [0-9] matches only 0123456789 characters, while \d matches [0-9] and other digit characters, for example Eastern Arabic numerals ??????????.

select and echo a single field from mysql db using PHP

Read the manual, it covers it very well: http://php.net/manual/en/function.mysql-query.php

Usually you do something like this:

while ($row = mysql_fetch_assoc($result)) {
  echo $row['firstname'];
  echo $row['lastname'];
  echo $row['address'];
  echo $row['age'];
}

How to check if a value exists in an array in Ruby

You're looking for include?:

>> ['Cat', 'Dog', 'Bird'].include? 'Dog'
=> true

How to get an object's methods?

In modern browsers you can use Object.getOwnPropertyNames to get all properties (both enumerable and non-enumerable) on an object. For instance:

function Person ( age, name ) {
    this.age = age;
    this.name = name;
}

Person.prototype.greet = function () {
    return "My name is " + this.name;
};

Person.prototype.age = function () {
    this.age = this.age + 1;
};

// ["constructor", "greet", "age"]
Object.getOwnPropertyNames( Person.prototype );

Note that this only retrieves own-properties, so it will not return properties found elsewhere on the prototype chain. That, however, doesn't appear to be your request so I will assume this approach is sufficient.

If you would only like to see enumerable properties, you can instead use Object.keys. This would return the same collection, minus the non-enumerable constructor property.

jQuery .live() vs .on() method for adding a click event after loading dynamic html

$(document).on('click', '.selector', function() { /* do stuff */ });

EDIT: I'm providing a bit more information on how this works, because... words. With this example, you are placing a listener on the entire document.

When you click on any element(s) matching .selector, the event bubbles up to the main document -- so long as there's no other listeners that call event.stopPropagation() method -- which would top the bubbling of an event to parent elements.

Instead of binding to a specific element or set of elements, you are listening for any events coming from elements that match the specified selector. This means you can create one listener, one time, that will automatically match currently existing elements as well as any dynamically added elements.

This is smart for a few reasons, including performance and memory utilization (in large scale applications)

EDIT:

Obviously, the closest parent element you can listen on is better, and you can use any element in place of document as long as the children you want to monitor events for are within that parent element... but that really does not have anything to do with the question.

MySql : Grant read only options?

Note for MySQL 8 it's different

You need to do it in two steps:

CREATE USER 'readonly_user'@'localhost' IDENTIFIED BY 'some_strong_password';
GRANT SELECT, SHOW VIEW ON *.* TO 'readonly_user'@'localhost';
flush privileges;

How to allow only numeric (0-9) in HTML inputbox using jQuery?

Note: This is an updated answer. Comments below refer to an old version which messed around with keycodes.

jQuery

Try it yourself on JSFiddle.

There is no native jQuery implementation for this, but you can filter the input values of a text <input> with the following inputFilter plugin (supports Copy+Paste, Drag+Drop, keyboard shortcuts, context menu operations, non-typeable keys, the caret position, different keyboard layouts, and all browsers since IE 9):

// Restricts input for the set of matched elements to the given inputFilter function.
(function($) {
  $.fn.inputFilter = function(inputFilter) {
    return this.on("input keydown keyup mousedown mouseup select contextmenu drop", function() {
      if (inputFilter(this.value)) {
        this.oldValue = this.value;
        this.oldSelectionStart = this.selectionStart;
        this.oldSelectionEnd = this.selectionEnd;
      } else if (this.hasOwnProperty("oldValue")) {
        this.value = this.oldValue;
        this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd);
      } else {
        this.value = "";
      }
    });
  };
}(jQuery));

You can now use the inputFilter plugin to install an input filter:

$(document).ready(function() {
  $("#myTextBox").inputFilter(function(value) {
    return /^\d*$/.test(value);    // Allow digits only, using a RegExp
  });
});

See the JSFiddle demo for more input filter examples. Also note that you still must do server side validation!

Pure JavaScript (without jQuery)

jQuery isn't actually needed for this, you can do the same thing with pure JavaScript as well. See this answer.

HTML 5

HTML 5 has a native solution with <input type="number"> (see the specification), but note that browser support varies:

  • Most browsers will only validate the input when submitting the form, and not when typing.
  • Most mobile browsers don't support the step, min and max attributes.
  • Chrome (version 71.0.3578.98) still allows the user to enter the characters e and E into the field. Also see this question.
  • Firefox (version 64.0) and Edge (EdgeHTML version 17.17134) still allow the user to enter any text into the field.

Try it yourself on w3schools.com.

Save classifier to disk in scikit-learn

sklearn.externals.joblib has been deprecated since 0.21 and will be removed in v0.23:

/usr/local/lib/python3.7/site-packages/sklearn/externals/joblib/init.py:15: FutureWarning: sklearn.externals.joblib is deprecated in 0.21 and will be removed in 0.23. Please import this functionality directly from joblib, which can be installed with: pip install joblib. If this warning is raised when loading pickled models, you may need to re-serialize those models with scikit-learn 0.21+.
warnings.warn(msg, category=FutureWarning)


Therefore, you need to install joblib:

pip install joblib

and finally write the model to disk:

import joblib
from sklearn.datasets import load_digits
from sklearn.linear_model import SGDClassifier


digits = load_digits()
clf = SGDClassifier().fit(digits.data, digits.target)

with open('myClassifier.joblib.pkl', 'wb') as f:
    joblib.dump(clf, f, compress=9)

Now in order to read the dumped file all you need to run is:

with open('myClassifier.joblib.pkl', 'rb') as f:
    my_clf = joblib.load(f)

Object variable or With block variable not set (Error 91)

As I wrote in my comment, the solution to your problem is to write the following:

Set hyperLinkText = hprlink.Range

Set is needed because TextRange is a class, so hyperLinkText is an object; as such, if you want to assign it, you need to make it point to the actual object that you need.

jQuery validation plugin: accept only alphabetical characters?

 $('.AlphabetsOnly').keypress(function (e) {
        var regex = new RegExp(/^[a-zA-Z\s]+$/);
        var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
        if (regex.test(str)) {
            return true;
        }
        else {
            e.preventDefault();
            return false;
        }
    });

Getting RAW Soap Data from a Web Reference Client running in ASP.net

Here's a simplified version of the top answer. Add this to the <configuration> element of your web.config or App.config file. It will create a trace.log file in your project's bin/Debug folder. Or, you can specify an absolute path for the log file using the initializeData attribute.

  <system.diagnostics>
    <trace autoflush="true"/>
    <sources>
      <source name="System.Net" maxdatasize="9999" tracemode="protocolonly">
        <listeners>
          <add name="TraceFile" type="System.Diagnostics.TextWriterTraceListener" initializeData="trace.log"/>
        </listeners>
      </source>
    </sources>
    <switches>
      <add name="System.Net" value="Verbose"/>
    </switches>
  </system.diagnostics>

It warns that the maxdatasize and tracemode attributes are not allowed, but they increase the amount of data that can be logged, and avoid logging everything in hex.

Numpy: Get random set of rows from 2D array

I see permutation has been suggested. In fact it can be made into one line:

>>> A = np.random.randint(5, size=(10,3))
>>> np.random.permutation(A)[:2]

array([[0, 3, 0],
       [3, 1, 2]])

VBA using ubound on a multidimensional array

ubound(arr, 1) 

and

ubound(arr, 2) 

Convert JSON format to CSV format for MS Excel

I'm not sure what you're doing, but this will go from JSON to CSV using JavaScript. This is using the open source JSON library, so just download JSON.js into the same folder you saved the code below into, and it will parse the static JSON value in json3 into CSV and prompt you to download/open in Excel.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>JSON to CSV</title>
    <script src="scripts/json.js" type="text/javascript"></script>
    <script type="text/javascript">
    var json3 = { "d": "[{\"Id\":1,\"UserName\":\"Sam Smith\"},{\"Id\":2,\"UserName\":\"Fred Frankly\"},{\"Id\":1,\"UserName\":\"Zachary Zupers\"}]" }

    DownloadJSON2CSV(json3.d);

    function DownloadJSON2CSV(objArray)
    {
        var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;

        var str = '';

        for (var i = 0; i < array.length; i++) {
            var line = '';

            for (var index in array[i]) {
                line += array[i][index] + ',';
            }

            // Here is an example where you would wrap the values in double quotes
            // for (var index in array[i]) {
            //    line += '"' + array[i][index] + '",';
            // }

            line.slice(0,line.Length-1); 

            str += line + '\r\n';
        }
        window.open( "data:text/csv;charset=utf-8," + escape(str))
    }

    </script>

</head>
<body>
    <h1>This page does nothing....</h1>
</body>
</html>

Use awk to find average of a column

awk '{ sum += $2; n++ } END { if (n > 0) print sum / n; }'

Add the numbers in $2 (second column) in sum (variables are auto-initialized to zero by awk) and increment the number of rows (which could also be handled via built-in variable NR). At the end, if there was at least one value read, print the average.

awk '{ sum += $2 } END { if (NR > 0) print sum / NR }'

If you want to use the shebang notation, you could write:

#!/bin/awk

{ sum += $2 }
END { if (NR > 0) print sum / NR }

You can also control the format of the average with printf() and a suitable format ("%13.6e\n", for example).

You can also generalize the code to average the Nth column (with N=2 in this sample) using:

awk -v N=2 '{ sum += $N } END { if (NR > 0) print sum / NR }'

In C, how should I read a text file and print all strings

Use "read()" instead o fscanf:

ssize_t read(int fildes, void *buf, size_t nbyte);

DESCRIPTION

The read() function shall attempt to read nbyte bytes from the file associated with the open file descriptor, fildes, into the buffer pointed to by buf.

Here is an example:

http://cmagical.blogspot.com/2010/01/c-programming-on-unix-implementing-cat.html

Working part from that example:

f=open(argv[1],O_RDONLY);
while ((n=read(f,l,80)) > 0)
    write(1,l,n);

An alternate approach is to use getc/putc to read/write 1 char at a time. A lot less efficient. A good example: http://www.eskimo.com/~scs/cclass/notes/sx13.html

How do I use the includes method in lodash to check if an object is in the collection?

The includes (formerly called contains and include) method compares objects by reference (or more precisely, with ===). Because the two object literals of {"b": 2} in your example represent different instances, they are not equal. Notice:

({"b": 2} === {"b": 2})
> false

However, this will work because there is only one instance of {"b": 2}:

var a = {"a": 1}, b = {"b": 2};
_.includes([a, b], b);
> true

On the other hand, the where(deprecated in v4) and find methods compare objects by their properties, so they don't require reference equality. As an alternative to includes, you might want to try some (also aliased as any):

_.some([{"a": 1}, {"b": 2}], {"b": 2})
> true

Distinct in Linq based on only one field of the table

data.Select(x=>x.Name).Distinct().Select(x => new SelectListItem { Text = x });

Revert to a commit by a SHA hash in Git?

The best way to rollback to a specific commit is:

git reset --hard <commit-id>

Then:

git push <reponame> -f

The authorization mechanism you have provided is not supported. Please use AWS4-HMAC-SHA256

Code for Flask (boto3)

Don't forget to import Config. Also If you have your own config class, then change its name.

from botocore.client import Config

s3 = boto3.client('s3',config=Config(signature_version='s3v4'),region_name=app.config["AWS_REGION"],aws_access_key_id=app.config['AWS_ACCESS_KEY'], aws_secret_access_key=app.config['AWS_SECRET_KEY'])
s3.upload_fileobj(file,app.config["AWS_BUCKET_NAME"],file.filename)
url = s3.generate_presigned_url('get_object', Params = {'Bucket':app.config["AWS_BUCKET_NAME"] , 'Key': file.filename}, ExpiresIn = 10000)

How to query the permissions on an Oracle directory?

With Oracle 11g R2 (at least with 11.2.02) there is a view named datapump_dir_objs.

SELECT * FROM datapump_dir_objs;

The view shows the NAME of the directory object, the PATH as well as READ and WRITE permissions for the currently connected user. It does not show any directory objects which the current user has no permission to read from or write to, though.

What is a stored procedure?

Generally, a stored procedure is a "SQL Function." They have:

-- a name
CREATE PROCEDURE spGetPerson
-- parameters
CREATE PROCEDURE spGetPerson(@PersonID int)
-- a body
CREATE PROCEDURE spGetPerson(@PersonID int)
AS
SELECT FirstName, LastName ....
FROM People
WHERE PersonID = @PersonID

This is a T-SQL focused example. Stored procedures can execute most SQL statements, return scalar and table-based values, and are considered to be more secure because they prevent SQL injection attacks.

How to update std::map after using the find method?

You can use std::map::at member function, it returns a reference to the mapped value of the element identified with key k.

std::map<char,int> mymap = {
                               { 'a', 0 },
                               { 'b', 0 },
                           };

  mymap.at('a') = 10;
  mymap.at('b') = 20;

The maximum value for an int type in Go

MaxInt8   = 1<<7 - 1
MinInt8   = -1 << 7
MaxInt16  = 1<<15 - 1
MinInt16  = -1 << 15
MaxInt32  = 1<<31 - 1
MinInt32  = -1 << 31
MaxInt64  = 1<<63 - 1
MinInt64  = -1 << 63
MaxUint8  = 1<<8 - 1
MaxUint16 = 1<<16 - 1
MaxUint32 = 1<<32 - 1
MaxUint64 = 1<<64 - 1

Write applications in C or C++ for Android?

The Android NDK is a toolset that lets you implement parts of your app in native code, using languages such as C and C++. For certain types of apps, this can help you reuse code libraries written in those languages.

For more info on how to get started with native development, follow this link.

Sample applications can be found here.

Count immediate child div elements using jQuery

var n_numTabs = $("#superpics div").size();

or

var n_numTabs = $("#superpics div").length;

As was already said, both return the same result.
But the size() function is more jQuery "P.C".
I had a similar problem with my page.
For now on, just omit the > and it should work fine.

Why do I get a C malloc assertion failure?

I was porting one application from Visual C to gcc over Linux and I had the same problem with

malloc.c:3096: sYSMALLOc: Assertion using gcc on UBUNTU 11.

I moved the same code to a Suse distribution (on other computer ) and I don't have any problem.

I suspect that the problems are not in our programs but in the own libc.

Java : Comparable vs Comparator

When your class implements Comparable, the compareTo method of the class is defining the "natural" ordering of that object. That method is contractually obligated (though not demanded) to be in line with other methods on that object, such as a 0 should always be returned for objects when the .equals() comparisons return true.

A Comparator is its own definition of how to compare two objects, and can be used to compare objects in a way that might not align with the natural ordering.

For example, Strings are generally compared alphabetically. Thus the "a".compareTo("b") would use alphabetical comparisons. If you wanted to compare Strings on length, you would need to write a custom comparator.

In short, there isn't much difference. They are both ends to similar means. In general implement comparable for natural order, (natural order definition is obviously open to interpretation), and write a comparator for other sorting or comparison needs.

SQL Server function to return minimum date (January 1, 1753)

Have you seen the SqlDateTime object? use SqlDateTime.MinValue to get your minimum date (Jan 1 1753).

how to reset <input type = "file">

Particularly for Angular

document.getElementById('uploadFile').value = "";

Will work, But if you use Angular It will say "Property 'value' does not exist on type 'HTMLElement'.any"

document.getElementById() returns the type HTMLElement which does not contain a value property. So, cast it into HTMLInputElement

(<HTMLInputElement>document.getElementById('uploadFile')).value = "";

EXTRA :-

However, we should not use DOM manipulation (document.xyz()) in angular.

To do that angular has provided @VIewChild, @ViewChildren, etc which are document.querySelector(), document.queryselectorAll() respectively.

Even I haven't read it. Better to follows expert's blogs

Go through this link1, link2

No line-break after a hyphen

You can also do it "the joiner way" by inserting "U+2060 Word Joiner".

If Accept-Charset permits, the unicode character itself can be inserted directly into the HTML output.

Otherwise, it can be done using entity encoding. E.g. to join the text red-brown, use:

red-&#x2060;brown

or (decimal equivalent):

red-&#8288;brown

. Another usable character is "U+FEFF Zero Width No-break Space"[⁠ ⁠1 ]:

red-&#xfeff;brown

and (decimal equivalent):

red-&#65279;brown

[1]: Note that while this method still works in major browsers like Chrome, it has been deprecated since Unicode 3.2.


Comparison of "the joiner way" with "U+2011 Non-breaking Hyphen":

  • The word joiner can be used for all other characters, not just hyphens.

  • When using the word joiner, most renderers will rasterize the text identically. On Chrome, FireFox, IE, and Opera, the rendering of normal hyphens, eg:

    a-b-c-d-e-f-g-h-i-j-k-l-m-n-o-p-q-r-s-t-u-v-w-x-y-z

    is identical to the rendering of normal hyphens (with U+2060 Word Joiner), eg:

    a-⁠b-⁠c-⁠d-⁠e-⁠f-⁠g-⁠h-⁠i-⁠j-⁠k-⁠l-⁠m-⁠n-⁠o-⁠p-⁠q-⁠r-⁠s-⁠t-⁠u-⁠v-⁠w-⁠x-⁠y-⁠z

    while the above two renders differ from the rendering of "Non-breaking Hyphen", eg:

    a‑b‑c‑d‑e‑f‑g‑h‑i‑j‑k‑l‑m‑n‑o‑p‑q‑r‑s‑t‑u‑v‑w‑x‑y‑z

    . (The extent of the difference is browser-dependent and font-dependent. E.g. when using a font declaration of "arial", Firefox and IE11 show relatively huge variations, while Chrome and Opera show smaller variations.)

Comparison of "the joiner way" with <span class=c1></span> (CSS .c1 {white-space:nowrap;}) and <nobr></nobr>:

  • The word joiner can be used for situations where usage of HTML tags is restricted, e.g. forms of websites and forums.

  • On the spectrum of presentation and content, majority will consider the word joiner to be closer to content, when compared to tags.


• As tested on Windows 8.1 Core 64-bit using:
    • IE 11.0.9600.18205
    • Firefox 43.0.4
    • Chrome 48.0.2564.109 (Official Build) m (32-bit)
    • Opera 35.0.2066.92

.htaccess deny from all

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

2.2 configuration syntax was

Order deny,allow
Deny from all

2.4 configuration now is

Require all denied

Thus, this 2.2 syntax

order deny,allow
deny from all
allow from 127.0.0.1

Would ne now written

Require local

git status (nothing to commit, working directory clean), however with changes commited

Your local branch doensn't know about the remote branch. If you don't tell git that your local branch (master) is supposed to compare itself to the remote counterpart (origin/master in this case); then git status won't tell you the difference between your branch and the remote one. So you should use:

git branch --set-upstream-to origin/master

or with the short option:

git branch -u origin/master

This options --set-upstream-to (or -u in short) was introduced in git 1.8.0.

Once you have set this option; git status will show you something like:

# Your branch is ahead of 'origin/master' by 1 commit.

Getting command-line password input in Python

Use getpass for this purpose.

getpass.getpass - Prompt the user for a password without echoing

jQuery: selecting each td in a tr

Your $(magicSelector) could be $('td', this). This will grab all td that are children of this, which in your case is each tr. This is the same as doing $(this).find('td').

$('td', this).each(function() {
// Logic
});

How to solve "sign_and_send_pubkey: signing failed: agent refused operation"?

This should be rather a SuperUser question.

Right I have the exact same error inside MacOSX SourceTree, however, inside a iTerm2 terminal, things work just dandy.

However, the problem seemed to be that I've got two ssh-agents running ;(

The first being /usr/bin/ssh-agent (aka MacOSX's) and then also the HomeBrew installed /usr/local/bin/ssh-agent running.

Firing up a terminal from SourceTree, allowed me to see the differences in SSH_AUTH_SOCK, using lsof I found the two different ssh-agents and then I was able to load the keys (using ssh-add) into the system's default ssh-agent (ie. /usr/bin/ssh-agent), SourceTree was working again.

Create a BufferedImage from file and make it TYPE_INT_ARGB

Create a BufferedImage from file and make it TYPE_INT_RGB

import java.io.*;
import java.awt.image.*;
import javax.imageio.*;
public class Main{
    public static void main(String args[]){
        try{
            BufferedImage img = new BufferedImage( 
                500, 500, BufferedImage.TYPE_INT_RGB );
            File f = new File("MyFile.png");
            int r = 5;
            int g = 25; 
            int b = 255;
            int col = (r << 16) | (g << 8) | b;
            for(int x = 0; x < 500; x++){
                for(int y = 20; y < 300; y++){
                    img.setRGB(x, y, col);
                }
            }
            ImageIO.write(img, "PNG", f); 
        }
        catch(Exception e){ 
            e.printStackTrace();
        }
    }
}

This paints a big blue streak across the top.

If you want it ARGB, do it like this:

    try{
        BufferedImage img = new BufferedImage( 
            500, 500, BufferedImage.TYPE_INT_ARGB );
        File f = new File("MyFile.png");
        int r = 255;
        int g = 10;
        int b = 57;
        int alpha = 255;
        int col = (alpha << 24) | (r << 16) | (g << 8) | b;
        for(int x = 0; x < 500; x++){
            for(int y = 20; y < 30; y++){
                img.setRGB(x, y, col);
            }
        }
        ImageIO.write(img, "PNG", f);
    }
    catch(Exception e){
        e.printStackTrace();
    }

Open up MyFile.png, it has a red streak across the top.

How do I dynamically assign properties to an object in TypeScript?

If you are using Typescript, presumably you want to use the type safety; in which case naked Object and 'any' are counterindicated.

Better to not use Object or {}, but some named type; or you might be using an API with specific types, which you need extend with your own fields. I've found this to work:

class Given { ... }  // API specified fields; or maybe it's just Object {}

interface PropAble extends Given {
    props?: string;  // you can cast any Given to this and set .props
    // '?' indicates that the field is optional
}
let g:Given = getTheGivenObject();
(g as PropAble).props = "value for my new field";

// to avoid constantly casting: 
let k:PropAble = getTheGivenObject();
k.props = "value for props";

Downgrade npm to an older version

Even I run npm install -g npm@4, it is not ok for me.

Finally, I download and install the old node.js version.

https://nodejs.org/download/release/v7.10.1/

It is npm version 4.

You can choose any version here https://nodejs.org/download/release/

Why can't Python parse this JSON data?

"Ultra JSON" or simply "ujson" can handle having [] in your JSON file input. If you're reading a JSON input file into your program as a list of JSON elements; such as, [{[{}]}, {}, [], etc...] ujson can handle any arbitrary order of lists of dictionaries, dictionaries of lists.

You can find ujson in the Python package index and the API is almost identical to Python's built-in json library.

ujson is also much faster if you're loading larger JSON files. You can see the performance details in comparison to other Python JSON libraries in the same link provided.

jQuery.post( ) .done( ) and success:

Both .done() and .success() are callback functions and they essentially function the same way.

Here's the documentation. The difference is that .success() is deprecated as of jQuery 1.8. You should use .done() instead.

In case you don't want to click the link:

Deprecation Notice

The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callback methods introduced in jQuery 1.5 are deprecated as of jQuery 1.8. To prepare your code for their eventual removal, use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.

Create table (structure) from existing table

SELECT * INTO newtable
from Oldtable

How to set index.html as root file in Nginx?

According to the documentation Checks the existence of files in the specified order and uses the first found file for request processing; the processing is performed in the current context. The path to a file is constructed from the file parameter according to the root and alias directives. It is possible to check directory’s existence by specifying a slash at the end of a name, e.g. “$uri/”. If none of the files were found, an internal redirect to the uri specified in the last parameter is made. Important

an internal redirect to the uri specified in the last parameter is made.

So in last parameter you should add your page or code if first two parameters returns false.

location / {
  try_files $uri $uri/index.html index.html;
}

Android: Storing username and password?

You should use the Android AccountManager. It's purpose-built for this scenario. It's a little bit cumbersome but one of the things it does is invalidate the local credentials if the SIM card changes, so if somebody swipes your phone and throws a new SIM in it, your credentials won't be compromised.

This also gives the user a quick and easy way to access (and potentially delete) the stored credentials for any account they have on the device, all from one place.

SampleSyncAdapter (like @Miguel mentioned) is an example that makes use of stored account credentials.

Freemarker iterating over hashmap keys

Edit: Don't use this solution with FreeMarker 2.3.25 and up, especially not .get(prop). See other answers.

You use the built-in keys function, e.g. this should work:

<#list user?keys as prop>
    ${prop} = ${user.get(prop)}
</#list>  

Spring MVC - How to get all request params in a map in Spring controller?

While the other answers are correct it certainly is not the "Spring way" to use the HttpServletRequest object directly. The answer is actually quite simple and what you would expect if you're familiar with Spring MVC.

@RequestMapping(value = {"/search/", "/search"}, method = RequestMethod.GET)
public String search(
@RequestParam Map<String,String> allRequestParams, ModelMap model) {
   return "viewName";
}

Binding ConverterParameter

There is also an alternative way to use MarkupExtension in order to use Binding for a ConverterParameter. With this solution you can still use the default IValueConverter instead of the IMultiValueConverter because the ConverterParameter is passed into the IValueConverter just like you expected in your first sample.

Here is my reusable MarkupExtension:

/// <summary>
///     <example>
///         <TextBox>
///             <TextBox.Text>
///                 <wpfAdditions:ConverterBindableParameter Binding="{Binding FirstName}"
///                     Converter="{StaticResource TestValueConverter}"
///                     ConverterParameterBinding="{Binding ConcatSign}" />
///             </TextBox.Text>
///         </TextBox>
///     </example>
/// </summary>
[ContentProperty(nameof(Binding))]
public class ConverterBindableParameter : MarkupExtension
{
    #region Public Properties

    public Binding Binding { get; set; }
    public BindingMode Mode { get; set; }
    public IValueConverter Converter { get; set; }
    public Binding ConverterParameter { get; set; }

    #endregion

    public ConverterBindableParameter()
    { }

    public ConverterBindableParameter(string path)
    {
        Binding = new Binding(path);
    }

    public ConverterBindableParameter(Binding binding)
    {
        Binding = binding;
    }

    #region Overridden Methods

    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        var multiBinding = new MultiBinding();
        Binding.Mode = Mode;
        multiBinding.Bindings.Add(Binding);
        if (ConverterParameter != null)
        {
            ConverterParameter.Mode = BindingMode.OneWay;
            multiBinding.Bindings.Add(ConverterParameter);
        }
        var adapter = new MultiValueConverterAdapter
        {
            Converter = Converter
        };
        multiBinding.Converter = adapter;
        return multiBinding.ProvideValue(serviceProvider);
    }

    #endregion

    [ContentProperty(nameof(Converter))]
    private class MultiValueConverterAdapter : IMultiValueConverter
    {
        public IValueConverter Converter { get; set; }

        private object lastParameter;

        public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
        {
            if (Converter == null) return values[0]; // Required for VS design-time
            if (values.Length > 1) lastParameter = values[1];
            return Converter.Convert(values[0], targetType, lastParameter, culture);
        }

        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
        {
            if (Converter == null) return new object[] { value }; // Required for VS design-time

            return new object[] { Converter.ConvertBack(value, targetTypes[0], lastParameter, culture) };
        }
    }
}

With this MarkupExtension in your code base you can simply bind the ConverterParameter the following way:

<Style TargetType="FrameworkElement">
<Setter Property="Visibility">
    <Setter.Value>
     <wpfAdditions:ConverterBindableParameter Binding="{Binding Tag, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}"
                 Converter="{StaticResource AccessLevelToVisibilityConverter}"
                 ConverterParameterBinding="{Binding RelativeSource={RelativeSource Mode=Self}, Path=Tag}" />          
    </Setter.Value>
</Setter>

Which looks almost like your initial proposal.

Does Spring @Transactional attribute work on a private method?

Spring Docs explain that

In proxy mode (which is the default), only external method calls coming in through the proxy are intercepted. This means that self-invocation, in effect, a method within the target object calling another method of the target object, will not lead to an actual transaction at runtime even if the invoked method is marked with @Transactional.

Consider the use of AspectJ mode (see mode attribute in table below) if you expect self-invocations to be wrapped with transactions as well. In this case, there will not be a proxy in the first place; instead, the target class will be weaved (that is, its byte code will be modified) in order to turn @Transactional into runtime behavior on any kind of method.

Another way is user BeanSelfAware

Adding Jar files to IntellijIdea classpath

On the Mac version I was getting the error when trying to run JSON-Clojure.json.clj, which is the script to export a database table to JSON. To get it to work I had to download the latest Clojure JAR from http://clojure.org/ and then right-click on PHPStorm app in the Finder and "Show Package Contents". Then go to Contents in there. Then open the lib folder, and see a bunch of .jar files. Copy the clojure-1.8.0.jar file from the unzipped archive I downloaded from clojure.org into the aforementioned lib folder inside the PHPStorm.app/Contents/lib. Restart the app. Now it freaking works.

EDIT: You also have to put the JSR-223 script engine into PHPStorm.app/Contents/lib. It can be built from https://github.com/ato/clojure-jsr223 or downloaded from https://www.dropbox.com/s/jg7s0c41t5ceu7o/clojure-jsr223-1.5.1.jar?dl=0 .

Fastest way to check if a file exist using standard C++/C++11/C?

Same as suggested by PherricOxide but in C

#include <sys/stat.h>
int exist(const char *name)
{
  struct stat   buffer;
  return (stat (name, &buffer) == 0);
}

SSIS expression: convert date to string

If, like me, you are trying to use GETDATE() within an expression and have the seemingly unreasonable requirement (SSIS/SSDT seems very much a work in progress to me, and not a polished offering) of wanting that date to get inserted into SQL Server as a valid date (type = datetime), then I found this expression to work:

@[User::someVar] = (DT_WSTR,4)YEAR(GETDATE()) + "-"  + RIGHT("0" + (DT_WSTR,2)MONTH(GETDATE()), 2) + "-"  + RIGHT("0" + (DT_WSTR,2)DAY( GETDATE()), 2) + " " + RIGHT("0" + (DT_WSTR,2)DATEPART("hh", GETDATE()), 2) + ":" + RIGHT("0" + (DT_WSTR,2)DATEPART("mi", GETDATE()), 2) + ":" + RIGHT("0" + (DT_WSTR,2)DATEPART("ss", GETDATE()), 2)

I found this code snippet HERE

Using RegEX To Prefix And Append In Notepad++

Regular Expression that can be used:

Find: \w.+
Replace: able:"$&"

As, $& will give you the string you search for.

Refer: regexr

How to sort a Ruby Hash by number value?

Since value is the last entry, you can do:

metrics.sort_by(&:last)

How do I get the first n characters of a string without checking the size or going out of bounds?

Use the substring method, as follows:

int n = 8;
String s = "Hello, World!";
System.out.println(s.substring(0,n);

If n is greater than the length of the string, this will throw an exception, as one commenter has pointed out. one simple solution is to wrap all this in the condition if(s.length()<n) in your else clause, you can choose whether you just want to print/return the whole String or handle it another way.

Uri content://media/external/file doesn't exist for some devices

Most probably it has to do with caching on the device. Catching the exception and ignoring is not nice but my problem was fixed and it seems to work.

How to check if a folder exists

There is no need to separately call the exists() method, as isDirectory() implicitly checks whether the directory exists or not.

npm can't find package.json

ok, try to go to the home "user@user:~$ " (cd + enter key), and npm install -g your your_module.