Programs & Examples On #Griffon

For questions relating to Griffon, client application platform that uses Groovy and Java.

Change onclick action with a Javascript function

Your code is calling the function and assigning the return value to onClick, also it should be 'onclick'. This is how it should look.

document.getElementById("a").onclick = Bar;

Looking at your other code you probably want to do something like this:

document.getElementById(id+"Button").onclick = function() { HideError(id); }

How to insert programmatically a new line in an Excel cell in C#?

Have you tried "\n" I guess, it should work.

Calling Member Functions within Main C++

On an informal note, you can also call non-static member functions on temporaries:

MyClass().printInformation();

(on another informal note, the end of the lifetime of the temporary variable (variable is important, because you can also call non-const member functions) comes at the end of the full expression (";"))

Git status shows files as changed even though contents are the same

For me it was because 2 linux VMs were both mapped to the same home file system. One VM was running git-1.7.1 an the other was running git-2.14

The VM running git-1.7.1 would always show 4 files as changed (even thought the contents and line endings were identical).

Once 'git status' was run on the VM running g-2.14, then both VMs would start reporting the repository as clean. 'git status' has side effects. It is not an immutable operation. And git-1.7.1 does not understand the world in the same way that git-2+ does.

Javascript/DOM: How to remove all events of a DOM object?

You can add a hook function to intercept all calls to addEventHandler. The hook will push the handler to a list that can be used for cleanup. For example,

if (EventTarget.prototype.original_addEventListener == null) {
    EventTarget.prototype.original_addEventListener = EventTarget.prototype.addEventListener;

    function addEventListener_hook(typ, fn, opt) {
        console.log('--- add event listener',this.nodeName,typ);
        this.all_handlers = this.all_handlers || [];
        this.all_handlers.push({typ,fn,opt});
        this.original_addEventListener(typ, fn, opt);  
    }

    EventTarget.prototype.addEventListener = addEventListener_hook;
}

You should insert this code near the top of your main web page (e.g. index.html). During cleanup, you can loop thru all_handlers, and call removeEventHandler for each. Don't worry about calling removeEventHandler multiple times with the same function. It is harmless.

For example,

function cleanup(elem) {
    for (let t in elem) if (t.startsWith('on') && elem[t] != null) {
        elem[t] = null;
        console.log('cleanup removed listener from '+elem.nodeName,t);
    } 
    for (let t of elem.all_handlers || []) {
        elem.removeEventListener(t.typ, t.fn, t.opt);
        console.log('cleanup removed listener from '+elem.nodeName,t.typ);
    } 
}

Note: for IE use Element instead of EventTarget, and change => to function, and various other things.

force css grid container to fill full screen of device

If you want the .wrapper to be fullscreen, just add the following in the wrapper class:

position: absolute; width: 100%; height: 100%;

You can also add top: 0 and left:0

Format a datetime into a string with milliseconds

I dealt with the same problem but in my case it was important that the millisecond was rounded and not truncated

from datetime import datetime, timedelta

def strftime_ms(datetime_obj):
    y,m,d,H,M,S = datetime_obj.timetuple()[:6]
    ms = timedelta(microseconds = round(datetime_obj.microsecond/1000.0)*1000)
    ms_date = datetime(y,m,d,H,M,S) + ms
    return ms_date.strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]

Adding to a vector of pair

IMHO, a very nice solution is to use c++11 emplace_back function:

revenue.emplace_back("string", map[i].second);

It just creates a new element in place.

How to delete a column from a table in MySQL

ALTER TABLE tbl_Country DROP COLUMN IsDeleted;

Here's a working example.

Note that the COLUMN keyword is optional, as MySQL will accept just DROP IsDeleted. Also, to drop multiple columns, you have to separate them by commas and include the DROP for each one.

ALTER TABLE tbl_Country
  DROP COLUMN IsDeleted,
  DROP COLUMN CountryName;

This allows you to DROP, ADD and ALTER multiple columns on the same table in the one statement. From the MySQL reference manual:

You can issue multiple ADD, ALTER, DROP, and CHANGE clauses in a single ALTER TABLE statement, separated by commas. This is a MySQL extension to standard SQL, which permits only one of each clause per ALTER TABLE statement.

Efficient way to do batch INSERTS with JDBC

SQLite: The above answers are all correct. For SQLite, it is a little bit different. Nothing really helps, even to put it in a batch is (sometimes) not improving performance. In that case, try to disable auto-commit and commit by hand after you are done (Warning! When multiple connections write at the same time, you can clash with these operations)

// connect(), yourList and compiledQuery you have to implement/define beforehand
try (Connection conn = connect()) {
     conn.setAutoCommit(false);
     preparedStatement pstmt = conn.prepareStatement(compiledQuery);
     for(Object o : yourList){
        pstmt.setString(o.toString());
        pstmt.executeUpdate();
        pstmt.getGeneratedKeys(); //if you need the generated keys
     }
     pstmt.close();
     conn.commit();

}

When to Redis? When to MongoDB?

And you should use neither if you have plenty of RAM. Redis and MongoDB come to the price of a general purpose tool. This introduce a lot of overhead.

There was the saying that Redis is 10 times faster than Mongo. That might not be that true anymore. MongoDB (if i remember correctly) claimed to beat memcache for storing and caching documents as long as the memory configurations are the same.

Anyhow. Redis good, MongoDB is good. If you care about substructures and need aggregation go for MongoDB. If storing keys and values is your main concern its all about Redis. (or any other key value store).

Comparing two strings, ignoring case in C#

My general answer to this kind of question on "efficiency" is almost always, which ever version of the code is most readable, is the most efficient.

That being said, I think (val.ToLowerCase() == "astringvalue") is pretty understandable at a glance by most people.

The efficience I refer to is not necesseraly in the execution of the code but rather in the maintanance and generally readability of the code in question.

How do you round to 1 decimal place in Javascript?

If you care about proper rounding up then:

function roundNumericStrings(str , numOfDecPlacesRequired){ 
     var roundFactor = Math.pow(10, numOfDecPlacesRequired);  
     return (Math.round(parseFloat(str)*roundFactor)/roundFactor).toString();  }

Else if you don't then you already have a reply from previous posts

str.slice(0, -1)

GCC C++ Linker errors: Undefined reference to 'vtable for XXX', Undefined reference to 'ClassName::ClassName()'

I had this error message. The problem was that I declared a virtual destructor in the header file, but the virtual functions' body was actually not implemented.

Using '<%# Eval("item") %>'; Handling Null Value and showing 0 against

Used a modified version of Jason's answer:

public string ProcessMyDataItem(object myValue)
{
  if (myValue.ToString().Length < 1)
  {
     return "0 value";
  }

  return myValue.ToString();
}

if arguments is equal to this string, define a variable like this string

Don't forget about spaces:

source=""
samples=("")
if [ $1 = "country" ]; then
   source="country"
   samples="US Canada Mexico..."
else
  echo "try again"
fi

Rotate label text in seaborn factorplot

If anyone wonders how to this for clustermap CorrGrids (part of a given seaborn example):

import seaborn as sns
import matplotlib.pyplot as plt
sns.set(context="paper", font="monospace")

# Load the datset of correlations between cortical brain networks
df = sns.load_dataset("brain_networks", header=[0, 1, 2], index_col=0)
corrmat = df.corr()

# Set up the matplotlib figure
f, ax = plt.subplots(figsize=(12, 9))

# Draw the heatmap using seaborn
g=sns.clustermap(corrmat, vmax=.8, square=True)
rotation = 90 
for i, ax in enumerate(g.fig.axes):   ## getting all axes of the fig object
     ax.set_xticklabels(ax.get_xticklabels(), rotation = rotation)


g.fig.show()

How do I print the key-value pairs of a dictionary in python

A little intro to dictionary

d={'a':'apple','b':'ball'}
d.keys()  # displays all keys in list
['a','b']
d.values() # displays your values in list
['apple','ball']
d.items() # displays your pair tuple of key and value
[('a','apple'),('b','ball')

Print keys,values method one

for x in d.keys():
    print x +" => " + d[x]

Another method

for key,value in d.items():
    print key + " => " + value

You can get keys using iter

>>> list(iter(d))
['a', 'b']

You can get value of key of dictionary using get(key, [value]):

d.get('a')
'apple'

If key is not present in dictionary,when default value given, will return value.

d.get('c', 'Cat')
'Cat'

Use CSS3 transitions with gradient backgrounds

You can FAKE transitions between gradients, using transitions in the opacity of a few stacked gradients, as described in a few of the answers here:

CSS3 animation with gradients.

You can also transition the position instead, as described here:

CSS3 gradient transition with background-position.

Some more techniques here:

Animating CSS3 Gradients.

Cordova : Requirements check failed for JDK 1.8 or greater

You don't have to uninstall any higher version of sdk. just install jdk1.8.0_161 or don't if it is already install.

Now just set the JAVA_HOME USER variable (not system variable) as shown in the below image.

enter image description here

This way you don't have to uninstall higher version and the problem get resolved.

How to quickly check if folder is empty (.NET)?

My code is amazing it just took 00:00:00.0007143 less than milisecond with 34 file in folder

   System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
    sw.Start();

     bool IsEmptyDirectory = (Directory.GetFiles("d:\\pdf").Length == 0);

     sw.Stop();
     Console.WriteLine(sw.Elapsed);

Labels for radio buttons in rails form

Using true/false as the value will have the field pre-filled if the model passed to the form has this attribute already filled:

= f.radio_button(:public?, true)
= f.label(:public?, "yes", value: true)
= f.radio_button(:public?, false)
= f.label(:public?, "no", value: false)

When should I use Lazy<T>?

Just to point onto the example posted by Mathew

public sealed class Singleton
{
    // Because Singleton's constructor is private, we must explicitly
    // give the Lazy<Singleton> a delegate for creating the Singleton.
    private static readonly Lazy<Singleton> instanceHolder =
        new Lazy<Singleton>(() => new Singleton());

    private Singleton()
    {
        ...
    }

    public static Singleton Instance
    {
        get { return instanceHolder.Value; }
    }
}

before the Lazy was born we would have done it this way:

private static object lockingObject = new object();
public static LazySample InstanceCreation()
{
    if(lazilyInitObject == null)
    {
         lock (lockingObject)
         {
              if(lazilyInitObject == null)
              {
                   lazilyInitObject = new LazySample ();
              }
         }
    }
    return lazilyInitObject ;
}

MySQL remove all whitespaces from the entire column

Just use the following sql, you are done:

SELECT replace(CustomerName,' ', '') FROM Customers;

you can test this sample over here: W3School

How do I move focus to next input with jQuery?

You can do something like this:

$("input").change(function() {
  var inputs = $(this).closest('form').find(':input');
  inputs.eq( inputs.index(this)+ 1 ).focus();
});

The other answers posted here may not work for you since they depend on the next input being the very next sibling element, which often isn't the case. This approach goes up to the form and searches for the next input type element.

Command not found when using sudo

Ok this is my solution: in ~/.bash_aliases just add the following:

# ADDS MY PATH WHEN SET AS ROOT
if [ $(id -u) = "0" ]; then
   export PATH=$PATH:/home/your_user/bin 
fi

Voila! Now you can execute your own scripts with sudo or set as ROOT without having to do an export PATH=$PATH:/home/your_user/bin everytime.

Notice that I need to be explicit when adding my PATH since HOME for superuser is /root

ORA-01950: no privileges on tablespace 'USERS'

You cannot insert data because you have a quota of 0 on the tablespace. To fix this, run

ALTER USER <user> quota unlimited on <tablespace name>;

or

ALTER USER <user> quota 100M on <tablespace name>;

as a DBA user (depending on how much space you need / want to grant).

How to call a JavaScript function, declared in <head>, in the body when I want to call it

Just drop

<script>
myfunction();
</script>

in the body where you want it to be called, understanding that when the page loads and the browser reaches that point, that's when the call will occur.

Casting variables in Java

Casting in Java isn't magic, it's you telling the compiler that an Object of type A is actually of more specific type B, and thus gaining access to all the methods on B that you wouldn't have had otherwise. You're not performing any kind of magic or conversion when performing casting, you're essentially telling the compiler "trust me, I know what I'm doing and I can guarantee you that this Object at this line is actually an <Insert cast type here>." For example:

Object o = "str";
String str = (String)o;

The above is fine, not magic and all well. The object being stored in o is actually a string, and therefore we can cast to a string without any problems.

There's two ways this could go wrong. Firstly, if you're casting between two types in completely different inheritance hierarchies then the compiler will know you're being silly and stop you:

String o = "str";
Integer str = (Integer)o; //Compilation fails here

Secondly, if they're in the same hierarchy but still an invalid cast then a ClassCastException will be thrown at runtime:

Number o = new Integer(5);
Double n = (Double)o; //ClassCastException thrown here

This essentially means that you've violated the compiler's trust. You've told it you can guarantee the object is of a particular type, and it's not.

Why do you need casting? Well, to start with you only need it when going from a more general type to a more specific type. For instance, Integer inherits from Number, so if you want to store an Integer as a Number then that's ok (since all Integers are Numbers.) However, if you want to go the other way round you need a cast - not all Numbers are Integers (as well as Integer we have Double, Float, Byte, Long, etc.) And even if there's just one subclass in your project or the JDK, someone could easily create another and distribute that, so you've no guarantee even if you think it's a single, obvious choice!

Regarding use for casting, you still see the need for it in some libraries. Pre Java-5 it was used heavily in collections and various other classes, since all collections worked on adding objects and then casting the result that you got back out the collection. However, with the advent of generics much of the use for casting has gone away - it has been replaced by generics which provide a much safer alternative, without the potential for ClassCastExceptions (in fact if you use generics cleanly and it compiles with no warnings, you have a guarantee that you'll never get a ClassCastException.)

How to create folder with PHP code?

Purely basic folder creation

<?php mkdir("testing"); ?> <= this, actually creates a folder called "testing".



Basic file creation

<?php
$file = fopen("test.txt","w");
echo fwrite($file,"Hello World. Testing!");
fclose($file);
?>

Use the a or a+ switch to add/append to file.



EDIT:

This version will create a file and folder at the same time and show it on screen after.

<?php

// change the name below for the folder you want
$dir = "new_folder_name";

$file_to_write = 'test.txt';
$content_to_write = "The content";

if( is_dir($dir) === false )
{
    mkdir($dir);
}

$file = fopen($dir . '/' . $file_to_write,"w");

// a different way to write content into
// fwrite($file,"Hello World.");

fwrite($file, $content_to_write);

// closes the file
fclose($file);

// this will show the created file from the created folder on screen
include $dir . '/' . $file_to_write;

?>

Scaling an image to fit on canvas

You made the error, for the second call, to set the size of source to the size of the target.
Anyway i bet that you want the same aspect ratio for the scaled image, so you need to compute it :

var hRatio = canvas.width / img.width    ;
var vRatio = canvas.height / img.height  ;
var ratio  = Math.min ( hRatio, vRatio );
ctx.drawImage(img, 0,0, img.width, img.height, 0,0,img.width*ratio, img.height*ratio);

i also suppose you want to center the image, so the code would be :

function drawImageScaled(img, ctx) {
   var canvas = ctx.canvas ;
   var hRatio = canvas.width  / img.width    ;
   var vRatio =  canvas.height / img.height  ;
   var ratio  = Math.min ( hRatio, vRatio );
   var centerShift_x = ( canvas.width - img.width*ratio ) / 2;
   var centerShift_y = ( canvas.height - img.height*ratio ) / 2;  
   ctx.clearRect(0,0,canvas.width, canvas.height);
   ctx.drawImage(img, 0,0, img.width, img.height,
                      centerShift_x,centerShift_y,img.width*ratio, img.height*ratio);  
}

you can see it in a jsbin here : http://jsbin.com/funewofu/1/edit?js,output

Producer/Consumer threads using a Queue

Java 5+ has all the tools you need for this kind of thing. You will want to:

  1. Put all your Producers in one ExecutorService;
  2. Put all your Consumers in another ExecutorService;
  3. If necessary, communicate between the two using a BlockingQueue.

I say "if necessary" for (3) because from my experience it's an unnecessary step. All you do is submit new tasks to the consumer executor service. So:

final ExecutorService producers = Executors.newFixedThreadPool(100);
final ExecutorService consumers = Executors.newFixedThreadPool(100);
while (/* has more work */) {
  producers.submit(...);
}
producers.shutdown();
producers.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
consumers.shutdown();
consumers.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);

So the producers submit directly to consumers.

Best way to incorporate Volley (or other library) into Android Studio project

For incorporate volley in android studio,

  1. paste the following command in terminal (
    git clone https://android.googlesource.com/platform/frameworks/volley ) and run it.

    Refer android developer tutorial for this.

    It will create a folder name volley in the src directory.
  2. Then go to android studio and right click on the project.
  3. choose New -> Module from the list.
  4. Then click on import existing Project from the below list.
  5. you will see a text input area namely source directory, browse the folder you downloaded (volley) and then click on finish.
  6. you will see a folder volley in your project view.
  7. the switch to android view and open the build:gradle(Module:app) file and append the following line in the dependency area:

    compile 'com.mcxiaoke.volley:library-aar:1.0.0'

  8. Now synchronise your project and also build your project.

Add centered text to the middle of a <hr/>-like line

Woohoo my first post even though this is a year old. To avoid the background-coloring issues with wrappers, you could use inline-block with hr (nobody said that explicitly). Text-align should center correctly since they are inline elements.

<div style="text-align:center">
    <hr style="display:inline-block; position:relative; top:4px; width:45%" />
       &nbsp;New Section&nbsp;
    <hr style="display:inline-block; position:relative; top:4px; width:45%" />
</div>

python encoding utf-8

You don't need to encode data that is already encoded. When you try to do that, Python will first try to decode it to unicode before it can encode it back to UTF-8. That is what is failing here:

>>> data = u'\u00c3'            # Unicode data
>>> data = data.encode('utf8')  # encoded to UTF-8
>>> data
'\xc3\x83'
>>> data.encode('utf8')         # Try to *re*-encode it
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0: ordinal not in range(128)

Just write your data directly to the file, there is no need to encode already-encoded data.

If you instead build up unicode values instead, you would indeed have to encode those to be writable to a file. You'd want to use codecs.open() instead, which returns a file object that will encode unicode values to UTF-8 for you.

You also really don't want to write out the UTF-8 BOM, unless you have to support Microsoft tools that cannot read UTF-8 otherwise (such as MS Notepad).

For your MySQL insert problem, you need to do two things:

  • Add charset='utf8' to your MySQLdb.connect() call.

  • Use unicode objects, not str objects when querying or inserting, but use sql parameters so the MySQL connector can do the right thing for you:

    artiste = artiste.decode('utf8')  # it is already UTF8, decode to unicode
    
    c.execute('SELECT COUNT(id) AS nbr FROM artistes WHERE nom=%s', (artiste,))
    
    # ...
    
    c.execute('INSERT INTO artistes(nom,status,path) VALUES(%s, 99, %s)', (artiste, artiste + u'/'))
    

It may actually work better if you used codecs.open() to decode the contents automatically instead:

import codecs

sql = mdb.connect('localhost','admin','ugo&(-@F','music_vibration', charset='utf8')

with codecs.open('config/index/'+index, 'r', 'utf8') as findex:
    for line in findex:
        if u'#artiste' not in line:
            continue

        artiste=line.split(u'[:::]')[1].strip()

    cursor = sql.cursor()
    cursor.execute('SELECT COUNT(id) AS nbr FROM artistes WHERE nom=%s', (artiste,))
    if not cursor.fetchone()[0]:
        cursor = sql.cursor()
        cursor.execute('INSERT INTO artistes(nom,status,path) VALUES(%s, 99, %s)', (artiste, artiste + u'/'))
        artists_inserted += 1

You may want to brush up on Unicode and UTF-8 and encodings. I can recommend the following articles:

jQuery check if it is clicked or not

    <script type="text/javascript" src="jquery-1.6.1.min.js"></script>
<script type="text/javascript">
var val;
        $(document).ready(function () {
            $("#click").click(function () {
                val = 1;
                get();
                });
                });
          function get(){
            if (val == 1){
                alert(val);
                }

          }
</script>
    <table>
    <tr><td id='click'>ravi</td></tr>
    </table>

How to return a part of an array in Ruby?

If you want to split/cut the array on an index i,

arr = arr.drop(i)

> arr = [1,2,3,4,5]
 => [1, 2, 3, 4, 5] 
> arr.drop(2)
 => [3, 4, 5] 

How to select where ID in Array Rails ActiveRecord without exception

Update: This answer is more relevant for Rails 4.x

Do this:

current_user.comments.where(:id=>[123,"456","Michael Jackson"])

The stronger side of this approach is that it returns a Relation object, to which you can join more .where clauses, .limit clauses, etc., which is very helpful. It also allows non-existent IDs without throwing exceptions.

The newer Ruby syntax would be:

current_user.comments.where(id: [123, "456", "Michael Jackson"])

Activating Anaconda Environment in VsCode

As I was not able to solve my problem by suggested ways, I will share how I fixed it.

First of all, even if I was able to activate an environment, the corresponding environment folder was not present in C:\ProgramData\Anaconda3\envs directory.

So I created a new anaconda environment using Anaconda prompt, a new folder named same as your given environment name will be created in the envs folder.

Next, I activated that environment in Anaconda prompt. Installed python with conda install python command.

Then on anaconda navigator, selected the newly created environment in the 'Applications on' menu. Launched vscode through Anaconda navigator.

Now as suggested by other answers, in vscode, opened command palette with Ctrl + Shift + P keyboard shortcut. Searched and selected Python: Select Interpreter

If the interpreter with newly created environment isn't listed out there, select Enter Interpreter Path and choose the newly created python.exe which is located similar to C:\ProgramData\Anaconda3\envs\<your-new-env>\ . So the total path will look like C:\ProgramData\Anaconda3\envs\<your-nev-env>\python.exe

Next time onwards the interpreter will be automatically listed among other interpreters.

Now you might see your selected conda environment at bottom left side in vscode.

Linq to Entities join vs groupjoin

Behaviour

Suppose you have two lists:

Id  Value
1   A
2   B
3   C

Id  ChildValue
1   a1
1   a2
1   a3
2   b1
2   b2

When you Join the two lists on the Id field the result will be:

Value ChildValue
A     a1
A     a2
A     a3
B     b1
B     b2

When you GroupJoin the two lists on the Id field the result will be:

Value  ChildValues
A      [a1, a2, a3]
B      [b1, b2]
C      []

So Join produces a flat (tabular) result of parent and child values.
GroupJoin produces a list of entries in the first list, each with a group of joined entries in the second list.

That's why Join is the equivalent of INNER JOIN in SQL: there are no entries for C. While GroupJoin is the equivalent of OUTER JOIN: C is in the result set, but with an empty list of related entries (in an SQL result set there would be a row C - null).

Syntax

So let the two lists be IEnumerable<Parent> and IEnumerable<Child> respectively. (In case of Linq to Entities: IQueryable<T>).

Join syntax would be

from p in Parent
join c in Child on p.Id equals c.Id
select new { p.Value, c.ChildValue }

returning an IEnumerable<X> where X is an anonymous type with two properties, Value and ChildValue. This query syntax uses the Join method under the hood.

GroupJoin syntax would be

from p in Parent
join c in Child on p.Id equals c.Id into g
select new { Parent = p, Children = g }

returning an IEnumerable<Y> where Y is an anonymous type consisting of one property of type Parent and a property of type IEnumerable<Child>. This query syntax uses the GroupJoin method under the hood.

We could just do select g in the latter query, which would select an IEnumerable<IEnumerable<Child>>, say a list of lists. In many cases the select with the parent included is more useful.

Some use cases

1. Producing a flat outer join.

As said, the statement ...

from p in Parent
join c in Child on p.Id equals c.Id into g
select new { Parent = p, Children = g }

... produces a list of parents with child groups. This can be turned into a flat list of parent-child pairs by two small additions:

from p in parents
join c in children on p.Id equals c.Id into g // <= into
from c in g.DefaultIfEmpty()               // <= flattens the groups
select new { Parent = p.Value, Child = c?.ChildValue }

The result is similar to

Value Child
A     a1
A     a2
A     a3
B     b1
B     b2
C     (null)

Note that the range variable c is reused in the above statement. Doing this, any join statement can simply be converted to an outer join by adding the equivalent of into g from c in g.DefaultIfEmpty() to an existing join statement.

This is where query (or comprehensive) syntax shines. Method (or fluent) syntax shows what really happens, but it's hard to write:

parents.GroupJoin(children, p => p.Id, c => c.Id, (p, c) => new { p, c })
       .SelectMany(x => x.c.DefaultIfEmpty(), (x,c) => new { x.p.Value, c?.ChildValue } )

So a flat outer join in LINQ is a GroupJoin, flattened by SelectMany.

2. Preserving order

Suppose the list of parents is a bit longer. Some UI produces a list of selected parents as Id values in a fixed order. Let's use:

var ids = new[] { 3,7,2,4 };

Now the selected parents must be filtered from the parents list in this exact order.

If we do ...

var result = parents.Where(p => ids.Contains(p.Id));

... the order of parents will determine the result. If the parents are ordered by Id, the result will be parents 2, 3, 4, 7. Not good. However, we can also use join to filter the list. And by using ids as first list, the order will be preserved:

from id in ids
join p in parents on id equals p.Id
select p

The result is parents 3, 7, 2, 4.

Resetting MySQL Root Password with XAMPP on Localhost

Reset XAMPP MySQL root password through SQL update phpmyadmin to work with it:

-Start the Apache Server and MySQL instances from the XAMPP control panel. After the server started, open any web browser and go to http://localhost/phpmyadmin/. This will open the phpMyAdmin interface. Using this interface we can manager the MySQL server from the web browser.

-In the phpMyAdmin window, select SQL tab from the right panel. This will open the SQL tab where we can run the SQL queries.

-Now type the following query in the textarea and click Go

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

  • hit go

  • "FLUSH PRIVILEGES;"

  • hit go

-Now you will see a message saying that the query has been executed successfully.

-If you refresh the page, you will be getting a error message. This is because the phpMyAdmin configuration file is not aware of our newly set root passoword. To do this we have to modify the phpMyAdmin config file.

-Open the file C:\xampp\phpMyAdmin\config.inc.php in your favorite text editor. Search for the string:

$cfg\['Servers'\]\[$i\]['password'] = ''; and change it to like this, 
$cfg\['Servers'\]\[$i\]['password'] = 'password'; Here the ‘password’ is what we set to the root user using the SQL query.
$cfg['Servers'][$i]['AllowNoPassword'] = false; // set to false for password required
$cfg['Servers'][$i]['auth_type'] = 'cookie'; // web cookie auth

-Now all set to go. Save the config.inc.php file and restart the XAMPP server.

Modified from Source: http://veerasundar.com/blog/2009/01/how-to-change-the-root-password-for-mysql-in-xampp/

How to use terminal commands with Github?

To add all file at a time, use git add -A

To check git whole status, use git log

Alter a SQL server function to accept new optional parameter

The way to keep SELECT dbo.fCalculateEstimateDate(647) call working is:

ALTER function [dbo].[fCalculateEstimateDate] (@vWorkOrderID numeric)
Returns varchar(100)  AS
   Declare @Result varchar(100)
   SELECT @Result = [dbo].[fCalculateEstimateDate_v2] (@vWorkOrderID,DEFAULT)
   Return @Result
Begin
End

CREATE function [dbo].[fCalculateEstimateDate_v2] (@vWorkOrderID numeric,@ToDate DateTime=null)
Returns varchar(100)  AS
Begin
  <Function Body>
End

How to find the first and second maximum number?

OK I found it.

=LARGE($E$4:$E$9;A12)

=large(array, k)

Array Required. The array or range of data for which you want to determine the k-th largest value.

K Required. The position (from the largest) in the array or cell range of data to return.

jQuery hasClass() - check for more than one class

element.is('.class1, .class2')

works, but it's 35% slower than

element.hasClass('class1') || element.hasClass('class2')

enter image description here

If you doubt what i say, you can verify on jsperf.com.

Hope this help someone.

Display a loading bar before the entire page is loaded

I've recently made a page loader in vanilla .js for a project, just wanted to share it as all the other answers are jQuery based. It's a plug and play, one-liner.

It automatically creates a <div> tag prepended to the <body>, with a <svg> loader. If you want to customize the color you just have to update the t variable at the beginning of the script.

var t="#106CF6",u=document.querySelector("*"),s=document.createElement("style"),a=document.createElement("aside"),m="http://www.w3.org/2000/svg",g=document.createElementNS(m,"svg"),c=document.createElementNS(m,"circle");document.head.appendChild(s),(s.innerHTML="#sailor {background:"+t+";color:"+t+";display:flex;align-items:center;justify-content:center;position:fixed;top:0;height:100vh;width:100vw;z-index:2147483647}@keyframes swell{to{transform:rotate(360deg)}}#sailor svg{animation:.3s swell infinite linear}"),a.setAttribute("id","sailor"),document.body.prepend(a),g.setAttribute("height","50"),g.setAttribute("filter","brightness(175%)"),g.setAttribute("viewBox","0 0 100 100"),a.prepend(g),c.setAttribute("cx","50"),c.setAttribute("cy","50"),c.setAttribute("r","35"),c.setAttribute("fill","none"),c.setAttribute("stroke","currentColor"),c.setAttribute("stroke-dasharray","165 57"),c.setAttribute("stroke-width","10"),g.prepend(c),(u.style.pointerEvents="none"),(u.style.userSelect="none"),(u.style.cursor="wait"),window.addEventListener("load",function(){setTimeout(function(){(u.style.pointerEvents=""),(u.style.userSelect=""),(u.style.cursor="");a.remove()},100)})

You can see the full project and documentation on the GitHub

Unzip a file with php

I updated answer of @rdlowrey to a cleaner and better code, This will unzip a file into current directory using __DIR__.

<?php 
    // config
    // -------------------------------
    // only file name + .zip
    $zip_filename = "YOURFILENAME.zip";
?>

<!DOCTYPE html>
<html>
<head>
    <meta charset='utf-8' >
    <title>Unzip</title>
    <style>
        body{
            font-family: arial, sans-serif;
            word-wrap: break-word;
        }
        .wrapper{
            padding:20px;
            line-height: 1.5;
            font-size: 1rem;
        }
        span{
            font-family: 'Consolas', 'courier new', monospace;
            background: #eee;
            padding:2px;
        }
    </style>
</head>
<body>
    <div class="wrapper">
        <?php
        echo "Unzipping <span>" .__DIR__. "/" .$zip_filename. "</span> to <span>" .__DIR__. "</span><br>";
        echo "current dir: <span>" . __DIR__ . "</span><br>";
        $zip = new ZipArchive;
        $res = $zip->open(__DIR__ . '/' .$zip_filename);
        if ($res === TRUE) {
          $zip->extractTo(__DIR__);
          $zip->close();
          echo '<p style="color:#00C324;">Extract was successful! Enjoy ;)</p><br>';
        } else {
          echo '<p style="color:red;">Zip file not found!</p><br>';
        }
        ?>
        End Script.
    </div>
</body>
</html> 

Printing *s as triangles in Java?

You might be interested in this too

      Scanner sc = new Scanner(System.in);
      int n=sc.nextInt();
      int b=0;
      for(int i=n;i>=1;i--){
      if(i!=n){
      for(int k=1;k<=b;k++){
      System.out.print(" ");
        }
            }
       for(int j=i;j>=1;j--){
       System.out.print("*");
       if(i!=1){
       System.out.print(" ");
        }
            }
       System.out.println();
       b=b+2;
        }

Output:: 5

       * * * * * 
         * * * * 
           * * * 
             * * 
               *

How do you remove an array element in a foreach loop?

Instead of doing foreach() loop on the array, it would be faster to use array_search() to find the proper key. On small arrays, I would go with foreach for better readibility, but for bigger arrays, or often executed code, this should be a bit more optimal:

$result=array_search($unwantedValue,$array,true);
if($result !== false) {
  unset($array[$result]);   
}

The strict comparsion operator !== is needed, because array_search() can return 0 as the index of the $unwantedValue.

Also, the above example will remove just the first value $unwantedValue, if the $unwantedValue can occur more then once in the $array, You should use array_keys(), to find all of them:

$result=array_keys($array,$unwantedValue,true)
foreach($result as $key) {
  unset($array[$key]);
}

Check http://php.net/manual/en/function.array-search.php for more information.

How do I use Join-Path to combine more than two strings into a file path?

You can use the .NET Path class:

[IO.Path]::Combine('C:\', 'Foo', 'Bar')

How to change option menu icon in the action bar?

you can achieve this by doing

<item
    android:id="@+id/menus"
    android:actionProviderClass="@android:style/Widget.Holo.ActionButton.Overflow"
    android:icon="@drawable/your_icon"
    android:showAsAction="always">
  <item android:id="@+id/Bugreport"
   android:title="@string/option_bugreport" />

  <item android:id="@+id/Info"
  android:title="@string/option_info" />

 <item android:id="@+id/About"
   android:title="@string/option_about" />
  </item>

ReactNative: how to center text?

textAlignVertical: "center"

is the real magic.

Create thumbnail image

Here is a version based on the accepted answer. It fixes two problems...

  1. Improper disposing of the images.
  2. Maintaining the aspect ratio of the image.

I found this tool to be fast and effective for both JPG and PNG files.

private static FileInfo CreateThumbnailImage(string imageFileName, string thumbnailFileName)
{
    const int thumbnailSize = 150;
    using (var image = Image.FromFile(imageFileName))
    {
        var imageHeight = image.Height;
        var imageWidth = image.Width;
        if (imageHeight > imageWidth)
        {
            imageWidth = (int) (((float) imageWidth / (float) imageHeight) * thumbnailSize);
            imageHeight = thumbnailSize;
        }
        else
        {
            imageHeight = (int) (((float) imageHeight / (float) imageWidth) * thumbnailSize);
            imageWidth = thumbnailSize;
        }

        using (var thumb = image.GetThumbnailImage(imageWidth, imageHeight, () => false, IntPtr.Zero))
            //Save off the new thumbnail
            thumb.Save(thumbnailFileName);
    }

    return new FileInfo(thumbnailFileName);
}

How can I manually generate a .pyc file from a .py file

I found several ways to compile python scripts into bytecode

  1. Using py_compile in terminal:

    python -m py_compile File1.py File2.py File3.py ...
    

    -m specifies the module(s) name to be compiled.

    Or, for interactive compilation of files

    python -m py_compile -
    File1.py
    File2.py
    File3.py
       .
       .
       .
    
  2. Using py_compile.compile:

    import py_compile
    py_compile.compile('YourFileName.py')
    
  3. Using py_compile.main():

    It compiles several files at a time.

    import py_compile
    py_compile.main(['File1.py','File2.py','File3.py'])
    

    The list can grow as long as you wish. Alternatively, you can obviously pass a list of files in main or even file names in command line args.

    Or, if you pass ['-'] in main then it can compile files interactively.

  4. Using compileall.compile_dir():

    import compileall
    compileall.compile_dir(direname)
    

    It compiles every single Python file present in the supplied directory.

  5. Using compileall.compile_file():

    import compileall
    compileall.compile_file('YourFileName.py')
    

Take a look at the links below:

https://docs.python.org/3/library/py_compile.html

https://docs.python.org/3/library/compileall.html

SSLHandshakeException: No subject alternative names present

Unlike some browsers, Java follows the HTTPS specification strictly when it comes to the server identity verification (RFC 2818, Section 3.1) and IP addresses.

When using a host name, it's possible to fall back to the Common Name in the Subject DN of the server certificate, instead of using the Subject Alternative Name.

When using an IP address, there must be a Subject Alternative Name entry (of type IP address, not DNS name) in the certificate.

You'll find more details about the specification and how to generate such a certificate in this answer.

How to delete columns in numpy.array

Removing Matrix columns that contain NaN. This is a lengthy answer, but hopefully easy to follow.

def column_to_vector(matrix, i):
    return [row[i] for row in matrix]
import numpy
def remove_NaN_columns(matrix):
    import scipy
    import math
    from numpy import column_stack, vstack

    columns = A.shape[1]
    #print("columns", columns)
    result = []
    skip_column = True
    for column in range(0, columns):
        vector = column_to_vector(A, column)
        skip_column = False
        for value in vector:
            # print(column, vector, value, math.isnan(value) )
            if math.isnan(value):
                skip_column = True
        if skip_column == False:
            result.append(vector)
    return column_stack(result)

### test it
A = vstack(([ float('NaN'), 2., 3., float('NaN')], [ 1., 2., 3., 9]))
print("A shape", A.shape, "\n", A)
B = remove_NaN_columns(A)
print("B shape", B.shape, "\n", B)

A shape (2, 4) 
 [[ nan   2.   3.  nan]
 [  1.   2.   3.   9.]]
B shape (2, 2) 
 [[ 2.  3.]
 [ 2.  3.]]

Best way to update an element in a generic List

AllDogs.First(d => d.Id == "2").Name = "some value";

However, a safer version of that might be this:

var dog = AllDogs.FirstOrDefault(d => d.Id == "2");
if (dog != null) { dog.Name = "some value"; }

jQuery posting valid json in request body

An actual JSON request would look like this:

data: '{"command":"on"}',

Where you're sending an actual JSON string. For a more general solution, use JSON.stringify() to serialize an object to JSON, like this:

data: JSON.stringify({ "command": "on" }),

To support older browsers that don't have the JSON object, use json2.js which will add it in.


What's currently happening is since you have processData: false, it's basically sending this: ({"command":"on"}).toString() which is [object Object]...what you see in your request.

Comparing two joda DateTime instances

This code (example) :

    Chronology ch1 = GregorianChronology.getInstance();     Chronology ch2 = ISOChronology.getInstance();      DateTime dt = new DateTime("2013-12-31T22:59:21+01:00",ch1);     DateTime dt2 = new DateTime("2013-12-31T22:59:21+01:00",ch2);      System.out.println(dt);     System.out.println(dt2);      boolean b = dt.equals(dt2);      System.out.println(b); 

Will print :

2013-12-31T16:59:21.000-05:00 2013-12-31T16:59:21.000-05:00 false 

You are probably comparing two DateTimes with same date but different Chronology.

How do I redirect with JavaScript?

Compared to window.location="url"; it is much easyer to do just location="url"; I always use that

jQuery get values of checked checkboxes into array

Needed the form elements named in the HTML as an array to be an array in the javascript object, as if the form was actually submitted.

If there is a form with multiple checkboxes such as:

<input name='breath[0]' type='checkbox' value='presence0'/>
<input name='breath[1]' type='checkbox' value='presence1'/>
<input name='breath[2]' type='checkbox' value='presence2'/>
<input name='serenity'  type='text' value='Is within the breath.'/>
...

The result is an object with:

data = {
   'breath':['presence0','presence1','presence2'],
   'serenity':'Is within the breath.'
}


var $form = $(this),
    data  = {};

$form.find("input").map(function()
{
    var $el  = $(this),
        name = $el.attr("name");

    if (/radio|checkbox/i.test($el.attr('type')) && !$el.prop('checked'))return;

    if(name.indexOf('[') > -1)
    {
        var name_ar = name.split(']').join('').split('['),
            name    = name_ar[0],
            index   = name_ar[1];

        data[name]  = data[name] || [];
        data[name][index] = $el.val();
    }
    else data[name] = $el.val();
});

And there are tons of answers here which helped improve my code, but they were either too complex or didn't do exactly want I wanted: Convert form data to JavaScript object with jQuery

Works but can be improved: only works on one-dimensional arrays and the resulting indexes may not be sequential. The length property of an array returns the next index number as the length of the array, not the actually length.

Hope this helped. Namaste!

Importing text file into excel sheet

There are many ways you can import Text file to the current sheet. Here are three (including the method that you are using above)

  1. Using a QueryTable
  2. Open the text file in memory and then write to the current sheet and finally applying Text To Columns if required.
  3. If you want to use the method that you are currently using then after you open the text file in a new workbook, simply copy it over to the current sheet using Cells.Copy

Using a QueryTable

Here is a simple macro that I recorded. Please amend it to suit your needs.

Sub Sample()
    With ActiveSheet.QueryTables.Add(Connection:= _
        "TEXT;C:\Sample.txt", Destination:=Range("$A$1") _
        )
        .Name = "Sample"
        .FieldNames = True
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .PreserveFormatting = True
        .RefreshOnFileOpen = False
        .RefreshStyle = xlInsertDeleteCells
        .SavePassword = False
        .SaveData = True
        .AdjustColumnWidth = True
        .RefreshPeriod = 0
        .TextFilePromptOnRefresh = False
        .TextFilePlatform = 437
        .TextFileStartRow = 1
        .TextFileParseType = xlDelimited
        .TextFileTextQualifier = xlTextQualifierDoubleQuote
        .TextFileConsecutiveDelimiter = False
        .TextFileTabDelimiter = True
        .TextFileSemicolonDelimiter = False
        .TextFileCommaDelimiter = True
        .TextFileSpaceDelimiter = False
        .TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1)
        .TextFileTrailingMinusNumbers = True
        .Refresh BackgroundQuery:=False
    End With
End Sub

Open the text file in memory

Sub Sample()
    Dim MyData As String, strData() As String

    Open "C:\Sample.txt" For Binary As #1
    MyData = Space$(LOF(1))
    Get #1, , MyData
    Close #1
    strData() = Split(MyData, vbCrLf)
End Sub

Once you have the data in the array you can export it to the current sheet.

Using the method that you are already using

Sub Sample()
    Dim wbI As Workbook, wbO As Workbook
    Dim wsI As Worksheet

    Set wbI = ThisWorkbook
    Set wsI = wbI.Sheets("Sheet1") '<~~ Sheet where you want to import

    Set wbO = Workbooks.Open("C:\Sample.txt")

    wbO.Sheets(1).Cells.Copy wsI.Cells

    wbO.Close SaveChanges:=False
End Sub

FOLLOWUP

You can use the Application.GetOpenFilename to choose the relevant file. For example...

Sub Sample()
    Dim Ret

    Ret = Application.GetOpenFilename("Prn Files (*.prn), *.prn")

    If Ret <> False Then
        With ActiveSheet.QueryTables.Add(Connection:= _
        "TEXT;" & Ret, Destination:=Range("$A$1"))

            '~~> Rest of the code

        End With
    End If
End Sub

Counter inside xsl:for-each loop

Try:

<xsl:value-of select="count(preceding-sibling::*) + 1" />

Edit - had a brain freeze there, position() is more straightforward!

What is the difference between String and StringBuffer in Java?

String is immutable. 

Why? Check here.

StringBuffer is not. It is thread safe. 

Further questions like when to use which and other concepts can be figured out following this.

Hope this helps.

How to open .SQLite files

My favorite:

https://inloop.github.io/sqlite-viewer/

No installation needed. Just drop the file.

Last executed queries for a specific database

This works for me to find queries on any database in the instance. I'm sysadmin on the instance (check your privileges):

SELECT deqs.last_execution_time AS [Time], dest.text AS [Query], dest.*
FROM sys.dm_exec_query_stats AS deqs
CROSS APPLY sys.dm_exec_sql_text(deqs.sql_handle) AS dest
WHERE dest.dbid = DB_ID('msdb')
ORDER BY deqs.last_execution_time DESC

This is the same answer that Aaron Bertrand provided but it wasn't placed in an answer.

Reactjs - Form input validation

I've taken your code and adapted it with library react-form-with-constraints: https://codepen.io/tkrotoff/pen/LLraZp

const {
  FormWithConstraints,
  FieldFeedbacks,
  FieldFeedback
} = ReactFormWithConstraints;

class Form extends React.Component {
  handleChange = e => {
    this.form.validateFields(e.target);
  }

  contactSubmit = e => {
    e.preventDefault();

    this.form.validateFields();

    if (!this.form.isValid()) {
      console.log('form is invalid: do not submit');
    } else {
      console.log('form is valid: submit');
    }
  }

  render() {
    return (
      <FormWithConstraints
        ref={form => this.form = form}
        onSubmit={this.contactSubmit}
        noValidate>

        <div className="col-md-6">
          <input name="name" size="30" placeholder="Name"
                 required onChange={this.handleChange}
                 className="form-control" />
          <FieldFeedbacks for="name">
            <FieldFeedback when="*" />
          </FieldFeedbacks>

          <input type="email" name="email" size="30" placeholder="Email"
                 required onChange={this.handleChange}
                 className="form-control" />
          <FieldFeedbacks for="email">
            <FieldFeedback when="*" />
          </FieldFeedbacks>

          <input name="phone" size="30" placeholder="Phone"
                 required onChange={this.handleChange}
                 className="form-control" />
          <FieldFeedbacks for="phone">
            <FieldFeedback when="*" />
          </FieldFeedbacks>

          <input name="address" size="30" placeholder="Address"
                 required onChange={this.handleChange}
                 className="form-control" />
          <FieldFeedbacks for="address">
            <FieldFeedback when="*" />
          </FieldFeedbacks>
        </div>

        <div className="col-md-6">
          <textarea name="comments" cols="40" rows="20" placeholder="Message"
                    required minLength={5} maxLength={50}
                    onChange={this.handleChange}
                    className="form-control" />
          <FieldFeedbacks for="comments">
            <FieldFeedback when="*" />
          </FieldFeedbacks>
        </div>

        <div className="col-md-12">
          <button className="btn btn-lg btn-primary">Send Message</button>
        </div>
      </FormWithConstraints>
    );
  }
}

Screenshot:

form validation screenshot

This is a quick hack. For a proper demo, check https://github.com/tkrotoff/react-form-with-constraints#examples

'uint32_t' does not name a type

just navigate to /usr/include/x86_64-linux-gnu/bits open stdint-uintn.h and add these lines

typedef __uint8_t uint8_t;
typedef __uint16_t uint16_t;
typedef __uint32_t uint32_t;
typedef __uint64_t uint64_t;

again open stdint-intn.h and add

typedef __int8_t int8_t;
typedef __int16_t int16_t;
typedef __int32_t int32_t;
typedef __int64_t int64_t;

note these lines are already present just copy and add the missing lines cheerss..

Volley JsonObjectRequest Post request not working

Easy one for me ! I got it few weeks ago :

This goes in getBody() method, not in getParams() for a post request.

Here is mine :

    @Override
/**
 * Returns the raw POST or PUT body to be sent.
 *
 * @throws AuthFailureError in the event of auth failure
 */
public byte[] getBody() throws AuthFailureError {
    //        Map<String, String> params = getParams();
    Map<String, String> params = new HashMap<String, String>();
    params.put("id","1");
    params.put("name", "myname");
    if (params != null && params.size() > 0) {
        return encodeParameters(params, getParamsEncoding());
    }
    return null;

}

(I assumed you want to POST the params you wrote in your getParams)

I gave the params to the request inside the constructor, but since you are creating the request on the fly, you can hard coded them inside your override of the getBody() method.

This is what my code looks like :

    Bundle param = new Bundle();
    param.putString(HttpUtils.HTTP_CALL_TAG_KEY, tag);
    param.putString(HttpUtils.HTTP_CALL_PATH_KEY, url);
    param.putString(HttpUtils.HTTP_CALL_PARAM_KEY, params);

    switch (type) {
    case RequestType.POST:
        param.putInt(HttpUtils.HTTP_CALL_TYPE_KEY, RequestType.POST);
        SCMainActivity.mRequestQueue.add(new SCRequestPOST(Method.POST, url, this, tag, receiver, params));

and if you want even more this last string params comes from :

param = JsonUtils.XWWWUrlEncoder.encode(new JSONObject(paramasJObj)).toString();

and the paramasJObj is something like this : {"id"="1","name"="myname"} the usual JSON string.

How to fix 'sudo: no tty present and no askpass program specified' error?

1 open /etc/sudoers

type sudo vi /etc/sudoers. This will open your file in edit mode.

2 Add/Modify linux user

Look for the entry for Linux user. Modify as below if found or add a new line.

<USERNAME> ALL=(ALL) NOPASSWD: ALL

3 Save and Exit from edit mode

How does DISTINCT work when using JPA and Hibernate

I agree with kazanaki's answer, and it helped me. I wanted to select the whole entity, so I used

 select DISTINCT(c) from Customer c

In my case I have many-to-many relationship, and I want to load entities with collections in one query.

I used LEFT JOIN FETCH and at the end I had to make the result distinct.

IPython Notebook save location

  1. Based on my experience, if you use "ipython.exe" in python-2.7.5/Scripts from other directory, as typing at the comamnd prompt as ipython notebook, *.ipynb files will be loaded and saved in the current directory. ("notebook" is just a comamnd line parameter) I think the "ipython notebook.exe" in Winpython top directory is not relevant for your request. As for me, I added the ipython.exe directory to the Path only.
  2. If you want to make your profile in user directory, see below: https://code.google.com/p/winpython/wiki/Installation#Settings

Linq filter List<string> where it contains a string value from another List<string>

you can do that

var filteredFileList = fileList.Where(fl => filterList.Contains(fl.ToString()));

How do I update a formula with Homebrew?

You will first need to update the local formulas by doing

brew update

and then upgrade the package by doing

brew upgrade formula-name

An example would be if i wanted to upgrade mongodb, i would do something like this, assuming mongodb was already installed :

brew update && brew upgrade mongodb && brew cleanup mongodb

How to delete a record by id in Flask-SQLAlchemy

You can do this,

User.query.filter_by(id=123).delete()

or

User.query.filter(User.id == 123).delete()

Make sure to commit for delete() to take effect.

Using boolean values in C

You can use a char, or another small number container for it.

Pseudo-code

#define TRUE  1
#define FALSE 0

char bValue = TRUE;

How can I convert a datetime object to milliseconds since epoch (unix time) in Python?

Here's another form of a solution with normalization of your time object:

def to_unix_time(timestamp):
    epoch = datetime.datetime.utcfromtimestamp(0) # start of epoch time
    my_time = datetime.datetime.strptime(timestamp, "%Y/%m/%d %H:%M:%S.%f") # plugin your time object
    delta = my_time - epoch
    return delta.total_seconds() * 1000.0

How do getters and setters work?

In Java getters and setters are completely ordinary functions. The only thing that makes them getters or setters is convention. A getter for foo is called getFoo and the setter is called setFoo. In the case of a boolean, the getter is called isFoo. They also must have a specific declaration as shown in this example of a getter and setter for 'name':

class Dummy
{
    private String name;

    public Dummy() {}

    public Dummy(String name) {
        this.name = name;
    }

    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

The reason for using getters and setters instead of making your members public is that it makes it possible to change the implementation without changing the interface. Also, many tools and toolkits that use reflection to examine objects only accept objects that have getters and setters. JavaBeans for example must have getters and setters as well as some other requirements.

How do I initialize a TypeScript Object with a JSON-Object?

TLDR: TypedJSON (working proof of concept)


The root of the complexity of this problem is that we need to deserialize JSON at runtime using type information that only exists at compile time. This requires that type-information is somehow made available at runtime.

Fortunately, this can be solved in a very elegant and robust way with decorators and ReflectDecorators:

  1. Use property decorators on properties which are subject to serialization, to record metadata information and store that information somewhere, for example on the class prototype
  2. Feed this metadata information to a recursive initializer (deserializer)

 

Recording Type-Information

With a combination of ReflectDecorators and property decorators, type information can be easily recorded about a property. A rudimentary implementation of this approach would be:

function JsonMember(target: any, propertyKey: string) {
    var metadataFieldKey = "__propertyTypes__";

    // Get the already recorded type-information from target, or create
    // empty object if this is the first property.
    var propertyTypes = target[metadataFieldKey] || (target[metadataFieldKey] = {});

    // Get the constructor reference of the current property.
    // This is provided by TypeScript, built-in (make sure to enable emit
    // decorator metadata).
    propertyTypes[propertyKey] = Reflect.getMetadata("design:type", target, propertyKey);
}

For any given property, the above snippet will add a reference of the constructor function of the property to the hidden __propertyTypes__ property on the class prototype. For example:

class Language {
    @JsonMember // String
    name: string;

    @JsonMember// Number
    level: number;
}

class Person {
    @JsonMember // String
    name: string;

    @JsonMember// Language
    language: Language;
}

And that's it, we have the required type-information at runtime, which can now be processed.

 

Processing Type-Information

We first need to obtain an Object instance using JSON.parse -- after that, we can iterate over the entires in __propertyTypes__ (collected above) and instantiate the required properties accordingly. The type of the root object must be specified, so that the deserializer has a starting-point.

Again, a dead simple implementation of this approach would be:

function deserialize<T>(jsonObject: any, Constructor: { new (): T }): T {
    if (!Constructor || !Constructor.prototype.__propertyTypes__ || !jsonObject || typeof jsonObject !== "object") {
        // No root-type with usable type-information is available.
        return jsonObject;
    }

    // Create an instance of root-type.
    var instance: any = new Constructor();

    // For each property marked with @JsonMember, do...
    Object.keys(Constructor.prototype.__propertyTypes__).forEach(propertyKey => {
        var PropertyType = Constructor.prototype.__propertyTypes__[propertyKey];

        // Deserialize recursively, treat property type as root-type.
        instance[propertyKey] = deserialize(jsonObject[propertyKey], PropertyType);
    });

    return instance;
}
var json = '{ "name": "John Doe", "language": { "name": "en", "level": 5 } }';
var person: Person = deserialize(JSON.parse(json), Person);

The above idea has a big advantage of deserializing by expected types (for complex/object values), instead of what is present in the JSON. If a Person is expected, then it is a Person instance that is created. With some additional security measures in place for primitive types and arrays, this approach can be made secure, that resists any malicious JSON.

 

Edge Cases

However, if you are now happy that the solution is that simple, I have some bad news: there is a vast number of edge cases that need to be taken care of. Only some of which are:

  • Arrays and array elements (especially in nested arrays)
  • Polymorphism
  • Abstract classes and interfaces
  • ...

If you don't want to fiddle around with all of these (I bet you don't), I'd be glad to recommend a working experimental version of a proof-of-concept utilizing this approach, TypedJSON -- which I created to tackle this exact problem, a problem I face myself daily.

Due to how decorators are still being considered experimental, I wouldn't recommend using it for production use, but so far it served me well.

Create <div> and append <div> dynamically

window.onload = function() {
  var iDiv = document.createElement('div');
  iDiv.id = 'block';
  iDiv.className = 'block';
  document.body.appendChild(iDiv);

  var iiDiv = document.createElement('div');
  iiDiv.className = 'block-2';

  var s = document.getElementById('block');
  s.appendChild(iiDiv);
}

Visual Studio C# IntelliSense not automatically displaying

At the bottommost right look at the blue line where Ln, Col, Spaces, UTF, CRLF,..... here the language is specified. Check that your language and the language specified there are the same. In my case, it was Django Python while I was trying to use HTML.

Global javascript variable inside document.ready

Use window.intro inside of $(document).ready().

Convert hex to binary

Another way:

import math

def hextobinary(hex_string):
    s = int(hex_string, 16) 
    num_digits = int(math.ceil(math.log(s) / math.log(2)))
    digit_lst = ['0'] * num_digits
    idx = num_digits
    while s > 0:
        idx -= 1
        if s % 2 == 1: digit_lst[idx] = '1'
        s = s / 2
    return ''.join(digit_lst)

print hextobinary('abc123efff')

Finding the last index of an array

Array starts from index 0 and ends at n-1.

static void Main(string[] args)
{
    int[] arr = { 1, 2, 3, 4, 5 };
    int length = arr.Length - 1;   // starts from 0 to n-1

    Console.WriteLine(length);     // this will give the last index.
    Console.Read();
}

Display PDF within web browser

I recently needed to provide a more mobile-friendly, responsive version of a .pdf document, because narrow phone screens required scrolling right and left a lot. To allow just vertical scrolling and avoid horizontal scrolling, the following steps worked for me:

  • Open the .pdf in Chrome browser
  • Click Open with Google Docs
  • Click File > Download > Web Page
  • Click on the downloaded document to unzip it
  • Click on the unzipped HTML document to open it in Chrome browser
  • Press fn F12 to open Chrome Dev Tools
  • Paste copy(document.documentElement.outerHTML.replace(/padding:72pt 72pt 72pt 72pt;/, '').replace(/margin-right:.*?pt/g, '')) into the Console, and press Enter to copy the tweaked document to the clipboard
  • Open a text editor (e.g., Notepad), or in my case VSCode, paste, and save with a .html extension.

The result looked good and was usable in both desktop and mobile environments.

Move an item inside a list?

A slightly shorter solution, that only moves the item to the end, not anywhere is this:

l += [l.pop(0)]

For example:

>>> l = [1,2,3,4,5]
>>> l += [l.pop(0)]
>>> l
[2, 3, 4, 5, 1]

Spark DataFrame groupBy and sort in the descending order (pyspark)

Use orderBy:

df.orderBy('column_name', ascending=False)

Complete answer:

group_by_dataframe.count().filter("`count` >= 10").orderBy('count', ascending=False)

http://spark.apache.org/docs/2.0.0/api/python/pyspark.sql.html

Why is printing "B" dramatically slower than printing "#"?

Yes the culprit is definitely word-wrapping. When I tested your two programs, NetBeans IDE 8.2 gave me the following result.

  1. First Matrix: O and # = 6.03 seconds
  2. Second Matrix: O and B = 50.97 seconds

Looking at your code closely you have used a line break at the end of first loop. But you didn't use any line break in second loop. So you are going to print a word with 1000 characters in the second loop. That causes a word-wrapping problem. If we use a non-word character " " after B, it takes only 5.35 seconds to compile the program. And If we use a line break in the second loop after passing 100 values or 50 values, it takes only 8.56 seconds and 7.05 seconds respectively.

Random r = new Random();
for (int i = 0; i < 1000; i++) {
    for (int j = 0; j < 1000; j++) {
        if(r.nextInt(4) == 0) {
            System.out.print("O");
        } else {
            System.out.print("B");
        }
        if(j%100==0){               //Adding a line break in second loop      
            System.out.println();
        }                    
    }
    System.out.println("");                
}

Another advice is that to change settings of NetBeans IDE. First of all, go to NetBeans Tools and click Options. After that click Editor and go to Formatting tab. Then select Anywhere in Line Wrap Option. It will take almost 6.24% less time to compile the program.

NetBeans Editor Settings

How can I set a website image that will show as preview on Facebook?

Note also that if you have wordpress just scroll down to the bottom of the webpage when in edit mode, and select "featured image" (bottom right side of screen).

TempData keep() vs peek()

When an object in a TempDataDictionary is read, it will be marked for deletion at the end of that request.

That means if you put something on TempData like

TempData["value"] = "someValueForNextRequest";

And on another request you access it, the value will be there but as soon as you read it, the value will be marked for deletion:

//second request, read value and is marked for deletion
object value = TempData["value"];

//third request, value is not there as it was deleted at the end of the second request
TempData["value"] == null

The Peek and Keep methods allow you to read the value without marking it for deletion. Say we get back to the first request where the value was saved to TempData.

With Peek you get the value without marking it for deletion with a single call, see msdn:

//second request, PEEK value so it is not deleted at the end of the request
object value = TempData.Peek("value");

//third request, read value and mark it for deletion
object value = TempData["value"];

With Keep you specify a key that was marked for deletion that you want to keep. Retrieving the object and later on saving it from deletion are 2 different calls. See msdn

//second request, get value marking it from deletion
object value = TempData["value"];
//later on decide to keep it
TempData.Keep("value");

//third request, read value and mark it for deletion
object value = TempData["value"];

You can use Peek when you always want to retain the value for another request. Use Keep when retaining the value depends on additional logic.

You have 2 good questions about how TempData works here and here

Hope it helps!

How to run Visual Studio post-build events for debug build only

Add your post build event like normal. Then save your project, open it in Notepad (or your favorite editor), and add condition to the PostBuildEvent property group. Here's an example:

<PropertyGroup Condition=" '$(Configuration)' == 'Debug' ">
    <PostBuildEvent>start gpedit</PostBuildEvent>
</PropertyGroup>

Reset the Value of a Select Box

The easiest method without using javaScript is to put all your <select> dropdown inside a <form> tag and use form reset button. Example:

<form>
  <select>
    <option>one</option>
    <option>two</option>
    <option selected>three</option>
  </select>
  <input type="reset" value="Reset" />
</form>

Or, using JavaScript, it can be done in following way:

HTML Code:

<select>
  <option selected>one</option>
  <option>two</option>
  <option>three</option>
</select>
<button id="revert">Reset</button>

And JavaScript code:

const button = document.getElementById("revert");
const options = document.querySelectorAll('select option');
button.onclick = () => {
  for (var i = 0; i < options.length; i++) {
    options[i].selected = options[i].defaultSelected;
  }
}

Both of these methods will work if you have multiple selected items or single selected item.

Function inside a function.?

X returns (value +3), while Y returns (value*2)

Given a value of 4, this means (4+3) * (4*2) = 7 * 8 = 56.

Although functions are not limited in scope (which means that you can safely 'nest' function definitions), this particular example is prone to errors:

1) You can't call y() before calling x(), because function y() won't actually be defined until x() has executed once.

2) Calling x() twice will cause PHP to redeclare function y(), leading to a fatal error:

Fatal error: Cannot redeclare y()

The solution to both would be to split the code, so that both functions are declared independent of each other:

function x ($y) 
{
  return($y+3);
}

function y ($z)
{
  return ($z*2);
}

This is also a lot more readable.

What is the preferred Bash shebang?

You should use #!/usr/bin/env bash for portability: different *nixes put bash in different places, and using /usr/bin/env is a workaround to run the first bash found on the PATH. And sh is not bash.

invalid operands of types int and double to binary 'operator%'

Because % is only defined for integer types. That's the modulus operator.

5.6.2 of the standard:

The operands of * and / shall have arithmetic or enumeration type; the operands of % shall have integral or enumeration type. [...]

As Oli pointed out, you can use fmod(). Don't forget to include math.h.

List supported SSL/TLS versions for a specific OpenSSL build

When you run OPENSSL command using s_client this is the output. See the Cipher, if the cipher NULL it means that version of TLS is not supported.

TLSv1/SSLv3, Cipher is ECDHE-RSA-AES256
Server public key is 2048 bit
Secure Renegotiation IS supported
Compression: NONE
Expansion: NONE
No ALPN negotiated
SSL-Session:
    Protocol  : TLSv1
    Cipher    : ECDHE-RSA-AES256
    Session-ID: A84600002D4945DE6
    Session-ID-ctx:
    Master-Key:  
    Start Time: 15852343333860
    Timeout   : 2343 (sec)
    Verify return code: 0 (ok)

Changing column names of a data frame

Just to correct and slightly extend Scott Wilson answer.
You can use data.table's setnames function on data.frames too.

Do not expect speed up of the operation but you can expect the setnames to be more efficient for memory consumption as it updates column names by reference. This can be tracked with address function, see below.

library(data.table)
set.seed(123)
n = 1e8

df = data.frame(bad=sample(1:3, n, TRUE), worse=rnorm(n))
address(df)
#[1] "0x208f9f00"
colnames(df) <- c("good", "better")
address(df)
#[1] "0x208fa1d8"
rm(df)

dt = data.table(bad=sample(1:3, n, TRUE), worse=rnorm(n))
address(dt)
#[1] "0x535c830"
setnames(dt, c("good", "better"))
address(dt)
#[1] "0x535c830"
rm(dt)

So if you are hitting your memory limits you may consider to use this one instead.

How do I create a Bash alias?

I need to run the Postgres database and created an alias for the purpose. The work through is provided below:

$ nano ~/.bash_profile 

# in the bash_profile, insert the following texts:

alias pgst="pg_ctl -D /usr/local/var/postgres start"
alias pgsp="pg_ctl -D /usr/local/var/postgres stop"


$ source ~/.bash_profile 

### This will start the Postgres server 
$ pgst

### This will stop the Postgres server 
$ pgsp

I get a "An attempt was made to load a program with an incorrect format" error on a SQL Server replication project

The answer by baldy below is correct, but you may also need to enable 32-bit applications in your AppPool.

Source: http://www.alexjamesbrown.com/uncategorized/could-not-load-file-or-assembly-chilkatdotnet2-or-one-of-its-dependencies-an-attempt-was-made-to-load-a-program-with-an-incorrect-format/

Whilst setting up an application to run on my local machine (running Vista 64bit) I encountered this error:

Could not load file or assembly ChilkatDotNet2 or one of its dependencies. An attempt was made to load a program with an incorrect format.

Obviously, the application uses ChilKat components, but it would seem that the version we are using, is only the 32bit version.

To resolve this error, I set my app pool in IIS to allow 32bit applications. Open up IIS Manager, right click on the app pool, and select Advanced Settings (See below)

enter image description here

Then set "Enable 32-bit Applications" to True.

enter image description here

All done!

How do I declare and initialize an array in Java?

Type[] variableName = new Type[capacity];

Type[] variableName = {comma-delimited values};



Type variableName[] = new Type[capacity]; 

Type variableName[] = {comma-delimited values};

is also valid, but I prefer the brackets after the type, because it's easier to see that the variable's type is actually an array.

wait until all threads finish their work in java

You can join to the threads. The join blocks until the thread completes.

for (Thread thread : threads) {
    thread.join();
}

Note that join throws an InterruptedException. You'll have to decide what to do if that happens (e.g. try to cancel the other threads to prevent unnecessary work being done).

Finding the max/min value in an array of primitives using Java

You could easily do it with an IntStream and the max() method.

Example

public static int maxValue(final int[] intArray) {
  return IntStream.range(0, intArray.length).map(i -> intArray[i]).max().getAsInt();
}

Explanation

  1. range(0, intArray.length) - To get a stream with as many elements as present in the intArray.

  2. map(i -> intArray[i]) - Map every element of the stream to an actual element of the intArray.

  3. max() - Get the maximum element of this stream as OptionalInt.

  4. getAsInt() - Unwrap the OptionalInt. (You could also use here: orElse(0), just in case the OptionalInt is empty.)

How to force reloading a page when using browser back button?

Currently this is the most up to date way reload page if the user clicks the back button.

const [entry] = performance.getEntriesByType("navigation");

// Show it in a nice table in the developer console
console.table(entry.toJSON());

if (entry["type"] === "back_forward")
    location.reload();

See here for source

SQL Statement with multiple SETs and WHEREs

NO!

You'll need to handle those individually

Update [table]
Set ID = 111111259
WHERE ID = 2555

Update [table]
Set ID = 111111261
WHERE ID = 2724

--...

Git, fatal: The remote end hung up unexpectedly

In my case I got this error, when pushing with Intellij Idea.

Here is how I traced down my error and fixed it.

  • enable debug logging within the terminal, which is never a bad idea :)
set GIT_CURL_VERBOSE=1 set GIT_TRACE=1 
  • push via the terminal, not via intellij
git push 
-> fatal: The current branch feature/my-new-feature has no upstream branch.
To push the current branch and set the remote as upstream

Solution was to set the upstream, which must have been gone wrong before:

git push --set-upstream origin feature/my-new-feature

CodeIgniter: How To Do a Select (Distinct Fieldname) MySQL Query

$record = '123';

$this->db->distinct();

$this->db->select('accessid');

$this->db->where('record', $record); 

$query = $this->db->get('accesslog');

then

$query->num_rows();

should go a long way towards it.

Is there any simple way to convert .xls file to .csv file? (Excel)

This is a modification of nate_weldon's answer with a few improvements:

  • More robust releasing of Excel objects
  • Set application.DisplayAlerts = false; before attempting to save to hide prompts

Also note that the application.Workbooks.Open and ws.SaveAs methods expect sourceFilePath and targetFilePath to be full paths (ie. directory path + filename)

private static void SaveAs(string sourceFilePath, string targetFilePath)
{
    Application application = null;
    Workbook wb = null;
    Worksheet ws = null;

    try
    {
        application = new Application();
        application.DisplayAlerts = false;
        wb = application.Workbooks.Open(sourceFilePath);
        ws = (Worksheet)wb.Sheets[1];
        ws.SaveAs(targetFilePath, XlFileFormat.xlCSV);
    }
    catch (Exception e)
    {
        // Handle exception
    }
    finally
    {
        if (application != null) application.Quit();
        if (ws != null) Marshal.ReleaseComObject(ws);
        if (wb != null) Marshal.ReleaseComObject(wb);
        if (application != null) Marshal.ReleaseComObject(application);
    }
}

How to convert InputStream to FileInputStream

Use ClassLoader#getResource() instead if its URI represents a valid local disk file system path.

URL resource = classLoader.getResource("resource.ext");
File file = new File(resource.toURI());
FileInputStream input = new FileInputStream(file);
// ...

If it doesn't (e.g. JAR), then your best bet is to copy it into a temporary file.

Path temp = Files.createTempFile("resource-", ".ext");
Files.copy(classLoader.getResourceAsStream("resource.ext"), temp, StandardCopyOption.REPLACE_EXISTING);
FileInputStream input = new FileInputStream(temp.toFile());
// ...

That said, I really don't see any benefit of doing so, or it must be required by a poor helper class/method which requires FileInputStream instead of InputStream. If you can, just fix the API to ask for an InputStream instead. If it's a 3rd party one, by all means report it as a bug. I'd in this specific case also put question marks around the remainder of that API.

Visual Studio Code: Auto-refresh file changes

SUPER-SHIFT-p > File: Revert File is the only way

(where SUPER is Command on Mac and Ctrl on PC)

Rails find_or_create_by more than one attribute?

For anyone else who stumbles across this thread but needs to find or create an object with attributes that might change depending on the circumstances, add the following method to your model:

# Return the first object which matches the attributes hash
# - or -
# Create new object with the given attributes
#
def self.find_or_create(attributes)
  Model.where(attributes).first || Model.create(attributes)
end

Optimization tip: regardless of which solution you choose, consider adding indexes for the attributes you are querying most frequently.

How to 'update' or 'overwrite' a python list

What about replace the item if you know the position:

aList[0]=2014

Or if you don't know the position loop in the list, find the item and then replace it

aList = [123, 'xyz', 'zara', 'abc']
    for i,item in enumerate(aList):
      if item==123:
        aList[i]=2014
        break
    
    print aList

How to select rows with one or more nulls from a pandas DataFrame without listing columns explicitly?

def nans(df): return df[df.isnull().any(axis=1)]

then when ever you need it you can type:

nans(your_dataframe)

Buiding Hadoop with Eclipse / Maven - Missing artifact jdk.tools:jdk.tools:jar:1.6

maybe system install jdk package, but maybe some devel tools or plugin.

I find this problem under opensuse env. and I install java-1_6_0-openjdk-devel

the problem is disppeared..

Freeze screen in chrome debugger / DevTools panel for popover inspection?

To be able to inspect any element do the following. This should work even if it's hard to duplicate the hover state:

  • Run the following javascript in the console. This will break into the debugger in 5 seconds.

    setTimeout(function(){debugger;}, 5000)

  • Go show your element (by hovering or however) and wait until Chrome breaks into the Debugger.

  • Now click on the Elements tab in the Chrome Inspector, and you can look for your element there.
  • You may also be able to click on the Find Element icon (looks like a magnifying glass) and Chrome will let you go and inspect and find your element on the page by right clicking on it, then choosing Inspect Element

Note that this approach is a slight variation to this other great answer on this page.

Can I draw rectangle in XML?

Use this code

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >

    <corners
        android:bottomLeftRadius="5dp"
        android:bottomRightRadius="5dp"
        android:radius="0.1dp"
        android:topLeftRadius="5dp"
        android:topRightRadius="5dp" />

    <solid android:color="#Efffff" />

    <stroke
        android:width="2dp"
        android:color="#25aaff" />

</shape>

How do I remove/delete a virtualenv?

If you're a windows user, you can also delete the environment by going to: C:/Users/username/Anaconda3/envs Here you can see a list of virtual environment and delete the one that you no longer need.

Should I use encodeURI or encodeURIComponent for encoding URLs?

Here is a summary.

  1. escape() will not encode @ * _ + - . /

    Do not use it.

  2. encodeURI() will not encode A-Z a-z 0-9 ; , / ? : @ & = + $ - _ . ! ~ * ' ( ) #

    Use it when your input is a complete URL like 'https://searchexample.com/search?q=wiki'

  3. encodeURIComponent() will not encode A-Z a-z 0-9 - _ . ! ~ * ' ( ) Use it when your input is part of a complete URL e.g const queryStr = encodeURIComponent(someString)

How to clone object in C++ ? Or Is there another solution?

In C++ copying the object means cloning. There is no any special cloning in the language.

As the standard suggests, after copying you should have 2 identical copies of the same object.

There are 2 types of copying: copy constructor when you create object on a non initialized space and copy operator where you need to release the old state of the object (that is expected to be valid) before setting the new state.

How to store token in Local or Session Storage in Angular 2?

Simple example:

var userID = data.id;

localStorage.setItem('userID',JSON.stringify(userID));

Differences between Lodash and Underscore.js

Lodash is inspired by Underscore.js, but nowadays it is a superior solution. You can make your custom builds, have a higher performance, support AMD and have great extra features. Check this Lodash vs. Underscore.js benchmarks on jsperf and... this awesome post about Lodash:

One of the most useful feature when you work with collections, is the shorthand syntax:

var characters = [
  { 'name': 'barney', 'age': 36, 'blocked': false },
  { 'name': 'fred',   'age': 40, 'blocked': true }
];

// Using "_.filter" callback shorthand
_.filter(characters, { 'age': 36 });

// Using Underscore.js
_.filter(characters, function(character) { return character.age === 36; } );

// ? [{ 'name': 'barney', 'age': 36, 'blocked': false }]

(taken from Lodash documentation)

Print to the same line and not a new line?

for object "pega" that provides StartRunning(), StopRunning(), boolean getIsRunning() and integer getProgress100() returning value in range of 0 to 100, this provides text progress bar while running...

now = time.time()
timeout = now + 30.0
last_progress = -1

pega.StartRunning()

while now < timeout and pega.getIsRunning():
    time.sleep(0.5)
    now = time.time()

    progress = pega.getTubProgress100()
    if progress != last_progress:
        print('\r'+'='*progress+'-'*(100-progress)+' ' + str(progress) + "% ", end='', flush=True)
        last_progress = progress

pega.StopRunning()

progress = pega.getTubProgress100()
print('\r'+'='*progress+'-'*(100-progress)+' ' + str(progress) + "% ", flush=True)

git - remote add origin vs remote set-url origin

Below will reinitialize your local repo; also clearing remote repos (ie origin):

git init

Then below, will create 'origin' if it doesn't exist:

git remote add origin [repo-url]

Else, you can use the set-url subcommand to edit an existing remote:

git remote set-url origin [repo-url]

Also, you can check existing remotes with

git remote -v

Hope this helps!

copy db file with adb pull results in 'permission denied' error

I had the same problem. My work around is to use adb shell and su. Next, copy the file to /sdcard/Download

Then, I can use adb pull to get the file.

Iterate over array of objects in Typescript

You can use the built-in forEach function for arrays.

Like this:

//this sets all product descriptions to a max length of 10 characters
data.products.forEach( (element) => {
    element.product_desc = element.product_desc.substring(0,10);
});

Your version wasn't wrong though. It should look more like this:

for(let i=0; i<data.products.length; i++){
    console.log(data.products[i].product_desc); //use i instead of 0
}

Display tooltip on Label's hover?

Are you find with using standard tooltip? You could use title attribute like

<label for="male" title="Hello This Will Have Some Value">Hello...</label>

You could add the title attribute of same value to the element that label is for as well.

How to import a Python class that is in a directory above?

How to load a module that is a directory up

preface: I did a substantial rewrite of a previous answer with the hopes of helping ease people into python's ecosystem, and hopefully give everyone the best change of success with python's import system.

This will cover relative imports within a package, which I think is the most probable case to OP's question.

Python is a modular system

This is why we write import foo to load a module "foo" from the root namespace, instead of writing:

foo = dict();  # please avoid doing this
with open(os.path.join(os.path.dirname(__file__), '../foo.py') as foo_fh:  # please avoid doing this
    exec(compile(foo_fh.read(), 'foo.py', 'exec'), foo)  # please avoid doing this

Python isn't coupled to a file-system

This is why we can embed python in environment where there isn't a defacto filesystem without providing a virtual one, such as Jython.

Being decoupled from a filesystem lets imports be flexible, this design allows for things like imports from archive/zip files, import singletons, bytecode caching, cffi extensions, even remote code definition loading.

So if imports are not coupled to a filesystem what does "one directory up" mean? We have to pick out some heuristics but we can do that, for example when working within a package, some heuristics have already been defined that makes relative imports like .foo and ..foo work within the same package. Cool!

If you sincerely want to couple your source code loading patterns to a filesystem, you can do that. You'll have to choose your own heuristics, and use some kind of importing machinery, I recommend importlib

Python's importlib example looks something like so:

import importlib.util
import sys

# For illustrative purposes.
file_path = os.path.join(os.path.dirname(__file__), '../foo.py')
module_name = 'foo'

foo_spec = importlib.util.spec_from_file_location(module_name, file_path)
# foo_spec is a ModuleSpec specifying a SourceFileLoader
foo_module = importlib.util.module_from_spec(foo_spec)
sys.modules[module_name] = foo_module
foo_spec.loader.exec_module(foo_module)

foo = sys.modules[module_name]
# foo is the sys.modules['foo'] singleton

Packaging

There is a great example project available officially here: https://github.com/pypa/sampleproject

A python package is a collection of information about your source code, that can inform other tools how to copy your source code to other computers, and how to integrate your source code into that system's path so that import foo works for other computers (regardless of interpreter, host operating system, etc)

Directory Structure

Lets have a package name foo, in some directory (preferably an empty directory).

some_directory/
    foo.py  # `if __name__ == "__main__":`  lives here

My preference is to create setup.py as sibling to foo.py, because it makes writing the setup.py file simpler, however you can write configuration to change/redirect everything setuptools does by default if you like; for example putting foo.py under a "src/" directory is somewhat popular, not covered here.

some_directory/
    foo.py
    setup.py

.

#!/usr/bin/env python3
# setup.py

import setuptools

setuptools.setup(
    name="foo",
    ...
    py_modules=['foo'],
)

.

python3 -m pip install --editable ./  # or path/to/some_directory/

"editable" aka -e will yet-again redirect the importing machinery to load the source files in this directory, instead copying the current exact files to the installing-environment's library. This can also cause behavioral differences on a developer's machine, be sure to test your code! There are tools other than pip, however I'd recommend pip be the introductory one :)

I also like to make foo a "package" (a directory containing __init__.py) instead of a module (a single ".py" file), both "packages" and "modules" can be loaded into the root namespace, modules allow for nested namespaces, which is helpful if we want to have a "relative one directory up" import.

some_directory/
    foo/
        __init__.py
    setup.py

.

#!/usr/bin/env python3
# setup.py

import setuptools

setuptools.setup(
    name="foo",
    ...
    packages=['foo'],
)

I also like to make a foo/__main__.py, this allows python to execute the package as a module, eg python3 -m foo will execute foo/__main__.py as __main__.

some_directory/
    foo/
        __init__.py
        __main__.py  # `if __name__ == "__main__":`  lives here, `def main():` too!
    setup.py

.

#!/usr/bin/env python3
# setup.py

import setuptools

setuptools.setup(
    name="foo",
    ...
    packages=['foo'],
    ...
    entry_points={
        'console_scripts': [
            # "foo" will be added to the installing-environment's text mode shell, eg `bash -c foo`
            'foo=foo.__main__:main',
        ]
    },
)

Lets flesh this out with some more modules: Basically, you can have a directory structure like so:

some_directory/
    bar.py           # `import bar`
    foo/
        __init__.py  # `import foo`
        __main__.py
        baz.py       # `import foo.baz
        spam/           
            __init__.py  # `import foo.spam`
            eggs.py      # `import foo.spam.eggs`
    setup.py

setup.py conventionally holds metadata information about the source code within, such as:

  • what dependencies are needed to install named "install_requires"
  • what name should be used for package management (install/uninstall "name"), I suggest this match your primary python package name in our case foo, though substituting underscores for hyphens is popular
  • licensing information
  • maturity tags (alpha/beta/etc),
  • audience tags (for developers, for machine learning, etc),
  • single-page documentation content (like a README),
  • shell names (names you type at user shell like bash, or names you find in a graphical user shell like a start menu),
  • a list of python modules this package will install (and uninstall)
  • a defacto "run tests" entry point python ./setup.py test

Its very expansive, it can even compile c extensions on the fly if a source module is being installed on a development machine. For a every-day example I recommend the PYPA Sample Repository's setup.py

If you are releasing a build artifact, eg a copy of the code that is meant to run nearly identical computers, a requirements.txt file is a popular way to snapshot exact dependency information, where "install_requires" is a good way to capture minimum and maximum compatible versions. However, given that the target machines are nearly identical anyway, I highly recommend creating a tarball of an entire python prefix. This can be tricky, too detailed to get into here. Check out pip install's --target option, or virtualenv aka venv for leads.

back to the example

how to import a file one directory up:

From foo/spam/eggs.py, if we wanted code from foo/baz we could ask for it by its absolute namespace:

import foo.baz

If we wanted to reserve capability to move eggs.py into some other directory in the future with some other relative baz implementation, we could use a relative import like:

import ..baz

Generic XSLT Search and Replace template

Here's one way in XSLT 2

<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">   <xsl:template match="@*|node()">     <xsl:copy>       <xsl:apply-templates select="@*|node()"/>     </xsl:copy>   </xsl:template>   <xsl:template match="text()">     <xsl:value-of select="translate(.,'&quot;','''')"/>   </xsl:template> </xsl:stylesheet> 

Doing it in XSLT1 is a little more problematic as it's hard to get a literal containing a single apostrophe, so you have to resort to a variable:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">   <xsl:template match="@*|node()">     <xsl:copy>       <xsl:apply-templates select="@*|node()"/>     </xsl:copy>   </xsl:template>   <xsl:variable name="apos">'</xsl:variable>   <xsl:template match="text()">     <xsl:value-of select="translate(.,'&quot;',$apos)"/>   </xsl:template> </xsl:stylesheet> 

fs.writeFile in a promise, asynchronous-synchronous stuff

Because fs.writefile is a traditional asynchronous callback - you need to follow the promise spec and return a new promise wrapping it with a resolve and rejection handler like so:

return new Promise(function(resolve, reject) {
    fs.writeFile("<filename.type>", data, '<file-encoding>', function(err) {
        if (err) reject(err);
        else resolve(data);
    });
});

So in your code you would use it like so right after your call to .then():

 .then(function(results) {
    return new Promise(function(resolve, reject) {
            fs.writeFile(ASIN + '.json', JSON.stringify(results), function(err) {
               if (err) reject(err);
               else resolve(data);
            });
    });
  }).then(function(results) {
       console.log("results here: " + results)
  }).catch(function(err) {
       console.log("error here: " + err);
  });

Rolling back bad changes with svn in Eclipse

In Eclipse Ganymede (Subclipse)

Select project/file that contains bad change, and from pop-up menu choose:

Team -> Show History

Revisions related to that project/file will be shown in History tab.

Find revision where "bad changes" were committed and from pop-up menu choose:

Revert Changes from Revision X

This will merge changes in file(s) modified within bad revision, with revision prior to bad revision.

There are two scenarios from here:

  1. If you committed no changes for that file (bad revision is last revision for that file), it will simply remove changes made in bad revision. Those changes are merged to your working copy so you have to commit them.

  2. If you committed some changes for that file (bad revision is not last revision for that file), you will have to manually resolve conflict. Let say that you have file readme.txt with, and bad revision number is 33. Also, you've made another commit for that file in revision 34. After you choose Revert Changes from Revision 33 you will have following in your working copy:

readme.txt.merge-left.r33 - bad revision

readme.txt.merge-right.r32 - before bad revision

readme.txt.working - working copy version (same as in r34 if you don't have any uncommitted changes)

Original readme.txt will be marked conflicted, and will contain merged version (where changes from bad revision are removed) with some markers (<<<<<<< .working etc). If you just want to remove changes from bad revision and keep changes made after that, then all you have to do is remove markers. Otherwise, you can copy contents from one of 3 files mentioned above to original file. Whatever you choose, when you are done, mark conflict resolved by

Team - Mark Resolved

Temporary files will be removed and your file will be marked changed. As in 1, you have to commit changes.

Note that this does not remove revision from revision history in svn repository. You simply made new revision where changes from bad revision are removed.

How to format numbers by prepending 0 to single-digit numbers?

    function colorOf(r,g,b){
  var f = function (x) {
    return (x<16 ? '0' : '') + x.toString(16) 
  };

  return "#" +  f(r) + f(g) + f(b);
}

NULL or BLANK fields (ORACLE)

SELECT COUNT (COL_NAME) 
FROM TABLE 
WHERE TRIM (COL_NAME) IS NULL 
or COL_NAME='NULL'

Using other keys for the waitKey() function of opencv

As to me, the below code does't work, when it runs,the image will step to the next quickly without your press:

import cv2
img = cv2.imread('sof.jpg') # load a dummy image
while(1):
    cv2.imshow('img',img)
    k = cv2.waitKey(33)
    if k==27:    # Esc key to stop
        break
    elif k==-1:  # normally -1 returned,so don't print it
        continue
    else:
        print k # else print its value

But this works:

def test_wait_key():
    lst_img_path = [
        '/home/xy/yy_face_head/face_det_test/111.png',
        '/home/xy/yy_face_head/face_det_test/222.png'
        #.....more path ...
    ]

    for f_path in lst_img_path:
        img = cv2.imread(f_path)
        cv2.imshow('tmp', img)
        c = cv2.waitKey(0) % 256

        if c == ord('a'):
            print "pressed a"
        else:
            print 'you press %s' % chr(c)

Output as below:

enter image description here

Reflection: How to Invoke Method with parameters

I tried to work with all the suggested answers above but nothing seems to work for me. So i am trying to explain what worked for me here.

I believe if you are calling some method like the Main below or even with a single parameter as in your question, you just have to change the type of parameter from string to object for this to work. I have a class like below

//Assembly.dll
namespace TestAssembly{
    public class Main{

        public void Hello()
        { 
            var name = Console.ReadLine();
            Console.WriteLine("Hello() called");
            Console.WriteLine("Hello" + name + " at " + DateTime.Now);
        }

        public void Run(string parameters)
        { 
            Console.WriteLine("Run() called");
            Console.Write("You typed:"  + parameters);
        }

        public string TestNoParameters()
        {
            Console.WriteLine("TestNoParameters() called");
            return ("TestNoParameters() called");
        }

        public void Execute(object[] parameters)
        { 
            Console.WriteLine("Execute() called");
           Console.WriteLine("Number of parameters received: "  + parameters.Length);

           for(int i=0;i<parameters.Length;i++){
               Console.WriteLine(parameters[i]);
           }
        }

    }
}

Then you have to pass the parameterArray inside an object array like below while invoking it. The following method is what you need to work

private void ExecuteWithReflection(string methodName,object parameterObject = null)
{
    Assembly assembly = Assembly.LoadFile("Assembly.dll");
    Type typeInstance = assembly.GetType("TestAssembly.Main");

    if (typeInstance != null)
    {
        MethodInfo methodInfo = typeInstance.GetMethod(methodName);
        ParameterInfo[] parameterInfo = methodInfo.GetParameters();
        object classInstance = Activator.CreateInstance(typeInstance, null);

        if (parameterInfo.Length == 0)
        {
            // there is no parameter we can call with 'null'
            var result = methodInfo.Invoke(classInstance, null);
        }
        else
        {
            var result = methodInfo.Invoke(classInstance,new object[] { parameterObject } );
        }
    }
}

This method makes it easy to invoke the method, it can be called as following

ExecuteWithReflection("Hello");
ExecuteWithReflection("Run","Vinod");
ExecuteWithReflection("TestNoParameters");
ExecuteWithReflection("Execute",new object[]{"Vinod","Srivastav"});

How to measure the a time-span in seconds using System.currentTimeMillis()?

TimeUnit.SECONDS.convert(start6, TimeUnit.MILLISECONDS);

External resource not being loaded by AngularJs

Had the same issue here. I needed to bind to Youtube links. What worked for me, as a global solution, was to add the following to my config:

.config(['$routeProvider', '$sceDelegateProvider',
        function ($routeProvider, $sceDelegateProvider) {

    $sceDelegateProvider.resourceUrlWhitelist(['self', new RegExp('^(http[s]?):\/\/(w{3}.)?youtube\.com/.+$')]);

}]);

Adding 'self' in there is important - otherwise will fail to bind to any URL. From the angular docs

'self' - The special string, 'self', can be used to match against all URLs of the same domain as the application document using the same protocol.

With that in place, I'm now able to bind directly to any Youtube link.

You'll obviously have to customise the regex to your needs. Hope it helps!

How can I install the Beautiful Soup module on the Mac?

Download the package and unpack it. In Terminal, go to the package's directory and type

python setup.py install

What do *args and **kwargs mean?

Another good use for *args and **kwargs: you can define generic "catch all" functions, which is great for decorators where you return such a wrapper instead of the original function.

An example with a trivial caching decorator:

import pickle, functools
def cache(f):
  _cache = {}
  def wrapper(*args, **kwargs):
    key = pickle.dumps((args, kwargs))
    if key not in _cache:
      _cache[key] = f(*args, **kwargs) # call the wrapped function, save in cache
    return _cache[key] # read value from cache
  functools.update_wrapper(wrapper, f) # update wrapper's metadata
  return wrapper

import time
@cache
def foo(n):
  time.sleep(2)
  return n*2

foo(10) # first call with parameter 10, sleeps
foo(10) # returns immediately

Using Google Translate in C#

Here is my slighly different code, solving also the encoding issue:

public string TranslateText(string input, string languagePair)
{
    string url = String.Format("http://www.google.com/translate_t?hl=en&ie=UTF8&text={0}&langpair={1}", input, languagePair);
    WebClient webClient = new WebClient();
    webClient.Encoding = System.Text.Encoding.Default;
    string result = webClient.DownloadString(url);
    result = result.Substring(result.IndexOf("TRANSLATED_TEXT"));
    result = result.Substring(result.IndexOf("'")+1);
    result = result.Substring(0, result.IndexOf("'"));
    return result;
}

Example of the function call:

var input_language = "en";
var output_language = "es";
var result = TranslateText("Hello", input_language + "|" + output_language);

The result will be "Hola"

How to test valid UUID/GUID?

Use the .match() method to check whether String is UUID.

public boolean isUUID(String s){
    return s.match("^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$");
}

Creating a 3D sphere in Opengl using Visual C++

In OpenGL you don't create objects, you just draw them. Once they are drawn, OpenGL no longer cares about what geometry you sent it.

glutSolidSphere is just sending drawing commands to OpenGL. However there's nothing special in and about it. And since it's tied to GLUT I'd not use it. Instead, if you really need some sphere in your code, how about create if for yourself?

#define _USE_MATH_DEFINES
#include <GL/gl.h>
#include <GL/glu.h>
#include <vector>
#include <cmath>

// your framework of choice here

class SolidSphere
{
protected:
    std::vector<GLfloat> vertices;
    std::vector<GLfloat> normals;
    std::vector<GLfloat> texcoords;
    std::vector<GLushort> indices;

public:
    SolidSphere(float radius, unsigned int rings, unsigned int sectors)
    {
        float const R = 1./(float)(rings-1);
        float const S = 1./(float)(sectors-1);
        int r, s;

        vertices.resize(rings * sectors * 3);
        normals.resize(rings * sectors * 3);
        texcoords.resize(rings * sectors * 2);
        std::vector<GLfloat>::iterator v = vertices.begin();
        std::vector<GLfloat>::iterator n = normals.begin();
        std::vector<GLfloat>::iterator t = texcoords.begin();
        for(r = 0; r < rings; r++) for(s = 0; s < sectors; s++) {
                float const y = sin( -M_PI_2 + M_PI * r * R );
                float const x = cos(2*M_PI * s * S) * sin( M_PI * r * R );
                float const z = sin(2*M_PI * s * S) * sin( M_PI * r * R );

                *t++ = s*S;
                *t++ = r*R;

                *v++ = x * radius;
                *v++ = y * radius;
                *v++ = z * radius;

                *n++ = x;
                *n++ = y;
                *n++ = z;
        }

        indices.resize(rings * sectors * 4);
        std::vector<GLushort>::iterator i = indices.begin();
        for(r = 0; r < rings; r++) for(s = 0; s < sectors; s++) {
                *i++ = r * sectors + s;
                *i++ = r * sectors + (s+1);
                *i++ = (r+1) * sectors + (s+1);
                *i++ = (r+1) * sectors + s;
        }
    }

    void draw(GLfloat x, GLfloat y, GLfloat z)
    {
        glMatrixMode(GL_MODELVIEW);
        glPushMatrix();
        glTranslatef(x,y,z);

        glEnableClientState(GL_VERTEX_ARRAY);
        glEnableClientState(GL_NORMAL_ARRAY);
        glEnableClientState(GL_TEXTURE_COORD_ARRAY);

        glVertexPointer(3, GL_FLOAT, 0, &vertices[0]);
        glNormalPointer(GL_FLOAT, 0, &normals[0]);
        glTexCoordPointer(2, GL_FLOAT, 0, &texcoords[0]);
        glDrawElements(GL_QUADS, indices.size(), GL_UNSIGNED_SHORT, &indices[0]);
        glPopMatrix();
    }
};

SolidSphere sphere(1, 12, 24);

void display()
{
    int const win_width  = …; // retrieve window dimensions from
    int const win_height = …; // framework of choice here
    float const win_aspect = (float)win_width / (float)win_height;

    glViewport(0, 0, win_width, win_height);

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluPerspective(45, win_aspect, 1, 10);

    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

#ifdef DRAW_WIREFRAME
    glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
#endif
    sphere.draw(0, 0, -5);

    swapBuffers();
}

int main(int argc, char *argv[])
{
    // initialize and register your framework of choice here
    return 0;
}

Shuffling a list of objects

The shuffling process is "with replacement", so the occurrence of each item may change! At least when when items in your list is also list.

E.g.,

ml = [[0], [1]] * 10

After,

random.shuffle(ml)

The number of [0] may be 9 or 8, but not exactly 10.

Convert DataTable to CSV stream

If you wish to stream the CSV out to the user without creating a file then I found the following to be the simplest method. You can use any extension/method to create the ToCsv() function (which returns a string based on the given DataTable).

        var report = myDataTable.ToCsv();
        var bytes = Encoding.GetEncoding("iso-8859-1").GetBytes(report);

        Response.Buffer = true;
        Response.Clear();
        Response.AddHeader("content-disposition", "attachment; filename=report.csv");
        Response.ContentType = "text/csv";
        Response.BinaryWrite(bytes);
        Response.End();

Could not find the main class, program will exit

I had this problem when I "upgraded" to Windows 7, which is 64-bit. My go to Java JRE is a 64-bit JVM. I had a 32-bit JRE on my machine for my browser, so I set up a system variable:

JRE32=C:\Program Files\Java\jre7

When I run:

"%JRE32\bin\java" -version

I get:

java version "1.7.0_51"
Java(TM) SE Runtime Environment (build 1.7.0_51-b13)
Java HotSpot(TM) Client VM (build 24.51-b03, mixed mode, sharing)

Which is a 32-bit JVM. It would say "Java HotSpot(TM) 64-Bit" otherwise.

I edited the "squirrel-sql.bat" file, REMarking out line 4 and adding line 5 as follows:

(4) rem set "IZPACK_JAVA=%JAVA_HOME%"
(5) set IZPACK_JAVA=%JRE32%

And now everything works, fine and dandy.

Getting TypeError: __init__() missing 1 required positional argument: 'on_delete' when trying to add parent table after child table with entries

Post Django version 1.9, on_delete became a required argument, i.e. from Django 2.0.

In older versions, it defaults to CASCADE.

So, if you want to replicate the functionality that you used in earlier versions. Use the following argument.

categorie = models.ForeignKey('Categorie', on_delete = models.CASCADE)

This will have the same effect as that was in earlier versions, without specifying it explicitly.

Official Documentation on other arguments that go with on_delete

How to let PHP to create subdomain automatically for each user?

In addition to configuration changes on your WWW server to handle the new subdomain, your code would need to be making changes to your DNS records. So, unless you're running your own BIND (or similar), you'll need to figure out how to access your name server provider's configuration. If they don't offer some sort of API, this might get tricky.

Update: yes, I would check with your registrar if they're also providing the name server service (as is often the case). I've never explored this option before but I suspect most of the consumer registrars do not. I Googled for GoDaddy APIs and GoDaddy DNS APIs but wasn't able to turn anything up, so I guess the best option would be to check out the online help with your provider, and if that doesn't answer the question, get a hold of their support staff.

Query to convert from datetime to date mysql

Either Cybernate or OMG Ponies solution will work. The fundamental problem is that the DATE_FORMAT() function returns a string, not a date. When you wrote

(Select Date_Format(orders.date_purchased,'%m/%d/%Y')) As Date 

I think you were essentially asking MySQL to try to format the values in date_purchased according to that format string, and instead of calling that column date_purchased, call it "Date". But that column would no longer contain a date, it would contain a string. (Because Date_Format() returns a string, not a date.)

I don't think that's what you wanted to do, but that's what you were doing.

Don't confuse how a value looks with what the value is.

What are the -Xms and -Xmx parameters when starting JVM?

-Xms initial heap size for the startup, however, during the working process the heap size can be less than -Xms due to users' inactivity or GC iterations. This is not a minimal required heap size.

-Xmx maximal heap size

Truncate Decimal number not Round Off

Try this:

decimal original = GetSomeDecimal(); // 22222.22939393
int number1 = (int)original; // contains only integer value of origina number
decimal temporary = original - number1; // contains only decimal value of original number
int decimalPlaces = GetDecimalPlaces(); // 3
temporary *= (Math.Pow(10, decimalPlaces)); // moves some decimal places to integer
temporary = (int)temporary; // removes all decimal places
temporary /= (Math.Pow(10, decimalPlaces)); // moves integer back to decimal places
decimal result = original + temporary; // add integer and decimal places together

It can be writen shorter, but this is more descriptive.

EDIT: Short way:

decimal original = GetSomeDecimal(); // 22222.22939393
int decimalPlaces = GetDecimalPlaces(); // 3
decimal result = ((int)original) + (((int)(original * Math.Pow(10, decimalPlaces)) / (Math.Pow(10, decimalPlaces));

How to find sitemap.xml path on websites?

The location of the sitemap affects which URLs that it can include, but otherwise there is no standard. Here is a good link with more explaination: http://www.sitemaps.org/protocol.html#location

Responsive table handling in Twitter Bootstrap

One option that is available is fooTable. Works great on a Responsive website and allows you to set multiple breakpoints... fooTable Link

Python Script to convert Image into Byte array

i don't know about converting into a byte array, but it's easy to convert it into a string:

import base64

with open("t.png", "rb") as imageFile:
    str = base64.b64encode(imageFile.read())
    print str

Source

List files with certain extensions with ls and grep

In case you are still looking for an alternate solution:

ls | grep -i -e '\\.tcl$' -e '\\.exe$' -e '\\.mp4$'

Feel free to add more -e flags if needed.

Git: add vs push vs commit

  1. git add adds your modified files to the queue to be committed later. Files are not committed

  2. git commit commits the files that have been added and creates a new revision with a log... If you do not add any files, git will not commit anything. You can combine both actions with git commit -a

  3. git push pushes your changes to the remote repository.

This figure from this git cheat sheet gives a good idea of the work flow

enter image description here

git add isn't on the figure because the suggested way to commit is the combined git commit -a, but you can mentally add a git add to the change block to understand the flow.

Lastly, the reason why push is a separate command is because of git's philosophy. git is a distributed versioning system, and your local working directory is your repository! All changes you commit are instantly reflected and recorded. push is only used to update the remote repo (which you might share with others) when you're done with whatever it is that you're working on. This is a neat way to work and save changes locally (without network overhead) and update it only when you want to, instead of at every commit. This indirectly results in easier commits/branching etc (why not, right? what does it cost you?) which leads to more save points, without messing with the repository.

How do I make a redirect in PHP?

Like others here said, sending the location header with:

header( "Location: http://www.mywebsite.com/otherpage.php" );

but you need to do it before you've sent any other output to the browser.

Also, if you're going to use this to block un-authenticated users from certain pages, like you mentioned, keep in mind that some user agents will ignore this and continue on the current page anyway, so you'll need to die() after you send it.

How to convert Moment.js date to users local timezone?

You do not need to use moment-timezone for this. The main moment.js library has full functionality for working with UTC and the local time zone.

var testDateUtc = moment.utc("2015-01-30 10:00:00");
var localDate = moment(testDateUtc).local();

From there you can use any of the functions you might expect:

var s = localDate.format("YYYY-MM-DD HH:mm:ss");
var d = localDate.toDate();
// etc...

Note that by passing testDateUtc, which is a moment object, back into the moment() constructor, it creates a clone. Otherwise, when you called .local(), it would also change the testDateUtc value, instead of just the localDate value. Moments are mutable.

Also note that if your original input contains a time zone offset such as +00:00 or Z, then you can just parse it directly with moment. You don't need to use .utc or .local. For example:

var localDate = moment("2015-01-30T10:00:00Z");

How to calculate a logistic sigmoid function in Python?

Good answer from @unwind. It however can't handle extreme negative number (throwing OverflowError).

My improvement:

def sigmoid(x):
    try:
        res = 1 / (1 + math.exp(-x))
    except OverflowError:
        res = 0.0
    return res

Get day of week using NSDate

SWIFT 2.0 code to present the current week starting from monday.

@IBAction func show(sender: AnyObject) {

   // Getting Days of week corresponding to their dateFormat

    let calendar = NSCalendar.currentCalendar()
    let dayInt: Int!
    var weekDate: [String] = []
    var i = 2

    print("Dates corresponding to days are")
    while((dayInt - dayInt) + i < 9)
    {
        let weekFirstDate = calendar.dateByAddingUnit(.Day, value: (-dayInt+i), toDate: NSDate(), options: [])
        let dateFormatter = NSDateFormatter()
        dateFormatter.dateFormat = "EEEE dd MMMM"
        let dayOfWeekString = dateFormatter.stringFromDate(weekFirstDate!)
        weekDate.append(dayOfWeekString)
        i++
    }
    for i in weekDate
    {
        print(i) //Printing the day stored in array
    }
}

// function to get week day
func getDayOfWeek(today:String)->Int {

    let formatter  = NSDateFormatter()
    formatter.dateFormat = "MMM-dd-yyyy"
    let todayDate = formatter.dateFromString(today)!
    let myCalendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
    let myComponents = myCalendar.components(.Weekday, fromDate: todayDate)
    let weekDay = myComponents.weekday
    return weekDay
}


@IBAction func DateTitle(sender: AnyObject) {


    // Getting currentDate and weekDay corresponding to it
    let currentDate = NSDate()
    let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "MMM-dd-yyyy"
    let dayOfWeekStrings = dateFormatter.stringFromDate(currentDate)
    dayInt = getDayOfWeek(dayOfWeekStrings)

}

git stash blunder: git stash pop and ended up with merge conflicts

See man git merge (HOW TO RESOLVE CONFLICTS):

After seeing a conflict, you can do two things:

  • Decide not to merge. The only clean-ups you need are to reset the index file to the HEAD commit to reverse 2. and to clean up working tree changes made by 2. and 3.; git-reset --hard can be used for this.

  • Resolve the conflicts. Git will mark the conflicts in the working tree. Edit the files into shape and git add them to the index. Use git commit to seal the deal.

And under TRUE MERGE (to see what 2. and 3. refers to):

When it is not obvious how to reconcile the changes, the following happens:

  1. The HEAD pointer stays the same.

  2. The MERGE_HEAD ref is set to point to the other branch head.

  3. Paths that merged cleanly are updated both in the index file and in your working tree.

  4. ...

So: use git reset --hard if you want to remove the stash changes from your working tree, or git reset if you want to just clean up the index and leave the conflicts in your working tree to merge by hand.

Under man git stash (OPTIONS, pop) you can read in addition:

Applying the state can fail with conflicts; in this case, it is not removed from the stash list. You need to resolve the conflicts by hand and call git stash drop manually afterwards.

Writing a dict to txt file and reading it back?

You can iterate through the key-value pair and write it into file

pair = {'name': name,'location': location}
with open('F:\\twitter.json', 'a') as f:
     f.writelines('{}:{}'.format(k,v) for k, v in pair.items())
     f.write('\n')

Reading InputStream as UTF-8

String file = "";

try {

    InputStream is = new FileInputStream(filename);
    String UTF8 = "utf8";
    int BUFFER_SIZE = 8192;

    BufferedReader br = new BufferedReader(new InputStreamReader(is,
            UTF8), BUFFER_SIZE);
    String str;
    while ((str = br.readLine()) != null) {
        file += str;
    }
} catch (Exception e) {

}

Try this,.. :-)

How to make the first option of <select> selected with jQuery

For me, it only worked when I added the following line of code

$('#target').val($('#target').find("option:first").val());

Double precision - decimal places

A double holds 53 binary digits accurately, which is ~15.9545898 decimal digits. The debugger can show as many digits as it pleases to be more accurate to the binary value. Or it might take fewer digits and binary, such as 0.1 takes 1 digit in base 10, but infinite in base 2.

This is odd, so I'll show an extreme example. If we make a super simple floating point value that holds only 3 binary digits of accuracy, and no mantissa or sign (so range is 0-0.875), our options are:

binary - decimal
000    - 0.000
001    - 0.125
010    - 0.250
011    - 0.375
100    - 0.500
101    - 0.625
110    - 0.750
111    - 0.875

But if you do the numbers, this format is only accurate to 0.903089987 decimal digits. Not even 1 digit is accurate. As is easy to see, since there's no value that begins with 0.4?? nor 0.9??, and yet to display the full accuracy, we require 3 decimal digits.

tl;dr: The debugger shows you the value of the floating point variable to some arbitrary precision (19 digits in your case), which doesn't necessarily correlate with the accuracy of the floating point format (17 digits in your case).

System.Windows.Markup.XamlParseException' occurred in PresentationFramework.dll?

I had this when build my application with "All cpu" target while it referenced a 3rd party x64-only (managed) dll.

Try reinstalling `node-sass` on node 0.12?

I had the same issue as @Kos had, only for some reason I had to modify the gulp-sass package from the old package.json file I had. It then installed the dependencies currently and now it finally works!

Apache Cordova - uninstall globally

Super late here and I still couldn't uninstall using sudo as the other answers suggest. What did it for me was checking where cordova was installed by running

which cordova

it will output something like this

/usr/local/bin/

then removing by

rm -rf /usr/local/bin/cordova

How do I check if a variable is of a certain type (compare two types) in C?

C does not support this form of type introspection. What you are asking is not possible in C (at least without compiler-specific extensions; it would be possible in C++, however).

In general, with C you're expected to know the types of your variable. Since every function has concrete types for its parameters (except for varargs, I suppose), you don't need to check in the function body. The only remaining case I can see is in a macro body, and, well, C macros aren't really all that powerful.

Further, note that C does not retain any type information into runtime. This means that, even if, hypothetically, there was a type comparison extension, it would only work properly when the types are known at compile time (ie, it wouldn't work to test whether two void * point to the same type of data).

As for typeof: First, typeof is a GCC extension. It is not a standard part of C. It's typically used to write macros that only evaluate their arguments once, eg (from the GCC manual):

 #define max(a,b) \
   ({ typeof (a) _a = (a); \
      typeof (b) _b = (b); \
     _a > _b ? _a : _b; })

The typeof keyword lets the macro define a local temporary to save the values of its arguments, allowing them to be evaluated only once.

In short, C does not support overloading; you'll just have to make a func_a(struct a *) and func_b(struct b *), and call the correct one. Alternately, you could make your own introspection system:

struct my_header {
  int type;
};

#define TYPE_A 0
#define TYPE_B 1

struct a {
  struct my_header header;
  /* ... */
};

struct b {
  struct my_header header;
  /* ... */
};

void func_a(struct a *p);
void func_b(struct b *p);

void func_switch(struct my_header *head);
#define func(p) func_switch( &(p)->header )

void func_switch(struct my_header *head) {
  switch (head->type) {
    case TYPE_A: func_a((struct a *)head); break;
    case TYPE_B: func_b((struct b *)head); break;
    default: assert( ("UNREACHABLE", 0) );
  }
}

You must, of course, remember to initialize the header properly when creating these objects.

Getting a timestamp for today at midnight?

Updated Answer in 19 April, 2020

Simply we can do this:

$today = date('Y-m-d 00:00:00');

Flutter Countdown Timer

If all you need is a simple countdown timer, this is a good alternative instead of installing a package. Happy coding!

countDownTimer() async {
 int timerCount;
 for (int x = 5; x > 0; x--) {
   await Future.delayed(Duration(seconds: 1)).then((_) {
     setState(() {
       timerCount -= 1;
    });
  });
 }
}

How do I get the picture size with PIL?

This is a complete example loading image from URL, creating with PIL, printing the size and resizing...

import requests
h = { 'User-Agent': 'Neo'}
r = requests.get("https://images.freeimages.com/images/large-previews/85c/football-1442407.jpg", headers=h)

from PIL import Image
from io import BytesIO
# create image from binary content
i = Image.open(BytesIO(r.content))


width, height = i.size
print(width, height)
i = i.resize((100,100))
display(i)

jQuery: Uncheck other checkbox on one checked

Bind a change handler, then just uncheck all of the checkboxes, apart from the one checked:

$('input.example').on('change', function() {
    $('input.example').not(this).prop('checked', false);  
});

Here's a fiddle

How do I call an Angular 2 pipe with multiple arguments?

I use Pipes in Angular 2+ to filter arrays of objects. The following takes multiple filter arguments but you can send just one if that suits your needs. Here is a StackBlitz Example. It will find the keys you want to filter by and then filters by the value you supply. It's actually quite simple, if it sounds complicated it's not, check out the StackBlitz Example.

Here is the Pipe being called in an *ngFor directive,

<div *ngFor='let item of items | filtermulti: [{title:"mr"},{last:"jacobs"}]' >
  Hello {{item.first}} !
</div>

Here is the Pipe,

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'filtermulti'
})
export class FiltermultiPipe implements PipeTransform {
  transform(myobjects: Array<object>, args?: Array<object>): any {
    if (args && Array.isArray(myobjects)) {
      // copy all objects of original array into new array of objects
      var returnobjects = myobjects;
      // args are the compare oprators provided in the *ngFor directive
      args.forEach(function (filterobj) {
        let filterkey = Object.keys(filterobj)[0];
        let filtervalue = filterobj[filterkey];
        myobjects.forEach(function (objectToFilter) {
          if (objectToFilter[filterkey] != filtervalue && filtervalue != "") {
            // object didn't match a filter value so remove it from array via filter
            returnobjects = returnobjects.filter(obj => obj !== objectToFilter);
          }
        })
      });
      // return new array of objects to *ngFor directive
      return returnobjects;
    }
  }
}

And here is the Component containing the object to filter,

import { Component } from '@angular/core';
import { FiltermultiPipe } from './pipes/filtermulti.pipe';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';
  items = [{ title: "mr", first: "john", last: "jones" }
   ,{ title: "mr", first: "adrian", last: "jacobs" }
   ,{ title: "mr", first: "lou", last: "jones" }
   ,{ title: "ms", first: "linda", last: "hamilton" }
  ];
}

StackBlitz Example

GitHub Example: Fork a working copy of this example here

*Please note that in an answer provided by Gunter, Gunter states that arrays are no longer used as filter interfaces but I searched the link he provides and found nothing speaking to that claim. Also, the StackBlitz example provided shows this code working as intended in Angular 6.1.9. It will work in Angular 2+.

Happy Coding :-)

Regular expression to detect semi-colon terminated C++ for & while loops

I wouldn't even pay attention to the contents of the parens.

Just match any line that starts with for and ends with semi-colon:

^\t*for.+;$

Unless you've got for statements split over multiple lines, that will work fine?

Why doesn't wireshark detect my interface?

Just uninstall NPCAP and install wpcap. This will fix the issue.

How to clear Tkinter Canvas?

Every canvas item is an object that Tkinter keeps track of. If you are clearing the screen by just drawing a black rectangle, then you effectively have created a memory leak -- eventually your program will crash due to the millions of items that have been drawn.

To clear a canvas, use the delete method. Give it the special parameter "all" to delete all items on the canvas (the string "all"" is a special tag that represents all items on the canvas):

canvas.delete("all")

If you want to delete only certain items on the canvas (such as foreground objects, while leaving the background objects on the display) you can assign tags to each item. Then, instead of "all", you could supply the name of a tag.

If you're creating a game, you probably don't need to delete and recreate items. For example, if you have an object that is moving across the screen, you can use the move or coords method to move the item.

Difference between Inheritance and Composition

Composition is just as it sounds - you create an object by plugging in parts.

EDIT the rest of this answer is erroneously based on the following premise.
This is accomplished with Interfaces.
For example, using the Car example above,

Car implements iDrivable, iUsesFuel, iProtectsOccupants
Motorbike implements iDrivable, iUsesFuel, iShortcutThroughTraffic
House implements iProtectsOccupants
Generator implements iUsesFuel

So with a few standard theoretical components you can build up your object. It's then your job to fill in how a House protects its occupants, and how a Car protects its occupants.

Inheritance is like the other way around. You start off with a complete (or semi-complete) object and you replace or Override the various bits you want to change.

For example, MotorVehicle may come with a Fuelable method and Drive method. You may leave the Fuel method as it is because it's the same to fill up a motorbike and a car, but you may override the Drive method because the Motorbike drives very differently to a Car.

With inheritance, some classes are completely implemented already, and others have methods that you are forced to override. With Composition nothing's given to you. (but you can Implement the interfaces by calling methods in other classes if you happen to have something laying around).

Composition is seen as more flexible, because if you have a method such as iUsesFuel, you can have a method somewhere else (another class, another project) that just worries about dealing with objects that can be fueled, regardless of whether it's a car, boat, stove, barbecue, etc. Interfaces mandate that classes that say they implement that interface actually have the methods that that interface is all about. For example,

iFuelable Interface:
   void AddSomeFuel()
   void UseSomeFuel()
   int  percentageFull()

then you can have a method somewhere else

private void FillHerUp(iFuelable : objectToFill) {

   Do while (objectToFill.percentageFull() <= 100)  {

        objectToFill.AddSomeFuel();
   }

Strange example, but it's shows that this method doesn't care what it's filling up, because the object implements iUsesFuel, it can be filled. End of story.

If you used Inheritance instead, you would need different FillHerUp methods to deal with MotorVehicles and Barbecues, unless you had some rather weird "ObjectThatUsesFuel" base object from which to inherit.

Comparing a variable with a string python not working when redirecting from bash script

When you read() the file, you may get a newline character '\n' in your string. Try either

if UserInput.strip() == 'List contents': 

or

if 'List contents' in UserInput: 

Also note that your second file open could also use with:

with open('/Users/.../USER_INPUT.txt', 'w+') as UserInputFile:     if UserInput.strip() == 'List contents': # or if s in f:         UserInputFile.write("ls")     else:         print "Didn't work" 

How to use 'git pull' from the command line?

One more option is to add the path of the privatekey file like this in terminal:

ssh-add "path to the privatekeyfile"

and then execute the pull command

java.lang.ClassNotFoundException: HttpServletRequest

Thanks guys. All above failed except this that deleted all content from the file C:\Users\debasish\workspace\.metadata\.plugins\org.eclipse.wst.server.core then creating server again.

But delete server first before deleting those file contents.

How to set dialog to show in full screen?

based on this link , the correct answer (which i've tested myself) is:

put this code in the constructor or the onCreate() method of the dialog:

getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT,
                WindowManager.LayoutParams.MATCH_PARENT);

in addition , set the style of the dialog to :

<style name="full_screen_dialog">
    <item name="android:windowFrame">@null</item>
    <item name="android:windowIsFloating">true</item>
    <item name="android:windowContentOverlay">@null</item>
    <item name="android:windowAnimationStyle">@android:style/Animation.Dialog</item>
    <item name="android:windowSoftInputMode">stateUnspecified|adjustPan</item>
</style>

this could be achieved via the constructor , for example :

public FullScreenDialog(Context context)
{
  super(context, R.style.full_screen_dialog);
  ...

EDIT: an alternative to all of the above would be to set the style to android.R.style.ThemeOverlay and that's it.

Trouble setting up git with my GitHub Account error: could not lock config file

I am old to the party but may be this will help some one. Thanks to @paperclip

In Windows 10:

Step 1: Go to This PC > Right click Properties

step 2: Click Advanced System Settings and click Environment Variables

Step 3: Under System Variables create new variable called HOME and input the value as %USERPROFILE% like below

enter image description here

Step 4: Important You must restart your PC to take effect

Step 5: Install Git for Windows now and optional Tortoise Git for windows if you prefer.

Make a git clone request or try pushing something in to your repo. Magic it will work. All should work fine now.

Should MySQL have its timezone set to UTC?

PHP and MySQL have their own default timezone configurations. You should synchronize time between your data base and web application, otherwise you could run some issues.

Read this tutorial: How To Synchronize Your PHP and MySQL Timezones

get the value of input type file , and alert if empty

<script type="text/javascript">
$(document).ready(function() {
    $('#upload').bind("click",function() 
    { 
        var imgVal = $('#uploadImage').val(); 
        if(imgVal=='') 
        { 
            alert("empty input file"); 

        } 
        return false; 

    }); 
});
</script> 

<input type="file" name="image" id="uploadImage" size="30" /> 
<input type="submit" name="upload" id="upload"  class="send_upload" value="upload" /> 

How to check if a variable is not null?

There is another possible scenario I have just come across.

I did an ajax call and got data back as null, in a string format. I had to check it like this:

if(value != 'null'){}

So, null was a string which read "null" rather than really being null.

EDIT: It should be understood that I'm not selling this as the way it should be done. I had a scenario where this was the only way it could be done. I'm not sure why... perhaps the guy who wrote the back-end was presenting the data incorrectly, but regardless, this is real life. It's frustrating to see this down-voted by someone who understands that it's not quite right, and then up-voted by someone it actually helps.

How do I install package.json dependencies in the current directory using npm

In my case I need to do

sudo npm install  

my project is inside /var/www so I also need to set proper permissions.

currently unable to handle this request HTTP ERROR 500

My take on this for future people watching this:

This could also happen if you're using: <? instead of <?php.

How to set null value to int in c#?

Use Null.NullInteger ex: private int _ReservationID = Null.NullInteger;

ASP.NET Core Dependency Injection error: Unable to resolve service for type while attempting to activate

You need to add a new service for DBcontext in the startup

Default

services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(
                    Configuration.GetConnectionString("DefaultConnection")));

Add this

services.AddDbContext<NewDBContext>(options =>
                options.UseSqlServer(
                    Configuration.GetConnectionString("NewConnection")));

Force hide address bar in Chrome on Android

Check this has everything you need

http://www.html5rocks.com/en/mobile/fullscreen/

The Chrome team has recently implemented a feature that tells the browser to launch the page fullscreen when the user has added it to the home screen. It is similar to the iOS Safari model.

<meta name="mobile-web-app-capable" content="yes">

RSA Public Key format

Starting from the decoded base64 data of an OpenSSL rsa-ssh Key, i've been able to guess a format:

  • 00 00 00 07: four byte length prefix (7 bytes)
  • 73 73 68 2d 72 73 61: "ssh-rsa"
  • 00 00 00 01: four byte length prefix (1 byte)
  • 25: RSA Exponent (e): 25
  • 00 00 01 00: four byte length prefix (256 bytes)
  • RSA Modulus (n):

    7f 9c 09 8e 8d 39 9e cc d5 03 29 8b c4 78 84 5f
    d9 89 f0 33 df ee 50 6d 5d d0 16 2c 73 cf ed 46 
    dc 7e 44 68 bb 37 69 54 6e 9e f6 f0 c5 c6 c1 d9 
    cb f6 87 78 70 8b 73 93 2f f3 55 d2 d9 13 67 32 
    70 e6 b5 f3 10 4a f5 c3 96 99 c2 92 d0 0f 05 60 
    1c 44 41 62 7f ab d6 15 52 06 5b 14 a7 d8 19 a1 
    90 c6 c1 11 f8 0d 30 fd f5 fc 00 bb a4 ef c9 2d 
    3f 7d 4a eb d2 dc 42 0c 48 b2 5e eb 37 3c 6c a0 
    e4 0a 27 f0 88 c4 e1 8c 33 17 33 61 38 84 a0 bb 
    d0 85 aa 45 40 cb 37 14 bf 7a 76 27 4a af f4 1b 
    ad f0 75 59 3e ac df cd fc 48 46 97 7e 06 6f 2d 
    e7 f5 60 1d b1 99 f8 5b 4f d3 97 14 4d c5 5e f8 
    76 50 f0 5f 37 e7 df 13 b8 a2 6b 24 1f ff 65 d1 
    fb c8 f8 37 86 d6 df 40 e2 3e d3 90 2c 65 2b 1f 
    5c b9 5f fa e9 35 93 65 59 6d be 8c 62 31 a9 9b 
    60 5a 0e e5 4f 2d e6 5f 2e 71 f3 7e 92 8f fe 8b
    

The closest validation of my theory i can find it from RFC 4253:

The "ssh-rsa" key format has the following specific encoding:

  string    "ssh-rsa"
  mpint     e
  mpint     n

Here the 'e' and 'n' parameters form the signature key blob.

But it doesn't explain the length prefixes.


Taking the random RSA PUBLIC KEY i found (in the question), and decoding the base64 into hex:

30 82 01 0a 02 82 01 01 00 fb 11 99 ff 07 33 f6 e8 05 a4 fd 3b 36 ca 68 
e9 4d 7b 97 46 21 16 21 69 c7 15 38 a5 39 37 2e 27 f3 f5 1d f3 b0 8b 2e 
11 1c 2d 6b bf 9f 58 87 f1 3a 8d b4 f1 eb 6d fe 38 6c 92 25 68 75 21 2d 
dd 00 46 87 85 c1 8a 9c 96 a2 92 b0 67 dd c7 1d a0 d5 64 00 0b 8b fd 80 
fb 14 c1 b5 67 44 a3 b5 c6 52 e8 ca 0e f0 b6 fd a6 4a ba 47 e3 a4 e8 94 
23 c0 21 2c 07 e3 9a 57 03 fd 46 75 40 f8 74 98 7b 20 95 13 42 9a 90 b0 
9b 04 97 03 d5 4d 9a 1c fe 3e 20 7e 0e 69 78 59 69 ca 5b f5 47 a3 6b a3 
4d 7c 6a ef e7 9f 31 4e 07 d9 f9 f2 dd 27 b7 29 83 ac 14 f1 46 67 54 cd 
41 26 25 16 e4 a1 5a b1 cf b6 22 e6 51 d3 e8 3f a0 95 da 63 0b d6 d9 3e 
97 b0 c8 22 a5 eb 42 12 d4 28 30 02 78 ce 6b a0 cc 74 90 b8 54 58 1f 0f 
fb 4b a3 d4 23 65 34 de 09 45 99 42 ef 11 5f aa 23 1b 15 15 3d 67 83 7a 
63 02 03 01 00 01

From RFC3447 - Public-Key Cryptography Standards (PKCS) #1: RSA Cryptography Specifications Version 2.1:

A.1.1 RSA public key syntax

An RSA public key should be represented with the ASN.1 type RSAPublicKey:

  RSAPublicKey ::= SEQUENCE {
     modulus           INTEGER,  -- n
     publicExponent    INTEGER   -- e
  }

The fields of type RSAPublicKey have the following meanings:

  • modulus is the RSA modulus n.
  • publicExponent is the RSA public exponent e.

Using Microsoft's excellent (and the only real) ASN.1 documentation:

30 82 01 0a       ;SEQUENCE (0x010A bytes: 266 bytes)
|  02 82 01 01    ;INTEGER  (0x0101 bytes: 257 bytes)
|  |  00          ;leading zero because high-bit, but number is positive
|  |  fb 11 99 ff 07 33 f6 e8 05 a4 fd 3b 36 ca 68 
|  |  e9 4d 7b 97 46 21 16 21 69 c7 15 38 a5 39 37 2e 27 f3 f5 1d f3 b0 8b 2e 
|  |  11 1c 2d 6b bf 9f 58 87 f1 3a 8d b4 f1 eb 6d fe 38 6c 92 25 68 75 21 2d 
|  |  dd 00 46 87 85 c1 8a 9c 96 a2 92 b0 67 dd c7 1d a0 d5 64 00 0b 8b fd 80 
|  |  fb 14 c1 b5 67 44 a3 b5 c6 52 e8 ca 0e f0 b6 fd a6 4a ba 47 e3 a4 e8 94 
|  |  23 c0 21 2c 07 e3 9a 57 03 fd 46 75 40 f8 74 98 7b 20 95 13 42 9a 90 b0 
|  |  9b 04 97 03 d5 4d 9a 1c fe 3e 20 7e 0e 69 78 59 69 ca 5b f5 47 a3 6b a3 
|  |  4d 7c 6a ef e7 9f 31 4e 07 d9 f9 f2 dd 27 b7 29 83 ac 14 f1 46 67 54 cd 
|  |  41 26 25 16 e4 a1 5a b1 cf b6 22 e6 51 d3 e8 3f a0 95 da 63 0b d6 d9 3e 
|  |  97 b0 c8 22 a5 eb 42 12 d4 28 30 02 78 ce 6b a0 cc 74 90 b8 54 58 1f 0f 
|  |  fb 4b a3 d4 23 65 34 de 09 45 99 42 ef 11 5f aa 23 1b 15 15 3d 67 83 7a 
|  |  63 
|  02 03          ;INTEGER (3 bytes)
|     01 00 01

giving the public key modulus and exponent:

  • modulus = 0xfb1199ff0733f6e805a4fd3b36ca68...837a63
  • exponent = 65,537

Update: My expanded form of this answer in another question

Spring: How to inject a value to static field?

First of all, public static non-final fields are evil. Spring does not allow injecting to such fields for a reason.

Your workaround is valid, you don't even need getter/setter, private field is enough. On the other hand try this:

@Value("${my.name}")
public void setPrivateName(String privateName) {
    Sample.name = privateName;
}  

(works with @Autowired/@Resource). But to give you some constructive advice: Create a second class with private field and getter instead of public static field.

Manually map column names with class properties

Kaleb Pederson's solution worked for me. I updated the ColumnAttributeTypeMapper to allow a custom attribute (had requirement for two different mappings on same domain object) and updated properties to allow private setters in cases where a field needed to be derived and the types differed.

public class ColumnAttributeTypeMapper<T,A> : FallbackTypeMapper where A : ColumnAttribute
{
    public ColumnAttributeTypeMapper()
        : base(new SqlMapper.ITypeMap[]
            {
                new CustomPropertyTypeMap(
                   typeof(T),
                   (type, columnName) =>
                       type.GetProperties( BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance).FirstOrDefault(prop =>
                           prop.GetCustomAttributes(true)
                               .OfType<A>()
                               .Any(attr => attr.Name == columnName)
                           )
                   ),
                new DefaultTypeMap(typeof(T))
            })
    {
        //
    }
}

Combine two columns of text in pandas dataframe

As many have mentioned previously, you must convert each column to string and then use the plus operator to combine two string columns. You can get a large performance improvement by using NumPy.

%timeit df['Year'].values.astype(str) + df.quarter
71.1 ms ± 3.76 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

%timeit df['Year'].astype(str) + df['quarter']
565 ms ± 22.3 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

Bootstrap date time picker

Well, here the positioning of the css and script links makes a to of difference. Bootstrap executes in CSS and then Scripts fashion. So if you have even one script written at incorrect place it makes a lot of difference. You can follow the below snippet and change your code accordingly.

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
    <meta charset="utf-8">_x000D_
    <meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>_x000D_
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
_x000D_
    <!-- <link rel="stylesheet" type="text/css" href="css/bootstrap-datetimepicker.css"> -->_x000D_
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.1/moment.min.js"></script>_x000D_
    <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.43/css/bootstrap-datetimepicker.min.css"> _x000D_
    <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.43/css/bootstrap-datetimepicker-standalone.css"> _x000D_
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.43/js/bootstrap-datetimepicker.min.js"></script>_x000D_
    _x000D_
</head>_x000D_
<body>_x000D_
     <div class="container">_x000D_
          <div class="row">_x000D_
            <div class='col-sm-6'>_x000D_
                <div class="form-group">_x000D_
                    <div class='input-group date' id='datetimepicker1'>_x000D_
                        <input type='text' class="form-control" />_x000D_
                        <span class="input-group-addon">_x000D_
                            <span class="glyphicon glyphicon-calendar"></span>_x000D_
                        </span>_x000D_
                    </div>_x000D_
                </div>_x000D_
            </div>_x000D_
            <script type="text/javascript">_x000D_
                $(function () {_x000D_
                    $('#datetimepicker1').datetimepicker();_x000D_
                });_x000D_
            </script>_x000D_
          </div>_x000D_
       </div>_x000D_
    </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Can I use Objective-C blocks as properties?

For posterity / completeness's sake… Here are two FULL examples of how to implement this ridiculously versatile "way of doing things". @Robert's answer is blissfully concise and correct, but here I want to also show ways to actually "define" the blocks.

@interface       ReusableClass : NSObject
@property (nonatomic,copy) CALayer*(^layerFromArray)(NSArray*);
@end

@implementation  ResusableClass
static  NSString const * privateScope = @"Touch my monkey.";

- (CALayer*(^)(NSArray*)) layerFromArray { 
     return ^CALayer*(NSArray* array){
        CALayer *returnLayer = CALayer.layer
        for (id thing in array) {
            [returnLayer doSomethingCrazy];
            [returnLayer setValue:privateScope
                         forKey:@"anticsAndShenanigans"];
        }
        return list;
    };
}
@end

Silly? Yes. Useful? Hells yeah. Here is a different, "more atomic" way of setting the property.. and a class that is ridiculously useful…

@interface      CALayoutDelegator : NSObject
@property (nonatomic,strong) void(^layoutBlock)(CALayer*);
@end

@implementation CALayoutDelegator
- (id) init { 
   return self = super.init ? 
         [self setLayoutBlock: ^(CALayer*layer){
          for (CALayer* sub in layer.sublayers)
            [sub someDefaultLayoutRoutine];
         }], self : nil;
}
- (void) layoutSublayersOfLayer:(CALayer*)layer {
   self.layoutBlock ? self.layoutBlock(layer) : nil;
}   
@end

This illustrates setting the block property via the accessor (albeit inside init, a debatably dicey practice..) vs the first example's "nonatomic" "getter" mechanism. In either case… the "hardcoded" implementations can always be overwritten, per instance.. a lá..

CALayoutDelegator *littleHelper = CALayoutDelegator.new;
littleHelper.layoutBlock = ^(CALayer*layer){
  [layer.sublayers do:^(id sub){ [sub somethingElseEntirely]; }];
};
someLayer.layoutManager = littleHelper;

Also.. if you want to add a block property in a category... say you want to use a Block instead of some old-school target / action "action"... You can just use associated values to, well.. associate the blocks.

typedef    void(^NSControlActionBlock)(NSControl*); 
@interface       NSControl            (ActionBlocks)
@property (copy) NSControlActionBlock  actionBlock;    @end
@implementation  NSControl            (ActionBlocks)

- (NSControlActionBlock) actionBlock { 
    // use the "getter" method's selector to store/retrieve the block!
    return  objc_getAssociatedObject(self, _cmd); 
} 
- (void) setActionBlock:(NSControlActionBlock)ab {

    objc_setAssociatedObject( // save (copy) the block associatively, as categories can't synthesize Ivars.
    self, @selector(actionBlock),ab ,OBJC_ASSOCIATION_COPY);
    self.target = self;                  // set self as target (where you call the block)
    self.action = @selector(doItYourself); // this is where it's called.
}
- (void) doItYourself {

    if (self.actionBlock && self.target == self) self.actionBlock(self);
}
@end

Now, when you make a button, you don't have to set up some IBAction drama.. Just associate the work to be done at creation...

_button.actionBlock = ^(NSControl*thisButton){ 

     [doc open]; [thisButton setEnabled:NO]; 
};

This pattern can be applied OVER and OVER to Cocoa API's. Use properties to bring the relevant parts of your code closer together, eliminate convoluted delegation paradigms, and leverage the power of objects beyond that of just acting as dumb "containers".

Installing Tomcat 7 as Service on Windows Server 2008

  1. Edit service.bat – Swap two lines so that they appear in following order: if not “%JAVA_HOME%“ == ““ goto got JdkHome if not “%JRE_HOME%“ == ““ goto got JreHome
  2. Open cmd and run command service.bat install
  3. Open Services and find Apache Tomcat 7.0 Tomcat7. Right click and Properties. Change its startup type to Automatic (with delay).
  4. Reboot machine to verify if the service started automatically

Getting Git to work with a proxy server - fails with "Request timed out"

Set a system variable named http_proxy with the value of ProxyServer:Port. That is the simplest solution. Respectively, use https_proxy as daefu pointed out in the comments.

Setting gitproxy (as sleske mentions) is another option, but that requires a "command", which is not as straightforward as the above solution.

References: http://bardofschool.blogspot.com/2008/11/use-git-behind-proxy.html

R : how to simply repeat a command?

You could use replicate or sapply:

R> colMeans(replicate(10000, sample(100, size=815, replace=TRUE, prob=NULL))) R> sapply(seq_len(10000), function(...) mean(sample(100, size=815, replace=TRUE, prob=NULL))) 

replicate is a wrapper for the common use of sapply for repeated evaluation of an expression (which will usually involve random number generation).