Programs & Examples On #Mkfifo

Which HTTP methods match up to which CRUD methods?

Create = PUT with a new URI
         POST to a base URI returning a newly created URI
Read   = GET
Update = PUT with an existing URI
Delete = DELETE

PUT can map to both Create and Update depending on the existence of the URI used with the PUT.

POST maps to Create.

Correction: POST can also map to Update although it's typically used for Create. POST can also be a partial update so we don't need the proposed PATCH method.

Comments in .gitignore?

Yes, you may put comments in there. They however must start at the beginning of a line.

cf. http://git-scm.com/book/en/Git-Basics-Recording-Changes-to-the-Repository#Ignoring-Files

The rules for the patterns you can put in the .gitignore file are as follows:
- Blank lines or lines starting with # are ignored.
[…]

The comment character is #, example:

# no .a files
*.a

Enable UTF-8 encoding for JavaScript

The encoding for the page is not set correctly. Either add a header

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

or use set the appropriate http header.

Content-Type:text/html; charset=UTF-8

Firefox also allows you to change the encoding in View -> Character encoding.

If that's ok, I think javascript should handle UTF8 just fine.

Converting URL to String and back again

There is a nicer way of getting the string version of the path from the NSURL in Swift:

let path:String = url.path

What is the difference between join and merge in Pandas?

  • Join: Default Index (If any same column name then it will throw an error in default mode because u have not defined lsuffix or rsuffix))
df_1.join(df_2)
  • Merge: Default Same Column Names (If no same column name it will throw an error in default mode)
df_1.merge(df_2)
  • on parameter has different meaning in both cases
df_1.merge(df_2, on='column_1')

df_1.join(df_2, on='column_1') // It will throw error
df_1.join(df_2.set_index('column_1'), on='column_1')

Checking if a file is a directory or just a file

You can call the stat() function and use the S_ISREG() macro on the st_mode field of the stat structure in order to determine if your path points to a regular file:

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

int is_regular_file(const char *path)
{
    struct stat path_stat;
    stat(path, &path_stat);
    return S_ISREG(path_stat.st_mode);
}

Note that there are other file types besides regular and directory, like devices, pipes, symbolic links, sockets, etc. You might want to take those into account.

pip connection failure: cannot fetch index base URL http://pypi.python.org/simple/

I tried almost all answers and nothing fix my error, so I just reinstall python (in my case I have version 2.7.9 and I install 2.7.15) and the error finally fixed. No need to uninstall python first, the installer do it for you.

How do I import .sql files into SQLite 3?

You can also do:

sqlite3 database.db -init dump.sql

How to make a .jar out from an Android Studio project

task deleteJar(type: Delete) {
    delete 'libs/mylibrary.jar'
}           

task exportjar(type: Copy) {
    from('build/intermediates/compile_library_classes/release/')
    into('libs/')
    include('classes.jar')
    rename('classes.jar', 'mylibrary.jar')
}

exportjar.dependsOn(deleteJar, build)

How to change text color of simple list item

The simplest way to do this without needing to create anything extra would be to just modify the simple list TextView:

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, android.R.id.text1, strings) {
            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                TextView textView = (TextView) super.getView(position, convertView, parent);
                textView.setTextColor({YourColorHere});
                return textView;
            }
        };

Python: CSV write by column rather than row

The reason csv doesn't support that is because variable-length lines are not really supported on most filesystems. What you should do instead is collect all the data in lists, then call zip() on them to transpose them after.

>>> l = [('Result_1', 'Result_2', 'Result_3', 'Result_4'), (1, 2, 3, 4), (5, 6, 7, 8)]
>>> zip(*l)
[('Result_1', 1, 5), ('Result_2', 2, 6), ('Result_3', 3, 7), ('Result_4', 4, 8)]

How do I check what version of Python is running my script?

A attempt using os.popen to read it in a variable:

import os
ver = os.popen('python -V').read().strip()
print(ver)

$http.get(...).success is not a function

The .success syntax was correct up to Angular v1.4.3.

For versions up to Angular v.1.6, you have to use then method. The then() method takes two arguments: a success and an error callback which will be called with a response object.

Using the then() method, attach a callback function to the returned promise.

Something like this:

app.controller('MainCtrl', function ($scope, $http){
   $http({
      method: 'GET',
      url: 'api/url-api'
   }).then(function (response){

   },function (error){

   });
}

See reference here.

Shortcut methods are also available.

$http.get('api/url-api').then(successCallback, errorCallback);

function successCallback(response){
    //success code
}
function errorCallback(error){
    //error code
}

The data you get from the response is expected to be in JSON format. JSON is a great way of transporting data, and it is easy to use within AngularJS

The major difference between the 2 is that .then() call returns a promise (resolved with a value returned from a callback) while .success() is more traditional way of registering callbacks and doesn't return a promise.

Calculating bits required to store decimal number

Ok to generalize the technique of how many bits you need to represent a number is done this way. You have R symbols for a representation and you want to know how many bits, solve this equation R=2^n or log2(R)=n. Where n is the numbers of bits and R is the number of symbols for the representation.

For the decimal number system R=9 so we solve 9=2^n, the answer is 3.17 bits per decimal digit. Thus a 3 digit number will need 9.51 bits or 10. A 1000 digit number needs 3170 bits

Npm install failed with "cannot run in wd"

The documentation says (also here):

If npm was invoked with root privileges, then it will change the uid to the user account or uid specified by the user config, which defaults to nobody. Set the unsafe-perm flag to run scripts with root privileges.

Your options are:

  1. Run npm install with the --unsafe-perm flag:

    [sudo] npm install --unsafe-perm
    
  2. Add the unsafe-perm flag to your package.json:

    "config": {
        "unsafe-perm":true
    }
    
  3. Don't use the preinstall script to install global modules, install them separately and then run the regular npm install without root privileges:

    sudo npm install -g coffee-script node-gyp
    npm install
    

Related:

cURL equivalent in Node.js?

Since looks like node-curl is dead, I've forked it, renamed, and modified to be more curl like and to compile under Windows.

node-libcurl

Usage example:

var Curl = require( 'node-libcurl' ).Curl;

var curl = new Curl();

curl.setOpt( Curl.option.URL, 'www.google.com' );
curl.setOpt( 'FOLLOWLOCATION', true );

curl.on( 'end', function( statusCode, body, headers ) {

    console.info( statusCode );
    console.info( '---' );
    console.info( body.length );
    console.info( '---' );
    console.info( headers );
    console.info( '---' );
    console.info( this.getInfo( Curl.info.TOTAL_TIME ) );

    this.close();
});

curl.on( 'error', function( err, curlErrorCode ) {

    console.error( err.message );
    console.error( '---' );
    console.error( curlErrorCode );

    this.close();

});

curl.perform();

Perform is async, and there is no way to use it synchronous currently (and probably will never have).

It's still in alpha, but this is going to change soon, and help is appreciated.

Now it's possible to use Easy handle directly for sync requests, example:

var Easy = require( 'node-libcurl' ).Easy,
    Curl = require( 'node-libcurl' ).Curl,
    url = process.argv[2] || 'http://www.google.com',
    ret, ch;

ch = new Easy();

ch.setOpt( Curl.option.URL, url );

ch.setOpt( Curl.option.HEADERFUNCTION, function( buf, size, nmemb ) {

    console.log( buf );

    return size * nmemb;
});

ch.setOpt( Curl.option.WRITEFUNCTION, function( buf, size, nmemb ) {

    console.log( arguments );

    return size * nmemb;
});

// this call is sync!
ret = ch.perform();

ch.close();

console.log( ret, ret == Curl.code.CURLE_OK, Easy.strError( ret ) );

Also, the project is stable now!

Set the selected index of a Dropdown using jQuery

You want to grab the value of the first option in the select element.

$("*[id$='" + originalId + "']").val($("*[id$='" + originalId + "'] option:first").attr('value'));

Write to rails console

I think you should use the Rails debug options:

logger.debug "Person attributes hash: #{@person.attributes.inspect}"
logger.info "Processing the request..."
logger.fatal "Terminating application, raised unrecoverable error!!!"

https://guides.rubyonrails.org/debugging_rails_applications.html

How to print a dictionary line by line in Python?

You could use the json module for this. The dumps function in this module converts a JSON object into a properly formatted string which you can then print.

import json

cars = {'A':{'speed':70, 'color':2},
        'B':{'speed':60, 'color':3}}

print(json.dumps(cars, indent = 4))

The output looks like

{
    "A": {
        "color": 2,
        "speed": 70
    },
    "B": {
        "color": 3,
        "speed": 60
    }
}

The documentation also specifies a bunch of useful options for this method.

Best way to check if a URL is valid

if anyone is interested to use the cURL for validation. You can use the following code.

<?php 
public function validationUrl($Url){
        if ($Url == NULL){
            return $false;
        }
        $ch = curl_init($Url);
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $data = curl_exec($ch);
        $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        return ($httpcode >= 200 && $httpcode < 300) ? true : false; 
    }

How get value from URL

You can access those values with the global $_GET variable

//www.example.com/index.php?id=7
print $_GET['id']; // prints "7"

You should check all "incoming" user data - so here, that "id" is an INT. Don't use it directly in your SQL (vulnerable to SQL injections).

How to find Port number of IP address?

 domain = self.env['ir.config_parameter'].get_param('web.base.url')

I got the hostname and port number using this.

Java enum with multiple value types

First, the enum methods shouldn't be in all caps. They are methods just like other methods, with the same naming convention.

Second, what you are doing is not the best possible way to set up your enum. Instead of using an array of values for the values, you should use separate variables for each value. You can then implement the constructor like you would any other class.

Here's how you should do it with all the suggestions above:

public enum States {
    ...
    MASSACHUSETTS("Massachusetts",  "MA",   true),
    MICHIGAN     ("Michigan",       "MI",   false),
    ...; // all 50 of those

    private final String full;
    private final String abbr;
    private final boolean originalColony;

    private States(String full, String abbr, boolean originalColony) {
        this.full = full;
        this.abbr = abbr;
        this.originalColony = originalColony;
    }

    public String getFullName() {
        return full;
    }

    public String getAbbreviatedName() {
        return abbr;
    }

    public boolean isOriginalColony(){
        return originalColony;
    }
}

Disable form autofill in Chrome without disabling autocomplete

After a lot of struggle, I have found that the solution is a lot more simple that you could imagine:

Instead of autocomplete="off" just simply use autocomplete="false" ;)

Try this...

$(document).ready(function () {
    $('input').attr('autocomplete', 'false');
});

How do I send an HTML Form in an Email .. not just MAILTO

> 2020 Answer = The Easy Way using Google Apps Script (5 Mins)

We had a similar challenge to solve yesterday, and we solved it using a Google Apps Script!

Send Email From an HTML Form Without a Backend (Server) via Google!

The solution takes 5 mins to implement and I've documented with step-by-step instructions: https://github.com/nelsonic/html-form-send-email-via-google-script-without-server

Brief Overview

A. Using the sample script, deploy a Google App Script

Deploy the sample script as a Google Spreadsheet APP Script: google-script-just-email.js

3-script-editor-showing-script

remember to set the TO_ADDRESS in the script to where ever you want the emails to be sent.
and copy the APP URL so you can use it in the next step when you publish the script.

B. Create your HTML Form and Set the action to the App URL

Using the sample html file: index.html create a basic form.

7-html-form

remember to paste your APP URL into the form action in the HTML form.

C. Test the HTML Form in your Browser

Open the HTML Form in your Browser, Input some data & submit it!

html form

Submit the form. You should see a confirmation that it was sent: form sent

Open the inbox for the email address you set (above)

email received

Done.

Everything about this is customisable, you can easily style/theme the form with your favourite CSS Library and Store the submitted data in a Google Spreadsheet for quick analysis.
The complete instructions are available on GitHub:
https://github.com/nelsonic/html-form-send-email-via-google-script-without-server

Convert a String to Modified Camel Case in Java or Title Case as is otherwise called

Refer:

    static String toCamelCase(String s){
           String[] parts = s.split(" ");
           String camelCaseString = "";
           for (String part : parts){
               if(part!=null && part.trim().length()>0)
              camelCaseString = camelCaseString + toProperCase(part);
               else
                   camelCaseString=camelCaseString+part+" ";   
           }
           return camelCaseString;
        }

        static String toProperCase(String s) {
            String temp=s.trim();
            String spaces="";
            if(temp.length()!=s.length())
            {
            int startCharIndex=s.charAt(temp.indexOf(0));
            spaces=s.substring(0,startCharIndex);
            }
            temp=temp.substring(0, 1).toUpperCase() +
            spaces+temp.substring(1).toLowerCase()+" ";
            return temp;

        }
  public static void main(String[] args) {
     String string="HI tHiS is   SomE Statement";
     System.out.println(toCamelCase(string));
  }

How can I reload .emacs after changing it?

solution

M-: (load user-init-file)


notes

  • you type it in Eval: prompt (including the parentheses)
  • user-init-file is a variable holding the ~/.emacs value (pointing to the configuration file path) by default
  • (load) is shorter, older, and non-interactive version of (load-file); it is not an emacs command (to be typed in M-x) but a mere elisp function

conclusion

M-: > M-x

Update a column in MySQL

UPDATE table1 SET col_a = 'newvalue'

Add a WHERE condition if you want to only update some of the rows.

Getting the URL of the current page using Selenium WebDriver

Put sleep. It will work. I have tried. The reason is that the page wasn't loaded yet. Check this question to know how to wait for load - Wait for page load in Selenium

Catching FULL exception message

I found it!

Simply print out $Error[0] for the last error message.

How to override Bootstrap's Panel heading background color?

You can create a custom class for your panel heading. Using this css class you can style the panel heading. I have a simple Fiddle for this.

HTML:

<div class="panel panel-default">
   <div class="panel-heading panel-heading-custom">
       <h3 class="panel-title">Panel title</h3>
   </div>
   <div class="panel-body">
       Panel content
   </div>
</div>

CSS:

.panel-default > .panel-heading-custom {
background: #ff0000; color: #fff; }

Demo Link:

http://jsfiddle.net/kiranvarthi/t1Lq966k/

What is the documents directory (NSDocumentDirectory)?

You can access documents directory using this code it is basically used for storing file in plist format:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths firstObject];
return documentsDirectory;

Delete commits from a branch in Git

In my case, my magic code for this pupose is this one:

git reset --hard @{u}

Test it and tell me. I have tried a few different ones, but this one was the only that helped me.

How to convert an int value to string in Go?

Use the strconv package's Itoa function.

For example:

package main

import (
    "strconv"
    "fmt"
)

func main() {
    t := strconv.Itoa(123)
    fmt.Println(t)
}

You can concat strings simply by +'ing them, or by using the Join function of the strings package.

Changing navigation bar color in Swift

Here are some very basic appearance customization that you can apply app wide:

UINavigationBar.appearance().backgroundColor = UIColor.greenColor()
UIBarButtonItem.appearance().tintColor = UIColor.magentaColor()
//Since iOS 7.0 UITextAttributeTextColor was replaced by NSForegroundColorAttributeName
UINavigationBar.appearance().titleTextAttributes = [UITextAttributeTextColor: UIColor.blueColor()]
UITabBar.appearance().backgroundColor = UIColor.yellowColor();

More about UIAppearance API in Swift you can read here: https://developer.apple.com/documentation/uikit/uiappearance

Passing arrays as parameters in bash

function aecho {
  set "$1[$2]"
  echo "${!1}"
}

Example

$ foo=(dog cat bird)

$ aecho foo 1
cat

Angular2 - Http POST request parameters

so just to make it a complete answer:

login(username, password) {
        var headers = new Headers();
        headers.append('Content-Type', 'application/x-www-form-urlencoded');
        let urlSearchParams = new URLSearchParams();
        urlSearchParams.append('username', username);
        urlSearchParams.append('password', password);
        let body = urlSearchParams.toString()
        return this.http.post('http://localHost:3000/users/login', body, {headers:headers})
            .map((response: Response) => {
                // login successful if there's a jwt token in the response
                console.log(response);
                var body = response.json();
                console.log(body);
                if (body.response){
                    let user = response.json();
                    if (user && user.token) {
                        // store user details and jwt token in local storage to keep user logged in between page refreshes
                        localStorage.setItem('currentUser', JSON.stringify(user)); 
                    }
                }
                else{
                    return body;
                }
            });
    }

Symbolicating iPhone App Crash Reports

Using Xcode 4, the task is even simpler:

  • open Organizer,
  • click on Library | Device Log in the left column
  • click on "Import" button on the bottom of the screen...

and voilà. The log file is imported and Symbolized automatically for you. Provided you Archived the build using Xcode -> Product -> Archive first.

How to generate javadoc comments in Android Studio

  • Another way to add java docs comment is press : Ctrl + Shift + A >> show a popup >> type : Add javadocs >> Enter .

  • Ctrl + Shirt + A: Command look-up (autocomplete command name)

enter image description here

How to modify list entries during for loop?

Since the loop below only modifies elements already seen, it would be considered acceptable:

a = ['a',' b', 'c ', ' d ']

for i, s in enumerate(a):
    a[i] = s.strip()

print(a) # -> ['a', 'b', 'c', 'd']

Which is different from:

a[:] = [s.strip() for s in a]

in that it doesn't require the creation of a temporary list and an assignment of it to replace the original, although it does require more indexing operations.

Caution: Although you can modify entries this way, you can't change the number of items in the list without risking the chance of encountering problems.

Here's an example of what I mean—deleting an entry messes-up the indexing from that point on:

b = ['a', ' b', 'c ', ' d ']

for i, s in enumerate(b):
    if s.strip() != b[i]:  # leading or trailing whitespace?
        del b[i]

print(b)  # -> ['a', 'c ']  # WRONG!

(The result is wrong because it didn't delete all the items it should have.)

Update

Since this is a fairly popular answer, here's how to effectively delete entries "in-place" (even though that's not exactly the question):

b = ['a',' b', 'c ', ' d ']

b[:] = [entry for entry in b if entry.strip() == entry]

print(b)  # -> ['a']  # CORRECT

Android: Getting a file URI from a content URI?

If you have a content Uri with content://com.externalstorage... you can use this method to get absolute path of a folder or file on Android 19 or above.

public static String getPath(final Context context, final Uri uri) {
    final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

    // DocumentProvider
    if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
        System.out.println("getPath() uri: " + uri.toString());
        System.out.println("getPath() uri authority: " + uri.getAuthority());
        System.out.println("getPath() uri path: " + uri.getPath());

        // ExternalStorageProvider
        if ("com.android.externalstorage.documents".equals(uri.getAuthority())) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];
            System.out.println("getPath() docId: " + docId + ", split: " + split.length + ", type: " + type);

            // This is for checking Main Memory
            if ("primary".equalsIgnoreCase(type)) {
                if (split.length > 1) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1] + "/";
                } else {
                    return Environment.getExternalStorageDirectory() + "/";
                }
                // This is for checking SD Card
            } else {
                return "storage" + "/" + docId.replace(":", "/");
            }

        }
    }
    return null;
}

You can check each part of Uri using println. Returned values for my SD card and device main memory are listed below. You can access and delete if file is on memory, but I wasn't able to delete file from SD card using this method, only read or opened image using this absolute path. If you find a solution to delete using this method, please share.

SD CARD

getPath() uri: content://com.android.externalstorage.documents/tree/612E-B7BF%3A/document/612E-B7BF%3A
getPath() uri authority: com.android.externalstorage.documents
getPath() uri path: /tree/612E-B7BF:/document/612E-B7BF:
getPath() docId: 612E-B7BF:, split: 1, type: 612E-B7BF

MAIN MEMORY

getPath() uri: content://com.android.externalstorage.documents/tree/primary%3A/document/primary%3A
getPath() uri authority: com.android.externalstorage.documents
getPath() uri path: /tree/primary:/document/primary:
getPath() docId: primary:, split: 1, type: primary

If you wish to get Uri with file:/// after getting path use

DocumentFile documentFile = DocumentFile.fromFile(new File(path));
documentFile.getUri() // will return a Uri with file Uri

How to sort List of objects by some property

In java you need to use the static Collections.sort method. Here is an example for a list of CompanyRole objects, sorted first by begin and then by end. You can easily adapt for your own object.

private static void order(List<TextComponent> roles) {

    Collections.sort(roles, new Comparator() {
        @Override
        public int compare(Object o1, Object o2) {
            int x1 = ((CompanyRole) o1).getBegin();
            int x2 = ((CompanyRole) o2).getBegin();

            if (x1 != x2) {
                return x1 - x2;
            } else {
                int y1 = ((CompanyRole) o1).getEnd();
                int y2 = ((CompanyRole) o2).getEnd();
                return y2 - y1;
            }
        }
    });
}

MSBuild doesn't copy references (DLL files) if using project dependencies in solution

Referencing assemblies that are not used during build is not the correct practice. You should augment your build file so it will copy the additional files. Either by using a post build event or by updating the property group.

Some examples can be found in other post

Convert a PHP script into a stand-alone windows executable

I tried most of solution given in the 1st answer, the only one that worked for me and is non-commercial is php-desktop.

I simply put my php files in the www/ folder, changed the name of .exe and was able to run my php as an exe !!

Also there is a complete documentation, up to date support, windows and linux (and soon mac) compatibility and options can easily be changed.

Java getHours(), getMinutes() and getSeconds()

For a time difference, note that the calendar starts at 01.01.1970, 01:00, not at 00:00. If you're using java.util.Date and java.text.SimpleDateFormat, you will have to compensate for 1 hour:

long start = System.currentTimeMillis();
long end = start + (1*3600 + 23*60 + 45) * 1000 + 678; // 1 h 23 min 45.678 s
Date timeDiff = new Date(end - start - 3600000); // compensate for 1h in millis
SimpleDateFormat timeFormat = new SimpleDateFormat("H:mm:ss.SSS");
System.out.println("Duration: " + timeFormat.format(timeDiff));

This will print:

Duration: 1:23:45.678

What is the preferred/idiomatic way to insert into a map?

As of C++11, you have two major additional options. First, you can use insert() with list initialization syntax:

function.insert({0, 42});

This is functionally equivalent to

function.insert(std::map<int, int>::value_type(0, 42));

but much more concise and readable. As other answers have noted, this has several advantages over the other forms:

  • The operator[] approach requires the mapped type to be assignable, which isn't always the case.
  • The operator[] approach can overwrite existing elements, and gives you no way to tell whether this has happened.
  • The other forms of insert that you list involve an implicit type conversion, which may slow your code down.

The major drawback is that this form used to require the key and value to be copyable, so it wouldn't work with e.g. a map with unique_ptr values. That has been fixed in the standard, but the fix may not have reached your standard library implementation yet.

Second, you can use the emplace() method:

function.emplace(0, 42);

This is more concise than any of the forms of insert(), works fine with move-only types like unique_ptr, and theoretically may be slightly more efficient (although a decent compiler should optimize away the difference). The only major drawback is that it may surprise your readers a little, since emplace methods aren't usually used that way.

UL or DIV vertical scrollbar

You need to define height of ul or your div and set overflow equals to auto as below:

<ul style="width: 300px; height: 200px; overflow: auto">
  <li>text</li>
  <li>text</li>

Error: Uncaught SyntaxError: Unexpected token <

This is a browser issue rather than a javascript or JQuery issue; it's attempting to interpret the angle bracket as an HTML tag.

Try doing this when setting up your javascripts:

<script>
//<![CDATA[

    // insert teh codez

//]]>
</script>

Alternatively, move your javascript to a separate file.

Edit: Ahh.. with that link I've tracked it down. What I said was the issue wasn't the issue at all. this is the issue, stripped from the website:

<script type="text/javascript"
    $(document).ready(function() {
    $('#infobutton').click(function() {
        $('#music_descrip').dialog('open');
    });
        $('#music_descrip').dialog({
            title: '<img src="/images/text/text_mario_planet_jukebox.png" id="text_mario_planet_jukebox"/>',
            autoOpen: false,
            height: 375,
            width: 500,
            modal: true,
            resizable: false,
            buttons: {
                'Without Music': function() {
                    $(this).dialog('close');
                    $.cookie('autoPlay', 'no', { expires: 365 * 10 });
                },
                'With Music': function() {
                    $(this).dialog('close');
                    $.cookie('autoPlay', 'yes', { expires: 365 * 10 });
                }
            }
        });
    });

Can you spot the error? It's in the first line: the <script tag isn't closed. It should be <script type="text/javascript">

My previous suggestion still stands, however: you should enclose intra-tagged scripts in a CDATA block, or move them to a separately linked file.

That wasn't the issue here, but it would have shown the real issue faster.

Calling a javascript function recursively

I know this is an old question, but I thought I'd present one more solution that could be used if you'd like to avoid using named function expressions. (Not saying you should or should not avoid them, just presenting another solution)

  var fn = (function() {
    var innerFn = function(counter) {
      console.log(counter);

      if(counter > 0) {
        innerFn(counter-1);
      }
    };

    return innerFn;
  })();

  console.log("running fn");
  fn(3);

  var copyFn = fn;

  console.log("running copyFn");
  copyFn(3);

  fn = function() { console.log("done"); };

  console.log("fn after reassignment");
  fn(3);

  console.log("copyFn after reassignment of fn");
  copyFn(3);

How do I make background-size work in IE?

I tried with the following script -

.selector { 
background-image: url("img/image.jpg");
background-size: 100%;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-repeat: no-repeat;
}

It worked for me!

How can I determine if a String is non-null and not only whitespace in Groovy?

You could add a method to String to make it more semantic:

String.metaClass.getNotBlank = { !delegate.allWhitespace }

which let's you do:

groovy:000> foo = ''
===> 
groovy:000> foo.notBlank
===> false
groovy:000> foo = 'foo'
===> foo
groovy:000> foo.notBlank
===> true

How to verify if a file exists in a batch file?

Here is a good example on how to do a command if a file does or does not exist:

if exist C:\myprogram\sync\data.handler echo Now Exiting && Exit
if not exist C:\myprogram\html\data.sql Exit

We will take those three files and put it in a temporary place. After deleting the folder, it will restore those three files.

xcopy "test" "C:\temp"
xcopy "test2" "C:\temp"
del C:\myprogram\sync\
xcopy "C:\temp" "test"
xcopy "C:\temp" "test2"
del "c:\temp"

Use the XCOPY command:

xcopy "C:\myprogram\html\data.sql"  /c /d /h /e /i /y  "C:\myprogram\sync\"

I will explain what the /c /d /h /e /i /y means:

  /C           Continues copying even if errors occur.
  /D:m-d-y     Copies files changed on or after the specified date.
               If no date is given, copies only those files whose
               source time is newer than the destination time.
  /H           Copies hidden and system files also.
  /E           Copies directories and subdirectories, including empty ones.
               Same as /S /E. May be used to modify /T.
  /T           Creates directory structure, but does not copy files. Does not
               include empty directories or subdirectories. /T /E includes
  /I           If destination does not exist and copying more than one file,
               assumes that destination must be a directory.
  /Y           Suppresses prompting to confirm you want to overwrite an
               existing destination file.

`To see all the commands type`xcopy /? in cmd

Call other batch file with option sync.bat myprogram.ini.

I am not sure what you mean by this, but if you just want to open both of these files you just put the path of the file like

Path/sync.bat
Path/myprogram.ini

If it was in the Bash environment it was easy for me, but I do not know how to test if a file or folder exists and if it is a file or folder.

You are using a batch file. You mentioned earlier you have to create a .bat file to use this:

I have to create a .BAT file that does this:

MYSQL Truncated incorrect DOUBLE value

Mainly invalid query strings will give this warning.

Wrong due to a subtle syntax error (misplaced right parenthesis) when using INSTR function:

INSERT INTO users (user_name) SELECT name FROM site_users WHERE
INSTR(status, 'active'>0);

Correct:

INSERT INTO users (user_name) SELECT name FROM site_users WHERE
INSTR(status, 'active')>0;

string encoding and decoding?

That's because your input string can’t be converted according to the encoding rules (strict by default).

I don't know, but I always encoded using directly unicode() constructor, at least that's the ways at the official documentation:

unicode(your_str, errors="ignore")

How can I easily add storage to a VirtualBox machine with XP installed?

These steps worked for me to increase the space on my windows VM:

  1. Clone the current VM and select "Full Clone" when prompted:

enter image description here

  1. Resize the VDI:

    VBoxManage modifyhd Cloned.vdi --resize 45000

  2. Run your cloned VM, go to Disk Management and extend the volume.

What does += mean in Python?

Google 'python += operator' leads you to http://docs.python.org/library/operator.html

Search for += once the page loads up for a more detailed answer.

Object not found! The requested URL was not found on this server. localhost

If the page you are visiting is index.php, then your url should look like

http://localhost/test/content/home/ OR http://localhost/test/content/home/index.php

not the way you specified - http://localhost/test/content/home

Kotlin: How to get and set a text to TextView in Android using Kotlin?

In kotlin don't use getters and setters as like in java.The correct format of the kotlin is given below.

val textView: TextView = findViewById(R.id.android_text) as TextView
textView.setOnClickListener {
    textView.text = getString(R.string.name)
}

To get the values from the Textview we have to use this method

 val str: String = textView.text.toString()

 println("the value is $str")

Oracle PL/SQL - How to create a simple array variable?

Another solution is to use an Oracle Collection as a Hashmap:

declare 
-- create a type for your "Array" - it can be of any kind, record might be useful
  type hash_map is table of varchar2(1000) index by varchar2(30);
  my_hmap hash_map ;
-- i will be your iterator: it must be of the index's type
  i varchar2(30);
begin
  my_hmap('a') := 'apple';
  my_hmap('b') := 'box';
  my_hmap('c') := 'crow';
-- then how you use it:

  dbms_output.put_line (my_hmap('c')) ;

-- or to loop on every element - it's a "collection"
  i := my_hmap.FIRST;

  while (i is not null)  loop     
    dbms_output.put_line(my_hmap(i));      
    i := my_hmap.NEXT(i);
  end loop;

end;

Compare every item to every other item in ArrayList

The following code will compare each item with other list of items using contains() method.Length of for loop must be bigger size() of bigger list then only it will compare all the values of both list.

List<String> str = new ArrayList<String>();
str.add("first");
str.add("second");
str.add("third");
List<String> str1 = new ArrayList<String>();
str1.add("first");
str1.add("second");
str1.add("third1");
for (int i = 0; i<str1.size(); i++)
{
System.out.println(str.contains(str1.get(i)));
}

Output is true true false

How to calculate date difference in JavaScript?

<html lang="en">
<head>
<script>
function getDateDiff(time1, time2) {
  var str1= time1.split('/');
  var str2= time2.split('/');

  //                yyyy   , mm       , dd
  var t1 = new Date(str1[2], str1[0]-1, str1[1]);
  var t2 = new Date(str2[2], str2[0]-1, str2[1]);

  var diffMS = t1 - t2;    
  console.log(diffMS + ' ms');

  var diffS = diffMS / 1000;    
  console.log(diffS + ' ');

  var diffM = diffS / 60;
  console.log(diffM + ' minutes');

  var diffH = diffM / 60;
  console.log(diffH + ' hours');

  var diffD = diffH / 24;
  console.log(diffD + ' days');
  alert(diffD);
}

//alert(getDateDiff('10/18/2013','10/14/2013'));
</script>
</head>
<body>
  <input type="button" 
       onclick="getDateDiff('10/18/2013','10/14/2013')" 
       value="clickHere()" />

</body>
</html>

Get textarea text with javascript or Jquery

Get textarea text with JavaScript:

<!DOCTYPE html>
<body>
<form id="form1">
    <div>
        <textarea id="area1" rows="5">Yes</textarea>
        <input type="button" value="get txt" onclick="go()" />
        <br />
        <p id="as">Now what</p>
    </div>
</form>
</body>

function go() {
    var c1 = document.getElementById('area1').value;
    var d1 = document.getElementById('as');
    d1.innerHTML = c1;
}

http://jsfiddle.net/PUpeJ/3/

How do I check if a string is valid JSON in Python?

I came up with an generic, interesting solution to this problem:

class SafeInvocator(object):
    def __init__(self, module):
        self._module = module

    def _safe(self, func):
        def inner(*args, **kwargs):
            try:
                return func(*args, **kwargs)
            except:
                return None

        return inner

    def __getattr__(self, item):
        obj = getattr(self.module, item)
        return self._safe(obj) if hasattr(obj, '__call__') else obj

and you can use it like so:

safe_json = SafeInvocator(json)
text = "{'foo':'bar'}"
item = safe_json.loads(text)
if item:
    # do something

Scroll RecyclerView to show selected item on top

what i did to restore the scroll position after refreshing the RecyclerView on button clicked:

if (linearLayoutManager != null) {

    index = linearLayoutManager.findFirstVisibleItemPosition();
    View v = linearLayoutManager.getChildAt(0);
    top = (v == null) ? 0 : (v.getTop() - linearLayoutManager.getPaddingTop());
    Log.d("TAG", "visible position " + " " + index);
}

else{
    index = 0;
}

linearLayoutManager = new LinearLayoutManager(getApplicationContext());
linearLayoutManager.scrollToPositionWithOffset(index, top);

getting the offset of the first visible item from the top before creating the linearLayoutManager object and after instantiating it the scrollToPositionWithOffset of the LinearLayoutManager object was called.

Play local (hard-drive) video file with HTML5 video tag?

It is possible to play a local video file.

<input type="file" accept="video/*"/>
<video controls autoplay></video>

When a file is selected via the input element:

  1. 'change' event is fired
  2. Get the first File object from the input.files FileList
  3. Make an object URL that points to the File object
  4. Set the object URL to the video.src property
  5. Lean back and watch :)

http://jsfiddle.net/dsbonev/cCCZ2/embedded/result,js,html,css/

_x000D_
_x000D_
(function localFileVideoPlayer() {_x000D_
  'use strict'_x000D_
  var URL = window.URL || window.webkitURL_x000D_
  var displayMessage = function(message, isError) {_x000D_
    var element = document.querySelector('#message')_x000D_
    element.innerHTML = message_x000D_
    element.className = isError ? 'error' : 'info'_x000D_
  }_x000D_
  var playSelectedFile = function(event) {_x000D_
    var file = this.files[0]_x000D_
    var type = file.type_x000D_
    var videoNode = document.querySelector('video')_x000D_
    var canPlay = videoNode.canPlayType(type)_x000D_
    if (canPlay === '') canPlay = 'no'_x000D_
    var message = 'Can play type "' + type + '": ' + canPlay_x000D_
    var isError = canPlay === 'no'_x000D_
    displayMessage(message, isError)_x000D_
_x000D_
    if (isError) {_x000D_
      return_x000D_
    }_x000D_
_x000D_
    var fileURL = URL.createObjectURL(file)_x000D_
    videoNode.src = fileURL_x000D_
  }_x000D_
  var inputNode = document.querySelector('input')_x000D_
  inputNode.addEventListener('change', playSelectedFile, false)_x000D_
})()
_x000D_
video,_x000D_
input {_x000D_
  display: block;_x000D_
}_x000D_
_x000D_
input {_x000D_
  width: 100%;_x000D_
}_x000D_
_x000D_
.info {_x000D_
  background-color: aqua;_x000D_
}_x000D_
_x000D_
.error {_x000D_
  background-color: red;_x000D_
  color: white;_x000D_
}
_x000D_
<h1>HTML5 local video file player example</h1>_x000D_
<div id="message"></div>_x000D_
<input type="file" accept="video/*" />_x000D_
<video controls autoplay></video>
_x000D_
_x000D_
_x000D_

RGB to hex and hex to RGB

A simple answer for rgb to hex

    function rgbtohex(r,g,b){
        return "#" + (Math.round(r) * 65536 + Math.round(g) * 256 + Math.round(b)).toString(16));
    }

AngularJs ReferenceError: angular is not defined

Always make sure that js file (angular.min.js) is referenced first in the HTML file. For example:

----------------- This reference will THROW error -------------------------

< script src="otherXYZ.js"></script>
< script src="angular.min.js"></script>

----------------- This reference will WORK as expected -------------------

< script src="angular.min.js"></script>
< script src="otherXYZ.js"></script>

Send Message in C#

It doesn't sound like a good idea to use send message. I think you should try to work around the problem that the DLLs can't reference each other...

Django Multiple Choice Field / Checkbox Select Multiple

ManyToManyField isn`t a good choice.You can use some snippets to implement MultipleChoiceField.You can be inspired by MultiSelectField with comma separated values (Field + FormField) But it has some bug in it.And you can install django-multiselectfield.This is more prefect.

How to hide console window in python?

Some additional info. for situations that'll need the win32gui solution posted by Mohsen Haddadi earlier in this thread:

As of python 361, win32gui & win32con are not part of the python std library. To use them, pywin32 package will need to be installed; now possible via pip.

More background info on pywin32 package is at: How to use the win32gui module with Python?.

Also, to apply discretion while closing a window so as to not inadvertently close any window in the foreground, the resolution could be extended along the lines of the following:

try     :

    import win32gui, win32con;

    frgrnd_wndw = win32gui.GetForegroundWindow();
    wndw_title  = win32gui.GetWindowText(frgrnd_wndw);
    if wndw_title.endswith("python.exe"):
        win32gui.ShowWindow(frgrnd_wndw, win32con.SW_HIDE);
    #endif
except  :
    pass

Calculate date from week number

I have written and tested the following code and is working perfectly fine for me. Please let me know if anyone face trouble with this, I have posted a question as well in order to get the best possible answer. Someone may find it useful.

public static DateTime GetFirstDateOfWeekByWeekNumber(int year, int weekNumber)
        {
            var date = new DateTime(year, 01, 01);
            var firstDayOfYear = date.DayOfWeek;
            var result = date.AddDays(weekNumber * 7);

            if (firstDayOfYear == DayOfWeek.Monday)
                return result.Date;
            if (firstDayOfYear == DayOfWeek.Tuesday)
                return result.AddDays(-1).Date;
            if (firstDayOfYear == DayOfWeek.Wednesday)
                return result.AddDays(-2).Date;
            if (firstDayOfYear == DayOfWeek.Thursday)
                return result.AddDays(-3).Date;
            if (firstDayOfYear == DayOfWeek.Friday)
                return result.AddDays(-4).Date;
            if (firstDayOfYear == DayOfWeek.Saturday)
                return result.AddDays(-5).Date;
            return result.AddDays(-6).Date;
        }

Simulator or Emulator? What is the difference?

In computer science both a simulation and emulation produce the same outputs, from the same inputs, that the original system does; However, an emulation also uses the same processes to achieve it and is made out of the same materials. A simulation uses different processes from the original system. Also worth noting is the term replication, which is the intermediate of the two - using the same processes but being made out of a different material.

So if I want to run my old Super Mario Bros game on my PC I use an SNES emulator, because it is using the same or similar computer code (processes) to run the game, and uses the same or similar materials (silicon chip). However, if I want to fly a Boeing 747 jet on my PC I use a flight simulator because it uses completely different processes from the original (there are no actual wings, lift or aerodynamics involved!).

Here are the exact definitions taken from a computer science glossary:

A simulation is a model of a system that captures the functional connections between inputs and outputs of the system, but without necessarily being based on processes that are the same as, or similar to, those of the system itself.

A replication is a model of a system that captures the functional connections between inputs and outputs of the system and is based on processes that are the same as, or similar to, those of the system itself.

An emulation is a model of some system that captures the functional connections between inputs and outputs of the system, based on processes that are the same as, or similar to, those of that system, and that is built of the same materials as that system.

Reference: The Open University, M366 Glossary 1.1, 2007

How do you get the cursor position in a textarea?

Here is code to get line number and column position

function getLineNumber(tArea) {

    return tArea.value.substr(0, tArea.selectionStart).split("\n").length;
}

function getCursorPos() {
    var me = $("textarea[name='documenttext']")[0];
    var el = $(me).get(0);
    var pos = 0;
    if ('selectionStart' in el) {
        pos = el.selectionStart;
    } else if ('selection' in document) {
        el.focus();
        var Sel = document.selection.createRange();
        var SelLength = document.selection.createRange().text.length;
        Sel.moveStart('character', -el.value.length);
        pos = Sel.text.length - SelLength;
    }
    var ret = pos - prevLine(me);
    alert(ret);

    return ret; 
}

function prevLine(me) {
    var lineArr = me.value.substr(0, me.selectionStart).split("\n");

    var numChars = 0;

    for (var i = 0; i < lineArr.length-1; i++) {
        numChars += lineArr[i].length+1;
    }

    return numChars;
}

tArea is the text area DOM element

Can't find @Nullable inside javax.annotation.*

The artifact has been moved from net.sourceforge.findbugs to

<dependency>
    <groupId>com.google.code.findbugs</groupId>
    <artifactId>jsr305</artifactId>
    <version>3.0.0</version>
</dependency>

How can I print each command before executing?

set -x is fine.

Another way to print each executed command is to use trap with DEBUG. Put this line at the beginning of your script :

trap 'echo "# $BASH_COMMAND"' DEBUG

You can find a lot of other trap usages here.

Avoiding NullPointerException in Java

I follow below guidelines to avoid null checks.

  1. Avoid lazy initialization of member variables as much as possible. Initialize the variables in declaration itself. This will handle NullPointerExceptions.

  2. Decide on mutability of member variables early in the cycle. Use language constructs like final keyword effectively.

  3. If you know that augments for method won't be changed, declare them as final.

  4. Limit the mutation of data as much as possible. Some variables can be created in a constructor and can never be changed. Remove public setter methods unless they are really required.

    E.g. Assume that one class in your application (A.java) is maintaining a collection like HashMap. Don't provide public getter method in A.java and allow B.java to directly add an element in Map. Instead provide an API in A.java, which adds an element into collection.

    // Avoid
    a.getMap().put(key,value)
    
    //recommended
    
    public void addElement(Object key, Object value){
           // Have null checks for both key and value here : single place
           map.put(key,value);
    }
    
  5. And finally, use try{} catch{} finally{} blocks at right places effectively.

Is there a way to get colored text in GitHubflavored Markdown?

In case this may be helpful for someone who just needs to show colors rather than output, as a hackish workaround (and FYI), since GitHub supports Unicode (as Unicode, numeric character references or HTML entities), you could try colored Unicode symbols, though it depends on the font rendering them in color (as it happens to be appearing for me on Windows 10 and Mac 10.12.5, at least, though on the Mac at least, the up/down-pointing small red triangles don't show in red):

  • RED APPLE (&#x1F34E;):
  • GREEN APPLE (&#x1F34F;):
  • BLUE HEART (&#x1F499;):
  • GREEN HEART (&#x1F49A;):
  • YELLOW HEART (&#x1F49B;):
  • PURPLE HEART (&#x1F49C;):
  • GREEN BOOK (&#x1F4D7;):
  • BLUE BOOK (&#x1F4D8;):
  • ORANGE BOOK (&#x1F4D9;):
  • LARGE RED CIRCLE (&#x1F534;):
  • LARGE BLUE CIRCLE (&#x1F535;):
  • LARGE ORANGE DIAMOND (&#x1F536;):
  • LARGE BLUE DIAMOND (&#x1F537;):
  • SMALL ORANGE DIAMOND (&#x1F538;):
  • SMALL BLUE DIAMOND (&#x1F539;):
  • UP-POINTING RED TRIANGLE (&#x1F53A;):
  • DOWN-POINTING RED TRIANGLE (&#x1F53B;):
  • UP-POINTING SMALL RED TRIANGLE (&#x1F53C;):
  • DOWN-POINTING SMALL RED TRIANGLE (&#x1F53D;):

How to correctly catch change/focusOut event on text input in React.js?

You'd need to be careful as onBlur has some caveats in IE11 (How to use relatedTarget (or equivalent) in IE?, https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/relatedTarget).

There is, however, no way to use onFocusOut in React as far as I can tell. See the issue on their github https://github.com/facebook/react/issues/6410 if you need more information.

How can I solve the error 'TS2532: Object is possibly 'undefined'?

Edit / Update:

If you are using Typescript 3.7 or newer you can now also do:

    const data = change?.after?.data();

    if(!data) {
      console.error('No data here!');
       return null
    }

    const maxLen = 100;
    const msgLen = data.messages.length;
    const charLen = JSON.stringify(data).length;

    const batch = db.batch();

    if (charLen >= 10000 || msgLen >= maxLen) {

      // Always delete at least 1 message
      const deleteCount = msgLen - maxLen <= 0 ? 1 : msgLen - maxLen
      data.messages.splice(0, deleteCount);

      const ref = db.collection("chats").doc(change.after.id);

      batch.set(ref, data, { merge: true });

      return batch.commit();
    } else {
      return null;
    }

Original Response

Typescript is saying that change or data is possibly undefined (depending on what onUpdate returns).

So you should wrap it in a null/undefined check:

if(change && change.after && change.after.data){
    const data = change.after.data();

    const maxLen = 100;
    const msgLen = data.messages.length;
    const charLen = JSON.stringify(data).length;

    const batch = db.batch();

    if (charLen >= 10000 || msgLen >= maxLen) {

      // Always delete at least 1 message
      const deleteCount = msgLen - maxLen <= 0 ? 1 : msgLen - maxLen
      data.messages.splice(0, deleteCount);

      const ref = db.collection("chats").doc(change.after.id);

      batch.set(ref, data, { merge: true });

      return batch.commit();
    } else {
      return null;
    }
}

If you are 100% sure that your object is always defined then you can put this:

const data = change.after!.data();

sudo service mongodb restart gives "unrecognized service error" in ubuntu 14.0.4

For me the solution was to replace

service mongod start

with

start mongod

How to get child element by class name?

Use the name of the id with the getElementById, no # sign before it. Then you can get the span child nodes using getElementsByTagName, and loop through them to find the one with the right class:

var doc = document.getElementById('test');

var c = doc.getElementsByTagName('span');

var e = null;
for (var i = 0; i < c.length; i++) {
    if (c[i].className == '4') {
        e = c[i];
        break;
    }
}

if (e != null) {
    alert(e.innerHTML);
}

Demo: http://jsfiddle.net/Guffa/xB62U/

java - iterating a linked list

As the definition of Linkedlist says, it is a sequence and you are guaranteed to get the elements in order.

eg:

import java.util.LinkedList;

public class ForEachDemonstrater {
  public static void main(String args[]) {
    LinkedList<Character> pl = new LinkedList<Character>();
    pl.add('j');
    pl.add('a');
    pl.add('v');
    pl.add('a');
    for (char s : pl)
      System.out.print(s+"->");
  }
}

Difference between INNER JOIN and LEFT SEMI JOIN

Trying to depict with venn diagrams for better understanding..

Left Semi join : A semi join returns values from the left side of the relation that has a match with the right. It is also referred to as a left semi join.

enter image description here

Note : There is another thing called left anti join : An anti join returns values from the left relation that has no match with the right. It is also referred to as a left anti join.

Inner join : It selects rows that have matching values in both relations.

enter image description here

Can I store images in MySQL

You can store images in MySQL as blobs. However, this is problematic for a couple of reasons:

  • The images can be harder to manipulate: you must first retrieve them from the database before bulk operations can be performed.
  • Except in very rare cases where the entire database is stored in RAM, MySQL databases are ultimately stored on disk. This means that your DB images are converted to blobs, inserted into a database, and then stored on disk; you can save a lot of overhead by simply storing them on disk.

Instead, consider updating your table to add an image_path field. For example:

ALTER TABLE `your_table`
ADD COLUMN `image_path` varchar(1024)

Then store your images on disk, and update the table with the image path. When you need to use the images, retrieve them from disk using the path specified.

An advantageous side-effect of this approach is that the images do not necessarily be stored on disk; you could just as easily store a URL instead of an image path, and retrieve images from any internet-connected location.

Ionic 2: Cordova is not available. Make sure to include cordova.js or run in a device/simulator (running in emulator)

This is quite late but anyone going through the same problem might benefit from this answer.First try to add browser by running below command ionic platform add browser and then run command ionic run browser.

which is the difference between ionic serve and ionic run browser?

Ionic serve - runs your app as a website (meaning it doesn't have any Cordova capabilities). Ionic run browser - runs your app in the Cordova browser platform, which will inject cordova.js and any plugins that have browser capabilities

You can refer this link to know more difference between ionic serve and ionic run browser command

Update

From Ionic 3 this command has been changed. Use the command below instead;

ionic cordova platform add browser

ionic cordova run browser

You can find out which version of ionic you are using by running: ionic --version

Is it possible to use the instanceof operator in a switch statement?

Just in case if someone will read it:

The BEST solution in java is :

public enum Action { 
    a{
        void doAction(...){
            // some code
        }

    }, 
    b{
        void doAction(...){
            // some code
        }

    }, 
    c{
        void doAction(...){
            // some code
        }

    };

    abstract void doAction (...);
}

The GREAT benefits of such pattern are:

  1. You just do it like (NO switches at all):

    void someFunction ( Action action ) {
        action.doAction(...);   
    }
    
  2. In case if you add new Action called "d" you MUST imlement doAction(...) method

NOTE: This pattern is described in Joshua's Bloch "Effective Java (2nd Edition)"

Component is not part of any NgModule or the module has not been imported into your module

In my case the imports of real routes in app.component.spec.ts were causing these error messages. Solution was to import RouterTestingModule instead.

import { TestBed, async } from '@angular/core/testing';
import { AppComponent } from './app.component';
import { RouterTestingModule } from '@angular/router/testing';

describe('AppComponent', () => {
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [
        AppComponent
      ],
      imports: [RouterTestingModule]
    }).compileComponents();
  }));

  it('should create the app', async(() => {
    const fixture = TestBed.createComponent(AppComponent);
    console.log(fixture);
    const app = fixture.debugElement.componentInstance;
    expect(app).toBeTruthy();
  }));

});

redirect to current page in ASP.Net

http://en.wikipedia.org/wiki/Post/Redirect/Get

The most common way to implement this pattern in ASP.Net is to use Response.Redirect(Request.RawUrl)

Consider the differences between Redirect and Transfer. Transfer really isn't telling the browser to forward to a clear form, it's simply returning a cleared form. That may or may not be what you want.

Response.Redirect() does not a waste round trip. If you post to a script that clears the form by Server.Transfer() and reload you will be asked to repost by most browsers since the last action was a HTTP POST. This may cause your users to unintentionally repeat some action, eg. place a second order which will have to be voided later.

Best practices when running Node.js with port 80 (Ubuntu / Linode)

Port 80

What I do on my cloud instances is I redirect port 80 to port 3000 with this command:

sudo iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 80 -j REDIRECT --to-port 3000

Then I launch my Node.js on port 3000. Requests to port 80 will get mapped to port 3000.

You should also edit your /etc/rc.local file and add that line minus the sudo. That will add the redirect when the machine boots up. You don't need sudo in /etc/rc.local because the commands there are run as root when the system boots.

Logs

Use the forever module to launch your Node.js with. It will make sure that it restarts if it ever crashes and it will redirect console logs to a file.

Launch on Boot

Add your Node.js start script to the file you edited for port redirection, /etc/rc.local. That will run your Node.js launch script when the system starts.

Digital Ocean & other VPS

This not only applies to Linode, but Digital Ocean, AWS EC2 and other VPS providers as well. However, on RedHat based systems /etc/rc.local is /ect/rc.d/local.

ASP.NET 5 MVC: unable to connect to web server 'IIS Express'

Change port manually for http and https (or disable https)

cell format round and display 2 decimal places

Another way is to use FIXED function, you can specify the number of decimal places but it defaults to 2 if the places aren't specified, i.e.

=FIXED(E5,2)

or just

=FIXED(E5)

SQL ORDER BY multiple columns

Sorting in an ORDER BY is done by the first column, and then by each additional column in the specified statement.

For instance, consider the following data:

Column1    Column2
=======    =======
1          Smith
2          Jones
1          Anderson
3          Andrews

The query

SELECT Column1, Column2 FROM thedata ORDER BY Column1, Column2

would first sort by all of the values in Column1

and then sort the columns by Column2 to produce this:

Column1    Column2
=======    =======
1          Anderson
1          Smith
2          Jones
3          Andrews

In other words, the data is first sorted in Column1 order, and then each subset (Column1 rows that have 1 as their value) are sorted in order of the second column.

The difference between the two statements you posted is that the rows in the first one would be sorted first by prod_price (price order, from lowest to highest), and then by order of name (meaning that if two items have the same price, the one with the lower alpha value for name would be listed first), while the second would sort in name order only (meaning that prices would appear in order based on the prod_name without regard for price).

How to exit an application properly

Application.Exit
    End

will work like a charm The "END" immediately terminates further execution while "Application.Exit" closes all forms and calls.

Best regrads,

Calling another method java GUI

I'm not sure what you're trying to do, but here's something to consider: c(); won't do anything. c is an instance of the class checkbox and not a method to be called. So consider this:

public class FirstWindow extends JFrame {      public FirstWindow() {         checkbox c = new checkbox();         c.yourMethod(yourParameters); // call the method you made in checkbox     } }  public class checkbox extends JFrame {      public checkbox(yourParameters) {          // this is the constructor method used to initialize instance variables     }      public void yourMethod() // doesn't have to be void     {         // put your code here     } } 

Returning Promises from Vuex actions

Just for an information on a closed topic: you don’t have to create a promise, axios returns one itself:

Ref: https://forum.vuejs.org/t/how-to-resolve-a-promise-object-in-a-vuex-action-and-redirect-to-another-route/18254/4

Example:

    export const loginForm = ({ commit }, data) => {
      return axios
        .post('http://localhost:8000/api/login', data)
        .then((response) => {
          commit('logUserIn', response.data);
        })
        .catch((error) => {
          commit('unAuthorisedUser', { error:error.response.data });
        })
    }

Another example:

    addEmployee({ commit, state }) {       
      return insertEmployee(state.employee)
        .then(result => {
          commit('setEmployee', result.data);
          return result.data; // resolve 
        })
        .catch(err => {           
          throw err.response.data; // reject
        })
    }

Another example with async-await

    async getUser({ commit }) {
        try {
            const currentUser = await axios.get('/user/current')
            commit('setUser', currentUser)
            return currentUser
        } catch (err) {
            commit('setUser', null)
            throw 'Unable to fetch current user'
        }
    },

NodeJS - Error installing with NPM

For windows

Check python path in system variable. npm plugins need node-gyp to be installed.

open command prompt with admin rights, and run following command.

npm install --global --production windows-build-tools

npm install --global node-gyp

How to display a Windows Form in full screen on top of the taskbar?

This is how I make forms full screen.

private void button1_Click(object sender, EventArgs e)
{
    int minx, miny, maxx, maxy;
    inx = miny = int.MaxValue;
    maxx = maxy = int.MinValue;

    foreach (Screen screen in Screen.AllScreens)
    {
        var bounds = screen.Bounds;
        minx = Math.Min(minx, bounds.X);
        miny = Math.Min(miny, bounds.Y);
        maxx = Math.Max(maxx, bounds.Right);
        maxy = Math.Max(maxy, bounds.Bottom);
    }

    Form3 fs = new Form3();
    fs.Activate();
    Rectangle tempRect = new Rectangle(1, 0, maxx, maxy);
    this.DesktopBounds = tempRect;
}

Is there a way to reduce the size of the git folder?

Don't know if it will shrink it, but after I run git clean, I often do git repack -ad as well, which reduces the number of pack files.

Data access object (DAO) in Java

What is DATA ACCESS OBJECT (DAO) -

It is a object/interface, which is used to access data from database of data storage.

WHY WE USE DAO:

it abstracts the retrieval of data from a data resource such as a database. The concept is to "separate a data resource's client interface from its data access mechanism."

The problem with accessing data directly is that the source of the data can change. Consider, for example, that your application is deployed in an environment that accesses an Oracle database. Then it is subsequently deployed to an environment that uses Microsoft SQL Server. If your application uses stored procedures and database-specific code (such as generating a number sequence), how do you handle that in your application? You have two options:

  • Rewrite your application to use SQL Server instead of Oracle (or add conditional code to handle the differences), or
  • Create a layer inbetween your application logic and the data access


Its in all referred as DAO Pattern, It consist of following:

  • Data Access Object Interface - This interface defines the standard operations to be performed on a model object(s).
  • Data Access Object concrete class -This class implements above interface. This class is responsible to get data from a datasource which can be database / xml or any other storage mechanism.
  • Model Object or Value Object - This object is simple POJO containing get/set methods to store data retrieved using DAO class.

Please check this example, This will clear things more clearly.

Example
I assume this things must have cleared your understanding of DAO up to certain extend.

How to check if an integer is within a range?

Most of the given examples assume that for the test range [$a..$b], $a <= $b, i.e. the range extremes are in lower - higher order and most assume that all are integer numbers.
But I needed a function to test if $n was between $a and $b, as described here:

Check if $n is between $a and $b even if:
    $a < $b  
    $a > $b
    $a = $b

All numbers can be real, not only integer.

There is an easy way to test.
I base the test it in the fact that ($n-$a) and ($n-$b) have different signs when $n is between $a and $b, and the same sign when $n is outside the $a..$b range.
This function is valid for testing increasing, decreasing, positive and negative numbers, not limited to test only integer numbers.

function between($n, $a, $b)
{
    return (($a==$n)&&($b==$n))? true : ($n-$a)*($n-$b)<0;
}

Docker container not starting (docker start)

What I need is to use Docker with MariaDb on different port /3301/ on my Ubuntu machine because I already had MySql installed and running on 3306.

To do this after half day searching did it using:

docker run -it -d -p 3301:3306 -v ~/mdbdata/mariaDb:/var/lib/mysql -e MYSQL_ROOT_PASSWORD=root --name mariaDb mariadb

This pulls the image with latest MariaDb, creates container called mariaDb, and run mysql on port 3301. All data of which is located in home directory in /mdbdata/mariaDb.

To login in mysql after that can use:

mysql -u root -proot -h 127.0.0.1 -P3301

Used sources are:

The answer of Iarks in this article /using -it -d was the key :) /

how-to-install-and-use-docker-on-ubuntu-16-04

installing-and-using-mariadb-via-docker

mariadb-and-docker-use-cases-part-1

Good luck all!

What's the difference between django OneToOneField and ForeignKey?

Be careful to realize that there are some differences between OneToOneField(SomeModel) and ForeignKey(SomeModel, unique=True). As stated in The Definitive Guide to Django:

OneToOneField

A one-to-one relationship. Conceptually, this is similar to a ForeignKey with unique=True, but the "reverse" side of the relation will directly return a single object.

In contrast to the OneToOneField "reverse" relation, a ForeignKey "reverse" relation returns a QuerySet.

Example

For example, if we have the following two models (full model code below):

  1. Car model uses OneToOneField(Engine)
  2. Car2 model uses ForeignKey(Engine2, unique=True)

From within python manage.py shell execute the following:

OneToOneField Example

>>> from testapp.models import Car, Engine
>>> c = Car.objects.get(name='Audi')
>>> e = Engine.objects.get(name='Diesel')
>>> e.car
<Car: Audi>

ForeignKey with unique=True Example

>>> from testapp.models import Car2, Engine2
>>> c2 = Car2.objects.get(name='Mazda')
>>> e2 = Engine2.objects.get(name='Wankel')
>>> e2.car2_set.all()
[<Car2: Mazda>]

Model Code

from django.db import models

class Engine(models.Model):
    name = models.CharField(max_length=25)

    def __unicode__(self):
        return self.name

class Car(models.Model):
    name = models.CharField(max_length=25)
    engine = models.OneToOneField(Engine)

    def __unicode__(self):
        return self.name

class Engine2(models.Model):
    name = models.CharField(max_length=25)

    def __unicode__(self):
        return self.name

class Car2(models.Model):
    name = models.CharField(max_length=25)
    engine = models.ForeignKey(Engine2, unique=True, on_delete=models.CASCADE)

    def __unicode__(self):
        return self.name

How do I generate a random number between two variables that I have stored?

If you have a C++11 compiler you can prepare yourself for the future by using c++'s pseudo random number faculties:

//make sure to include the random number generators and such
#include <random>
//the random device that will seed the generator
std::random_device seeder;
//then make a mersenne twister engine
std::mt19937 engine(seeder());
//then the easy part... the distribution
std::uniform_int_distribution<int> dist(min, max);
//then just generate the integer like this:
int compGuess = dist(engine);

That might be slightly easier to grasp, being you don't have to do anything involving modulos and crap... although it requires more code, it's always nice to know some new C++ stuff...

Hope this helps - Luke

Setting Django up to use MySQL

  1. Install mysqlclient

sudo pip3 install mysqlclient

if you get error:

Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-install-dbljg4tx/mysqlclient/

then:

 1. sudo apt install libmysqlclient-dev python-mysqldb

 2. sudo pip3 install mysqlclient

  1. Modify settings.py

    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql',
            'NAME': 'website',
            'USER': 'root',
            'PASSWORD': '',
            'HOST': '127.0.0.1',
            'PORT': '3306',
            'OPTION': {'init_command':"SET sql_mode='STRICT_TRANS_TABLE',"},
        }
    }
    

What programming languages can one use to develop iPhone, iPod Touch and iPad (iOS) applications?

With plans to slowly retire the long-used Objective-C, Apple has introduced a new programming language, called Swift, for designing apps and applications to run on Apple iOS devices and Apple Macintosh computers.

Apple says: "Swift is a new programming language for iOS and OS X apps that builds on the best of C and Objective-C, without the constraints of C compatibility. Swift adopts safe programming patterns and adds modern features to make programming easier, more flexible, and more fun. Swift’s clean slate, backed by the mature and much-loved Cocoa and Cocoa Touch frameworks, is an opportunity to reimagine how software development works."

Introducing swift

enter image description here

Difference between Width:100% and width:100vw?

vw and vh stand for viewport width and viewport height respectively.

The difference between using width: 100vw instead of width: 100% is that while 100% will make the element fit all the space available, the viewport width has a specific measure, in this case the width of the available screen, including the document margin.

If you set the style body { margin: 0 }, 100vw should behave the same as 100%.

Additional notes

Using vw as unit for everything in your website, including font sizes and heights, will make it so that the site is always displayed proportionally to the device's screen width regardless of it's resolution. This makes it super easy to ensure your website is displayed properly in both workstation and mobile.

You can set font-size: 1vw (or whatever size suits your project) in your body CSS and everything specified in rem units will automatically scale according to the device screen, so it's easy to port existing projects and even frameworks (such as Bootstrap) to this concept.

What is the difference between #import and #include in Objective-C?

The #import directive was added to Objective-C as an improved version of #include. Whether or not it's improved, however, is still a matter of debate. #import ensures that a file is only ever included once so that you never have a problem with recursive includes. However, most decent header files protect themselves against this anyway, so it's not really that much of a benefit.

Basically, it's up to you to decide which you want to use. I tend to #import headers for Objective-C things (like class definitions and such) and #include standard C stuff that I need. For example, one of my source files might look like this:

#import <Foundation/Foundation.h>

#include <asl.h>
#include <mach/mach.h>

Hosting ASP.NET in IIS7 gives Access is denied?

I had the same problem, I enabled "Anonymous Authentication" but it still did not work. So I also ENABLED "Forms Authentication" Then it worked without any problems.

How to check if android checkbox is checked within its onClick method (declared in XML)?

try this one :

public void itemClicked(View v) {
  //code to check if this checkbox is checked!
  CheckBox checkBox = (CheckBox)v;
  if(checkBox.isChecked()){

  }
}

PHP GuzzleHttp. How to make a post request with params?

Note in Guzzle V6.0+, another source of getting the following error may be incorrect use of JSON as an array:

Passing in the "body" request option as an array to send a POST request has been deprecated. Please use the "form_params" request option to send a application/x-www-form-urlencoded request, or a the "multipart" request option to send a multipart/form-data request.

Incorrect:

$response = $client->post('http://example.com/api', [
    'body' => [
        'name' => 'Example name',
    ]
])

Correct:

$response = $client->post('http://example.com/api', [
    'json' => [
        'name' => 'Example name',
    ]
])

Correct:

$response = $client->post('http://example.com/api', [
    'headers' => ['Content-Type' => 'application/json'],
    'body' => json_encode([
        'name' => 'Example name',
    ])
])

Bulk create model objects in django

The easiest way is to use the create Manager method, which creates and saves the object in a single step.

for item in items:
    MyModel.objects.create(name=item.name)

Using ListView : How to add a header view?

You can add as many headers as you like by calling addHeaderView() multiple times. You have to do it before setting the adapter to the list view.

And yes you can add header something like this way:

LayoutInflater inflater = getLayoutInflater();
ViewGroup header = (ViewGroup)inflater.inflate(R.layout.header, myListView, false);
myListView.addHeaderView(header, null, false);

"Cannot verify access to path (C:\inetpub\wwwroot)", when adding a virtual directory

ACCESSING LOCAL WEBSITE WITH IIS without Physical Path Authentication

  1. Make sure you have installed URL Rewrite to your IIS Manager

enter image description here

  1. Open the URL Rewrite application then navigate to Inbound Rules>Import Rules

enter image description here

  1. To import the rule, click the browse button then locate your .htaccess file then click import button

enter image description here

  1. The text labeled with red are errors that are not accepted by IIS, so you have to remove them by clicking the errors in the converted rules and remove the text from the rewrite rules. Once you have get rid of the errors Click the APPLY button located at the top right corner. Then try to access your site without engaging users into the pool auth.

enter image description here

I hope it helps. That's what I did.

Cannot instantiate the type List<Product>

List can be instantiated by any class implementing the interface.By this way,Java provides us polymorphic behaviour.See the example below:

List<String> list = new ArrayList<String>();

Instead of instantiating an ArrayList directly,I am using a List to refer to ArrayList object so that we are using only the List interface methods and do not care about its actual implementation.

Examples of classes implementing List are ArrayList,LinkedList,Vector.You probably want to create a List depending upon your requirements.

Example:- a LinkedList is more useful when you hve to do a number of inertion or deletions .Arraylist is more performance intensive as it is backed by a fixed size array and array contents have to be changed by moving or regrowing the array.

Again,using a List we can simply change our object instantiation without changing any code further in your programs.

Suppose we are using ArrayList<String> value = new ArrayList<String>();

we may use a specific method of ArrrayList and out code will not be robust

By using List<String> value = new ArrayList<String>();

we are making sure we are using only List interface methods..and if we want to change it to a LinkedList we simply have to change the code :

List<String> value = new ArrayList<String>(); 

------ your code uses List interface methods.....

value = new LinkedList<String>(); 

-----your code still uses List interface methods and we do not have to change anything---- and we dont have to change anything in our code further

By the way a LinkedList also works a Deque which obviously also you cannot instantiate as it is also an interface

Faster way to zero memory than with memset?

memset could be inlined by compiler as a series of efficient opcodes, unrolled for a few cycles. For very large memory blocks, like 4000x2000 64bit framebuffer, you can try optimizing it across several threads (which you prepare for that sole task), each setting its own part. Note that there is also bzero(), but it is more obscure, and less likely to be as optimized as memset, and the compiler will surely notice you pass 0.

What compiler usually assumes, is that you memset large blocks, so for smaller blocks it would likely be more efficient to just do *(uint64_t*)p = 0, if you init large number of small objects.

Generally, all x86 CPUs are different (unless you compile for some standardized platform), and something you optimize for Pentium 2 will behave differently on Core Duo or i486. So if you really into it and want to squeeze the last few bits of toothpaste, it makes sense to ship several versions your exe compiled and optimized for different popular CPU models. From personal experience Clang -march=native boosted my game's FPS from 60 to 65, compared to no -march.

HashMap: One Key, multiple Values

HashMap – Single Key and Multiple Values Using List

Map<String, List<String>> map = new HashMap<String, List<String>>();

  // create list one and store values

    List<String> One = new ArrayList<String>();
    One.add("Apple");
    One.add("Aeroplane");

    // create list two and store values
    List<String> Two = new ArrayList<String>();
    Two.add("Bat");
    Two.add("Banana");

    // put values into map
    map.put("A", One);
    map.put("B", Two);
    map.put("C", Three);

Event when window.location.href changes

Through Jquery, just try

$(window).on('beforeunload', function () {
    //your code goes here on location change 
});

By using javascript:

window.addEventListener("beforeunload", function (event) {
   //your code goes here on location change 
});

Refer Document : https://developer.mozilla.org/en-US/docs/Web/Events/beforeunload

ReSharper "Cannot resolve symbol" even when project builds

I tried all of the above solutions numerous times but none worked for me. I was using Visual Studio 2015 with ReSharper 9.0.

I was able to resolve this by upgrading to ReSharper 9.2. If you already have the latest update for your major version, maybe reinstalling ReSharper might fix this for you. I would suggest clearing you ReShaper cache first, just in case.

Here's the link to the archive versions of ReSharper: https://resharper-support.jetbrains.com/hc/en-us/articles/207242355-Where-can-I-download-an-old-previous-ReSharper-version-

Multiple submit buttons in an HTML form

If the fact that the first button is used by default is consistent across browsers, put them the right way around in the source code, and then use CSS to switch their apparent positions.

float them left and right to switch them around visually, for example.

How to call multiple functions with @click in vue?

Separate into pieces.

Inline:

<div @click="f1() + f2()"></div> 

OR: Through a composite function:

<div @click="f3()"></div> 

<script>
var app = new Vue({
  // ...
  methods: {
    f3: function() { f1() + f2(); }
    f1: function() {},
    f2: function() {}
  }
})
</script>

Angular2 Exception: Can't bind to 'routerLink' since it isn't a known native property

Word of caution when coding with Visual Studio (2013)

I have wasted 4 to 5 hours trying to debug this error. I tried all the solutions that I found on StackOverflow by the letter and I still got this error: Can't bind to 'routerlink' since it isn't a known native property

Be aware, Visual Studio has the nasty habit of autoformatting text when you copy/paste code. I always got a small instantaneous adjustment from VS13 (camel case disappears).

This:

<div>
    <a [routerLink]="['/catalog']">Catalog</a>
    <a [routerLink]="['/summary']">Summary</a>
</div>

Becomes:

<div>
    <a [routerlink]="['/catalog']">Catalog</a>
    <a [routerlink]="['/summary']">Summary</a>
</div>

It's a small difference, but enough to trigger the error. The ugliest part is that this small difference just kept avoiding my attention every time I copied and pasted. By sheer chance, I saw this small difference and solved it.

Java: Check if enum contains a given string?

You can first convert the enum to List and then use list contains method

enum Choices{A1, A2, B1, B2};

List choices = Arrays.asList(Choices.values());

//compare with enum value 
if(choices.contains(Choices.A1)){
   //do something
}

//compare with String value
if(choices.contains(Choices.valueOf("A1"))){
   //do something
}

What is the Python equivalent of Matlab's tic and toc functions?

Updating Eli's answer to Python 3:

class Timer(object):
    def __init__(self, name=None, filename=None):
        self.name = name
        self.filename = filename

    def __enter__(self):
        self.tstart = time.time()

    def __exit__(self, type, value, traceback):
        message = 'Elapsed: %.2f seconds' % (time.time() - self.tstart)
        if self.name:
            message = '[%s] ' % self.name + message
        print(message)
        if self.filename:
            with open(self.filename,'a') as file:
                print(str(datetime.datetime.now())+": ",message,file=file)

Just like Eli's, it can be used as a context manager:

import time 
with Timer('Count'):
    for i in range(0,10_000_000):
        pass

Output:

[Count] Elapsed: 0.27 seconds

I have also updated it to print the units of time reported (seconds) and trim the number of digits as suggested by Can, and with the option of also appending to a log file. You must import datetime to use the logging feature:

import time
import datetime 
with Timer('Count', 'log.txt'):    
    for i in range(0,10_000_000):
        pass

Pandas groupby: How to get a union of strings

Named aggregations with pandas >= 0.25.0

Since pandas version 0.25.0 we have named aggregations where we can groupby, aggregate and at the same time assign new names to our columns. This way we won't get the MultiIndex columns, and the column names make more sense given the data they contain:


aggregate and get a list of strings

grp = df.groupby('A').agg(B_sum=('B','sum'),
                          C=('C', list)).reset_index()

print(grp)
   A     B_sum               C
0  1  1.615586  [This, string]
1  2  0.421821         [is, !]
2  3  0.463468             [a]
3  4  0.643961        [random]

aggregate and join the strings

grp = df.groupby('A').agg(B_sum=('B','sum'),
                          C=('C', ', '.join)).reset_index()

print(grp)
   A     B_sum             C
0  1  1.615586  This, string
1  2  0.421821         is, !
2  3  0.463468             a
3  4  0.643961        random

How to get POSTed JSON in Flask?

For all those whose issue was from the ajax call, here is a full example :

Ajax call : the key here is to use a dict and then JSON.stringify

    var dict = {username : "username" , password:"password"};

    $.ajax({
        type: "POST", 
        url: "http://127.0.0.1:5000/", //localhost Flask
        data : JSON.stringify(dict),
        contentType: "application/json",
    });

And on server side :

from flask import Flask
from flask import request
import json

app = Flask(__name__)

@app.route("/",  methods = ['POST'])
def hello():
    print(request.get_json())
    return json.dumps({'success':True}), 200, {'ContentType':'application/json'} 

if __name__ == "__main__":
    app.run()

Duplicate Symbols for Architecture arm64

On upgrading to Xcode 8, I got a message to upgrade to recommended settings. I accepted and everything was updated. I started getting compile time issue :

Duplicate symbol for XXXX Duplicate symbol for XXXX Duplicate symbol for XXXX

A total of 143 errors. Went to Target->Build settings -> No Common Blocks -> Set it to NO. This resolved the issue. The issue was that the integrated projects had code blocks in common and hence was not able to compile it. Explanation can be found here.

How to append the output to a file?

Yeah.

command >> file to redirect just stdout of command.

command >> file 2>&1 to redirect stdout and stderr to the file (works in bash, zsh)

And if you need to use sudo, remember that just

sudo command >> /file/requiring/sudo/privileges does not work, as privilege elevation applies to command but not shell redirection part. However, simply using tee solves the problem:

command | sudo tee -a /file/requiring/sudo/privileges

How to iterate std::set?

How do you iterate std::set?

int main(int argc,char *argv[]) 
{
    std::set<int> mset;
    mset.insert(1); 
    mset.insert(2);
    mset.insert(3);

    for ( auto it = mset.begin(); it != mset.end(); it++ )
        std::cout << *it;
}

How do I push to GitHub under a different username?

If you use ssh and get

Permission to some_username/repository.git denied to Alice_username

while you don't wanna push as Alice_username, make sure Alice_username doesn't have your computer's ssh key added to its github account.

I deleted my ssh key from alice's github account and the push worked.

"inappropriate ioctl for device"

Since this is a fatal error and also quite difficult to debug, maybe the fix could be put somewhere (in the provided command line?):

export GPG_TTY=$(tty)

From: https://github.com/keybase/keybase-issues/issues/2798

PHP header redirect 301 - what are the implications?

Search engines like 301 redirects better than a 404 or some other type of client side redirect, no worries there.

CPU usage will be minimal, if you want to save even more cycles you could try and handle the redirect in apache using htaccess, then php won't even have to get involved. If you want to load test a server, you can use ab which comes with apache, or httperf if you are looking for a more robust testing tool.

Environment Variable with Maven

Following documentation from @Kevin's answer the below one worked for me for setting environment variable with maven sure-fire plugin

<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
    <environmentVariables>
        <WSNSHELL_HOME>conf</WSNSHELL_HOME>
    </environmentVariables>
</configuration>

Solutions for INSERT OR UPDATE on SQL Server

I had tried below solution and it works for me, when concurrent request for insert statement occurs.

begin tran
if exists (select * from table with (updlock,serializable) where key = @key)
begin
   update table set ...
   where key = @key
end
else
begin
   insert table (key, ...)
   values (@key, ...)
end
commit tran

What does __FILE__ mean in Ruby?

__FILE__ is the filename with extension of the file containing the code being executed.

In foo.rb, __FILE__ would be "foo.rb".

If foo.rb were in the dir /home/josh then File.dirname(__FILE__) would return /home/josh.

Access to build environment variables from a groovy script in a Jenkins build step (Windows)

The only way I could get this to work (on Linux) was to follow this advice:

https://wiki.jenkins-ci.org/display/JENKINS/Parameterized+System+Groovy+script

import hudson.model.*

// get current thread / Executor and current build
def thr = Thread.currentThread()
def build = thr?.executable

// if you want the parameter by name ...
def hardcoded_param = "FOOBAR"
def resolver = build.buildVariableResolver
def hardcoded_param_value = resolver.resolve(hardcoded_param)

println "param ${hardcoded_param} value : ${hardcoded_param_value}"

This is on Jenkins 1.624 running on CentOS 6.7

How to hide the border for specified rows of a table?

Use the CSS property border on the <td>s following the <tr>s you do not want to have the border.

In my example I made a class noBorder that I gave to one <tr>. Then I use a simple selector tr.noBorder td to make the border go away for all the <td>s that are inside of <tr>s with the noBorder class by assigning border: 0.

Note that you do not need to provide the unit (i.e. px) if you set something to 0 as it does not matter anyway. Zero is just zero.

_x000D_
_x000D_
table, tr, td {_x000D_
  border: 3px solid red;_x000D_
}_x000D_
tr.noBorder td {_x000D_
  border: 0;_x000D_
}
_x000D_
<table>_x000D_
  <tr>_x000D_
    <td>A1</td>_x000D_
    <td>B1</td>_x000D_
    <td>C1</td>_x000D_
  </tr>_x000D_
  <tr class="noBorder">_x000D_
    <td>A2</td>_x000D_
    <td>B2</td>_x000D_
    <td>C2</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>A3</td>_x000D_
    <td>A3</td>_x000D_
    <td>A3</td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Here's the output as an image:

Output from HTML

Sending mail attachment using Java

To send html file I have used below code in my project.

final String userID = "[email protected]";
final String userPass = "userpass";
final String emailTo = "[email protected]"

Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");

Session session = Session.getDefaultInstance(props,
        new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(userID, userPass);
            }
        });
try {

    Message message = new MimeMessage(session);
    message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(emailTo));
    message.setSubject("Hello, this is a test mail..");

    Multipart multipart = new MimeMultipart();
    String fileName = "fileName";

    addAttachment(multipart, fileName);

    MimeBodyPart messageBodyPart1 = new MimeBodyPart();
    messageBodyPart1.setText("No need to reply.");
    multipart.addBodyPart(messageBodyPart1);

    message.setContent(multipart);

    Transport.send(message);
    System.out.println("Email successfully sent to: " + emailTo);

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



private static void addAttachment(Multipart multipart, String fileName){
    DataSource source = null;
    File f = new File("filepath" +"/"+ fileName);
    if(f.exists() && !f.isDirectory()) {
        source = new FileDataSource("filepath" +"/"+ fileName);
        BodyPart messageBodyPart = new MimeBodyPart();
        try {
            messageBodyPart.setHeader("Content-Type", "text/html");
            messageBodyPart.setDataHandler(new DataHandler(source));
            messageBodyPart.setFileName(fileName);
            multipart.addBodyPart(messageBodyPart);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }
}

c# .net change label text

If I understand correctly you may be experiencing the problem because in order to be able to set the labels "text" property you actually have to use the "content" property.

so instead of:

  Label output = null;
        output = Label1;
        output.Text = "hello";

try:

Label output = null;
            output = Label1;
            output.Content = "hello";

Select top 2 rows in Hive

Here I think it's worth mentioning SORT BY and ORDER BY both clauses and why they different,

SELECT * FROM <table_name> SORT BY <column_name> DESC LIMIT 2

If you are using SORT BY clause it sort data per reducer which means if you have more than one MapReduce task it will result partially ordered data. On the other hand, the ORDER BY clause will result in ordered data for the final Reduce task. To understand more please refer to this link.

SELECT * FROM <table_name> ORDER BY <column_name> DESC LIMIT 2

Note: Finally, Even though the accepted answer contains SORT BY clause, I mostly prefer to use ORDER BY clause for the general use case to avoid any data loss.

Get last record of a table in Postgres

The column name plays an important role in the descending order:

select <COLUMN_NAME1, COLUMN_NAME2> from >TABLENAME> ORDER BY <COLUMN_NAME THAT MENTIONS TIME> DESC LIMIT 1;

For example: The below-mentioned table(user_details) consists of the column name 'created_at' that has timestamp for the table.

SELECT userid, username FROM user_details ORDER BY created_at DESC LIMIT 1;

How to read a local text file?

Get local file data in js(data.js) load:

function loadMyFile(){
    console.log("ut:"+unixTimeSec());
    loadScript("data.js?"+unixTimeSec(), loadParse);
}
function loadParse(){
    var mA_=mSdata.split("\n");
    console.log(mA_.length);
}
function loadScript(url, callback){

    var script = document.createElement("script")
    script.type = "text/javascript";

    if (script.readyState){  //IE
        script.onreadystatechange = function(){
            if (script.readyState == "loaded" ||
                    script.readyState == "complete"){
                script.onreadystatechange = null;
                callback();
            }
        };
    } else {  //Others
        script.onload = function(){
            callback();
        };
    }

    script.src = url;
    document.getElementsByTagName("head")[0].appendChild(script);
}
function hereDoc(f) {
  return f.toString().
      replace(/^[^\/]+\/\*![^\r\n]*[\r\n]*/, "").
      replace(/[\r\n][^\r\n]*\*\/[^\/]+$/, "");
}
function unixTimeSec(){
    return Math.round( (new Date()).getTime()/1000);
}

file of data.js like:

var mSdata = hereDoc(function() {/*!
17,399
1237,399
BLAHBLAH
BLAHBLAH
155,82
194,376
*/});

dynamic unixTime queryString prevents cached.

AJ works in web http://.

Selectors in Objective-C?

As per apple docs: https://developer.apple.com/library/archive/documentation/General/Conceptual/DevPedia-CocoaCore/Selector.html

A selector is the name used to select a method to execute for an object, or the unique identifier that replaces the name when the source code is compiled. A selector by itself doesn’t do anything. It simply identifies a method. The only thing that makes the selector method name different from a plain string is that the compiler makes sure that selectors are unique. What makes a selector useful is that (in conjunction with the runtime) it acts like a dynamic function pointer that, for a given name, automatically points to the implementation of a method appropriate for whichever class it’s used with. Suppose you had a selector for the method run, and classes Dog, Athlete, and ComputerSimulation (each of which implemented a method run). The selector could be used with an instance of each of the classes to invoke its run method—even though the implementation might be different for each.

Example: (lldb) breakpoint --set selector viewDidLoad

This will set a breakpoint on all viewDidLoad implementations in your app. So selector is kind of a global identifier for a method.

Rails - How to use a Helper Inside a Controller

Note: This was written and accepted back in the Rails 2 days; nowadays grosser's answer is the way to go.

Option 1: Probably the simplest way is to include your helper module in your controller:

class MyController < ApplicationController
  include MyHelper

  def xxxx
    @comments = []
    Comment.find_each do |comment|
      @comments << {:id => comment.id, :html => html_format(comment.content)}
    end
  end
end

Option 2: Or you can declare the helper method as a class function, and use it like so:

MyHelper.html_format(comment.content)

If you want to be able to use it as both an instance function and a class function, you can declare both versions in your helper:

module MyHelper
  def self.html_format(str)
    process(str)
  end

  def html_format(str)
    MyHelper.html_format(str)
  end
end

Hope this helps!

How to completely DISABLE any MOUSE CLICK

You can overlay a big, semi-transparent <div> that takes all the clicks. Just append a new <div> to <body> with this style:

.overlay {
    background-color: rgba(1, 1, 1, 0.7);
    bottom: 0;
    left: 0;
    position: fixed;
    right: 0;
    top: 0;
}

Redirect to external URI from ASP.NET MVC controller

If you're talking about ASP.NET MVC then you should have a controller method that returns the following:

return Redirect("http://www.google.com");

Otherwise we need more info on the error you're getting in the redirect. I'd step through to make sure the url isn't empty.

Apply CSS rules if browser is IE

A fast approach is to use the following according to ie that you want to focus (check the comments), inside your css files (where margin-top, set whatever css attribute you like):

margin-top: 10px\9; /*It will apply to all ie from 8 and below */
*margin-top: 10px; /*It will apply to ie 7 and below */
_margin-top: 10px; /*It will apply to ie 6 and below*/

A better approach would be to check user agent or a conditional if, in order to avoid the loading of unnecessary CSS in other browsers.

How to align the text middle of BUTTON

You can use text-align: center; line-height: 65px;

Demo

CSS

.loginBtn {
    background:url(images/loginBtn-center.jpg) repeat-x;
    width:175px;
    height:65px;
    margin:20px auto;
    border-radius:10px;
    -webkit-border-radius:10px;
    box-shadow:0 1px 2px #5e5d5b;
    text-align: center;  <--------- Here
    line-height: 65px;   <--------- Here
}

How to change the background color of a UIButton while it's highlighted?

simple is that use that UIButton Extension ONLY

extension UIButton {

    func setBackgroundColor(color: UIColor, forState: UIControl.State) {
        self.clipsToBounds = true  // add this to maintain corner radius
        UIGraphicsBeginImageContext(CGSize(width: 1, height: 1))
        if let context = UIGraphicsGetCurrentContext() {
            context.setFillColor(color.cgColor)
            context.fill(CGRect(x: 0, y: 0, width: 1, height: 1))
            let colorImage = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
            self.setBackgroundImage(colorImage, for: forState)
        }
    }

}

and use this

 optionButton.setBackgroundColor(color: UIColor(red:0.09, green:0.42, blue:0.82, alpha:1.0), forState: .selected)

 optionButton.setBackgroundColor(color: UIColor(red:0.96, green:0.96, blue:0.96, alpha:1.0), forState: .highlighted)

 optionButton.setBackgroundColor(color: UIColor(red:0.96, green:0.96, blue:0.96, alpha:1.0), forState: .normal)

Simple working Example of json.net in VB.net

Your class JSON_result does not match your JSON string. Note how the object JSON_result is going to represent is wrapped in another property named "Venue".

So either create a class for that, e.g.:

Public Class Container
    Public Venue As JSON_result
End Class

Public Class JSON_result
    Public ID As Integer
    Public Name As String
    Public NameWithTown As String
    Public NameWithDestination As String
    Public ListingType As String
End Class

Dim obj = JsonConvert.DeserializeObject(Of Container)(...your_json...)

or change your JSON string to

{
    "ID": 3145,
    "Name": "Big Venue, Clapton",
    "NameWithTown": "Big Venue, Clapton, London",
    "NameWithDestination": "Big Venue, Clapton, London",
    "ListingType": "A",
    "Address": {
        "Address1": "Clapton Raod",
        "Address2": "",
        "Town": "Clapton",
        "County": "Greater London",
        "Postcode": "PO1 1ST",
        "Country": "United Kingdom",
        "Region": "Europe"
    },
    "ResponseStatus": {
        "ErrorCode": "200",
        "Message": "OK"
    }
}

or use e.g. a ContractResolver to parse the JSON string.

Query to list number of records in each table in a database

As seen here, this will return correct counts, where methods using the meta data tables will only return estimates.

    CREATE PROCEDURE ListTableRowCounts 
    AS 
    BEGIN 
        SET NOCOUNT ON 

        CREATE TABLE #TableCounts
        ( 
            TableName VARCHAR(500), 
            CountOf INT 
        ) 

        INSERT #TableCounts
            EXEC sp_msForEachTable 
                'SELECT PARSENAME(''?'', 1), 
                COUNT(*) FROM ? WITH (NOLOCK)' 

        SELECT TableName , CountOf 
            FROM #TableCounts
            ORDER BY TableName 

        DROP TABLE #TableCounts
    END
    GO

Capturing a single image from my webcam in Java or Python

Some time ago I wrote simple Webcam Capture API which can be used for that. The project is available on Github.

Example code:

Webcam webcam = Webcam.getDefault();
webcam.open();
try {
  ImageIO.write(webcam.getImage(), "PNG", new File("test.png"));
} catch (IOException e) {
  e.printStackTrace();
} finally {
  webcam.close();
}

How do I make an html link look like a button?

Use below snippet.

    .a{
  color: $brn-acc-clr;
  background-color: transparent;
  border-color: #888888;

  &:hover:active{
    outline: none;
    color: #888888;
    border-color: #888888;
  }
  &:fill{
    background-color: #888888;
    color: #fff;
    box-shadow: 0 3px 10px rgba(#888888, 0.5);
    &:hover:active{
      color: #fff;
    }
    &:hover:not(:disabled){
      transform: translateY(-2px);
      background-color: darken(#888888, 4);
    }
  }
}

How To have Dynamic SQL in MySQL Stored Procedure

I don't believe MySQL supports dynamic sql. You can do "prepared" statements which is similar, but different.

Here is an example:

mysql> PREPARE stmt FROM 
    -> 'select count(*) 
    -> from information_schema.schemata 
    -> where schema_name = ? or schema_name = ?'
;
Query OK, 0 rows affected (0.00 sec)
Statement prepared
mysql> EXECUTE stmt 
    -> USING @schema1,@schema2
+----------+
| count(*) |
+----------+
|        2 |
+----------+
1 row in set (0.00 sec)
mysql> DEALLOCATE PREPARE stmt;

The prepared statements are often used to see an execution plan for a given query. Since they are executed with the execute command and the sql can be assigned to a variable you can approximate the some of the same behavior as dynamic sql.

Here is a good link about this:

Don't forget to deallocate the stmt using the last line!

Good Luck!

Leaflet changing Marker color

In R, use the addAwesomeMarkers() function. Sample code producing red marker:

leaflet() %>%
addTiles() %>%
addAwesomeMarkers(lng = -77.03654, lat = 38.8973, icon = awesomeIcons(icon = 'ion-ionic', library = 'ion', markerColor = 'red'))

Link for ion icons: http://ionicons.com/

Bootstrap 3: pull-right for col-lg only

Adding the CSS shown below to your Bootstrap 3 application enables support for

pull-{e|sm-|md-|lg-}left
pull-{e|sm-|md-|lg-}right

classes that work exactly like the new

float-{e|sm-|md-|lg-|xl-}left
float-{e|sm-|md-|lg-|xl-}right

classes that have been introduced in Bootstrap 4:

@media (min-width: 768px) {
    .pull-sm-left {
        float: left !important;
    }
    .pull-sm-right {
        float: right !important;
    }
    .pull-sm-none {
        float: none !important;
    }
}
@media (min-width: 992px) {
    .pull-md-left {
        float: left !important;
    }
    .pull-md-right {
        float: right !important;
    }
    .pull-md-none {
        float: none !important;
    }
}
@media (min-width: 1200px) {
    .pull-lg-left {
        float: left !important;
    }
    .pull-lg-right {
        float: right !important;
    }
    .pull-lg-none {
        float: none !important;
    }
}
.pull-none {
    float: none !important;
}

Apart from that, it adds

pull-{e|sm-|md-|lg-}none

for completeness, being compatible with

float-{e|sm-|md-|lg-|xl-}none

from Bootstrap 4.

DataGridView - how to set column width?

The following also can be tried:

DataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.DisplayedCells

or use the other setting options in the DataGridViewAutoSizeColumnsMode Enum

Swift: Convert enum value to String?

Starting from Swift 3.0 you can

var str = String(describing: Audience.friends)

CSS transition shorthand with multiple properties?

Syntax:

transition: <property> || <duration> || <timing-function> || <delay> [, ...];

Note that the duration must come before the delay, if the latter is specified.

Individual transitions combined in shorthand declarations:

-webkit-transition: height 0.3s ease-out, opacity 0.3s ease 0.5s;
-moz-transition: height 0.3s ease-out, opacity 0.3s ease 0.5s;
-o-transition: height 0.3s ease-out, opacity 0.3s ease 0.5s;
transition: height 0.3s ease-out, opacity 0.3s ease 0.5s;

Or just transition them all:

-webkit-transition: all 0.3s ease-out;
-moz-transition: all 0.3s ease-out;
-o-transition: all 0.3s ease-out;
transition: all 0.3s ease-out;

Here is a straightforward example. Here is another one with the delay property.


Edit: previously listed here were the compatibilities and known issues regarding transition. Removed for readability.

Bottom-line: just use it. The nature of this property is non-breaking for all applications and compatibility is now well above 94% globally.

If you still want to be sure, refer to http://caniuse.com/css-transitions

Is there any method to get the URL without query string?

To get every part of the URL except for the query:

var url = (location.origin).concat(location.pathname).concat(location.hash);

Note that this includes the hash as well, if there is one (I'm aware there's no hash in your example URL, but I included that aspect for completeness). To eliminate the hash, simply exclude .concat(location.hash).

It's better practice to use concat to join Javascript strings together (rather than +): in some situations it avoids problems such as type confusion.

Android Studio rendering problems

I was able to fix this in Android Studio 0.2.0 by changing API from API 18: Android 4.3 to API 17: Android 4.2.2

This is under the Android icon menu in the top right of the design window.

This was a solution from http://www.hankcs.com/program/mobiledev/idea-this-version-of-the-rendering-library-is-more-recent-than-your-version-of-intellij-idea-please-update-intellij-idea.html.This required a Google translation into English since it was in another language.

Hope it helps.

How to count the number of observations in R like Stata command count

The with function will let you use shorthand column references and sum will count TRUE results from the expression(s).

sum(with(aaa, sex==1 & group1==2))
## [1] 3

sum(with(aaa, sex==1 & group2=="A"))
## [1] 2

As @mnel pointed out, you can also do:

nrow(aaa[aaa$sex==1 & aaa$group1==2,])
## [1] 3

nrow(aaa[aaa$sex==1 & aaa$group2=="A",])
## [1] 2

The benefit of that is that you can do:

nrow(aaa)
## [1] 6

And, the behaviour matches Stata's count almost exactly (syntax notwithstanding).

Tomcat: LifecycleException when deploying

Check your WEB-INF/web.xml file for the servlet Mapping.

String.format() to format double in java

String.format("%4.3f" , x) ;

It means that we need total 4 digits in ans , of which 3 should be after decimal . And f is the format specifier of double . x means the variable for which we want to find it . Worked for me . . .

Leap year calculation

Will it not be much better if we make one step further. Assuming every 3200 year as no leap year, the length of the year will come

364.999696 + 1/3200 = 364.999696 + .0003125 = 365.0000085

and after this the adjustment will be required after around 120000 years.

Output of git branch in tree like fashion

Tested on Ubuntu:

sudo apt install git-extras
git-show-tree

This produces an effect similar to the 2 most upvoted answers here.

Source: http://manpages.ubuntu.com/manpages/bionic/man1/git-show-tree.1.html


Also, if you have arcanist installed (correction: Uber's fork of arcanist installed--see the bottom of this answer here for installation instructions), arc flow shows a beautiful dependency tree of upstream dependencies (ie: which were set previously via arc flow new_branch or manually via git branch --set-upstream-to=upstream_branch).

Bonus git tricks:

Related:

  1. What's the difference between `arc graft` and `arc patch`?

What does IFormatProvider do?

In adition to Ian Boyd's answer:

Also CultureInfo implements this interface and can be used in your case. So you could parse a French date string for example; you could use

var ci = new CultureInfo("fr-FR");
DateTime dt = DateTime.ParseExact(yourDateInputString, yourFormatString, ci);

Opening Android Settings programmatically

In case anyone finds this question and you want to open up settings for your specific application:

    val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
    intent.data = Uri.parse("package:" + context.packageName)
    startActivity(intent)

How to change an Eclipse default project into a Java project

  1. Right click on project
  2. Configure -> 'Convert to Faceted Form'
  3. You will get a popup, Select 'Java' in 'Project Facet' column.
  4. Press Apply and Ok.

Access Denied for User 'root'@'localhost' (using password: YES) - No Privileges?

A simple way to reset root password on Linux systems :

sudo dpkg-reconfigure mysql-server-5.5

Checkout some other reasons for Access denied :

https://dev.mysql.com/doc/refman/5.7/en/problems-connecting.html

No module named MySQLdb

I am at ubuntu (linux) and what worked for me was

sudo apt-get install python3-dev default-libmysqlclient-dev build-essential

and then finally

pip install mysqlclient

What is the email subject length limit?

I don't believe that there is a formal limit here, and I'm pretty sure there isn't any hard limit specified in the RFC either, as you found.

I think that some pretty common limitations for subject lines in general (not just e-mail) are:

  • 80 Characters
  • 128 Characters
  • 256 Characters

Obviously, you want to come up with something that is reasonable. If you're writing an e-mail client, you may want to go with something like 256 characters, and obviously test thoroughly against big commercial servers out there to make sure they serve your mail correctly.

Hope this helps!

Windows command to get service status?

according to this http://www.computerhope.com/nethlp.htm it should be NET START /LIST but i can't get it to work on by XP box. I'm sure there's some WMI that will give you the list.

What does the colon (:) operator do?

Just to add, when used in a for-each loop, the ":" can basically be read as "in".

So

for (String name : names) {
    // remainder omitted
}

should be read "For each name IN names do ..."

SQL grammar for SELECT MIN(DATE)

SELECT  MIN(Date)  AS Date  FROM tbl_Employee /*To get First date Of Employee*/

How to declare Return Types for Functions in TypeScript

Return types using arrow notation is the same as previous answers:

const sum = (a: number, b: number) : number => a + b;

Static Vs. Dynamic Binding in Java

The compiler only knows that the type of "a" is Animal; this happens at compile time, because of which it is called static binding (Method overloading). But if it is dynamic binding then it would call the Dog class method. Here is an example of dynamic binding.

public class DynamicBindingTest {

    public static void main(String args[]) {
        Animal a= new Dog(); //here Type is Animal but object will be Dog
        a.eat();       //Dog's eat called because eat() is overridden method
    }
}

class Animal {

    public void eat() {
        System.out.println("Inside eat method of Animal");
    }
}

class Dog extends Animal {

    @Override
    public void eat() {
        System.out.println("Inside eat method of Dog");
    }
}

Output: Inside eat method of Dog

Is there an XSL "contains" directive?

Sure there is! For instance:

<xsl:if test="not(contains($hhref, '1234'))">
  <li>
    <a href="{$hhref}" title="{$pdate}">
      <xsl:value-of select="title"/>
    </a>
  </li>
</xsl:if>

The syntax is: contains(stringToSearchWithin, stringToSearchFor)

Create Directory When Writing To File In Node.js

first taking the full path including directory and extracting the directory

//Just for the sake of example
cwd=process.cwd()
filendir=path.resolve(cwd,'_site/assets/text','node.txt')

// Extracting directory name
mkdir=path.dirname(filendir)

Now make the directory, add option recursive:true as stated by @David Weldon

fs.mkdirSync(mkdir,{recursive:true})

Then make the file

data='Some random text'
fs.writeFileSync(filendir,data)

Declare a variable as Decimal

The best way is to declare the variable as a Single or a Double depending on the precision you need. The data type Single utilizes 4 Bytes and has the range of -3.402823E38 to 1.401298E45. Double uses 8 Bytes.

You can declare as follows:

Dim decAsdf as Single

or

Dim decAsdf as Double

Here is an example which displays a message box with the value of the variable after calculation. All you have to do is put it in a module and run it.

Sub doubleDataTypeExample()
Dim doubleTest As Double


doubleTest = 0.0000045 * 0.005 * 0.01

MsgBox "doubleTest = " & doubleTest
End Sub

Select element based on multiple classes

You can use these solutions :

CSS rules applies to all tags that have following two classes :

.left.ui-class-selector {
    /*style here*/
}

CSS rules applies to all tags that have <li> with following two classes :

li.left.ui-class-selector {
   /*style here*/
}

jQuery solution :

$("li.left.ui-class-selector").css("color", "red");

Javascript solution :

document.querySelector("li.left.ui-class-selector").style.color = "red";

How do I list loaded plugins in Vim?

:help local-additions

Lists local plugins added.

Modify property value of the objects in list using Java 8 streams

just for modifying certain property from object collection you could directly use forEach with a collection as follows

collection.forEach(c -> c.setXyz(c.getXyz + "a"))

What is the purpose of a question mark after a type (for example: int? myVariable)?

Nullable Types

Nullable types are instances of the System.Nullable struct. A nullable type can represent the normal range of values for its underlying value type, plus an additional null value. For example, a [Nullable<Int32>], pronounced "Nullable of Int32," can be assigned any value from -2147483648 to 2147483647, or it can be assigned the null value. A [Nullable<bool>] can be assigned the values true or false, or null. The ability to assign null to numeric and Boolean types is particularly useful when dealing with databases and other data types containing elements that may not be assigned a value. For example, a Boolean field in a database can store the values true or false, or it may be undefined.

How do you add multi-line text to a UIButton?

For IOS 6 :

button.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
button.titleLabel.textAlignment = NSTextAlignmentCenter;

As

UILineBreakModeWordWrap and UITextAlignmentCenter

are deprecated in IOS 6 onwards..

jQuery.ajax returns 400 Bad Request

I was getting the 400 Bad Request error, even after setting:

contentType: "application/json",
dataType: "json"

The issue was with the type of a property passed in the json object, for the data property in the ajax request object.
To figure out the issue, I added an error handler and then logged the error to the console. Console log will clearly show validation errors for the properties if any.

This was my initial code:

var data = {
    "TestId": testId,
    "PlayerId": parseInt(playerId),
    "Result": result
};

var url = document.location.protocol + "//" + document.location.host + "/api/tests"
$.ajax({
    url: url,
    method: "POST",
    contentType: "application/json",
    data: JSON.stringify(data), // issue with a property type in the data object
    dataType: "json",
    error: function (e) {
        console.log(e); // logging the error object to console
    },
    success: function () {
        console.log('Success saving test result');
    }
});

Now after making the request, I checked the console tab in the browser development tool.
It looked like this: enter image description here

responseJSON.errors[0] clearly shows a validation error: The JSON value could not be converted to System.String. Path: $.TestId, which means I have to convert TestId to a string in the data object, before making the request.

Changing the data object creation like below fixed the issue for me:

var data = {
        "TestId": String(testId), //converting testId to a string
        "PlayerId": parseInt(playerId),
        "Result": result
};

I assume other possible errors could also be identified by logging and inspecting the error object.

Replace input type=file by an image

This is my method if i got your point

HTML

<label for="FileInput">
    <img src="tools/img/upload2.png" style="cursor:pointer" onmouseover="this.src='tools/img/upload.png'" onmouseout="this.src='tools/img/upload2.png'" alt="Injaz Msila" style="float:right;margin:7px" />
</label>
<form action="upload.php">
    <input type="file" id="FileInput" style="cursor: pointer;  display: none"/>
    <input type="submit" id="Up" style="display: none;" />
</form>

jQuery

<script type="text/javascript">
    $( "#FileInput" ).change(function() {
      $( "#Up" ).click();
    });
</script>

String formatting: % vs. .format vs. string literal

To answer your first question... .format just seems more sophisticated in many ways. An annoying thing about % is also how it can either take a variable or a tuple. You'd think the following would always work:

"hi there %s" % name

yet, if name happens to be (1, 2, 3), it will throw a TypeError. To guarantee that it always prints, you'd need to do

"hi there %s" % (name,)   # supply the single argument as a single-item tuple

which is just ugly. .format doesn't have those issues. Also in the second example you gave, the .format example is much cleaner looking.

Why would you not use it?

  • not knowing about it (me before reading this)
  • having to be compatible with Python 2.5

To answer your second question, string formatting happens at the same time as any other operation - when the string formatting expression is evaluated. And Python, not being a lazy language, evaluates expressions before calling functions, so in your log.debug example, the expression "some debug info: %s"%some_infowill first evaluate to, e.g. "some debug info: roflcopters are active", then that string will be passed to log.debug().

Passing a method as a parameter in Ruby

You want a proc object:

gaussian = Proc.new do |dist, *args|
  sigma = args.first || 10.0
  ...
end

def weightedknn(data, vec1, k = 5, weightf = gaussian)
  ...
  weight = weightf.call(dist)
  ...
end

Just note that you can't set a default argument in a block declaration like that. So you need to use a splat and setup the default in the proc code itself.


Or, depending on your scope of all this, it may be easier to pass in a method name instead.

def weightedknn(data, vec1, k = 5, weightf = :gaussian)
  ...
  weight = self.send(weightf)
  ...
end

In this case you are just calling a method that is defined on an object rather than passing in a complete chunk of code. Depending on how you structure this you may need replace self.send with object_that_has_the_these_math_methods.send


Last but not least, you can hang a block off the method.

def weightedknn(data, vec1, k = 5)
  ...
  weight = 
    if block_given?
      yield(dist)
    else
      gaussian.call(dist)
    end
  end
  ...
end

weightedknn(foo, bar) do |dist|
  # square the dist
  dist * dist
end

But it sounds like you would like more reusable chunks of code here.

DateTime.ToString() format that can be used in a filename or extension?

Using interpolation string & format specifier:

var filename = $"{DateTime.Now:yyyy.dd.M HH-mm-ss}"

Example Output for January 1st, 2020 at 10:40:45AM:

2020.28.01 10-40-45


Or if you want a standard date format:

var filename = $"{DateTime.Now:yyyy.M.dd HH-mm-ss}"

2020.01.28 10-40-45


Note: this feature is available in C# 6 and later versions of the language.

bootstrap datepicker change date event doesnt fire up when manually editing dates or clearing date

I was using AngularJS and AngularStrap 2.3.7 and trying to catch the 'change' event by listening to a <form> element (not the input itself) and none of the answers here worked for me. I tried to do:

$(form).on('change change.dp dp.change changeDate' function () {...})

And nothing would fire. I ended up listening to the focus and blur events and setting a custom property before/after on the element itself:

// special hack to make bs-datepickers fire change events
// use timeout to make sure they all exist first
$timeout(function () {  
    $('input[bs-datepicker]').on('focus', function (e){
        e.currentTarget.focusValue = e.currentTarget.value;
    });        
    $('input[bs-datepicker]').on('blur', function (e){
        if (e.currentTarget.focusValue !== e.currentTarget.value) {
            var event = new Event('change', { bubbles: true });
            e.currentTarget.dispatchEvent(event);
        }
    });
})

This basically manually checks the value before and after the focus and blur and dispatches a new 'change' event. The { bubbles: true } bit is what got the form to detect the change. If you have any datepicker elements inside of an ng-if you'll need to wrap the listeners in a $timeout to make sure the digest happens first so all of your datepicker elements exist.

Hope this helps someone!

Stretch Image to Fit 100% of Div Height and Width

Or you can put in the CSS,

<style>
div#img {
  background-image: url(“file.png");
  color:yellow (this part doesn't matter;
  height:100%;
  width:100%;
}
</style>

FileNotFoundException..Classpath resource not found in spring?

Looking at your classpath you exclude src/main/resources and src/test/resources:

    <classpathentry excluding="**" kind="src" output="target/classes" path="src/main/resources"/>
    <classpathentry excluding="**" kind="src" output="target/test-classes" path="src/test/resources"/>

Is there a reason for it? Try not to exclude a classpath to spring-config.xml :)

round() for float in C++

There are 2 problems we are looking at:

  1. rounding conversions
  2. type conversion.

Rounding conversions mean rounding ± float/double to nearest floor/ceil float/double. May be your problem ends here. But if you are expected to return Int/Long, you need to perform type conversion, and thus "Overflow" problem might hit your solution. SO, do a check for error in your function

long round(double x) {
   assert(x >= LONG_MIN-0.5);
   assert(x <= LONG_MAX+0.5);
   if (x >= 0)
      return (long) (x+0.5);
   return (long) (x-0.5);
}

#define round(x) ((x) < LONG_MIN-0.5 || (x) > LONG_MAX+0.5 ?\
      error() : ((x)>=0?(long)((x)+0.5):(long)((x)-0.5))

from : http://www.cs.tut.fi/~jkorpela/round.html

How can jQuery deferred be used?

You can use a deferred object to make a fluid design that works well in webkit browsers. Webkit browsers will fire resize event for each pixel the window is resized, unlike FF and IE which fire the event only once for each resize. As a result, you have no control over the order in which the functions bound to your window resize event will execute. Something like this solves the problem:

var resizeQueue = new $.Deferred(); //new is optional but it sure is descriptive
resizeQueue.resolve();

function resizeAlgorithm() {
//some resize code here
}

$(window).resize(function() {
    resizeQueue.done(resizeAlgorithm);
});

This will serialize the execution of your code so that it executes as you intended it to. Beware of pitfalls when passing object methods as callbacks to a deferred. Once such method is executed as a callback to deferred, the 'this' reference will be overwritten with reference to the deferred object and will no longer refer to the object the method belongs to.

Does not contain a definition for and no extension method accepting a first argument of type could be found

placeBets(betList, stakeAmt) is an instance method not a static method. You need to create an instance of CBetfairAPI first:

MyBetfair api = new MyBetfair();
ArrayList bets = api.placeBets(betList, stakeAmt);