Programs & Examples On #Safe mode

Is there a command to restart computer into safe mode?

My first answer!

This will set the safemode switch:

bcdedit /set {current} safeboot minimal 

with networking:

bcdedit /set {current} safeboot network

then reboot the machine with

shutdown /r

to put back in normal mode via dos:

bcdedit /deletevalue {current} safeboot

How to change a dataframe column from String type to Double type in PySpark?

the solution was simple -

toDoublefunc = UserDefinedFunction(lambda x: float(x),DoubleType())
changedTypedf = joindf.withColumn("label",toDoublefunc(joindf['show']))

How to convert date to timestamp?

Split the string into its parts and provide them directly to the Date constructor:

Update:

_x000D_
_x000D_
var myDate = "26-02-2012";
myDate = myDate.split("-");
var newDate = new Date( myDate[2], myDate[1] - 1, myDate[0]);
console.log(newDate.getTime());
_x000D_
_x000D_
_x000D_

Regular Expressions- Match Anything

Honestly alot of the answers are old so i found that if you simply just test any string regardless of character content with "/.*/i" will sufficiently get EVERYTHING.

How to enable PHP short tags?

To enable short_open_tag for a particular domain with php-fpm, you must edit :

/etc/php5/fpm/pool.d/xxxxxxxxxx.conf

Where xxxxx is the socket number of the domain.

And add : php_value[short_open_tag] = On

Make a table fill the entire window

This works fine for me:

_x000D_
_x000D_
<style type="text/css">_x000D_
#table {_x000D_
 position: absolute;_x000D_
 top: 0;_x000D_
 bottom: 0;_x000D_
 left: 0;_x000D_
 right: 0;_x000D_
 height: 100%;_x000D_
 width: 100%;_x000D_
}_x000D_
</style>
_x000D_
_x000D_
_x000D_

For me, just changing Height and Width to 100% doesn’t do it for me, and neither do setting left, right, top and bottom to 0, but using them both together will do the trick.

How to concatenate strings in twig

Also a little known feature in Twig is string interpolation:

{{ "http://#{app.request.host}" }}

When would you use the different git merge strategies?

"Resolve" vs "Recursive" merge strategy

Recursive is the current default two-head strategy, but after some searching I finally found some info about the "resolve" merge strategy.

Taken from O'Reilly book Version Control with Git (Amazon) (paraphrased):

Originally, "resolve" was the default strategy for Git merges.

In criss-cross merge situations, where there is more than one possible merge basis, the resolve strategy works like this: pick one of the possible merge bases, and hope for the best. This is actually not as bad as it sounds. It often turns out that the users have been working on different parts of the code. In that case, Git detects that it's remerging some changes that are already in place and skips the duplicate changes, avoiding the conflict. Or, if these are slight changes that do cause conflict, at least the conflict should be easy for the developer to handle..

I have successfully merged trees using "resolve" that failed with the default recursive strategy. I was getting fatal: git write-tree failed to write a tree errors, and thanks to this blog post (mirror) I tried "-s resolve", which worked. I'm still not exactly sure why... but I think it was because I had duplicate changes in both trees, and resolve "skipped" them properly.

(unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape

Try writing the file path as "C:\\Users\miche\Documents\school\jaar2\MIK\2.6\vektis_agb_zorgverlener" i.e with double backslash after the drive as opposed to "C:\Users\miche\Documents\school\jaar2\MIK\2.6\vektis_agb_zorgverlener"

How to install wget in macOS?

For macOS Sierra, to build wget 1.18 from source with Xcode 8.2.

  1. Install Xcode

  2. Build OpenSSL

    Since Xcode doesn't come with OpenSSL lib, you need build by yourself. I found this: https://github.com/sqlcipher/openssl-xcode, follow instruction and build OpenSSL lib. Then, prepare your OpenSSL directory with "include" and "lib/libcrypto.a", "lib/libssl.a" in it.

    Let's say it is: "/Users/xxx/openssl-xcode/openssl", so there should be "/Users/xxx/openssl-xcode/openssl/include" for OpenSSL include and "/Users/xxx/openssl-xcode/openssl/lib" for "libcrypto.a" and "libssl.a".

  3. Build wget

    Go to wget directory, configure:

    ./configure --with-ssl=openssl --with-libssl-prefix=/Users/xxx/openssl-xcode/openssl
    

    wget should configure and found OpenSSL, then make:

    make
    

    wget made out. Install wget:

    make install
    

    Or just copy wget to where you want.

  4. Configure cert

    You may find wget cannot verify any https connection, because there is no CA certs for the OpenSSL you built. You need to run:

    New way:

    If you machine doesn't have "/usr/local/ssl/" dir, first make it.

    ln -s /etc/ssl/cert.pem /usr/local/ssl/cert.pem
    

    Old way:

    security find-certificate -a -p /Library/Keychains/System.keychain > cert.pem
    security find-certificate -a -p /System/Library/Keychains/SystemRootCertificates.keychain >> cert.pem
    

    Then put cert.pem to: "/usr/local/ssl/cert.pem"

    DONE: It should be all right now.

How do I copy the contents of one ArrayList into another?

to copy one list into the other list, u can use the method called Collection.copy(myObject myTempObject).now after executing these line of code u can see all the list values in the myObject.

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

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

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

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

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

}

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

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

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

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

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

    $props = $ref->getProperties();

    if (in_array($key, $props)) {
        $this->stdInstance->$key = $value;
    } else {
        $this->content[$key] = $value;
    }
    return $this;
}

public function __get($value)
{
    //Search first your array as it is faster than using reflection
    if (array_key_exists($value, $this->content))
    {
        return $this->content[$value];
    } else {
        $ref = new ReflectionClass($this->stdInstance);

        //Fetch the props of the object
        $props = $ref->getProperties();

        if (in_array($value, $props)) {

        return $this->stdInstance->$value;
    } else {
        throw new \Exception('No prop in here...');
    }
}
 }
}

PS : I didn't test my code, just the general idea...

Print values for multiple variables on the same line from within a for-loop

Try out cat and sprintf in your for loop.

eg.

cat(sprintf("\"%f\" \"%f\"\n", df$r, df$interest))

See here

Change CSS class properties with jQuery

You can't change CSS properties directly with jQuery. But you can achieve the same effect in at least two ways.

Dynamically Load CSS from a File

function updateStyleSheet(filename) {
    newstylesheet = "style_" + filename + ".css";

    if ($("#dynamic_css").length == 0) {
        $("head").append("<link>")
        css = $("head").children(":last");

        css.attr({
          id: "dynamic_css",
          rel:  "stylesheet",
          type: "text/css",
          href: newstylesheet
        });
    } else {
        $("#dynamic_css").attr("href",newstylesheet);
    }
}

The example above is copied from:

Dynamically Add a Style Element

$("head").append('<style type="text/css"></style>');
var newStyleElement = $("head").children(':last');
newStyleElement.html('.red{background:green;}');

The example code is copied from this JSFiddle fiddle originally referenced by Alvaro in their comment.

How do I change the IntelliJ IDEA default JDK?

For latest version intellij, to set default jdk/sdk for new projects go to

Configure->Structure for New Projects -> Project Settings -> Project SDK

What is the significance of load factor in HashMap?

From the documentation:

The load factor is a measure of how full the hash table is allowed to get before its capacity is automatically increased

It really depends on your particular requirements, there's no "rule of thumb" for specifying an initial load factor.

Using an array from Observable Object with ngFor and Async Pipe Angular 2

Who ever also stumbles over this post.

I belive is the correct way:

  <div *ngFor="let appointment of (_nextFourAppointments | async).availabilities;"> 
    <div>{{ appointment }}</div>
  </div>

std::vector versus std::array in C++

A vector is a container class while an array is an allocated memory.

Sort objects in ArrayList by date?

With introduction of Java 1.8, streams are very useful in solving this kind of problems:

Comparator <DateTime> myComparator = (arg1, arg2) 
                -> {
                    if(arg1.lt(arg2)) 
                       return -1;
                    else if (arg1.lteq(arg2))
                       return 0;
                    else
                       return 1;
                   };

ArrayList<DateTime> sortedList = myList
                   .stream()
                   .sorted(myComparator)
                   .collect(Collectors.toCollection(ArrayList::new));

How do I find out what all symbols are exported from a shared object?

Usually, you would also have a header file that you include in your code to access the symbols.

ASP.NET Button to redirect to another page

You can either do a Response.Redirect("YourPage.aspx"); or a Server.Transfer("YourPage.aspx"); on your button click event. So it's gonna be like the following:

protected void btnConfirm_Click(object sender, EventArgs e)
{
    Response.Redirect("YourPage.aspx");
    //or
    Server.Transfer("YourPage.aspx");
}

Why I get 'list' object has no attribute 'items'?

items is one attribute of dict object.maybe you can try

qs[0].items()

Shell command to tar directory excluding certain files/folders

Use the find command in conjunction with the tar append (-r) option. This way you can add files to an existing tar in a single step, instead of a two pass solution (create list of files, create tar).

find /dir/dir -prune ... -o etc etc.... -exec tar rvf ~/tarfile.tar {} \;

laravel Eloquent ORM delete() method

check before delete the user otherwise throws error exeption

$user=User::find($request->id);
  
   if($user)
   {
   // return $user;           <------------------------user exist
       if($user->delete()){
         return 'user deleted';
         }
    else{
       return "something wrong";
        }   

   }
  else{
     return "user not exist";// <--------------------user not exist
    }

Cannot GET / Nodejs Error

I think you're missing your routes, you need to define at least one route for example '/' to index.

e.g.

app.get('/', function (req, res) {
  res.render('index', {});
});

How to get distinct values for non-key column fields in Laravel?

For those who like me doing same mistake. Here is the elaborated answer Tested in Laravel 5.7

A. Records in DB

UserFile::orderBy('created_at','desc')->get()->toArray();

Array
(
    [0] => Array
        (
            [id] => 2073
            [type] => 'DL'
            [url] => 'https://i.picsum.photos/12/884/200/300.jpg'
            [created_at] => 2020-08-05 17:16:48
            [updated_at] => 2020-08-06 18:08:38
        )

    [1] => Array
        (
            [id] => 2074
            [type] => 'PROFILE'
            [url] => 'https://i.picsum.photos/13/884/200/300.jpg'
            [created_at] => 2020-08-05 17:20:06
            [updated_at] => 2020-08-06 18:08:38
        )

    [2] => Array
        (
            [id] => 2076
            [type] => 'PROFILE'
            [url] => 'https://i.picsum.photos/13/884/200/300.jpg'
            [created_at] => 2020-08-05 17:22:01
            [updated_at] => 2020-08-06 18:08:38
        )

    [3] => Array
        (
            [id] => 2086
            [type] => 'PROFILE'
            [url] => 'https://i.picsum.photos/13/884/200/300.jpg'
            [created_at] => 2020-08-05 19:22:41
            [updated_at] => 2020-08-06 18:08:38
        )
)

B. Desired Grouped result

UserFile::select('type','url','updated_at)->distinct('type')->get()->toArray();

Array
(
    [0] => Array
        (
            [type] => 'DL'
            [url] => 'https://i.picsum.photos/12/884/200/300.jpg'
            [updated_at] => 2020-08-06 18:08:38 
        )

    [1] => Array
        (
            [type] => 'PROFILE'
            [url] => 'https://i.picsum.photos/13/884/200/300.jpg'
            [updated_at] => 2020-08-06 18:08:38
        )
)

So Pass only those columns in "select()", values of which are same. For example: 'type','url'. You can add more columns provided they have same value like 'updated_at'.

If you try to pass "created_at" or "id" in "select()", then you will get the records same as A. Because they are different for each row in DB.

Split string in Lua?

a way not seen in others

function str_split(str, sep)
    if sep == nil then
        sep = '%s'
    end 

    local res = {}
    local func = function(w)
        table.insert(res, w)
    end 

    string.gsub(str, '[^'..sep..']+', func)
    return res 
end

What is the default value for Guid?

To extend answers above, you cannot use Guid default value with Guid.Empty as an optional argument in method, indexer or delegate definition, because it will give you compile time error. Use default(Guid) or new Guid() instead.

Why is php not running?

When installing Apache and PHP under Ubuntu 14.04, I needed to specifically enable php configs by issuing a2enmod php5-cgi

how to evenly distribute elements in a div next to each other?

Make all spans used inline-block elements. Create an empty stretch span with a 100% width beneath the list of spans containing the menu items. Next make the div containing the spans text-align: justified. This would then force the inline-block elements [your menu items] to evenly distribute.

https://jsfiddle.net/freedawirl/bh0eadzz/3/

  <div id="container">

          <div class="social">
            <a href="#" target="_blank" aria-label="facebook-link">
            <img src="http://placehold.it/40x40">
            </a>
            <a href="#" target="_blank" aria-label="twitter-link">
                <img src="http://placehold.it/40x40">
            </a>
            <a href="#" target="_blank" aria-label="youtube-link">
                <img src="http://placehold.it/40x40">
            </a>
            <a href="#" target="_blank" aria-label="pinterest-link">
                 <img src="http://placehold.it/40x40">
            </a>
            <a href="#" target="_blank" aria-label="snapchat-link">
                <img src="http://placehold.it/40x40">
            </a>
            <a href="#" target="_blank" aria-label="blog-link">
                 <img src="http://placehold.it/40x40">
            </a>

            <a href="#" aria-label="phone-link">
                 <img src="http://placehold.it/40x40">
            </a>
            <span class="stretch"></span>
          </div>
             </div>

SQLite - getting number of rows in a database

I got same problem if i understand your question correctly, I want to know the last inserted id after every insert performance in SQLite operation. i tried the following statement:

select * from table_name order by id desc limit 1

The id is the first column and primary key of the table_name, the mentioned statement show me the record with the largest id.

But the premise is u never deleted any row so the numbers of id equal to the numbers of rows.

Why is there no multiple inheritance in Java, but implementing multiple interfaces is allowed?

Java supports multiple inheritance through interfaces only. A class can implement any number of interfaces but can extend only one class.

Multiple inheritance is not supported because it leads to deadly diamond problem. However, it can be solved but it leads to complex system so multiple inheritance has been dropped by Java founders.

In a white paper titled “Java: an Overview” by James Gosling in February 1995(link) gives an idea on why multiple inheritance is not supported in Java.

According to Gosling:

"JAVA omits many rarely used, poorly understood, confusing features of C++ that in our experience bring more grief than bene?t. This primarily consists of operator overloading (although it does have method overloading), multiple inheritance, and extensive automatic coercions."

How to dismiss keyboard for UITextView with return key?

Just like matt comment to samvermette, I don't like the idea of detecting "\n" either. The "return" key is there for a reason in UITextView, that is to go to next line of course.

The best solution in my opinion is to mimic iPhone message app - which is to add toolbar (and button) on the keyboard.

I got code from following blog post:

http://www.iosdevnotes.com/2011/02/iphone-keyboard-toolbar/

Steps:

-Add toolbar to your XIB file - set the height to 460

-Add toolbar button item (if not already added). If you need to right-align it, also add flexible bar button item to XIB, and move the toolbar button item

-Create action that link your button item to resignFirstResponder as follow:

- (IBAction)hideKeyboard:(id)sender {
    [yourUITextView resignFirstResponder];
}

-Then:

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];

    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}

- (void)keyboardWillShow:(NSNotification *)notification {
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.3];

    CGRect frame = self.keyboardToolbar.frame;
    frame.origin.y = self.view.frame.size.height - 260.0;
    self.keyboardToolbar.frame = frame;

    [UIView commitAnimations];
}

- (void)keyboardWillHide:(NSNotification *)notification {
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.3];

    CGRect frame = self.keyboardToolbar.frame;
    frame.origin.y = self.view.frame.size.height;
    self.keyboardToolbar.frame = frame;

    [UIView commitAnimations];
}

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

If you want to check for local files first do:

@font-face {
font-family: 'Green Sans Web';
src:
    local('Green Web'),
    local('GreenWeb-Regular'),
    url('GreenWeb.ttf');
}

There is a more elaborate description of what to do here.

How to set editor theme in IntelliJ Idea

If you are using a Windows System. You can press Ctrl + Alt + S, and select Appearance.

How to sort dates from Oldest to Newest in Excel?

Saw this ages after posting, but if anyone has the same problem I had, my dates were all the format DD.MM.YYYY (SPSS output) even formatting them to date in Excel still only let me sort from A-Z so basically the 1st-31st irrelevant of month.

Doing a find and replace of all "." to "/" fixed this so that they are now in the format of DD/MM/YYYY. Not sure why it didn't work in the other format when the cell type counted as date.

Interfaces vs. abstract classes

The advantages of an abstract class are:

  • Ability to specify default implementations of methods
  • Added invariant checking to functions
  • Have slightly more control in how the "interface" methods are called
  • Ability to provide behavior related or unrelated to the interface for "free"

Interfaces are merely data passing contracts and do not have these features. However, they are typically more flexible as a type can only be derived from one class, but can implement any number of interfaces.

How does cookie based authentication work?

A cookie is basically just an item in a dictionary. Each item has a key and a value. For authentication, the key could be something like 'username' and the value would be the username. Each time you make a request to a website, your browser will include the cookies in the request, and the host server will check the cookies. So authentication can be done automatically like that.

To set a cookie, you just have to add it to the response the server sends back after requests. The browser will then add the cookie upon receiving the response.

There are different options you can configure for the cookie server side, like expiration times or encryption. An encrypted cookie is often referred to as a signed cookie. Basically the server encrypts the key and value in the dictionary item, so only the server can make use of the information. So then cookie would be secure.

A browser will save the cookies set by the server. In the HTTP header of every request the browser makes to that server, it will add the cookies. It will only add cookies for the domains that set them. Example.com can set a cookie and also add options in the HTTP header for the browsers to send the cookie back to subdomains, like sub.example.com. It would be unacceptable for a browser to ever sends cookies to a different domain.

Curly braces in string in PHP

As for me, curly braces serve as a substitution for concatenation, they are quicker to type and code looks cleaner. Remember to use double quotes (" ") as their content is parsed by PHP, because in single quotes (' ') you'll get the literal name of variable provided:

<?php

 $a = '12345';

// This works:
 echo "qwe{$a}rty"; // qwe12345rty, using braces
 echo "qwe" . $a . "rty"; // qwe12345rty, concatenation used

// Does not work:
 echo 'qwe{$a}rty'; // qwe{$a}rty, single quotes are not parsed
 echo "qwe$arty"; // qwe, because $a became $arty, which is undefined

?>

Quick way to list all files in Amazon S3 bucket?

function showUploads(){
    if (!class_exists('S3')) require_once 'S3.php';
    // AWS access info
    if (!defined('awsAccessKey')) define('awsAccessKey', '234567665464tg');
    if (!defined('awsSecretKey')) define('awsSecretKey', 'dfshgfhfghdgfhrt463457');
    $bucketName = 'my_bucket1234';
    $s3 = new S3(awsAccessKey, awsSecretKey);
    $contents = $s3->getBucket($bucketName);
    echo "<hr/>List of Files in bucket : {$bucketName} <hr/>";
    $n = 1;
    foreach ($contents as $p => $v):
        echo $p."<br/>";
        $n++;
    endforeach;
}

How can I copy a Python string?

Copying a string can be done two ways either copy the location a = "a" b = a or you can clone which means b wont get affected when a is changed which is done by a = 'a' b = a[:]

How to create Java gradle project

I could handle it using a groovy method in build.gradle to create all source folders for java, resources and test. Then I set it to run before gradle eclipse task.

eclipseClasspath.doFirst {
    initSourceFolders()
}

def initSourceFolders() {
    sourceSets*.java.srcDirs*.each { it.mkdirs() }
    sourceSets*.resources.srcDirs*.each { it.mkdirs() }
}

Now we can setup a new gradle Java EE project to eclipse with only one command. I put this example at GitHub

cannot convert 'std::basic_string<char>' to 'const char*' for argument '1' to 'int system(const char*)'

The addition of a string literal with an std::string yields another std::string. system expects a const char*. You can use std::string::c_str() for that:

string name = "john";
string tmp = " quickscan.exe resolution 300 selectscanner jpg showui showprogress filename '"+name+".jpg'"
system(tmp.c_str());

How to get current domain name in ASP.NET

You can try the following code :

 Request.Url.Host +
    (Request.Url.IsDefaultPort ? "" : ":" + Request.Url.Port)

What's the -practical- difference between a Bare and non-Bare repository?

$ git help repository-layout

A Git repository comes in two different flavours:

  • a .git directory at the root of the working tree;
  • a .git directory that is a bare repository (i.e. without its own working tree), that is typically used for exchanging histories with others by pushing into it and fetching from it.

Defining a HTML template to append using JQuery

Old question, but since the question asks "using jQuery", I thought I'd provide an option that lets you do this without introducing any vendor dependency.

While there are a lot of templating engines out there, many of their features have fallen in to disfavour recently, with iteration (<% for), conditionals (<% if) and transforms (<%= myString | uppercase %>) seen as microlanguage at best, and anti-patterns at worst. Modern templating practices encourage simply mapping an object to its DOM (or other) representation, e.g. what we see with properties mapped to components in ReactJS (especially stateless components).

Templates Inside HTML

One property you can rely on for keeping the HTML for your template next to the rest of your HTML, is by using a non-executing <script> type, e.g. <script type="text/template">. For your case:

<script type="text/template" data-template="listitem">
    <a href="${url}" class="list-group-item">
        <table>
            <tr>
                <td><img src="${img}"></td>
                <td><p class="list-group-item-text">${title}</p></td>
            </tr>
        </table>
    </a>
</script>

On document load, read your template and tokenize it using a simple String#split

var itemTpl = $('script[data-template="listitem"]').text().split(/\$\{(.+?)\}/g);

Notice that with our token, you get it in the alternating [text, property, text, property] format. This lets us nicely map it using an Array#map, with a mapping function:

function render(props) {
  return function(tok, i) { return (i % 2) ? props[tok] : tok; };
}

Where props could look like { url: 'http://foo.com', img: '/images/bar.png', title: 'Lorem Ipsum' }.

Putting it all together assuming you've parsed and loaded your itemTpl as above, and you have an items array in-scope:

$('.search').keyup(function () {
  $('.list-items').append(items.map(function (item) {
    return itemTpl.map(render(item)).join('');
  }));
});

This approach is also only just barely jQuery - you should be able to take the same approach using vanilla javascript with document.querySelector and .innerHTML.

jsfiddle

Templates inside JS

A question to ask yourself is: do you really want/need to define templates as HTML files? You can always componentize + re-use a template the same way you'd re-use most things you want to repeat: with a function.

In es7-land, using destructuring, template strings, and arrow-functions, you can write downright pretty looking component functions that can be easily loaded using the $.fn.html method above.

const Item = ({ url, img, title }) => `
  <a href="${url}" class="list-group-item">
    <div class="image">
      <img src="${img}" />
    </div>
    <p class="list-group-item-text">${title}</p>
  </a>
`;

Then you could easily render it, even mapped from an array, like so:

$('.list-items').html([
  { url: '/foo', img: 'foo.png', title: 'Foo item' },
  { url: '/bar', img: 'bar.png', title: 'Bar item' },
].map(Item).join(''));

Oh and final note: don't forget to sanitize your properties passed to a template, if they're read from a DB, or someone could pass in HTML (and then run scripts, etc.) from your page.

Difference between virtual and abstract methods

Virtual methods have an implementation and provide the derived classes with the option of overriding it. Abstract methods do not provide an implementation and force the derived classes to override the method.

So, abstract methods have no actual code in them, and subclasses HAVE TO override the method. Virtual methods can have code, which is usually a default implementation of something, and any subclasses CAN override the method using the override modifier and provide a custom implementation.

public abstract class E
{
    public abstract void AbstractMethod(int i);

    public virtual void VirtualMethod(int i)
    {
        // Default implementation which can be overridden by subclasses.
    }
}

public class D : E
{
    public override void AbstractMethod(int i)
    {
        // You HAVE to override this method
    }
    public override void VirtualMethod(int i)
    {
        // You are allowed to override this method.
    }
}

Using Page_Load and Page_PreRender in ASP.Net

The main point of the differences as pointed out @BizApps is that Load event happens right after the ViewState is populated while PreRender event happens later, right before Rendering phase, and after all individual children controls' action event handlers are already executing. Therefore, any modifications done by the controls' actions event handler should be updated in the control hierarchy during PreRender as it happens after.

Formatting "yesterday's" date in python

Use datetime.timedelta()

>>> from datetime import date, timedelta
>>> yesterday = date.today() - timedelta(days=1)
>>> yesterday.strftime('%m%d%y')
'110909'

DateTime "null" value

I always set the time to DateTime.MinValue. This way I do not get any NullErrorException and I can compare it to a date that I know isn't set.

How to catch segmentation fault in Linux?

C++ solution found here (http://www.cplusplus.com/forum/unices/16430/)

#include <signal.h>
#include <stdio.h>
#include <unistd.h>
void ouch(int sig)
{
    printf("OUCH! - I got signal %d\n", sig);
}
int main()
{
    struct sigaction act;
    act.sa_handler = ouch;
    sigemptyset(&act.sa_mask);
    act.sa_flags = 0;
    sigaction(SIGINT, &act, 0);
    while(1) {
        printf("Hello World!\n");
        sleep(1);
    }
}

JavaScript string encryption and decryption?

Simple functions,


function Encrypt(value) 
{
  var result="";
  for(i=0;i<value.length;i++)
  {
    if(i<value.length-1)
    {
        result+=value.charCodeAt(i)+10;
        result+="-";
    }
    else
    {
        result+=value.charCodeAt(i)+10;
    }
  }
  return result;
}
function Decrypt(value)
{
  var result="";
  var array = value.split("-");

  for(i=0;i<array.length;i++)
  {
    result+=String.fromCharCode(array[i]-10);
  }
  return result;
} 

Can Mockito capture arguments of a method called multiple times?

First of all: you should always import mockito static, this way the code will be much more readable (and intuitive) - the code samples below require it to work:

import static org.mockito.Mockito.*;

In the verify() method you can pass the ArgumentCaptor to assure execution in the test and the ArgumentCaptor to evaluate the arguments:

ArgumentCaptor<MyExampleClass> argument = ArgumentCaptor.forClass(MyExampleClass.class);
verify(yourmock, atleast(2)).myMethod(argument.capture());

List<MyExampleClass> passedArguments = argument.getAllValues();

for (MyExampleClass data : passedArguments){
    //assertSometing ...
    System.out.println(data.getFoo());
}

The list of all passed arguments during your test is accessible via the argument.getAllValues() method.

The single (last called) argument's value is accessible via the argument.getValue() for further manipulation / checking or whatever you wish to do.

How do I create a readable diff of two spreadsheets using git diff?

Convert to cvs then upload to a version control system then diff with an advanced version control diff tool. When I used perforce it had a great diff tool, but I forget the name of it.

String formatting in Python 3

Python 3.6 now supports shorthand literal string interpolation with PEP 498. For your use case, the new syntax is simply:

f"({self.goals} goals, ${self.penalties})"

This is similar to the previous .format standard, but lets one easily do things like:

>>> width = 10
>>> precision = 4
>>> value = decimal.Decimal('12.34567')
>>> f'result: {value:{width}.{precision}}'
'result:      12.35'

How can I enable the MySQLi extension in PHP 7?

The problem is that the package that used to connect PHP to MySQL is deprecated (php5-mysql). If you install the new package,

sudo apt-get install php-mysql

this will automatically update Apache and PHP 7.

Run a controller function whenever a view is opened/shown

I had a similar problem with ionic where I was trying to load the native camera as soon as I select the camera tab. I resolved the issue by setting the controller to the ion-view component for the camera tab (in tabs.html) and then calling the $scope method that loads my camera (addImage).

In www/templates/tabs.html

  <ion-tab title="Camera" icon-off="ion-camera" icon-on="ion-camera" href="#/tab/chats" ng-controller="AddMediaCtrl" ng-click="addImage()">
    <ion-nav-view  name="tab-chats"></ion-nav-view>
  </ion-tab>

The addImage method, defined in AddMediaCtrl loads the native camera every time the user clicks the "Camera" tab. I did not have to change anything in the angular cache for this to work. I hope this helps.

Switch statement fallthrough in C#?

You forgot to add the "break;" statement into case 3. In case 2 you wrote it into the if block. Therefore try this:

case 3:            
{
    ans += string.Format("{0} hundred and ", numbers[number / 100]);
    break;
}


case 2:            
{
    int t = (number / 10) % 10;            
    if (t == 1)            
    {                
        ans += teens[number % 10];                
    }            
    else if (t > 1)                
    {
        ans += string.Format("{0}-", tens[t]);        
    }
    break;
}

case 1:            
{
    int o = number % 10;            
    ans += numbers[o];            
    break;        
}

default:            
{
    throw new ArgumentException("number");
}

Use xml.etree.ElementTree to print nicely formatted xml files

You could use the library lxml (Note top level link is now spam) , which is a superset of ElementTree. Its tostring() method includes a parameter pretty_print - for example:

>>> print(etree.tostring(root, pretty_print=True))
<root>
  <child1/>
  <child2/>
  <child3/>
</root>

Kotlin Error : Could not find org.jetbrains.kotlin:kotlin-stdlib-jre7:1.0.7

If you are using Android Studio 3.2 & above,then issue will be solved by adding google() & jcenter() to build.gradle of the project:

repositories {
        google()
        jcenter()
}

How to put a jar in classpath in Eclipse?

First copy your jar file and paste into you Android project's libs folder.

Now right click on newly added (Pasted) jar file and select option

Build Path -> Add to build path

Now you added jar file will get displayed under Referenced Libraries. Again right click on it and select option

Build Path -> Configure Build path

A new window will get appeared. Select Java Build Path from left menu panel and then select Order and export Enable check on added jar file.

Now run your project.

More details @ Add-JARs-to-Project-Build-Paths-in-Eclipse-(Java)

Create PostgreSQL ROLE (user) if it doesn't exist

The accepted answer suffers from a race condition if two such scripts are executed concurrently on the same Postgres cluster (DB server), as is common in continuous-integration environments.

It's generally safer to try to create the role and gracefully deal with problems when creating it:

DO $$
BEGIN
  CREATE ROLE my_role WITH NOLOGIN;
  EXCEPTION WHEN DUPLICATE_OBJECT THEN
  RAISE NOTICE 'not creating role my_role -- it already exists';
END
$$;

CodeIgniter - return only one row?

You can do like this

$q  = $this->db->get()->row();

return $q->campaign_id;

Documentation : http://www.codeigniter.com/user_guide/database/results.html

Text size of android design TabLayout tabs

Go on using tabTextAppearance as you did but

1) to fix the capital letter side effect add textAllCap in your style :

<style name="MyTabLayoutTextAppearance" parent="TextAppearance.AppCompat.Widget.ActionBar.Title.Inverse">
    <item name="android:textSize">14sp</item>
    <item name="android:textAllCaps">true</item>
</style>

2) to fix the selected tab color side effect add in TabLayout xml the following library attributes :

app:tabSelectedTextColor="@color/color1"
app:tabTextColor="@color/color2" 

Hope this helps.

Where does git config --global get written to?

Uninstall Msysgit and install Cygwin + Git. Then global '.gitconfig' will be here: C:\cygwin(64)\home\[userName]\.gitconfig .

Now you don't have to worry about an environment variable which may be used by other programs. For example, my environment variable pointed me to a mapped drive in my work windows domain environment. I dont want my global .gitconfig sitting on my "home" mapped drive. I also don't know what might happen to other applications that might rely on that windows environment variable. Operations division might need that environment variable set to the mapped drive for a reason.

Also you don't have to worry about Mysysgit overwriting your 'profile' configuration settings if you specify a specific path to global '.gitconfig', using this method.

In general, save yourself and use cygwin bash shell in windows and be happier

Scrollbar without fixed height/Dynamic height with scrollbar

Use this:

style="height: 150px; max-height: 300px; overflow: auto;" 

fixe a height, it will be the default height and then a scroll bar come to access to the entire height

How to print out a variable in makefile

If you don't want to modify the Makefile itself, you can use --eval to add a new target, and then execute the new target, e.g.

make --eval='print-tests: @echo TESTS $(TESTS) ' print-tests

You can insert the required TAB character in the command line using CTRL-V, TAB

example Makefile from above:

all: do-something

TESTS=
TESTS+='a'
TESTS+='b'
TESTS+='c'

do-something:
        @echo "doing something"
        @echo "running tests $(TESTS)"
        @exit 1

What is the difference between JOIN and JOIN FETCH when using JPA and Hibernate

Dherik : I'm not sure about what you say, when you don't use fetch the result will be of type : List<Object[ ]> which means a list of Object tables and not a list of Employee.

Object[0] refers an Employee entity 
Object[1] refers a Departement entity 

When you use fetch, there is just one select and the result is the list of Employee List<Employee> containing the list of departements. It overrides the lazy declaration of the entity.

Programmatically getting the MAC of an Android device

I know this is a very old question but there is one more method to do this. Below code compiles but I haven't tried it. You can write some C code and use JNI (Java Native Interface) to get MAC address. Here is the example main activity code:

package com.example.getmymac;

import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

public class GetMyMacActivity extends AppCompatActivity {
    static { // here we are importing native library.
        // name of the library is libnet-utils.so, in cmake and java code
        // we just use name "net-utils".
        System.loadLibrary("net-utils");
    }

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_screen);

        // some debug text and a TextView.
        Log.d(NetUtilsActivity.class.getSimpleName(), "Starting app...");
        TextView text = findViewById(R.id.sample_text);

        // the get_mac_addr native function, implemented in C code.
        byte[] macArr = get_mac_addr(null);
        // since it is a byte array, we format it and convert to string.
        String val = String.format("%02x:%02x:%02x:%02x:%02x:%02x",
                macArr[0], macArr[1], macArr[2],
                macArr[3], macArr[4], macArr[5]);
        // print it to log and TextView.
        Log.d(NetUtilsActivity.class.getSimpleName(), val);
        text.setText(val);
    }

    // here is the prototype of the native function.
    // use native keyword to indicate it is a native function,
    // implemented in C code.
    private native byte[] get_mac_addr(String interface_name);
}

And the layout file, main_screen.xml:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/sample_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/app_name"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>

Manifest file, I didn't know what permissions to add so I added some.

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.getmymac">

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <activity android:name=".GetMyMacActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
    </application>
</manifest>

C implementation of get_mac_addr function.

/* length of array that MAC address is stored. */
#define MAC_ARR_LEN 6

#define BUF_SIZE 256

#include <jni.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <net/if.h>
#include <sys/ioctl.h>
#include <unistd.h>

#define ERROR_IOCTL 1
#define ERROR_SOCKT 2

static jboolean
cstr_eq_jstr(JNIEnv *env, const char *cstr, jstring jstr) {
    /* see [this](https://stackoverflow.com/a/38204842) */

    jstring cstr_as_jstr = (*env)->NewStringUTF(env, cstr);
    jclass cls = (*env)->GetObjectClass(env, jstr);
    jmethodID method_id = (*env)->GetMethodID(env, cls, "equals", "(Ljava/lang/Object;)Z");
    jboolean equal = (*env)->CallBooleanMethod(env, jstr, method_id, cstr_as_jstr);
    return equal;
}

static void
get_mac_by_ifname(jchar *ifname, JNIEnv *env, jbyteArray arr, int *error) {
    /* see [this](https://stackoverflow.com/a/1779758) */

    struct ifreq ir;
    struct ifconf ic;
    char buf[BUF_SIZE];
    int ret = 0, sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP);

    if (sock == -1) {
        *error = ERROR_SOCKT;
        return;
    }

    ic.ifc_len = BUF_SIZE;
    ic.ifc_buf = buf;

    ret = ioctl(sock, SIOCGIFCONF, &ic);
    if (ret) {
        *error = ERROR_IOCTL;
        goto err_cleanup;
    }

    struct ifreq *it = ic.ifc_req; /* iterator */
    struct ifreq *end = it + (ic.ifc_len / sizeof(struct ifreq));

    int found = 0; /* found interface named `ifname' */

    /* while we find an interface named `ifname' or arrive end */
    while (it < end && found == 0) {
        strcpy(ir.ifr_name, it->ifr_name);
        ret = ioctl(sock, SIOCGIFFLAGS, &ir);
        if (ret == 0) {
            if (!(ir.ifr_flags & IFF_LOOPBACK)) {
                ret = ioctl(sock, SIOCGIFHWADDR, &ir);
                if (ret) {
                    *error = ERROR_IOCTL;
                    goto err_cleanup;
                }

                if (ifname != NULL) {
                    if (cstr_eq_jstr(env, ir.ifr_name, ifname)) {
                        found = 1;
                    }
                }
            }
        } else {
            *error = ERROR_IOCTL;
            goto err_cleanup;
        }
        ++it;
    }

    /* copy the MAC address to byte array */
    (*env)->SetByteArrayRegion(env, arr, 0, 6, ir.ifr_hwaddr.sa_data);
    /* cleanup, close the socket connection */
    err_cleanup: close(sock);
}

JNIEXPORT jbyteArray JNICALL
Java_com_example_getmymac_GetMyMacActivity_get_1mac_1addr(JNIEnv *env, jobject thiz,
                                                          jstring interface_name) {
    /* first, allocate space for the MAC address. */
    jbyteArray mac_addr = (*env)->NewByteArray(env, MAC_ARR_LEN);
    int error = 0;

    /* then just call `get_mac_by_ifname' function */
    get_mac_by_ifname(interface_name, env, mac_addr, &error);

    return mac_addr;
}

And finally, CMakeLists.txt file

cmake_minimum_required(VERSION 3.4.1)
add_library(net-utils SHARED src/main/cpp/net-utils.c)
target_link_libraries(net-utils android log)

How to increment a datetime by one day?

This was a straightforward solution for me:

from datetime import timedelta, datetime

today = datetime.today().strftime("%Y-%m-%d")
tomorrow = datetime.today() + timedelta(1)

Hive: how to show all partitions of a table?

Okay, I'm writing this answer by extending wmky's answer above & also, assuming that you've configured mysql for your metastore instead of derby.

select PART_NAME FROM PARTITIONS WHERE TBL_ID=(SELECT TBL_ID FROM TBLS WHERE TBL_NAME='<table_name>');

The above query gives you all possible values of the partition columns.

Example:

hive> desc clicks_fact;
OK
time                    timestamp                                   
..                              
day                     date                                        
file_date               varchar(8)                                  

# Partition Information      
# col_name              data_type               comment             

day                     date                                        
file_date               varchar(8)                                  
Time taken: 1.075 seconds, Fetched: 28 row(s)

I'm going to fetch the values of partition columns.

mysql> select PART_NAME FROM PARTITIONS WHERE TBL_ID=(SELECT TBL_ID FROM TBLS WHERE TBL_NAME='clicks_fact');
+-----------------------------------+
| PART_NAME                         |
+-----------------------------------+
| day=2016-08-16/file_date=20160816 |
| day=2016-08-17/file_date=20160816 |
....
....
| day=2017-09-09/file_date=20170909 |
| day=2017-09-08/file_date=20170909 |
| day=2017-09-09/file_date=20170910 |
| day=2017-09-10/file_date=20170910 |
+-----------------------------------+

1216 rows in set (0.00 sec)

Returns all partition columns.

Note: JOIN table DBS ON DB_ID when there is a DB involved (i.e, when, multiple DB's have same table_name)

How to change the CHARACTER SET (and COLLATION) throughout a database?

Beware that in Mysql, the utf8 character set is only a subset of the real UTF8 character set. In order to save one byte of storage, the Mysql team decided to store only three bytes of a UTF8 characters instead of the full four-bytes. That means that some east asian language and emoji aren't fully supported. To make sure you can store all UTF8 characters, use the utf8mb4 data type, and utf8mb4_bin or utf8mb4_general_ci in Mysql.

Newline in JLabel

Thanks Aakash for recommending JIDE MultilineLabel. JIDE's StyledLabel is also enhanced recently to support multiple line. I would recommend it over the MultilineLabel as it has many other great features. You can check out an article on StyledLabel below. It is still free and open source.

http://www.jidesoft.com/articles/StyledLabel.pdf

Slide right to left?

You can define first the width of the element as 0, floating right, and then on the event that you are about to show it.. it would be like

$('#the_element_to_slide_from_right_left').animate({ width:'your desired width' }, 600);

Simple as that.

How can I view array structure in JavaScript with alert()?

pass your js array to the function below and it will do the same as php print_r() function

 alert(print_r(your array));  //call it like this

function print_r(arr,level) {
var dumped_text = "";
if(!level) level = 0;

//The padding given at the beginning of the line.
var level_padding = "";
for(var j=0;j<level+1;j++) level_padding += "    ";

if(typeof(arr) == 'object') { //Array/Hashes/Objects 
    for(var item in arr) {
        var value = arr[item];

        if(typeof(value) == 'object') { //If it is an array,
            dumped_text += level_padding + "'" + item + "' ...\n";
            dumped_text += print_r(value,level+1);
        } else {
            dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
        }
    }
} else { //Stings/Chars/Numbers etc.
    dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
}
return dumped_text;
}

Reading RFID with Android phones

NFC enabled phones can ONLY read NFC and passive high frequency RFID (HF-RFID). These must be read at an extremely close range, typically a few centimeters. For longer range or any other type of RFID/active RFID, you must use an external reader for handling them with mobile devices.

You can get some decent readers from a lot of manufacturers by simply searching on google. There are a lot of plug in ones for all device types.

I deal a lot with HID readers capable of close proximity scans of HID enabled ID cards as well as NFC from smart phones and smart cards. I use SerialIO badge readers that I load a decryption profile onto that allows our secure company cards to be read and utilized by an application I built. They are great for large scale reliable bluetooth scanning. Because they are bluetooth, they work for PC/Android/iOS/Linux. The only problem is, HID readers are very expensive and are meant for enterprise use. Ours cost about $400 each, but again, they read HID, SmartCards, NFC, and RFID.

If this is a personal project, I suggest just using the phone and purchasing some HF-RFID tags. The tag manufacturer should have an SDK for you to use to connect to and manage the tags. You can also just use androids NFC docs to get started https://developer.android.com/guide/topics/connectivity/nfc/. Most android phones from the last 8 years have NFC, only iPhone 6 and newer apple phones have NFC, but only iOS 11 and newer will work for what you want to do.

T-SQL query to show table definition?

Visit http://www.stormrage.com/SQLStuff/sp_GetDDL_Latest.txt.

You will find the code of sp_getddl procedure for SQL Server. The purpose of the procedure is script any table, temp table or object.

USAGE:

exec sp_GetDDL GMACT

or

exec sp_GetDDL 'bob.example'

or

exec sp_GetDDL '[schemaname].[tablename]'

or

exec sp_GetDDL #temp

I tested it on SQL Server 2012, and it does an excellent job.

I'm not the author of the procedure. Any improvement you make to it send to Lowell Izaguirre ([email protected]).

Android: How can I print a variable on eclipse console?

I'm new to Android development and I do this:

1) Create a class:

import android.util.Log;

public final class Debug{
    private Debug (){}

    public static void out (Object msg){
        Log.i ("info", msg.toString ());
    }
}

When you finish the project delete the class.

2) To print a message to the LogCat write:

Debug.out ("something");

3) Create a filter in the LogCat and write "info" in the input "by Log Tag". All your messages will be written here. :)

Tip: Create another filter to filter all errors to debug easily.

Can we have functions inside functions in C++?

For all intents and purposes, C++ supports this via lambdas:1

int main() {
    auto f = []() { return 42; };
    std::cout << "f() = " << f() << std::endl;
}

Here, f is a lambda object that acts as a local function in main. Captures can be specified to allow the function to access local objects.

Behind the scenes, f is a function object (i.e. an object of a type that provides an operator()). The function object type is created by the compiler based on the lambda.


1 since C++11

Is there a better way to compare dictionary values

If your values are hashable (ie. strings), then you can simply compare the ItemsView of the two dicts.

https://docs.python.org/3/library/stdtypes.html#dict-views

set_with_unique_key_value_pairs = dict1.items() ^ dict2.items()
set_with_matching_key_value_pairs = dict1.items() & dict2.items()

Any set operations are available to you.

Since you might not care about keys in this case, you can also just use the ValuesView (again, provided the values are hashable).

set_with_matching_values = dict1.values() & dict2.values()

How to convert Integer to int?

Perhaps you have the compiler settings for your IDE set to Java 1.4 mode even if you are using a Java 5 JDK? Otherwise I agree with the other people who already mentioned autoboxing/unboxing.

How can I list (ls) the 5 last modified files in a directory?

By default ls -t sorts output from newest to oldest, so the combination of commands to use depends in which direction you want your output to be ordered.

For the newest 5 files ordered from newest to oldest, use head to take the first 5 lines of output:

ls -t | head -n 5

For the newest 5 files ordered from oldest to newest, use the -r switch to reverse ls's sort order, and use tail to take the last 5 lines of output:

ls -tr | tail -n 5

No newline after div?

There is no newline, just the div is a block element.

You can make the div inline by adding display: inline, which may be what you want.

How can I keep a container running on Kubernetes?

Containers are meant to run to completion. You need to provide your container with a task that will never finish. Something like this should work:

apiVersion: v1
kind: Pod
metadata:
  name: ubuntu
spec:
  containers:
  - name: ubuntu
    image: ubuntu:latest
    # Just spin & wait forever
    command: [ "/bin/bash", "-c", "--" ]
    args: [ "while true; do sleep 30; done;" ]

How can JavaScript save to a local file?

If you are using FireFox you can use the File HandleAPI

https://developer.mozilla.org/en-US/docs/Web/API/File_Handle_API

I had just tested it out and it works!

How to refactor Node.js code that uses fs.readFileSync() into using fs.readFile()?

var fs = require("fs");
var filename = "./index.html";

function start(resp) {
    resp.writeHead(200, {
        "Content-Type": "text/html"
    });
    fs.readFile(filename, "utf8", function(err, data) {
        if (err) throw err;
        resp.write(data);
        resp.end();
    });
}

How to pass parameters to a Script tag?

Thanks to the jQuery, a simple HTML5 compliant solution is to create an extra HTML tag, like div, to store the data.

HTML:

<div id='dataDiv' data-arg1='content1' data-arg2='content2'>
  <button id='clickButton'>Click me</button>
</div>

JavaScript:

$(document).ready(function() {
    var fetchData = $("#dataDiv").data('arg1') + 
                    $("#dataDiv").data('arg2') ;

    $('#clickButton').click(function() {
      console.log(fetchData);
    })
});

Live demo with the code above: http://codepen.io/anon/pen/KzzNmQ?editors=1011#0

On the live demo, one can see the data from HTML5 data-* attributes to be concatenated and printed to the log.

Source: https://api.jquery.com/data/

C# Connecting Through Proxy

            var getHtmlWeb = new HtmlWeb() { AutoDetectEncoding = false, OverrideEncoding = Encoding.GetEncoding("iso-8859-2") };

            WebProxy myproxy = new WebProxy("127.0.0.1:8888", false);
            NetworkCredential cred = (NetworkCredential)CredentialCache.DefaultCredentials;
            var document = getHtmlWeb.Load("URL", "GET", myproxy, cred);

How many bits or bytes are there in a character?

It depends what is the character and what encoding it is in:

  • An ASCII character in 8-bit ASCII encoding is 8 bits (1 byte), though it can fit in 7 bits.

  • An ISO-8895-1 character in ISO-8859-1 encoding is 8 bits (1 byte).

  • A Unicode character in UTF-8 encoding is between 8 bits (1 byte) and 32 bits (4 bytes).

  • A Unicode character in UTF-16 encoding is between 16 (2 bytes) and 32 bits (4 bytes), though most of the common characters take 16 bits. This is the encoding used by Windows internally.

  • A Unicode character in UTF-32 encoding is always 32 bits (4 bytes).

  • An ASCII character in UTF-8 is 8 bits (1 byte), and in UTF-16 - 16 bits.

  • The additional (non-ASCII) characters in ISO-8895-1 (0xA0-0xFF) would take 16 bits in UTF-8 and UTF-16.

That would mean that there are between 0.03125 and 0.125 characters in a bit.

Python, remove all non-alphabet chars from string

Try:

s = ''.join(filter(str.isalnum, s))

This will take every char from the string, keep only alphanumeric ones and build a string back from them.

Python: access class property from string

  • getattr(x, 'y') is equivalent to x.y
  • setattr(x, 'y', v) is equivalent to x.y = v
  • delattr(x, 'y') is equivalent to del x.y

Default text which won't be shown in drop-down list

Kyle's solution worked perfectly fine for me so I made my research in order to avoid any Js and CSS, but just sticking with HTML. Adding a value of selected to the item we want to appear as a header forces it to show in the first place as a placeholder. Something like:

<option selected disabled>Choose here</option>

The complete markup should be along these lines:

<select>
    <option selected disabled>Choose here</option>
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
    <option value="4">Four</option>
    <option value="5">Five</option>
</select>

You can take a look at this fiddle, and here's the result:

enter image description here

If you do not want the sort of placeholder text to appear listed in the options once a user clicks on the select box just add the hidden attribute like so:

<select>
    <option selected disabled hidden>Choose here</option>
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
    <option value="4">Four</option>
    <option value="5">Five</option>
</select>

Check the fiddle here and the screenshot below.

enter image description here


Here is the solution:

<select>
    <option style="display:none;" selected>Select language</option>
    <option>Option 1</option>
    <option>Option 2</option>
</select>

How to replace comma with a dot in the number (or any replacement)

After replacing the character, you need to be asign to the variable.

var tt = "88,9827";
tt = tt.replace(/,/g, '.')
alert(tt)

In the alert box it will shows 88.9827

Prevent nginx 504 Gateway timeout using PHP set_time_limit()

Using set_time_limit(0) is useless when using php-fpm or similar process manager.

Bottomline is not to use set_time_limit when using php-fpm, to increase your execution timeout, check this tutorial.

Cannot connect to the Docker daemon at unix:/var/run/docker.sock. Is the docker daemon running?

You can try out this:

systemctl start docker

It worked fine for me.

P.S.: after if there is commands that you can't do without sudo, try this:

gpasswd -a $USER docker

How to show full column content in a Spark Dataframe?

The following answer applies to a Spark Streaming application.

By setting the "truncate" option to false, you can tell the output sink to display the full column.

val query = out.writeStream
          .outputMode(OutputMode.Update())
          .format("console")
          .option("truncate", false)
          .trigger(Trigger.ProcessingTime("5 seconds"))
          .start()

Create a hidden field in JavaScript

I've found this to work:

var element1 = document.createElement("input");
element1.type = "hidden";
element1.value = "10";
element1.name = "a";
document.getElementById("chells").appendChild(element1);

Date formatting in WPF datagrid

If your bound property is DateTime, then all you need is

Binding={Property, StringFormat=d}

How to call URL action in MVC with javascript function?

try:

var url = '/Home/Index/' + e.value;
 window.location = window.location.host + url; 

That should get you where you want.

500 Internal Server Error for php file not for html

500 Internal Server Error is shown if your php code has fatal errors but error displaying is switched off. You may try this to see the error itself instead of 500 error page:

In your php file:

ini_set('display_errors', 1);

In .htaccess file:

php_flag display_errors 1

Best practices for copying files with Maven

Another way is to bundle these things into an artifact using the assembly plugin. Then you can use the dependency plugin to unpack these files where you want. There are also copy goals in the dependency plugin to copy artifacts.

How to check if a file exists from inside a batch file

C:\>help if

Performs conditional processing in batch programs.

IF [NOT] ERRORLEVEL number command

IF [NOT] string1==string2 command

IF [NOT] EXIST filename command

How can I get a value from a map?

Unfortunately std::map::operator[] is a non-const member function, and you have a const reference.

You either need to change the signature of function or do:

MAP::const_iterator pos = map.find("string");
if (pos == map.end()) {
    //handle the error
} else {
    std::string value = pos->second;
    ...
}

operator[] handles the error by adding a default-constructed value to the map and returning a reference to it. This is no use when all you have is a const reference, so you will need to do something different.

You could ignore the possibility and write string value = map.find("string")->second;, if your program logic somehow guarantees that "string" is already a key. The obvious problem is that if you're wrong then you get undefined behavior.

recursively use scp but excluding some folders

You can use extended globbing as in the example below:

#Enable extglob
shopt -s extglob

cp -rv !(./excludeme/*.jpg) /var/destination

Sass Nesting for :hover does not work

You can easily debug such things when you go through the generated CSS. In this case the pseudo-selector after conversion has to be attached to the class. Which is not the case. Use "&".

http://sass-lang.com/documentation/file.SASS_REFERENCE.html#parent-selector

.class {
    margin:20px;
    &:hover {
        color:yellow;
    }
}

error: the details of the application error from being viewed remotely

In my case I got this message because there's a special char (&) in my connectionstring, remove it then everything's good.

Cheers

How to set breakpoints in inline Javascript in Google Chrome?

My situation and what I did to fix it:
I have a javascript file included on an HTML page as follows:
Page Name: test.html

<!DOCTYPE html>
<html>
    <head>
        <script src="scripts/common.js"></script>
        <title>Test debugging JS in Chrome</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    </head>
    <body>
        <div>
         <script type="text/javascript">
            document.write("something");
         </script>

        </div>
     </body>
</html>

Now entering the Javascript Debugger in Chrome, I click the Scripts Tab, and drop down the list as shown above. I can clearly see scripts/common.js however I could NOT see the current html page test.html in the drop down, therefore I could not debug the embedded javascript:

<script type="text/javascript">
  document.write("something");
</script>

That was perplexing. However, when I removed the obsolete type="text/javascript" from the embedded script:

<script>
  document.write("something");
</script>

..and refreshed / reloaded the page, voila, it appeared in the drop down list, and all was well again.
I hope this is helpful to anyone who is having issues debugging embedded javascript on an html page.

Linq style "For Each"

There isn't anything like that in standard Linq, but there is a ForEach operator in MoreLinq.

How to resolve cURL Error (7): couldn't connect to host?

In PHP, If your network under proxy. You should set the proxy URL and port

curl_setopt($ch, CURLOPT_PROXY, "http://url.com"); //your proxy url
curl_setopt($ch, CURLOPT_PROXYPORT, "80"); // your proxy port number

This is solves my problem

Count table rows

Just do a

SELECT COUNT(*) FROM table;

You can specify conditions with a Where after that

SELECT COUNT(*) FROM table WHERE eye_color='brown';

Sending the bearer token with axios

axios by itself comes with two useful "methods" the interceptors that are none but middlewares between the request and the response. so if on each request you want to send the token. Use the interceptor.request.

I made apackage that helps you out:

$ npm i axios-es6-class

Now you can use axios as class

export class UserApi extends Api {
    constructor (config) {
        super(config);

        // this middleware is been called right before the http request is made.
        this.interceptors.request.use(param => {
            return {
                ...param,
                defaults: {
                    headers: {
                        ...param.headers,
                        "Authorization": `Bearer ${this.getToken()}`
                    },
                }
            }
        });

      this.login = this.login.bind(this);
      this.getSome = this.getSome.bind(this);
   }

   login (credentials) {
      return this.post("/end-point", {...credentials})
      .then(response => this.setToken(response.data))
      .catch(this.error);
   }


   getSome () {
      return this.get("/end-point")
      .then(this.success)
      .catch(this.error);
   }
}

I mean the implementation of the middleware depends on you, or if you prefer to create your own axios-es6-class https://medium.com/@enetoOlveda/how-to-use-axios-typescript-like-a-pro-7c882f71e34a it is the medium post where it came from

Create a pointer to two-dimensional array

In C99 (supported by clang and gcc) there's an obscure syntax for passing multi-dimensional arrays to functions by reference:

int l_matrix[10][20];

void test(int matrix_ptr[static 10][20]) {
}

int main(void) {
    test(l_matrix);
}

Unlike a plain pointer, this hints about array size, theoretically allowing compiler to warn about passing too-small array and spot obvious out of bounds access.

Sadly, it doesn't fix sizeof() and compilers don't seem to use that information yet, so it remains a curiosity.

GET and POST methods with the same Action name in the same Controller

Since you cannot have two methods with the same name and signature you have to use the ActionName attribute:

[HttpGet]
public ActionResult Index()
{
  // your code
  return View();
}

[HttpPost]
[ActionName("Index")]
public ActionResult IndexPost()
{
  // your code
  return View();
}

Also see "How a Method Becomes An Action"

What are the safe characters for making URLs?

I found it very useful to encode my URL to a safe one when I was returning a value through Ajax/PHP to a URL which was then read by the page again.

PHP output with URL encoder for the special character &:

// PHP returning the success information of an Ajax request
echo "".str_replace('&', '%26', $_POST['name']) . " category was changed";

// JavaScript sending the value to the URL
window.location.href = 'time.php?return=updated&val=' + msg;

// JavaScript/PHP executing the function printing the value of the URL,
// now with the text normally lost in space because of the reserved & character.

setTimeout("infoApp('updated','<?php echo $_GET['val'];?>');", 360);

What is the difference between 'java', 'javaw', and 'javaws'?

java: Java application executor which is associated with a console to display output/errors

javaw: (Java windowed) application executor not associated with console. So no display of output/errors. It can be used to silently push the output/errors to text files. It is mostly used to launch GUI-based applications.

javaws: (Java web start) to download and run the distributed web applications. Again, no console is associated.

All are part of JRE and use the same JVM.

Check If array is null or not in php

This checks if the array is empty

if (!empty($result) {
    // do stuf if array is not empty
} else {
    // do stuf if array is empty
}

This checks if the array is null or not

if (is_null($result) {
   // do stuf if array is null
} else {
   // do stuf if array is not null
}

How do I read a text file of about 2 GB?

I always use 010 Editor to open huge files. It can handle 2 GB easily. I was manipulating files with 50 GB with 010 Editor :-)

It's commercial now, but it has a trial version.

Team Build Error: The Path ... is already mapped to workspace

Simply delete the workspace:

workspace /delete "the-workspace-name"

Django ManyToMany filter()

Just restating what Tomasz said.

There are many examples of FOO__in=... style filters in the many-to-many and many-to-one tests. Here is syntax for your specific problem:

users_in_1zone = User.objects.filter(zones__id=<id1>)
# same thing but using in
users_in_1zone = User.objects.filter(zones__in=[<id1>])

# filtering on a few zones, by id
users_in_zones = User.objects.filter(zones__in=[<id1>, <id2>, <id3>])
# and by zone object (object gets converted to pk under the covers)
users_in_zones = User.objects.filter(zones__in=[zone1, zone2, zone3])

The double underscore (__) syntax is used all over the place when working with querysets.

Why is System.Web.Mvc not listed in Add References?

In VS Express 2012 I couldn't find System.Web.Mvc in the "assemblies" tab, but after a bit of searching I found out that I need to look into "assemblies\extensions" tab rather than the default "assemblies\framework" tab.

Setting Spring Profile variable

For Eclipse, setting -Dspring.profiles.active variable in the VM arguments would do the trick.

Go to

Right Click Project --> Run as --> Run Configurations --> Arguments

And add your -Dspring.profiles.active=dev in the VM arguments

Running script upon login mac

tl;dr: use OSX's native process launcher and manager, launchd.

To do so, make a launchctl daemon. You'll have full control over all aspects of the script. You can run once or keep alive as a daemon. In most cases, this is the way to go.

  1. Create a .plist file according to the instructions in the Apple Dev docs here or more detail below.
  2. Place in ~/Library/LaunchAgents
  3. Log in (or run manually via launchctl load [filename.plist])

For more on launchd, the wikipedia article is quite good and describes the system and its advantages over other older systems.


Here's the specific plist file to run a script at login.

Updated 2017/09/25 for OSX El Capitan and newer (credit to José Messias Jr):

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
   <key>Label</key>
   <string>com.user.loginscript</string>
   <key>ProgramArguments</key>
   <array><string>/path/to/executable/script.sh</string></array>
   <key>RunAtLoad</key>
   <true/>
</dict>
</plist>

Replace the <string> after the Program key with your desired command (note that any script referenced by that command must be executable: chmod a+x /path/to/executable/script.sh to ensure it is for all users).

Save as ~/Library/LaunchAgents/com.user.loginscript.plist

Run launchctl load ~/Library/LaunchAgents/com.user.loginscript.plist and log out/in to test (or to test directly, run launchctl start com.user.loginscript)

Tail /var/log/system.log for error messages.

The key is that this is a User-specific launchd entry, so it will be run on login for the given user. System-specific launch daemons (placed in /Library/LaunchDaemons) are run on boot.

If you want a script to run on login for all users, I believe LoginHook is your only option, and that's probably the reason it exists.

How can I safely create a nested directory?

Use this command check and create dir

 if not os.path.isdir(test_img_dir):
     os.mkdir(test_img_dir)

How to predict input image using trained model in Keras?

Forwarding the example by @ritiek, I'm a beginner in ML too, maybe this kind of formatting will help see the name instead of just class number.

images = np.vstack([x, y])

prediction = model.predict(images)

print(prediction)

i = 1

for things in prediction:  
    if(things == 0):
        print('%d.It is cancer'%(i))
    else:
        print('%d.Not cancer'%(i))
    i = i + 1

return, return None, and no return at all?

As other have answered, the result is exactly the same, None is returned in all cases.

The difference is stylistic, but please note that PEP8 requires the use to be consistent:

Be consistent in return statements. Either all return statements in a function should return an expression, or none of them should. If any return statement returns an expression, any return statements where no value is returned should explicitly state this as return None, and an explicit return statement should be present at the end of the function (if reachable).

Yes:

def foo(x):
    if x >= 0:
        return math.sqrt(x)
    else:
        return None

def bar(x):
    if x < 0:
        return None
    return math.sqrt(x)

No:

def foo(x):
    if x >= 0:
        return math.sqrt(x)

def bar(x):
    if x < 0:
        return
    return math.sqrt(x)

https://www.python.org/dev/peps/pep-0008/#programming-recommendations


Basically, if you ever return non-None value in a function, it means the return value has meaning and is meant to be caught by callers. So when you return None, it must also be explicit, to convey None in this case has meaning, it is one of the possible return values.

If you don't need return at all, you function basically works as a procedure instead of a function, so just don't include the return statement.

If you are writing a procedure-like function and there is an opportunity to return earlier (i.e. you are already done at that point and don't need to execute the remaining of the function) you may use empty an returns to signal for the reader it is just an early finish of execution and the None value returned implicitly doesn't have any meaning and is not meant to be caught (the procedure-like function always returns None anyway).

How to initialize a private static const map in C++?

If the map is to contain only entries that are known at compile time and the keys to the map are integers, then you do not need to use a map at all.

char get_value(int key)
{
    switch (key)
    {
        case 1:
            return 'a';
        case 2:
            return 'b';
        case 3:
            return 'c';
        default:
            // Do whatever is appropriate when the key is not valid
    }
}

Node.js EACCES error when listening on most ports

#Windows

Another one reason - maybe your port has been excluded by some reasons.

So, try open CMD under admin rights and run :

  1. net stop winnat
  2. net start winnat

In my case it was enough.

Solution found here : https://medium.com/@Bartleby/ports-are-not-available-listen-tcp-0-0-0-0-3000-165892441b9d

Go to next item in ForEach-Object

I know this is an old post, but I wanted to add something I learned for the next folks who land here while googling.

In Powershell 5.1, you want to use continue to move onto the next item in your loop. I tested with 6 items in an array, had a foreach loop through, but put an if statement with:

foreach($i in $array){    
    write-host -fore green "hello $i"
    if($i -like "something"){
        write-host -fore red "$i is bad"
        continue
        write-host -fore red "should not see this"
    }
}

Of the 6 items, the 3rd one was something. As expected, it looped through the first 2, then the matching something gave me the red line where $i matched, I saw something is bad and then it went on to the next item in the array without saying should not see this. I tested with return and it exited the loop altogether.

Show "loading" animation on button click

            //do processing
            $(this).attr("label", $(this).text()).text("loading ....").animate({ disabled: true }, 1000, function () {
                //original event call
                $.when($(elm).delay(1000).one("click")).done(function () {//processing finalized
                    $(this).text($(this).attr("label")).animate({ disabled: false }, 1000, function () {
                    })
                });
            });

How to compare DateTime in C#?

In general case you need to compare DateTimes with the same Kind:

if (date1.ToUniversalTime() < date2.ToUniversalTime())
    Console.WriteLine("date1 is earlier than date2");

Explanation from MSDN about DateTime.Compare (This is also relevant for operators like >, <, == and etc.):

To determine the relationship of t1 to t2, the Compare method compares the Ticks property of t1 and t2 but ignores their Kind property. Before comparing DateTime objects, ensure that the objects represent times in the same time zone.

Thus, a simple comparison may give an unexpected result when dealing with DateTimes that are represented in different timezones.

How to check currently internet connection is available or not in android

use the next code:

public static boolean isNetworkAvaliable(Context ctx) {
    ConnectivityManager connectivityManager = (ConnectivityManager) ctx
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    if ((connectivityManager
            .getNetworkInfo(ConnectivityManager.TYPE_MOBILE) != null && connectivityManager
            .getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED)
            || (connectivityManager
                    .getNetworkInfo(ConnectivityManager.TYPE_WIFI) != null && connectivityManager
                    .getNetworkInfo(ConnectivityManager.TYPE_WIFI)
                    .getState() == NetworkInfo.State.CONNECTED)) {
        return true;
    } else {
        return false;
    }
}

remember that yo need put in your manifest the next line:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

What is the function of FormulaR1C1?

I find the most valuable feature of .FormulaR1C1 is sheer speed. Versus eg a couple of very large loops filling some data into a sheet, If you can convert what you are doing into a .FormulaR1C1 form. Then a single operation eg myrange.FormulaR1C1 = "my particular formuala" is blindingly fast (can be a thousand times faster). No looping and counting - just fill the range at high speed.

How to restart Jenkins manually?

This can also be done using the Jenkins CLI:

java -jar jenkins-cli.jar -s http://[jenkins-server]/ restart

The jenkins-cli.jar file along with a full list of commands are available at http://[jenkins-server]/cli.

What is difference between sjlj vs dwarf vs seh?

There's a short overview at MinGW-w64 Wiki:

Why doesn't mingw-w64 gcc support Dwarf-2 Exception Handling?

The Dwarf-2 EH implementation for Windows is not designed at all to work under 64-bit Windows applications. In win32 mode, the exception unwind handler cannot propagate through non-dw2 aware code, this means that any exception going through any non-dw2 aware "foreign frames" code will fail, including Windows system DLLs and DLLs built with Visual Studio. Dwarf-2 unwinding code in gcc inspects the x86 unwinding assembly and is unable to proceed without other dwarf-2 unwind information.

The SetJump LongJump method of exception handling works for most cases on both win32 and win64, except for general protection faults. Structured exception handling support in gcc is being developed to overcome the weaknesses of dw2 and sjlj. On win64, the unwind-information are placed in xdata-section and there is the .pdata (function descriptor table) instead of the stack. For win32, the chain of handlers are on stack and need to be saved/restored by real executed code.

GCC GNU about Exception Handling:

GCC supports two methods for exception handling (EH):

  • DWARF-2 (DW2) EH, which requires the use of DWARF-2 (or DWARF-3) debugging information. DW-2 EH can cause executables to be slightly bloated because large call stack unwinding tables have to be included in th executables.
  • A method based on setjmp/longjmp (SJLJ). SJLJ-based EH is much slower than DW2 EH (penalising even normal execution when no exceptions are thrown), but can work across code that has not been compiled with GCC or that does not have call-stack unwinding information.

[...]

Structured Exception Handling (SEH)

Windows uses its own exception handling mechanism known as Structured Exception Handling (SEH). [...] Unfortunately, GCC does not support SEH yet. [...]

See also:

Starting Docker as Daemon on Ubuntu

I had the same issue on 14.04 with docker 1.9.1.

The upstart service command did work when I used sudo, even though I was root:

$ whoami
root
$ service docker status
status: Unbekannter Auftrag: docker

$ sudo service docker status
docker start/running, process 7394

It seems to depend on the environment variables.

service docker status works when becoming root with su -, but not when only using su:

$ su
Password:
$ service docker status
status: unknown job: docker
$ exit
$ su -
Password:
$ service docker status
docker start/running, process 2342

Maximum on http header values?

If you are going to use any DDOS provider like Akamai, they have a maximum limitation of 8k in the response header size. So essentially try to limit your response header size below 8k.

CGContextDrawImage draws image upside down when passed UIImage.CGImage

I'm not sure for UIImage, but this kind of behaviour usually occurs when coordinates are flipped. Most of OS X coordinate systems have their origin at the lower left corner, as in Postscript and PDF. But CGImage coordinate system has its origin at the upper left corner.

Possible solutions may involve an isFlipped property or a scaleYBy:-1 affine transform.

How do I properly force a Git push?

This was our solution for replacing master on a corporate gitHub repository while maintaining history.

push -f to master on corporate repositories is often disabled to maintain branch history. This solution worked for us.

git fetch desiredOrigin
git checkout -b master desiredOrigin/master // get origin master

git checkout currentBranch  // move to target branch
git merge -s ours master  // merge using ours over master
// vim will open for the commit message
git checkout master  // move to master
git merge currentBranch  // merge resolved changes into master

push your branch to desiredOrigin and create a PR

How to refresh app upon shaking the device?

You should subscribe as a SensorEventListener, and get the accelerometer data. Once you have it, you should monitor for sudden change in direction (sign) of acceleration on a certain axis. It would be a good indication for the 'shake' movement of device.

How do I display Ruby on Rails form validation error messages one at a time?

I resolved it like this:

<% @user.errors.each do |attr, msg| %>
  <li>
    <%= @user.errors.full_messages_for(attr).first if @user.errors[attr].first == msg %>
  </li>
<% end %>

This way you are using the locales for the error messages.

Switching between GCC and Clang/LLVM using CMake

You can use the toolchain file mechanism of cmake for this purpose, see e.g. here. You write a toolchain file for each compiler containing the corresponding definitions. At config time, you run e.g

 cmake -DCMAKE_TOOLCHAIN_FILE=/path/to/clang-toolchain.cmake ..

and all the compiler information will be set during the project() call from the toolchain file. Though in the documentation is mentionend only in the context of cross-compiling, it works as well for different compilers on the same system.

Importing lodash into angular2 + typescript application

Step 1: Modify package.json file to include lodash in the dependencies.

  "dependencies": {
"@angular/common":  "2.0.0-rc.1",
"@angular/compiler":  "2.0.0-rc.1",
"@angular/core":  "2.0.0-rc.1",
"@angular/http":  "2.0.0-rc.1",
"@angular/platform-browser":  "2.0.0-rc.1",
"@angular/platform-browser-dynamic":  "2.0.0-rc.1",
"@angular/router":  "2.0.0-rc.1",
"@angular/router-deprecated":  "2.0.0-rc.1",
"@angular/upgrade":  "2.0.0-rc.1",
"systemjs": "0.19.27",
"es6-shim": "^0.35.0",
"reflect-metadata": "^0.1.3",
"rxjs": "5.0.0-beta.6",
"zone.js": "^0.6.12",
"lodash":"^4.12.0",
"angular2-in-memory-web-api": "0.0.7",
"bootstrap": "^3.3.6"  }

Step 2:I am using SystemJs module loader in my angular2 application. So I would be modifying the systemjs.config.js file to map lodash.

(function(global) {

// map tells the System loader where to look for things
var map = {
    'app':                        'app', // 'dist',
    'rxjs':                       'node_modules/rxjs',
    'angular2-in-memory-web-api': 'node_modules/angular2-in-memory-web-api',
    '@angular':                   'node_modules/@angular',
    'lodash':                    'node_modules/lodash'
};

// packages tells the System loader how to load when no filename and/or no extension
var packages = {
    'app':                        { main: 'main.js',  defaultExtension: 'js' },
    'rxjs':                       { defaultExtension: 'js' },
    'angular2-in-memory-web-api': { defaultExtension: 'js' },
    'lodash':                    {main:'index.js', defaultExtension:'js'}
};

var packageNames = [
    '@angular/common',
    '@angular/compiler',
    '@angular/core',
    '@angular/http',
    '@angular/platform-browser',
    '@angular/platform-browser-dynamic',
    '@angular/router',
    '@angular/router-deprecated',
    '@angular/testing',
    '@angular/upgrade',
];

// add package entries for angular packages in the form '@angular/common': { main: 'index.js', defaultExtension: 'js' }
packageNames.forEach(function(pkgName) {
    packages[pkgName] = { main: 'index.js', defaultExtension: 'js' };
});

var config = {
    map: map,
    packages: packages
}

// filterSystemConfig - index.html's chance to modify config before we register it.
if (global.filterSystemConfig) { global.filterSystemConfig(config); }

System.config(config);})(this);

Step 3: Now do npm install

Step 4: To use lodash in your file.

import * as _ from 'lodash';
let firstIndexOfElement=_.findIndex(array,criteria);

Replace all elements of Python NumPy Array that are greater than some value

I think both the fastest and most concise way to do this is to use NumPy's built-in Fancy indexing. If you have an ndarray named arr, you can replace all elements >255 with a value x as follows:

arr[arr > 255] = x

I ran this on my machine with a 500 x 500 random matrix, replacing all values >0.5 with 5, and it took an average of 7.59ms.

In [1]: import numpy as np
In [2]: A = np.random.rand(500, 500)
In [3]: timeit A[A > 0.5] = 5
100 loops, best of 3: 7.59 ms per loop

Differences between cookies and sessions?

Google JSESSIONID. This will explain how the Servlet API initially uses URL re-writing and then, if cookies are enabled, cookies to manage sessions.

HTTP is stateless so the client browser must send the id of its session to the server with each request. The server, through whatever means, uses this id to retrieve any data for that session making it available for the lifetime of the request.

How can I add an item to a SelectList in ASP.net MVC

Here html helper for you

public static SelectList IndividualNamesOrAll(this SelectList Object)
{
    MedicalVarianceViewsDataContext LinqCtx = new MedicalVarianceViewsDataContext();

    //not correct need individual view!
    var IndividualsListBoxRaw =  ( from x in LinqCtx.ViewIndividualsNames 
                                 orderby x.FullName
                                 select x);

    List<SelectListItem> items = new SelectList (
                               IndividualsListBoxRaw, 
                              "First_Hospital_Case_Nbr", 
                              "FullName"
                               ).ToList();

    items.Insert(0, (new SelectListItem { Text = "All Individuals", 
                                        Value = "0.0", 
                                        Selected = true }));

    Object = new SelectList (items,"Value","Text");

    return Object;
}

Find CRLF in Notepad++

Make this setting. Menu-> View-> Show Symbol-> uncheck Show End of the Line

S3 limit to objects in a bucket

While you can store an unlimited number of files/objects in a single bucket, when you go to list a "directory" in a bucket, it will only give you the first 1000 files/objects in that bucket by default. To access all the files in a large "directory" like this, you need to make multiple calls to their API.

Convert varchar into datetime in SQL Server

I found this helpful for my conversion, without string manipulation. https://docs.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql

CONVERT(VARCHAR(23), @lastUploadEndDate, 121)

yyyy-mm-dd hh:mi:ss.mmm(24h) was the format I needed.

Image size (Python, OpenCV)

I use numpy.size() to do the same:

import numpy as np
import cv2

image = cv2.imread('image.jpg')
height = np.size(image, 0)
width = np.size(image, 1)

How to create a MySQL hierarchical recursive query?

enter image description here

It's a category table.

SELECT  id,
        NAME,
        parent_category 
FROM    (SELECT * FROM category
         ORDER BY parent_category, id) products_sorted,
        (SELECT @pv := '2') initialisation
WHERE   FIND_IN_SET(parent_category, @pv) > 0
AND     @pv := CONCAT(@pv, ',', id)

Output:: enter image description here

Check if number is prime number

This version calculates a list of primes square roots and only checks if the list of prime numbers below the square root, and uses a binarysearch in the list to find known primes. I looped through to check the first 1,000,000 primes, and it took about 7 seconds.

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

namespace ConsoleApplication5
{
    class Program
    {
        static void Main(string[] args)
        {
            //test();
            testMax();
            Console.ReadLine();
        }

        static void testMax()
        {
            List<int> CheckPrimes = Enumerable.Range(2, 1000000).ToList();
            PrimeChecker pc = new PrimeChecker(1000000);
            foreach (int i in CheckPrimes)
            {
                if (pc.isPrime(i))
                {
                    Console.WriteLine(i);
                }
            }
        }
    }

    public class PrimeChecker{
        public List<int> KnownRootPrimesList;
        public int HighestKnownPrime = 3;

        public PrimeChecker(int Max=1000000){
            KnownRootPrimesList = new List<int>();
            KnownRootPrimesList.Add(2);
            KnownRootPrimesList.Add(3);
            isPrime(Max);
        }

        public bool isPrime(int value)
        {
            int srt = Convert.ToInt32(Math.Ceiling(Math.Sqrt(Convert.ToDouble(value))));
            if(srt > HighestKnownPrime)
            {
                for(int i = HighestKnownPrime + 1; i <= srt; i++)
                {
                    if (i > HighestKnownPrime)
                    {
                        if(isPrimeCalculation(i))
                        {
                                KnownRootPrimesList.Add(i);
                                HighestKnownPrime = i;
                        }
                    }
                }
            }
            bool isValuePrime = isPrimeCalculation(value);
            return(isValuePrime);
        }

        private bool isPrimeCalculation(int value)
        {
            if (value < HighestKnownPrime)
            {
                if (KnownRootPrimesList.BinarySearch(value) > -1)
                {
                    return (true);
                }
                else
                {
                    return (false);
                }
            }
            int srt = Convert.ToInt32(Math.Ceiling(Math.Sqrt(Convert.ToDouble(value))));
            bool isPrime = true;
            List<int> CheckList = KnownRootPrimesList.ToList();
            if (HighestKnownPrime + 1 < srt)
            {
                CheckList.AddRange(Enumerable.Range(HighestKnownPrime + 1, srt));
            }
            foreach(int i in CheckList)
            {
                isPrime = ((value % i) != 0);
                if(!isPrime)
                {
                    break;
                }
            }
            return (isPrime);
        }

        public bool isPrimeStandard(int value)
        {
            int srt = Convert.ToInt32(Math.Ceiling(Math.Sqrt(Convert.ToDouble(value))));
            bool isPrime = true;
            List<int> CheckList = Enumerable.Range(2, srt).ToList();
            foreach (int i in CheckList)
            {
                isPrime = ((value % i) != 0);
                if (!isPrime)
                {
                    break;
                }
            }
            return (isPrime);
        }
    }
}

SQLite: How do I save the result of a query as a CSV file?

Good answers from gdw2 and d5e5. To make it a little simpler here are the recommendations pulled together in a single series of commands:

sqlite> .mode csv
sqlite> .output test.csv
sqlite> select * from tbl1;
sqlite> .output stdout

SQL Server date format yyyymmdd

SELECT TO_CHAR(created_at, 'YYYY-MM-DD') FROM table; //converts any date format to YYYY-MM-DD

Installing Bootstrap 3 on Rails App

gem bootstrap-sass

bootstrap-sass is easy to drop into Rails with the asset pipeline.

In your Gemfile you need to add the bootstrap-sass gem, and ensure that the sass-rails gem is present - it is added to new Rails applications by default.

gem 'sass-rails', '>= 3.2' # sass-rails needs to be higher than 3.2 gem 'bootstrap-sass', '~> 3.0.3.0'

bundle install and restart your server to make the files available through the pipeline.

Source: http://rubydoc.info/gems/bootstrap-sass/3.0.3.0/frames

Ways to circumvent the same-origin policy

AnyOrigin didn't function well with some https sites, so I just wrote an open source alternative called whateverorigin.org that seems to work well with https.

Code on github.

How to run Ruby code from terminal?

If Ruby is installed, then

ruby yourfile.rb

where yourfile.rb is the file containing the ruby code.

Or

irb

to start the interactive Ruby environment, where you can type lines of code and see the results immediately.

Simple two column html layout without using tables

I know this is an old post, but figured I'd add my two penneth. How about the seldom used and oft' forgot Description list? With a simple bit of css you can get a really clean markup.

<dl>
<dt></dt><dd></dd>
<dt></dt><dd></dd>
<dt></dt><dd></dd>
</dl>

take a look at this example http://codepen.io/butlerps/pen/wGmXPL

Pass react component as props

Using this.props.children is the idiomatic way to pass instantiated components to a react component

const Label = props => <span>{props.children}</span>
const Tab = props => <div>{props.children}</div>
const Page = () => <Tab><Label>Foo</Label></Tab>

When you pass a component as a parameter directly, you pass it uninstantiated and instantiate it by retrieving it from the props. This is an idiomatic way of passing down component classes which will then be instantiated by the components down the tree (e.g. if a component uses custom styles on a tag, but it wants to let the consumer choose whether that tag is a div or span):

const Label = props => <span>{props.children}</span>
const Button = props => {
    const Inner = props.inner; // Note: variable name _must_ start with a capital letter 
    return <button><Inner>Foo</Inner></button>
}
const Page = () => <Button inner={Label}/>

If what you want to do is to pass a children-like parameter as a prop, you can do that:

const Label = props => <span>{props.content}</span>
const Tab = props => <div>{props.content}</div>
const Page = () => <Tab content={<Label content='Foo' />} />

After all, properties in React are just regular JavaScript object properties and can hold any value - be it a string, function or a complex object.

When should a class be Comparable and/or Comparator?

If you see then logical difference between these two is Comparator in Java compare two objects provided to him, while Comparable interface compares "this" reference with the object specified.

Comparable in Java is used to implement natural ordering of object. In Java API String, Date and wrapper classes implement Comparable interface.

If any class implement Comparable interface in Java then collection of that object either List or Array can be sorted automatically by using Collections.sort() or Array.sort() method and object will be sorted based on there natural order defined by compareTo method.

Objects which implement Comparable in Java can be used as keys in a sorted map or elements in a sorted set for example TreeSet, without specifying any Comparator.

How to set focus on input field?

Here is my original solution:

plunker

var app = angular.module('plunker', []);
app.directive('autoFocus', function($timeout) {
    return {
        link: function (scope, element, attrs) {
            attrs.$observe("autoFocus", function(newValue){
                if (newValue === "true")
                    $timeout(function(){element[0].focus()});
            });
        }
    };
});

And the HTML:

<button ng-click="isVisible = !isVisible">Toggle input</button>
<input ng-show="isVisible" auto-focus="{{ isVisible }}" value="auto-focus on" />

What it does:

It focuses the input as it becomes visible with ng-show. No use of $watch or $on here.

Modulo operator with negative values

The sign in such cases (i.e when one or both operands are negative) is implementation-defined. The spec says in §5.6/4 (C++03),

The binary / operator yields the quotient, and the binary % operator yields the remainder from the division of the first expression by the second. If the second operand of / or % is zero the behavior is undefined; otherwise (a/b)*b + a%b is equal to a. If both operands are nonnegative then the remainder is nonnegative; if not, the sign of the remainder is implementation-defined.

That is all the language has to say, as far as C++03 is concerned.

6 digits regular expression

^[0-9]{1,6}$ should do it. I don't know VB.NET good enough to know if it's the same there.

For examples, have a look at the Wikipedia.

Matching an empty input box using CSS

It worked for me to add a class name to the input and then apply CSS rules to that:

<input type="text" name="product" class="product" />

<style>
input[value=""].product {
    display: none;
}
</style>

Check if URL has certain string with PHP

if( strpos( $url, $word ) !== false ) {
    // Do something
}

Regular expression to extract numbers from a string

we can use \b as a word boundary and then; \b\d+\b

jQuery checkbox check/uncheck

Use .prop() instead and if we go with your code then compare like this:

Look at the example jsbin:

  $("#news_list tr").click(function () {
    var ele = $(this).find(':checkbox');
    if ($(':checked').length) {
      ele.prop('checked', false);
      $(this).removeClass('admin_checked');
    } else {
      ele.prop('checked', true);
      $(this).addClass('admin_checked');
    }
 });

Changes:

  1. Changed input to :checkbox.
  2. Comparing the length of the checked checkboxes.

Clearing my form inputs after submission

Just include this line at the end of function and the Problem is solved easily!

document.getElementById("btnsubmit").value = "";

Convert time fields to strings in Excel

copy the column paste it into notepad copy it again paste special as Text

Expected response code 250 but got code "535", with message "535-5.7.8 Username and Password not accepted

Gmail tends to block usage of mailing addresses which are being used in other applications as username for security reasons. Either you should create a new email address for mail purpose or you must go to the Less Secure App Access and turn on the access for less secure apps. Gmail will send you a mail for confirmation from where you can verify that those changes were made by yourself. Only then, you can use such mailing addresses for mailing purpose through applications.

Find which version of package is installed with pip

import pkg_resources
packages = [dist.project_name for dist in pkg_resources.working_set]
try:
   for count, item in enumerate(packages):
      print(item, pkg_resources.get_distribution(item).version)
except:
    pass here

The indentations might not be perfect. The reason I am using a Try- Except block is that few library names will throw errors because of parsing the library names to process the versions. even though packages variable will contain all the libraries install in your environment.

How to get the name of the current Windows user in JavaScript

I think is not possible to do that. It would be a huge security risk if a browser access to that kind of personal information

Explode PHP string by new line

Try "\n\r" (double quotes) or just "\n".

If you're not sure which type of EOL you have, run a str_replace before your explode, replacing "\n\r" with "\n".

What's the most efficient way to erase duplicates and sort a vector?

std::unique only works on consecutive runs of duplicate elements, so you'd better sort first. However, it is stable, so your vector will remain sorted.

getting error HTTP Status 405 - HTTP method GET is not supported by this URL but not used `get` ever?

Override service method like this:

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

And Voila!

Parser Error Message: Could not load type 'TestMvcApplication.MvcApplication'

My problem was that I was trying to create a ASPX web application in a subfolder of a folder that already had a web.config file, and

So I opened up the parent folder in Visual Studio as a Web Site (Open > Web Site) I was able to add a new item ASPX page that had no issue parsing/loading.

How is using "<%=request.getContextPath()%>" better than "../"

request.getContextPath()- returns root path of your application, while ../ - returns parent directory of a file.

You use request.getContextPath(), as it will always points to root of your application. If you were to move your jsp file from one directory to another, nothing needs to be changed. Now, consider the second approach. If you were to move your jsp files from one folder to another, you'd have to make changes at every location where you are referring your files.

Also, better approach of using request.getContextPath() will be to set 'request.getContextPath()' in a variable and use that variable for referring your path.

<c:set var="context" value="${pageContext.request.contextPath}" />
<script src="${context}/themes/js/jquery.js"></script>

PS- This is the one reason I can figure out. Don't know if there is any more significance to it.

How do getters and setters work?

Tutorial is not really required for this. Read up on encapsulation

private String myField; //"private" means access to this is restricted

public String getMyField()
{
     //include validation, logic, logging or whatever you like here
    return this.myField;
}
public void setMyField(String value)
{
     //include more logic
     this.myField = value;
}

How to prevent sticky hover effects for buttons on touch devices

From 4 ways to deal with sticky hover on mobile: Here's a way to dynamically add or remove a "can touch" class to the document based on the current input type of the user. It works with hybrid devices as well where the user may be switching between touch and a mouse/trackpad:

<script>

;(function(){
    var isTouch = false //var to indicate current input type (is touch versus no touch) 
    var isTouchTimer 
    var curRootClass = '' //var indicating current document root class ("can-touch" or "")

    function addtouchclass(e){
        clearTimeout(isTouchTimer)
        isTouch = true
        if (curRootClass != 'can-touch'){ //add "can-touch' class if it's not already present
            curRootClass = 'can-touch'
            document.documentElement.classList.add(curRootClass)
        }
        isTouchTimer = setTimeout(function(){isTouch = false}, 500) //maintain "istouch" state for 500ms so removetouchclass doesn't get fired immediately following a touch event
    }

    function removetouchclass(e){
        if (!isTouch && curRootClass == 'can-touch'){ //remove 'can-touch' class if not triggered by a touch event and class is present
            isTouch = false
            curRootClass = ''
            document.documentElement.classList.remove('can-touch')
        }
    }

    document.addEventListener('touchstart', addtouchclass, false) //this event only gets called when input type is touch
    document.addEventListener('mouseover', removetouchclass, false) //this event gets called when input type is everything from touch to mouse/ trackpad
})();

</script>

RestTemplate: How to send URL and query parameters together

One simple way to do that is:

String url = "http://test.com/Services/rest/{id}/Identifier"

UriComponents uriComponents = UriComponentsBuilder.fromUriString(url).build();
uriComponents = uriComponents.expand(Collections.singletonMap("id", "1234"));

and then adds the query params.

tar: add all files and directories in current directory INCLUDING .svn and so on

If disk space space is not an issue, this could also be a very easy thing to do:

mkdir backup
cp -r ./* backup
tar -zcvf backup.tar.gz ./backup

How can I select random files from a directory in bash?

A simple solution for selecting 5 random files while avoiding to parse ls. It also works with files containing spaces, newlines and other special characters:

shuf -ezn 5 * | xargs -0 -n1 echo

Replace echo with the command you want to execute for your files.

How to give color to each class in scatter plot in R?

Here is a solution using traditional graphics (and Dirk's data):

> DF <- data.frame(x=1:10, y=rnorm(10)+5, z=sample(letters[1:3], 10, replace=TRUE)) 
> DF
    x        y z
1   1 6.628380 c
2   2 6.403279 b
3   3 6.708716 a
4   4 7.011677 c
5   5 6.363794 a
6   6 5.912945 b
7   7 2.996335 a
8   8 5.242786 c
9   9 4.455582 c
10 10 4.362427 a
> attach(DF); plot(x, y, col=c("red","blue","green")[z]); detach(DF)

This relies on the fact that DF$z is a factor, so when subsetting by it, its values will be treated as integers. So the elements of the color vector will vary with z as follows:

> c("red","blue","green")[DF$z]
 [1] "green" "blue"  "red"   "green" "red"   "blue"  "red"   "green" "green" "red"    

You can add a legend using the legend function:

legend(x="topright", legend = levels(DF$z), col=c("red","blue","green"), pch=1)

How to get request URI without context path?

With Spring you can do:

String path = new UrlPathHelper().getPathWithinApplication(request);

Including external HTML file to another HTML file

Another way is to use the object tag. This works on Chrome, IE, Firefox, Safari and Opera.

<object data="html/stuff_to_include.html"> 
    Your browser doesn’t support the object tag. 
</object>

more info at http://www.w3schools.com/tags/tag_object.asp

Hide Command Window of .BAT file that Executes Another .EXE File

Using Windows API we can start new process, a console application, and hide its "black" window. This can be done at process creation and avoid showing "black" window at all.

In CreateProcess function the dwCreationFlags parameter can have CREATE_NO_WINDOW flag:

The process is a console application that is being run
without a console window. Therefore, the console handle
for the application is not set. This flag is ignored if
the application is not a console application

Here is a link to hide-win32-console-window executable using this method and source code.

hide-win32-console-window is similar to Jamesdlin's silentbatch program.

There is open question: what to do with program's output when its window does not exist? What if exceptions happen? Not a good solution to throw away the output. hide-win32-console-window uses anonymous pipes to redirect program's output to file created in current directory.

Usage

batchscript_starter.exe full/path/to/application [arguments to pass on]

Example running python script

batchscript_starter.exe c:\Python27\python.exe -c "import time; print('prog start'); time.sleep(3.0); print('prog end');"

The output file is created in working directory named python.2019-05-13-13-32-39.log with output from the python command:

prog start
prog end

Example running command

batchscript_starter.exe C:\WINDOWS\system32\cmd.exe /C dir .

The output file is created in working directory named cmd.2019-05-13-13-37-28.log with output from CMD:

 Volume in drive Z is Storage
 Volume Serial Number is XXXX-YYYY

 Directory of hide_console_project\hide-win32-console-window

2019-05-13  13:37    <DIR>          .
2019-05-13  13:37    <DIR>          ..
2019-05-13  04:41            17,274 batchscript_starter.cpp
2018-04-10  01:08            46,227 batchscript_starter.ico
2019-05-12  11:27             7,042 batchscript_starter.rc
2019-05-12  11:27             1,451 batchscript_starter.sln
2019-05-12  21:51             8,943 batchscript_starter.vcxproj
2019-05-12  21:51             1,664 batchscript_starter.vcxproj.filters
2019-05-13  03:38             1,736 batchscript_starter.vcxproj.user
2019-05-13  13:37                 0 cmd.2019-05-13-13-37-28.log
2019-05-13  04:34             1,518 LICENSE
2019-05-13  13:32                22 python.2019-05-13-13-32-39.log
2019-05-13  04:55                82 README.md
2019-05-13  04:44             1,562 Resource.h
2018-04-10  01:08            46,227 small.ico
2019-05-13  04:44               630 targetver.h
2019-05-13  04:57    <DIR>          x64
              14 File(s)        134,378 bytes
               3 Dir(s)  ???,???,692,992 bytes free

Example shortcut for running .bat script

Shortcut for starting windowless .bat file

Target field:

C:\batchscript_starter.exe C:\WINDOWS\system32\cmd.exe /C C:\start_wiki.bat

Directory specified in Start in field will hold output files.

Override element.style using CSS

Use JavaScript.

For example:

var elements = document.getElementById("demoFour").getElementsByTagName("li");
for (var i = 0; i < elements.length; i++) {
    elements[i].style.display = "inline";
}

How can I set the maximum length of 6 and minimum length of 6 in a textbox?

You can use the HTML5 pattern attribute or use JavaScript.

The pattern could look for example like this:

<input id="groupidtext" type="text" pattern="(.){6,6}" style="width: 100px;" maxlength="6" />

But the pattern attribute will only work with HTML5 browsers. For old browsers you'll need JavaScript.

As suggested in the comments to add, this will only work as soon as a form is about to be submitted. If this input is not in a form and you need validation as a user types, use JavaScript.

Cheap way to search a large text file for a string

The following function works for textfiles and binary files (returns only position in byte-count though), it does have the benefit to find strings even if they would overlap a line or buffer and would not be found when searching line- or buffer-wise.

def fnd(fname, s, start=0):
    with open(fname, 'rb') as f:
        fsize = os.path.getsize(fname)
        bsize = 4096
        buffer = None
        if start > 0:
            f.seek(start)
        overlap = len(s) - 1
        while True:
            if (f.tell() >= overlap and f.tell() < fsize):
                f.seek(f.tell() - overlap)
            buffer = f.read(bsize)
            if buffer:
                pos = buffer.find(s)
                if pos >= 0:
                    return f.tell() - (len(buffer) - pos)
            else:
                return -1

The idea behind this is:

  • seek to a start position in file
  • read from file to buffer (the search strings has to be smaller than the buffer size) but if not at the beginning, drop back the - 1 bytes, to catch the string if started at the end of the last read buffer and continued on the next one.
  • return position or -1 if not found

I used something like this to find signatures of files inside larger ISO9660 files, which was quite fast and did not use much memory, you can also use a larger buffer to speed things up.

Setting background-image using jQuery CSS property

Try modifying the "style" attribute:

$('myObject').attr('style', 'background-image: url("' + imageUrl +'")');

List comprehension vs map

enter image description here

Image Source: Experfy

You can see for yourself which is better between - List Comprehension and the Map Function

(List Comprehension takes lesser time to process 1 million records when compared to a map function)

Hope it helps! Good Luck :)

MySQL JOIN ON vs USING?

Wikipedia has the following information about USING:

The USING construct is more than mere syntactic sugar, however, since the result set differs from the result set of the version with the explicit predicate. Specifically, any columns mentioned in the USING list will appear only once, with an unqualified name, rather than once for each table in the join. In the case above, there will be a single DepartmentID column and no employee.DepartmentID or department.DepartmentID.

Tables that it was talking about:

enter image description here

The Postgres documentation also defines them pretty well:

The ON clause is the most general kind of join condition: it takes a Boolean value expression of the same kind as is used in a WHERE clause. A pair of rows from T1 and T2 match if the ON expression evaluates to true.

The USING clause is a shorthand that allows you to take advantage of the specific situation where both sides of the join use the same name for the joining column(s). It takes a comma-separated list of the shared column names and forms a join condition that includes an equality comparison for each one. For example, joining T1 and T2 with USING (a, b) produces the join condition ON T1.a = T2.a AND T1.b = T2.b.

Furthermore, the output of JOIN USING suppresses redundant columns: there is no need to print both of the matched columns, since they must have equal values. While JOIN ON produces all columns from T1 followed by all columns from T2, JOIN USING produces one output column for each of the listed column pairs (in the listed order), followed by any remaining columns from T1, followed by any remaining columns from T2.

tomcat - CATALINA_BASE and CATALINA_HOME variables

CATALINA_BASE is optional.

However, in the following scenarios it helps to setup CATALINA_BASE that is separate from CATALINA_HOME.

  1. When more than 1 instances of tomcat are running on same host

    • This helps have only 1 runtime of tomcat installation, with multiple CATALINA_BASE server configurations running on separate ports.
    • If any patching, or version upgrade needs be, only 1 installation changes required, or need to be tested/verified/signed-off.
  2. Separation of concern (Single responsibility)

    • Tomcat runtime is standard and does not change during every release process. i.e. Tomcat binaries
    • Release process may add more stuff as webapplication (webapps folder), environment configuration (conf directory), logs/temp/work directory

Alternative for <blink>

Here's some code that'll substitute for the blink tag

<p id="blink">This text will blink!</p>
<script>
var blacktime = 1000;
var whitetime = 1000;
//These can be as long as you desire in milliseconds
setTimeout(whiteFunc,blacktime);
function whiteFunc(){
    document.getElementById("blink").style.color = "white";
    setTimeout(blackFunc,whitetime);
}
function blackFunc(){
    document.getElementById("blink").style.color = "black";
    setTimeout(whiteFunc,blacktime);
}
</script>

How do I use 3DES encryption/decryption in Java?

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.IvParameterSpec;
import java.util.Base64;
import java.util.Base64.Encoder;


/**
 * 
 * @author shivshankar pal
 * 
 *         this code is working properly. doing proper encription and decription
           note:- it will work only with jdk8

 * 

 * 
 */

public class TDes {
    private static byte[] key = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x02, 0x02,
            0x02, 0x02, 0x02, 0x02, 0x02, 0x02 };

    private static byte[] keyiv = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00 };



     public static String encode(String args) {


        System.out.println("plain data==>  " + args);

        byte[] encoding;
        try {
            encoding = Base64.getEncoder().encode(args.getBytes("UTF-8"));

        System.out.println("Base64.encodeBase64==>" + new String(encoding));
        byte[] str5 = des3EncodeCBC(key, keyiv, encoding);

        System.out.println("des3EncodeCBC==>  " + new String(str5));

        byte[] encoding1 = Base64.getEncoder().encode(str5);
        System.out.println("Base64.encodeBase64==> " + new String(encoding1));
        return new String(encoding1);
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }


    public static String decode(String args) {
        try {
            System.out.println("encrypted data==>" + new String(args.getBytes("UTF-8")));


        byte[] decode = Base64.getDecoder().decode(args.getBytes("UTF-8"));
        System.out.println("Base64.decodeBase64(main encription)==>" + new String(decode));

        byte[] str6 = des3DecodeCBC(key, keyiv, decode);
        System.out.println("des3DecodeCBC==>" + new String(str6));
        String data=new String(str6);
        byte[] decode1 = Base64.getDecoder().decode(data.trim().getBytes("UTF-8"));
        System.out.println("plaintext==>  " + new String(decode1));
        return new String(decode1);
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return "u mistaken in try block";

        }



    private static byte[] des3EncodeCBC(byte[] key, byte[] keyiv, byte[] data) {
        try {
            Key deskey = null;
            DESedeKeySpec spec = new DESedeKeySpec(key);
            SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");
            deskey = keyfactory.generateSecret(spec);

            Cipher cipher = Cipher.getInstance("desede/ CBC/PKCS5Padding");
            IvParameterSpec ips = new IvParameterSpec(keyiv);
            cipher.init(Cipher.ENCRYPT_MODE, deskey, ips);
            byte[] bout = cipher.doFinal(data);
            return bout;

        } catch (Exception e) {
            System.out.println("methods qualified name" + e);
        }
        return null;

    }

    private static byte[] des3DecodeCBC(byte[] key, byte[] keyiv, byte[] data) {
        try {
            Key deskey = null;
            DESedeKeySpec spec = new DESedeKeySpec(key);
            SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");
            deskey = keyfactory.generateSecret(spec);

            Cipher cipher = Cipher.getInstance("desede/ CBC/NoPadding");//PKCS5Padding NoPadding
            IvParameterSpec ips = new IvParameterSpec(keyiv);
            cipher.init(Cipher.DECRYPT_MODE, deskey, ips);

            byte[] bout = cipher.doFinal(data);


            return bout;

        } catch (Exception e) {
            System.out.println("methods qualified name" + e);
        }

        return null;

    }

}

What does `void 0` mean?

void 0 returns undefined and can not be overwritten while undefined can be overwritten.

var undefined = "HAHA";

belongs_to through associations

You can also delegate:

class Company < ActiveRecord::Base
  has_many :employees
  has_many :dogs, :through => :employees
end

class Employee < ActiveRescord::Base
  belongs_to :company
  has_many :dogs
end

class Dog < ActiveRecord::Base
  belongs_to :employee

  delegate :company, :to => :employee, :allow_nil => true
end

Spark read file from S3 using sc.textFile ("s3n://...)

Confirmed that this is related to the Spark build against Hadoop 2.60. Just installed Spark 1.4.0 "Pre built for Hadoop 2.4 and later" (instead of Hadoop 2.6). And the code now works OK.

sc.textFile("s3n://bucketname/Filename") now raises another error:

java.lang.IllegalArgumentException: AWS Access Key ID and Secret Access Key must be specified as the username or password (respectively) of a s3n URL, or by setting the fs.s3n.awsAccessKeyId or fs.s3n.awsSecretAccessKey properties (respectively).

The code below uses the S3 URL format to show that Spark can read S3 file. Using dev machine (no Hadoop libs).

scala> val lyrics = sc.textFile("s3n://MyAccessKeyID:MySecretKey@zpub01/SafeAndSound_Lyrics.txt")
lyrics: org.apache.spark.rdd.RDD[String] = MapPartitionsRDD[3] at textFile at <console>:21

scala> lyrics.count
res1: Long = 9

Even Better: the code above with AWS credentials inline in the S3N URI will break if the AWS Secret Key has a forward "/". Configuring AWS Credentials in SparkContext will fix it. Code works whether the S3 file is public or private.

sc.hadoopConfiguration.set("fs.s3n.awsAccessKeyId", "BLABLA")
sc.hadoopConfiguration.set("fs.s3n.awsSecretAccessKey", "....") // can contain "/"
val myRDD = sc.textFile("s3n://myBucket/MyFilePattern")
myRDD.count

Allow user to select camera or gallery for image

How to launch a single Intent to select images from either the Gallery or the Camera, or any application registered to browse the filesystem.

Rather than creating a Dialog with a list of Intent options, it is much better to use Intent.createChooser in order to get access to the graphical icons and short names of the various 'Camera', 'Gallery' and even Third Party filesystem browser apps such as 'Astro', etc.

This describes how to use the standard chooser-intent and add additional intents to that.

private Uri outputFileUri;

private void openImageIntent() {

    // Determine Uri of camera image to save.
    final File root = new File(Environment.getExternalStorageDirectory() + File.separator + "MyDir" + File.separator);
    root.mkdirs();
    final String fname = Utils.getUniqueImageFilename();
    final File sdImageMainDirectory = new File(root, fname);
    outputFileUri = Uri.fromFile(sdImageMainDirectory);

    // Camera.
    final List<Intent> cameraIntents = new ArrayList<Intent>();
    final Intent captureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
    final PackageManager packageManager = getPackageManager();
    final List<ResolveInfo> listCam = packageManager.queryIntentActivities(captureIntent, 0);
    for(ResolveInfo res : listCam) {
        final String packageName = res.activityInfo.packageName;
        final Intent intent = new Intent(captureIntent);
        intent.setComponent(new ComponentName(packageName, res.activityInfo.name));
        intent.setPackage(packageName);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
        cameraIntents.add(intent);
    }

    // Filesystem.
    final Intent galleryIntent = new Intent();
    galleryIntent.setType("image/*");
    galleryIntent.setAction(Intent.ACTION_GET_CONTENT);

    // Chooser of filesystem options.
    final Intent chooserIntent = Intent.createChooser(galleryIntent, "Select Source");

    // Add the camera options.
    chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, cameraIntents.toArray(new Parcelable[cameraIntents.size()]));

    startActivityForResult(chooserIntent, YOUR_SELECT_PICTURE_REQUEST_CODE);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == RESULT_OK) {
        if (requestCode == YOUR_SELECT_PICTURE_REQUEST_CODE) {
            final boolean isCamera;
            if (data == null) {
                isCamera = true;
            } else {
                final String action = data.getAction();
                if (action == null) {
                    isCamera = false;
                } else {
                    isCamera = action.equals(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                }
            }

            Uri selectedImageUri;
            if (isCamera) {
                selectedImageUri = outputFileUri;
            } else {
                selectedImageUri = data == null ? null : data.getData();
            }
        }
    }
}

Secondary axis with twinx(): how to add to legend?

I found an following official matplotlib example that uses host_subplot to display multiple y-axes and all the different labels in one legend. No workaround necessary. Best solution I found so far. http://matplotlib.org/examples/axes_grid/demo_parasite_axes2.html

from mpl_toolkits.axes_grid1 import host_subplot
import mpl_toolkits.axisartist as AA
import matplotlib.pyplot as plt

host = host_subplot(111, axes_class=AA.Axes)
plt.subplots_adjust(right=0.75)

par1 = host.twinx()
par2 = host.twinx()

offset = 60
new_fixed_axis = par2.get_grid_helper().new_fixed_axis
par2.axis["right"] = new_fixed_axis(loc="right",
                                    axes=par2,
                                    offset=(offset, 0))

par2.axis["right"].toggle(all=True)

host.set_xlim(0, 2)
host.set_ylim(0, 2)

host.set_xlabel("Distance")
host.set_ylabel("Density")
par1.set_ylabel("Temperature")
par2.set_ylabel("Velocity")

p1, = host.plot([0, 1, 2], [0, 1, 2], label="Density")
p2, = par1.plot([0, 1, 2], [0, 3, 2], label="Temperature")
p3, = par2.plot([0, 1, 2], [50, 30, 15], label="Velocity")

par1.set_ylim(0, 4)
par2.set_ylim(1, 65)

host.legend()

plt.draw()
plt.show()