Programs & Examples On #Coffeescript

CoffeeScript is a language that compiles into JavaScript. Underneath all of those embarrassing braces and semicolons, JavaScript has always had a gorgeous object model at its heart. CoffeeScript is an attempt to expose the good parts of JavaScript in a simple way.

How to use mongoose findOne

You might want to consider using console.log with the built-in "arguments" object:

console.log(arguments); // would have shown you [0] null, [1] yourResult

This will always output all of your arguments, no matter how many arguments you have.

How to rotate a 3D object on axis three.js?

Somewhere around r59 this gets easier (rotate around x):

bb.GraphicsEngine.prototype.calcRotation = function ( obj, rotationX)
{
    var euler = new THREE.Euler( rotationX, 0, 0, 'XYZ' );
    obj.position.applyEuler(euler);
}

How does Trello access the user's clipboard?

Daniel LeCheminant's code didn't work for me after converting it from CoffeeScript to JavaScript (js2coffee). It kept bombing out on the _.defer() line.

I assumed this was something to do with jQuery deferreds, so I changed it to $.Deferred() and it's working now. I tested it in Internet Explorer 11, Firefox 35, and Chrome 39 with jQuery 2.1.1. The usage is the same as described in Daniel's post.

var TrelloClipboard;

TrelloClipboard = new ((function () {
    function _Class() {
        this.value = "";
        $(document).keydown((function (_this) {
            return function (e) {
                var _ref, _ref1;
                if (!_this.value || !(e.ctrlKey || e.metaKey)) {
                    return;
                }
                if ($(e.target).is("input:visible,textarea:visible")) {
                    return;
                }
                if (typeof window.getSelection === "function" ? (_ref = window.getSelection()) != null ? _ref.toString() : void 0 : void 0) {
                    return;
                }
                if ((_ref1 = document.selection) != null ? _ref1.createRange().text : void 0) {
                    return;
                }
                return $.Deferred(function () {
                    var $clipboardContainer;
                    $clipboardContainer = $("#clipboard-container");
                    $clipboardContainer.empty().show();
                    return $("<textarea id='clipboard'></textarea>").val(_this.value).appendTo($clipboardContainer).focus().select();
                });
            };
        })(this));

        $(document).keyup(function (e) {
            if ($(e.target).is("#clipboard")) {
                return $("#clipboard-container").empty().hide();
            }
        });
    }

    _Class.prototype.set = function (value) {
        this.value = value;
    };

    return _Class;

})());

React onClick and preventDefault() link refresh/redirect?

A nice and simple option that worked for me was:

<a href="javascript: false" onClick={this.handlerName}>Click Me</a>

How to use executables from a package installed locally in node_modules?

I've always used the same approach as @guneysus to solve this problem, which is creating a script in the package.json file and use it running npm run script-name.

However, in the recent months I've been using npx and I love it.

For example, I downloaded an Angular project and I didn't want to install the Angular CLI globally. So, with npx installed, instead of using the global angular cli command (if I had installed it) like this:

ng serve

I can do this from the console:

npx ng serve

Here's an article I wrote about NPX and that goes deeper into it.

Why doesn't adding CORS headers to an OPTIONS route allow browsers to access my API?

Try this in your main js file:

app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
res.header(
  "Access-Control-Allow-Headers",
  "Authorization, X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Allow-Request-Method"
);
res.header("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, DELETE");
res.header("Allow", "GET, POST, OPTIONS, PUT, DELETE");
next();
});

This should solve your problem

How to run Gulp tasks sequentially one after the other

Try this hack :-) Gulp v3.x Hack for Async bug

I tried all of the "official" ways in the Readme, they didn't work for me but this did. You can also upgrade to gulp 4.x but I highly recommend you don't, it breaks so much stuff. You could use a real js promise, but hey, this is quick, dirty, simple :-) Essentially you use:

var wait = 0; // flag to signal thread that task is done
if(wait == 0) setTimeout(... // sleep and let nodejs schedule other threads

Check out the post!

How do I get the Back Button to work with an AngularJS ui-router state machine?

history.back() and switch to previous state often give effect not that you want. For example, if you have form with tabs and each tab has own state, this just switched previous tab selected, not return from form. In case nested states, you usually need so think about witch of parent states you want to rollback.

This directive solves problem

angular.module('app', ['ui-router-back'])

<span ui-back='defaultState'> Go back </span>

It returns to state, that was active before button has displayed. Optional defaultState is state name that used when no previous state in memory. Also it restores scroll position

Code

class UiBackData {
    fromStateName: string;
    fromParams: any;
    fromStateScroll: number;
}

interface IRootScope1 extends ng.IScope {
    uiBackData: UiBackData;
}

class UiBackDirective implements ng.IDirective {
    uiBackDataSave: UiBackData;

    constructor(private $state: angular.ui.IStateService,
        private $rootScope: IRootScope1,
        private $timeout: ng.ITimeoutService) {
    }

    link: ng.IDirectiveLinkFn = (scope, element, attrs) => {
        this.uiBackDataSave = angular.copy(this.$rootScope.uiBackData);

        function parseStateRef(ref, current) {
            var preparsed = ref.match(/^\s*({[^}]*})\s*$/), parsed;
            if (preparsed) ref = current + '(' + preparsed[1] + ')';
            parsed = ref.replace(/\n/g, " ").match(/^([^(]+?)\s*(\((.*)\))?$/);
            if (!parsed || parsed.length !== 4)
                throw new Error("Invalid state ref '" + ref + "'");
            let paramExpr = parsed[3] || null;
            let copy = angular.copy(scope.$eval(paramExpr));
            return { state: parsed[1], paramExpr: copy };
        }

        element.on('click', (e) => {
            e.preventDefault();

            if (this.uiBackDataSave.fromStateName)
                this.$state.go(this.uiBackDataSave.fromStateName, this.uiBackDataSave.fromParams)
                    .then(state => {
                        // Override ui-router autoscroll 
                        this.$timeout(() => {
                            $(window).scrollTop(this.uiBackDataSave.fromStateScroll);
                        }, 500, false);
                    });
            else {
                var r = parseStateRef((<any>attrs).uiBack, this.$state.current);
                this.$state.go(r.state, r.paramExpr);
            }
        });
    };

    public static factory(): ng.IDirectiveFactory {
        const directive = ($state, $rootScope, $timeout) =>
            new UiBackDirective($state, $rootScope, $timeout);
        directive.$inject = ['$state', '$rootScope', '$timeout'];
        return directive;
    }
}

angular.module('ui-router-back')
    .directive('uiBack', UiBackDirective.factory())
    .run(['$rootScope',
        ($rootScope: IRootScope1) => {

            $rootScope.$on('$stateChangeSuccess',
                (event, toState, toParams, fromState, fromParams) => {
                    if ($rootScope.uiBackData == null)
                        $rootScope.uiBackData = new UiBackData();
                    $rootScope.uiBackData.fromStateName = fromState.name;
                    $rootScope.uiBackData.fromStateScroll = $(window).scrollTop();
                    $rootScope.uiBackData.fromParams = fromParams;
                });
        }]);

Create an ISO date object in javascript

try below:

var temp_datetime_obj = new Date();

collection.find({
    start_date:{
        $gte: new Date(temp_datetime_obj.toISOString())
    }
}).toArray(function(err, items) { 
    /* you can console.log here */ 
});

Ternary operation in CoffeeScript

Coffeescript doesn't support javascript ternary operator. Here is the reason from the coffeescript author:

I love ternary operators just as much as the next guy (probably a bit more, actually), but the syntax isn't what makes them good -- they're great because they can fit an if/else on a single line as an expression.

Their syntax is just another bit of mystifying magic to memorize, with no analogue to anything else in the language. The result being equal, I'd much rather have if/elses always look the same (and always be compiled into an expression).

So, in CoffeeScript, even multi-line ifs will compile into ternaries when appropriate, as will if statements without an else clause:

if sunny   
  go_outside() 
else   
  read_a_book().

if sunny then go_outside() else read_a_book()

Both become ternaries, both can be used as expressions. It's consistent, and there's no new syntax to learn. So, thanks for the suggestion, but I'm closing this ticket as "wontfix".

Please refer to the github issue: https://github.com/jashkenas/coffeescript/issues/11#issuecomment-97802

Exec : display stdout "live"

exec will also return a ChildProcess object that is an EventEmitter.

var exec = require('child_process').exec;
var coffeeProcess = exec('coffee -cw my_file.coffee');

coffeeProcess.stdout.on('data', function(data) {
    console.log(data); 
});

OR pipe the child process's stdout to the main stdout.

coffeeProcess.stdout.pipe(process.stdout);

OR inherit stdio using spawn

spawn('coffee -cw my_file.coffee', { stdio: 'inherit' });

How do I define global variables in CoffeeScript?

If you're a bad person (I'm a bad person.), you can get as simple as this: (->@)()

As in,

(->@)().im_a_terrible_programmer = yes
console.log im_a_terrible_programmer

This works, because when invoking a Reference to a Function ‘bare’ (that is, func(), instead of new func() or obj.func()), something commonly referred to as the ‘function-call invocation pattern’, always binds this to the global object for that execution context.

The CoffeeScript above simply compiles to (function(){ return this })(); so we're exercising that behavior to reliably access the global object.

Simple way to change the position of UIView?

Other way:

CGPoint position = CGPointMake(100,30);
[self setFrame:(CGRect){
      .origin = position,
      .size = self.frame.size
}];

This i save size parameters and change origin only.

What is the role of the bias in neural networks?

When you use ANNs, you rarely know about the internals of the systems you want to learn. Some things cannot be learned without a bias. E.g., have a look at the following data: (0, 1), (1, 1), (2, 1), basically a function that maps any x to 1.

If you have a one layered network (or a linear mapping), you cannot find a solution. However, if you have a bias it's trivial!

In an ideal setting, a bias could also map all points to the mean of the target points and let the hidden neurons model the differences from that point.

Optimum way to compare strings in JavaScript?

Well in JavaScript you can check two strings for values same as integers so yo can do this:

  • "A" < "B"
  • "A" == "B"
  • "A" > "B"

And therefore you can make your own function that checks strings the same way as the strcmp().

So this would be the function that does the same:

function strcmp(a, b)
{   
    return (a<b?-1:(a>b?1:0));  
}

How to use the curl command in PowerShell?

Use splatting.

$CurlArgument = '-u', '[email protected]:yyyy',
                '-X', 'POST',
                'https://xxx.bitbucket.org/1.0/repositories/abcd/efg/pull-requests/2229/comments',
                '--data', 'content=success'
$CURLEXE = 'C:\Program Files\Git\mingw64\bin\curl.exe'
& $CURLEXE @CurlArgument

jquery - check length of input field?

That doesn't work because, judging by the rest of the code, the initial value of the text input is "Default text" - which is more than one character, and so your if condition is always true.

The simplest way to make it work, it seems to me, is to account for this case:

    var value = $(this).val();
    if ( value.length > 0 && value != "Default text" ) ...

PHPMailer AddAddress()

Some great answers above, using that info here is what I did today to solve the same issue:

$to_array = explode(',', $to);
foreach($to_array as $address)
{
    $mail->addAddress($address, 'Web Enquiry');
}

Warning: mysqli_query() expects at least 2 parameters, 1 given. What?

the mysqli_queryexcepts 2 parameters , first variable is mysqli_connectequivalent variable , second one is the query you have provided

$name1 = mysqli_connect(localhost,tdoylex1_dork,dorkk,tdoylex1_dork);

$name2 = mysqli_query($name1,"SELECT name FROM users ORDER BY RAND() LIMIT 1");

Android appcompat v7:23

Ran into a similar issue using React Native

> Could not find com.android.support:appcompat-v7:23.0.1.

the Support Libraries are Local Maven repository for Support Libraries

enter image description here

Get Request and Session Parameters and Attributes from JSF pages

You can get a request parameter id using the expression:

<h:outputText value="#{param['id']}" />
  • param—An immutable Map of the request parameters for this request, keyed by parameter name. Only the first value for each parameter name is included.
  • sessionScope—A Map of the session attributes for this request, keyed by attribute name.

Section 5.3.1.2 of the JSF 1.0 specification defines the objects that must be resolved by the variable resolver.

How to get MD5 sum of a string using python?

Try This 
import hashlib
user = input("Enter text here ")
h = hashlib.md5(user.encode())
h2 = h.hexdigest()
print(h2)

Recommended Fonts for Programming?

I've really fallen in love with Droid Sans Mono.

alt text

Column/Vertical selection with Keyboard in SublimeText 3

You should see Sublime Column Selection:

Using the Mouse

Different mouse buttons are used on each platform:

OS X

  • Left Mouse Button + ?
  • OR: Middle Mouse Button

  • Add to selection: ?

  • Subtract from selection: ?+?

Windows

  • Right Mouse Button + Shift
  • OR: Middle Mouse Button

  • Add to selection: Ctrl

  • Subtract from selection: Alt

Linux

  • Right Mouse Button + Shift

  • Add to selection: Ctrl

  • Subtract from selection: Alt

Using the Keyboard

OS X

  • Ctrl + Shift + ?
  • Ctrl + Shift + ?

Windows

  • Ctrl + Alt + ?
  • Ctrl + Alt + ?

Linux

  • Ctrl + Alt + ?
  • Ctrl + Alt + ?

Replace String in all files in Eclipse

ctrl + H  will show the option to replace in the bottom . 

enter image description here

Once you click on replace it will show as below

enter image description here

Select first empty cell in column F starting from row 1. (without using offset )

NextRow = Application.WorksheetFunction.CountA(Range("A:A")) + 1

How to avoid installing "Unlimited Strength" JCE policy files when deploying an application?

There are a couple of commonly quoted solutions to this problem. Unfortunately neither of these are entirely satisfactory:

  • Install the unlimited strength policy files. While this is probably the right solution for your development workstation, it quickly becomes a major hassle (if not a roadblock) to have non-technical users install the files on every computer. There is no way to distribute the files with your program; they must be installed in the JRE directory (which may even be read-only due to permissions).
  • Skip the JCE API and use another cryptography library such as Bouncy Castle. This approach requires an extra 1MB library, which may be a significant burden depending on the application. It also feels silly to duplicate functionality included in the standard libraries. Obviously, the API is also completely different from the usual JCE interface. (BC does implement a JCE provider, but that doesn't help because the key strength restrictions are applied before handing over to the implementation.) This solution also won't let you use 256-bit TLS (SSL) cipher suites, because the standard TLS libraries call the JCE internally to determine any restrictions.

But then there's reflection. Is there anything you can't do using reflection?

private static void removeCryptographyRestrictions() {
    if (!isRestrictedCryptography()) {
        logger.fine("Cryptography restrictions removal not needed");
        return;
    }
    try {
        /*
         * Do the following, but with reflection to bypass access checks:
         *
         * JceSecurity.isRestricted = false;
         * JceSecurity.defaultPolicy.perms.clear();
         * JceSecurity.defaultPolicy.add(CryptoAllPermission.INSTANCE);
         */
        final Class<?> jceSecurity = Class.forName("javax.crypto.JceSecurity");
        final Class<?> cryptoPermissions = Class.forName("javax.crypto.CryptoPermissions");
        final Class<?> cryptoAllPermission = Class.forName("javax.crypto.CryptoAllPermission");

        final Field isRestrictedField = jceSecurity.getDeclaredField("isRestricted");
        isRestrictedField.setAccessible(true);
        final Field modifiersField = Field.class.getDeclaredField("modifiers");
        modifiersField.setAccessible(true);
        modifiersField.setInt(isRestrictedField, isRestrictedField.getModifiers() & ~Modifier.FINAL);
        isRestrictedField.set(null, false);

        final Field defaultPolicyField = jceSecurity.getDeclaredField("defaultPolicy");
        defaultPolicyField.setAccessible(true);
        final PermissionCollection defaultPolicy = (PermissionCollection) defaultPolicyField.get(null);

        final Field perms = cryptoPermissions.getDeclaredField("perms");
        perms.setAccessible(true);
        ((Map<?, ?>) perms.get(defaultPolicy)).clear();

        final Field instance = cryptoAllPermission.getDeclaredField("INSTANCE");
        instance.setAccessible(true);
        defaultPolicy.add((Permission) instance.get(null));

        logger.fine("Successfully removed cryptography restrictions");
    } catch (final Exception e) {
        logger.log(Level.WARNING, "Failed to remove cryptography restrictions", e);
    }
}

private static boolean isRestrictedCryptography() {
    // This matches Oracle Java 7 and 8, but not Java 9 or OpenJDK.
    final String name = System.getProperty("java.runtime.name");
    final String ver = System.getProperty("java.version");
    return name != null && name.equals("Java(TM) SE Runtime Environment")
            && ver != null && (ver.startsWith("1.7") || ver.startsWith("1.8"));
}

Simply call removeCryptographyRestrictions() from a static initializer or such before performing any cryptographic operations.

The JceSecurity.isRestricted = false part is all that is needed to use 256-bit ciphers directly; however, without the two other operations, Cipher.getMaxAllowedKeyLength() will still keep reporting 128, and 256-bit TLS cipher suites won't work.

This code works on Oracle Java 7 and 8, and automatically skips the process on Java 9 and OpenJDK where it's not needed. Being an ugly hack after all, it likely doesn't work on other vendors' VMs.

It also doesn't work on Oracle Java 6, because the private JCE classes are obfuscated there. The obfuscation does not change from version to version though, so it is still technically possible to support Java 6.

Visual Studio Code - is there a Compare feature like that plugin for Notepad ++?

You can compare files from the explorer either from the working files section or the folder section. You can also trigger the global compare action from the command palette.

Python "\n" tag extra line

use join(), don't rely on the , for formatting, and also print automatically puts the cursor on a newline every time, so no need of adding another '\n' in your print.

In [24]: for x in board:
    print " ".join(map(str,x))
   ....:     
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 3 2 1 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0

Check if at least two out of three booleans are true

Yet another way to do this but not a very good one:

return (Boolean.valueOf(a).hashCode() + Boolean.valueOf(b).hashCode() + Boolean.valueOf(c).hashCode()) < 3705);

The Boolean hashcode values are fixed at 1231 for true and 1237 for false so could equally have used <= 3699

Generate random 5 characters string

$rand = substr(md5(microtime()),rand(0,26),5);

Would be my best guess--Unless you're looking for special characters, too:

$seed = str_split('abcdefghijklmnopqrstuvwxyz'
                 .'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
                 .'0123456789!@#$%^&*()'); // and any other characters
shuffle($seed); // probably optional since array_is randomized; this may be redundant
$rand = '';
foreach (array_rand($seed, 5) as $k) $rand .= $seed[$k];

Example

And, for one based on the clock (fewer collisions since it's incremental):

function incrementalHash($len = 5){
  $charset = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  $base = strlen($charset);
  $result = '';

  $now = explode(' ', microtime())[1];
  while ($now >= $base){
    $i = $now % $base;
    $result = $charset[$i] . $result;
    $now /= $base;
  }
  return substr($result, -5);
}

Note: incremental means easier to guess; If you're using this as a salt or a verification token, don't. A salt (now) of "WCWyb" means 5 seconds from now it's "WCWyg")

What is the difference between git pull and git fetch + git rebase?

TLDR:

git pull is like running git fetch then git merge
git pull --rebase is like git fetch then git rebase

In reply to your first statement,

git pull is like a git fetch + git merge.

"In its default mode, git pull is shorthand for git fetch followed by git merge FETCH_HEAD" More precisely, git pull runs git fetch with the given parameters and then calls git merge to merge the retrieved branch heads into the current branch"

(Ref: https://git-scm.com/docs/git-pull)


For your second statement/question:

'But what is the difference between git pull VS git fetch + git rebase'

Again, from same source:
git pull --rebase

"With --rebase, it runs git rebase instead of git merge."


Now, if you wanted to ask

'the difference between merge and rebase'

that is answered here too:
https://git-scm.com/book/en/v2/Git-Branching-Rebasing
(the difference between altering the way version history is recorded)

How to do logging in React Native?

Chrome Devtool is the best and easiest way for logging and debugging.

How to get a tab character?

I use <span style="display: inline-block; width: 2ch;">&#9;</span> for a two characters wide tab.

What is JSONP, and why was it created?

Because you can ask the server to prepend a prefix to the returned JSON object. E.g

function_prefix(json_object);

in order for the browser to eval "inline" the JSON string as an expression. This trick makes it possible for the server to "inject" javascript code directly in the Client browser and this with bypassing the "same origin" restrictions.

In other words, you can achieve cross-domain data exchange.


Normally, XMLHttpRequest doesn't permit cross-domain data-exchange directly (one needs to go through a server in the same domain) whereas:

<script src="some_other_domain/some_data.js&prefix=function_prefix>` one can access data from a domain different than from the origin.


Also worth noting: even though the server should be considered as "trusted" before attempting that sort of "trick", the side-effects of possible change in object format etc. can be contained. If a function_prefix (i.e. a proper js function) is used to receive the JSON object, the said function can perform checks before accepting/further processing the returned data.

Does uninstalling a package with "pip" also remove the dependent packages?

i've successfully removed dependencies of a package using this bash line:

for dep in $(pip show somepackage | grep Requires | sed 's/Requires: //g; s/,//g') ; do pip uninstall -y $dep ; done

this worked on pip 1.5.4

How to actually search all files in Visual Studio

One can access the "Find in Files" window via the drop-down menu selection and search all files in the Entire Solution: Edit > Find and Replace > Find in Files

enter image description here

Other, alternative is to open the "Find in Files" window via the "Standard Toolbars" button as highlighted in the below screen-short:

enter image description here

matching query does not exist Error in Django

In case anybody is here and the other two solutions do not make the trick, check that what you are using to filter is what you expect:

user = UniversityDetails.objects.get(email=email)

is email a str, or a None? or an int?

Laravel 5 – Clear Cache in Shared Hosting Server

Used this page a few times to copy and paste quick commands into composer, so I wrote a command that does these commands in one single artisan command.

namespace App\Console\Commands\Admin;

use Illuminate\Console\Command;

class ClearEverything extends Command
{

    protected $signature = 'traqza:clear-everything';

    protected $description = 'Clears routes, config, cache, views, compiled, and caches config.';

    public function __construct()
    {
        parent::__construct();
    }

    public function handle()
    {
        $validCommands = array('route:clear', 'config:clear', 'cache:clear', 'view:clear', 'clear-compiled', 'config:cache');
        foreach ($validCommands as $cmd) {
            $this->call('' . $cmd . '');

        }
    }
}

Place in app\Console\Commands\Admin folder

then run command in composer php artisan traqza:clear-everything

Happy coding.

Github -> https://github.com/Traqza/clear-everything

How do I write a backslash (\) in a string?

txtPath.Text = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)+"\\\Tasks";

Put a double backslash instead of a single backslash...

Express.js req.body undefined

You can use express body parser.

var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));

Single vs double quotes in JSON

JSON syntax is not Python syntax. JSON requires double quotes for its strings.

subquery in FROM must have an alias

In the case of nested tables, some DBMS require to use an alias like MySQL and Oracle but others do not have such a strict requirement, but still allow to add them to substitute the result of the inner query.

How do you run a .bat file from PHP?

You might need to run it via cmd, eg:

system("cmd /c C:[path to file]");

How to convert milliseconds into human readable form?

In java

public static String formatMs(long millis) {
    long hours = TimeUnit.MILLISECONDS.toHours(millis);
    long mins = TimeUnit.MILLISECONDS.toMinutes(millis);
    long secs = TimeUnit.MILLISECONDS.toSeconds(millis);
    return String.format("%dh %d min, %d sec",
            hours,
            mins - TimeUnit.HOURS.toMinutes(hours),
            secs - TimeUnit.MINUTES.toSeconds(mins)
    );
}

Gives something like this:

12h 1 min, 34 sec

How to use gitignore command in git

on my mac i found this file .gitignore_global ..it was in my home directory hidden so do a ls -altr to see it.

I added eclipse files i wanted git to ignore. the contents looks like this:

 *~
.DS_Store
.project
.settings
.classpath
.metadata

How to find whether or not a variable is empty in Bash?

[ "$variable" ] || echo empty
: ${variable="value_to_set_if_unset"}

#1025 - Error on rename of './database/#sql-2e0f_1254ba7' to './database/table' (errno: 150)

If you are adding a foreign key and faced this error, it could be the value in the child table is not present in the parent table.

Let's say for the column to which the foreign key has to be added has all values set to 0 and the value is not available in the table you are referencing it.

You can set some value which is present in the parent table and then adding foreign key worked for me.

Add / remove input field dynamically with jQuery

you can do it as follow:

 $("#addButton").click(function () {

    if(counter>10){
            alert("Only 10 textboxes allow");
            return false;
    }   

    var newTextBoxDiv = $(document.createElement('div'))
         .attr("id", 'TextBoxDiv' + counter);

    newTextBoxDiv.after().html('<label>Textbox #'+ counter + ' : </label>' +
          '<input type="text" name="textbox' + counter + 
          '" id="textbox' + counter + '" value="" >');

    newTextBoxDiv.appendTo("#TextBoxesGroup");


    counter++;
     });

     $("#removeButton").click(function () {
    if(counter==1){
          alert("No more textbox to remove");
          return false;
       }   

    counter--;

        $("#TextBoxDiv" + counter).remove();

     });

refer live demo http://www.mkyong.com/jquery/how-to-add-remove-textbox-dynamically-with-jquery/

What's the easiest way to escape HTML in Python?

For legacy code in Python 2.7, can do it via BeautifulSoup4:

>>> bs4.dammit import EntitySubstitution
>>> esub = EntitySubstitution()
>>> esub.substitute_html("r&d")
'r&amp;d'

Zookeeper connection error

This can happen if there are too many open connections.

Try increasing the maxClientCnxns setting.

From documentation:

maxClientCnxns (No Java system property)

Limits the number of concurrent connections (at the socket level) that a single client, identified by IP address, may make to a single member of the ZooKeeper ensemble. This is used to prevent certain classes of DoS attacks, including file descriptor exhaustion. Setting this to 0 or omitting it entirely removes the limit on concurrent connections.

You can edit settings in the config file. Most likely it can be found at /etc/zookeeper/conf/zoo.cfg.

In modern ZooKeeper versions default value is 60. You can increase it by adding the maxClientCnxns=4096 line to the end of the config file.

Why does Eclipse Java Package Explorer show question mark on some classes?

those icons are a way of Egit to show you status of the current file/folder in git. You might want to check this out:

image describing Eclipse icons for Egit

  • dirty (folder) - At least one file below the folder is dirty; that means that it has changes in the working tree that are neither in the index nor in the repository.
  • tracked - The resource is known to the Git repository. untracked - The resource is not known to the Git repository.
  • ignored - The resource is ignored by the Git team provider. Here only the preference settings under Team -> Ignored Resources and the "derived" flag are relevant. The .gitignore file is not taken into account.
  • dirty - The resource has changes in the working tree that are neither in the index nor in the repository.
  • staged - The resource has changes which are added to the index. Not that adding to the index is possible at the moment only on the commit dialog on the context menu of a resource.
  • partially-staged - The resource has changes which are added to the index and additionally changes in the working tree that are neither in the index nor in the repository.
  • added - The resource is not yet tracked by but added to the Git repository.
  • removed - The resource is staged for removal from the Git repository.
  • conflict - A merge conflict exists for the file.
  • assume-valid - The resource has the "assume unchanged" flag. This means that Git stops checking the working tree files for possible modifications, so you need to manually unset the bit to tell Git when you change the working tree file. This setting can be switched on with the menu action Team->Assume unchanged (or on the command line with git update-index--assume-unchanged).

Android - styling seek bar

For APIs < 21 (and >= 21) you can use the answer of @Ahamadullah Saikat or https://www.lvguowei.me/post/customize-android-seekbar-color/.

enter image description here

<SeekBar
    android:id="@+id/seekBar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:maxHeight="3dp"
    android:minHeight="3dp"
    android:progress="50"
    android:progressDrawable="@drawable/seek_bar_ruler"
    android:thumb="@drawable/seek_bar_slider"
    />

drawable/seek_bar_ruler.xml:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@android:id/background">
        <shape android:shape="rectangle">
            <solid
                android:color="#94A3B3" />
            <corners android:radius="2dp" />
        </shape>
    </item>
    <item android:id="@android:id/progress">
        <clip>
            <shape android:shape="rectangle">
                <solid
                    android:color="#18244D" />
                <corners android:radius="2dp" />
            </shape>
        </clip>
    </item>
</layer-list>

drawable/seek_bar_slider.xml:

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

    <solid android:color="#FFFFFF" />
    <stroke
        android:width="4dp"
        android:color="#18244D"
        />
    <size
        android:width="25dp"
        android:height="25dp"
        />
</shape>

writing to serial port from linux command line

SCREEN:

NOTE: screen is actually not able to send hex, as far as I know. To do that, use echo or printf

I was using the suggestions in this post to write to a serial port, then using the info from another post to read from the port, with mixed results. I found that using screen is an "easier" solution, since it opens a terminal session directly with that port. (I put easier in quotes, because screen has a really weird interface, IMO, and takes some further reading to figure it out.)

You can issue this command to open a screen session, then anything you type will be sent to the port, plus the return values will be printed below it:

screen /dev/ttyS0 19200,cs8

(Change the above to fit your needs for speed, parity, stop bits, etc.) I realize screen isn't the "linux command line" as the post specifically asks for, but I think it's in the same spirit. Plus, you don't have to type echo and quotes every time.

ECHO:

Follow praetorian droid's answer. HOWEVER, this didn't work for me until I also used the cat command (cat < /dev/ttyS0) while I was sending the echo command.

PRINTF:

I found that one can also use printf's '%x' command:

c="\x"$(printf '%x' 0x12)
printf $c >> $SERIAL_COMM_PORT

Again, for printf, start cat < /dev/ttyS0 before sending the command.

How is Pythons glob.glob ordered?

Order is arbitrary, but you can sort them yourself

If you want sorted by name:

sorted(glob.glob('*.png'))

sorted by modification time:

import os
sorted(glob.glob('*.png'), key=os.path.getmtime)

sorted by size:

import os
sorted(glob.glob('*.png'), key=os.path.getsize)

etc.

Remove the title bar in Windows Forms

if by Blue Border thats on top of the Window Form you mean titlebar, set Forms ControlBox property to false and Text property to empty string ("").

here's a snippet:

this.ControlBox = false;
this.Text = String.Empty;

Change mysql user password using command line

Note: u should login as root user

 SET PASSWORD FOR 'root'@'localhost' = PASSWORD('your password');

Batch script to delete files

in batch code your path should not contain any Space so pls change your folder name from "TEST 100%" to "TEST_100%" and your new code will be del "D:\TEST\TEST_100%\Archive*.TXT"

hope this will resolve your problem

Rename a column in MySQL

Use the following query:

ALTER TABLE tableName CHANGE oldcolname newcolname datatype(length);

The RENAME function is used in Oracle databases.

ALTER TABLE tableName RENAME COLUMN oldcolname TO newcolname datatype(length);

@lad2025 mentions it below, but I thought it'd be nice to add what he said. Thank you @lad2025!

You can use the RENAME COLUMN in MySQL 8.0 to rename any column you need renamed.

ALTER TABLE table_name RENAME COLUMN old_col_name TO new_col_name;

ALTER TABLE Syntax: RENAME COLUMN:

  • Can change a column name but not its definition.
  • More convenient than CHANGE to rename a column without changing its definition.

Parse error: syntax error, unexpected [

Are you using php 5.4 on your local? the render line is using the new way of initializing arrays. Try replacing ["title" => "Welcome "] with array("title" => "Welcome ")

What are the lengths of Location Coordinates, latitude and longitude?

If the latitude coordinate is reported as -6.3572375290155 or -63.572375290155 in decimal degrees then you could round-off and store up to 6 decimal places for 10 cm (or 0.1 meters) precision.

Overview

The valid range of latitude in degrees is -90 and +90 for the southern and northern hemisphere respectively. Longitude is in the range -180 and +180 specifying coordinates west and east of the Prime Meridian, respectively.

For reference, the Equator has a latitude of 0°, the North pole has a latitude of 90° north (written 90° N or +90°), and the South pole has a latitude of -90°.

The Prime Meridian has a longitude of 0° that goes through Greenwich, England. The International Date Line (IDL) roughly follows the 180° longitude. A longitude with a positive value falls in the eastern hemisphere and the negative value falls in the western hemisphere.

Decimal degrees precision

Six (6) decimal places precision in coordinates using decimal degrees notation is at a 10 cm (or 0.1 meters) resolution. Each .000001 difference in coordinate decimal degree is approximately 10 cm in length. For example, the imagery of Google Earth and Google Maps is typically at the 1-meter resolution, and some places have a higher resolution of 1 inch per pixel. One meter resolution can be represented using 5 decimal places so more than 6 decimal places are extraneous for that resolution. The distance between longitudes at the equator is the same as latitude, but the distance between longitudes reaches zero at the poles as the lines of meridian converge at that point.

For millimeter (mm) precision then represent lat/lon with 8 decimal places in decimal degrees format. Since most applications don't need that level of precision 6 decimal places is sufficient for most cases.

In the other direction, whole decimal degrees represent a distance of ~111 km (or 60 nautical miles) and a 0.1 decimal degree difference represents a ~11 km distance.

Here is a table of # decimal places difference in latitude with the delta degrees and the estimated distance in meters using 0,0 as the starting point.

Decimal places Decimal degrees Distance (meters)
1 0.10000000 11,057.43 11 km
2 0.01000000 1,105.74 1 km
3 0.00100000 110.57
4 0.00010000 11.06
5 0.00001000 1.11
6 0.00000100 0.11 11 cm
7 0.00000010 0.01 1 cm
8 0.00000001 0.001 1 mm

Degrees-minute-second (DMS) representation

For DMS notation 1 arc second = 1/60/60 degree = ~30 meter length and 0.1 arc sec delta is ~3 meters.

Example:

  • 0° 0' 0" W, 0° 0' 0" N ? 0° 0' 0" W, 0° 0' 1" N ? 30.715 meters
  • 0° 0' 0" W, 0° 0' 0" N ? 0° 0' 0" W, 0° 0' 0.1" N ? 3.0715 meters

1 arc minute = 1/60 degree = ~2000m (2km)


Update:

Here is an amusing comic strip about coordinate precision.

Tomcat started in Eclipse but unable to connect to http://localhost:8085/

Eclipse hooks Dynamic Web projects into tomcat and maintains it's own configuration but does not deploy the standard tomcat ROOT.war. As http://localhost:8085/ link returns 404 does indeed show that tomcat is up and running, just can't find a web app deployed to root.

By default, any deployed dynamic web projects use their project name as context root, so you should see http://localhost:8085/yourprojectname working properly, but check the Servers tab first to ensure that your web project has actually been deployed.

Hope that helps.

Insert if not exists Oracle

We can combine the DUAL and NOT EXISTS to archive your requirement:

INSERT INTO schema.myFoo ( 
    primary_key, value1, value2
) 
SELECT
    'bar', 'baz', 'bat' 
FROM DUAL
WHERE NOT EXISTS (
    SELECT 1 
    FROM schema.myFoo
    WHERE primary_key = 'bar'
);

Add zero-padding to a string

You can use PadLeft

var newString = Your_String.PadLeft(4, '0');

concat yesterdays date with a specific time

where date_dt = to_date(to_char(sysdate-1, 'YYYY-MM-DD') || ' 19:16:08', 'YYYY-MM-DD HH24:MI:SS') 

should work.

How do I extract data from a DataTable?

  var table = Tables[0]; //get first table from Dataset
  foreach (DataRow row in table.Rows)
     {
       foreach (var item in row.ItemArray)
         {
            console.Write("Value:"+item);
         }
     }

c# replace \" characters

\ => \\ and " => \"

so Replace("\\\"","")

How I add Headers to http.get or http.post in Typescript and angular 2?

You can define a Headers object with a dictionary of HTTP key/value pairs, and then pass it in as an argument to http.get() and http.post() like this:

const headerDict = {
  'Content-Type': 'application/json',
  'Accept': 'application/json',
  'Access-Control-Allow-Headers': 'Content-Type',
}

const requestOptions = {                                                                                                                                                                                 
  headers: new Headers(headerDict), 
};

return this.http.get(this.heroesUrl, requestOptions)

Or, if it's a POST request:

const data = JSON.stringify(heroData);
return this.http.post(this.heroesUrl, data, requestOptions);

Since Angular 7 and up you have to use HttpHeaders class instead of Headers:

const requestOptions = {                                                                                                                                                                                 
  headers: new HttpHeaders(headerDict), 
};

Copy Paste in Bash on Ubuntu on Windows

For pasting into Vim in the terminal (bash on ubuntu on windows):

export DISPLAY=localhost:0.0

Not sure how to copy from Vim though :-(

gcc: undefined reference to

Are you mixing C and C++? One issue that can occur is that the declarations in the .h file for a .c file need to be surrounded by:

#if defined(__cplusplus)
  extern "C" {                 // Make sure we have C-declarations in C++ programs
#endif

and:

#if defined(__cplusplus)
  }
#endif

Note: if unable / unwilling to modify the .h file(s) in question, you can surround their inclusion with extern "C":

extern "C" {
#include <abc.h>
} //extern

How to automatically generate N "distinct" colors?

I have written a package for R called qualpalr that is designed specifically for this purpose. I recommend you look at the vignette to find out how it works, but I will try to summarize the main points.

qualpalr takes a specification of colors in the HSL color space (which was described previously in this thread), projects it to the DIN99d color space (which is perceptually uniform) and find the n that maximize the minimum distance between any oif them.

# Create a palette of 4 colors of hues from 0 to 360, saturations between
# 0.1 and 0.5, and lightness from 0.6 to 0.85
pal <- qualpal(n = 4, list(h = c(0, 360), s = c(0.1, 0.5), l = c(0.6, 0.85)))

# Look at the colors in hex format
pal$hex
#> [1] "#6F75CE" "#CC6B76" "#CAC16A" "#76D0D0"

# Create a palette using one of the predefined color subspaces
pal2 <- qualpal(n = 4, colorspace = "pretty")

# Distance matrix of the DIN99d color differences
pal2$de_DIN99d
#>        #69A3CC #6ECC6E #CA6BC4
#> 6ECC6E      22                
#> CA6BC4      21      30        
#> CD976B      24      21      21

plot(pal2)

enter image description here

Plotting multiple lines, in different colors, with pandas dataframe

You could use groupby to split the DataFrame into subgroups according to the color:

for key, grp in df.groupby(['color']):

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_table('data', sep='\s+')
fig, ax = plt.subplots()

for key, grp in df.groupby(['color']):
    ax = grp.plot(ax=ax, kind='line', x='x', y='y', c=key, label=key)

plt.legend(loc='best')
plt.show()

yields enter image description here

How do I add a .click() event to an image?

Enclose <img> in <a> tag.

<a href="http://www.google.com.pk"><img src="smiley.gif"></a>

it will open link on same tab, and if you want to open link on new tab then use target="_blank"

<a href="http://www.google.com.pk" target="_blank"><img src="smiley.gif"></a>

How do you programmatically set an attribute?

Usually, we define classes for this.

class XClass( object ):
   def __init__( self ):
       self.myAttr= None

x= XClass()
x.myAttr= 'magic'
x.myAttr

However, you can, to an extent, do this with the setattr and getattr built-in functions. However, they don't work on instances of object directly.

>>> a= object()
>>> setattr( a, 'hi', 'mom' )
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'object' object has no attribute 'hi'

They do, however, work on all kinds of simple classes.

class YClass( object ):
    pass

y= YClass()
setattr( y, 'myAttr', 'magic' )
y.myAttr

How to access the value of a promise?

promiseA's then function returns a new promise (promiseB) that is immediately resolved after promiseA is resolved, its value is the value of the what is returned from the success function within promiseA.

In this case promiseA is resolved with a value - result and then immediately resolves promiseB with the value of result + 1.

Accessing the value of promiseB is done in the same way we accessed the result of promiseA.

promiseB.then(function(result) {
    // here you can use the result of promiseB
});

Edit December 2019: async/await is now standard in JS, which allows an alternative syntax to the approach described above. You can now write:

let result = await functionThatReturnsPromiseA();
result = result + 1;

Now there is no promiseB, because we've unwrapped the result from promiseA using await, and you can work with it directly.

However, await can only be used inside an async function. So to zoom out slightly, the above would have to be contained like so:

async function doSomething() {
    let result = await functionThatReturnsPromiseA();
    return result + 1;
}

Modify request parameter with servlet filter

As you've noted HttpServletRequest does not have a setParameter method. This is deliberate, since the class represents the request as it came from the client, and modifying the parameter would not represent that.

One solution is to use the HttpServletRequestWrapper class, which allows you to wrap one request with another. You can subclass that, and override the getParameter method to return your sanitized value. You can then pass that wrapped request to chain.doFilter instead of the original request.

It's a bit ugly, but that's what the servlet API says you should do. If you try to pass anything else to doFilter, some servlet containers will complain that you have violated the spec, and will refuse to handle it.

A more elegant solution is more work - modify the original servlet/JSP that processes the parameter, so that it expects a request attribute instead of a parameter. The filter examines the parameter, sanitizes it, and sets the attribute (using request.setAttribute) with the sanitized value. No subclassing, no spoofing, but does require you to modify other parts of your application.

Split string based on regex

I suggest

l = re.compile("(?<!^)\s+(?=[A-Z])(?!.\s)").split(s)

Check this demo.

Error Handler - Exit Sub vs. End Sub

Typically if you have database connections or other objects declared that, whether used safely or created prior to your exception, will need to be cleaned up (disposed of), then returning your error handling code back to the ProcExit entry point will allow you to do your garbage collection in both cases.

If you drop out of your procedure by falling to Exit Sub, you may risk having a yucky build-up of instantiated objects that are just sitting around in your program's memory.

"relocation R_X86_64_32S against " linking Error

I've got a similar error when installing FCL that needs CCD lib(libccd) like this:

/usr/bin/ld: /usr/local/lib/libccd.a(ccd.o): relocation R_X86_64_32S against `a local symbol' can not be used when making a shared object; recompile with -fPIC

I find that there is two different files named "libccd.a" :

  1. /usr/local/lib/libccd.a
  2. /usr/local/lib/x86_64-linux-gnu/libccd.a

I solved the problem by removing the first file.

How to convert seconds to time format?

This might be simpler

gmdate("H:i:s", $seconds)

PHP gmdate

What is trunk, branch and tag in Subversion?

If you're new to Subversion you may want to check out this post on SmashingMagazine.com, appropriately titled Ultimate Round-Up for Version Control with SubVersion.

It covers getting started with SubVersion with links to tutorials, reference materials, & book suggestions.

It covers tools (many are compatible windows), and it mentions AnkhSVN as a Visual Studio compatible plugin. The comments also mention VisualSVN as an alternative.

How can I detect when the mouse leaves the window?

This will work in chrome,

$(document).bind('dragleave', function (e) {
    if (e.originalEvent.clientX == 0){
        alert("left window");
    }
});

How can I change the font size using seaborn FacetGrid?

I've made small modifications to @paul-H code, such that you can set the font size for the x/y axes and legend independently. Hope it helps:

import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
x = np.random.normal(size=37)
y = np.random.lognormal(size=37)

# defaults                                                                                                         
sns.set()
fig, ax = plt.subplots()
ax.plot(x, y, marker='s', linestyle='none', label='small')
ax.legend(loc='upper left', fontsize=20,bbox_to_anchor=(0, 1.1))
ax.set_xlabel('X_axi',fontsize=20);
ax.set_ylabel('Y_axis',fontsize=20);

plt.show()

This is the output:

enter image description here

how to get the attribute value of an xml node using java

public static void main(String[] args) throws IOException {
    String filePath = "/Users/myXml/VH181.xml";
    File xmlFile = new File(filePath);
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder;
    try {
        dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(xmlFile);
        doc.getDocumentElement().normalize();
        printElement(doc);
        System.out.println("XML file updated successfully");
    } catch (SAXException | ParserConfigurationException e1) {
        e1.printStackTrace();
    }
}
private static void printElement(Document someNode) {
    NodeList nodeList = someNode.getElementsByTagName("choiceInteraction");
    for(int z=0,size= nodeList.getLength();z<size; z++) {
            String Value = nodeList.item(z).getAttributes().getNamedItem("id").getNodeValue();
            System.out.println("Choice Interaction Id:"+Value);
        }
    }

we Can try this code using method

Repeat a task with a time delay?

In my case, I had to execute a process if one of these conditions were true: if a previous process was completed or if 5 seconds had already passed. So, I did the following and worked pretty well:

private Runnable mStatusChecker;
private Handler mHandler;

class {
method() {
  mStatusChecker = new Runnable() {
            int times = 0;
            @Override
            public void run() {
                if (times < 5) {
                    if (process1.isRead()) {
                        executeProcess2();
                    } else {
                        times++;
                        mHandler.postDelayed(mStatusChecker, 1000);
                    }
                } else {
                    executeProcess2();
                }
            }
        };

        mHandler = new Handler();
        startRepeatingTask();
}

    void startRepeatingTask() {
       mStatusChecker.run();
    }

    void stopRepeatingTask() {
        mHandler.removeCallbacks(mStatusChecker);
    }


}

If process1 is read, it executes process2. If not, it increments the variable times, and make the Handler be executed after one second. It maintains a loop until process1 is read or times is 5. When times is 5, it means that 5 seconds passed and in each second, the if clause of process1.isRead() is executed.

How to change the href for a hyperlink using jQuery

Use the attr method on your lookup. You can switch out any attribute with a new value.

$("a.mylink").attr("href", "http://cupcream.com");

javascript, is there an isObject function like isArray?

You can use typeof operator.

if( (typeof A === "object" || typeof A === 'function') && (A !== null) )
{
    alert("A is object");
}

Note that because typeof new Number(1) === 'object' while typeof Number(1) === 'number'; the first syntax should be avoided.

Best way to detect when a user leaves a web page?

In the case you need to do some asynchronous code (like sending a message to the server that the user is not focused on your page right now), the event beforeunload will not give time to the async code to run. In the case of async I found that the visibilitychange and mouseleave events are the best options. These events fire when the user change tab, or hiding the browser, or taking the courser out of the window scope.

_x000D_
_x000D_
document.addEventListener('mouseleave', e=>{_x000D_
     //do some async code_x000D_
})_x000D_
_x000D_
document.addEventListener('visibilitychange', e=>{_x000D_
     if (document.visibilityState === 'visible') {_x000D_
   //report that user is in focus_x000D_
    } else {_x000D_
     //report that user is out of focus_x000D_
    }  _x000D_
})
_x000D_
_x000D_
_x000D_

Android: How to change the ActionBar "Home" Icon to be something other than the app icon?

The ActionBar will use the android:logo attribute of your manifest, if one is provided. That lets you use separate drawable resources for the icon (Launcher) and the logo (ActionBar, among other things).

Is it possible to insert HTML content in XML document?

You can include HTML content. One possibility is encoding it in BASE64 as you have mentioned.

Another might be using CDATA tags.

Example using CDATA:

<xml>
    <title>Your HTML title</title>
    <htmlData><![CDATA[<html>
        <head>
            <script/>
        </head>
        <body>
        Your HTML's body
        </body>
        </html>
     ]]>
    </htmlData>
</xml>

Please note:

CDATA's opening character sequence: <![CDATA[

CDATA's closing character sequence: ]]>

Is there a label/goto in Python?

A working version has been made: http://entrian.com/goto/.

Note: It was offered as an April Fool's joke. (working though)

# Example 1: Breaking out from a deeply nested loop:
from goto import goto, label

for i in range(1, 10):
    for j in range(1, 20):
        for k in range(1, 30):
            print i, j, k
            if k == 3:
                goto .end
label .end
print "Finished\n"

Needless to say. Yes its funny, but DONT use it.

Python FileNotFound

try block should be around open. Not around prompt.

while True:
    prompt = input("\n Hello to Sudoku valitator,"
    "\n \n Please type in the path to your file and press 'Enter': ")
    try:
        sudoku = open(prompt, 'r').readlines()
    except FileNotFoundError:
        print("Wrong file or file path")
    else:
        break

Regular Expression: Allow letters, numbers, and spaces (with at least one letter or number)

$("#ValuationName").bind("keypress", function (event) {
    if (event.charCode!=0) {
        var regex = new RegExp("^[a-zA-Z ]+$");
        var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
        if (!regex.test(key)) {
            event.preventDefault();
            return false;
        }
    }
});

Handling of non breaking space: <p>&nbsp;</p> vs. <p> </p>

How about a workaround? In my case I took the value of the textarea in a jQuery variable, and changed all "<p>&nbsp" to <p class="clear"> and clear class to have certain height and margin, as the following example:

jQuery

tinyMCE.triggerSave();
var val = $('textarea').val();
val = val.replace(/<p>&nbsp/g, '<p class="clear">');

the val is then saved to the database with the new val.

CSS

p.clear{height: 2px; margin-bottom: 3px;}

You can adjust the height & margin as you wish. And since 'p' is a display: block element. it should give you the expected output.

Hope that helps!

Find JavaScript function definition in Chrome

If you are already debugging, you can hover over the function and the tooltip will allow you to navigate directly to the function definition:

Chrome Debugger Function Tooltip / Datatip

Further Reading:

Java 8 stream map on entry set

On Java 9 or later, Map.entry can be used, so long as you know that neither the key nor value will be null. If either value could legitimately be null, AbstractMap.SimpleEntry (as suggested in another answer) or AbstractMap.SimpleImmutableEntry would be the way to go.

private Map<String, AttributeType> mapConfig(Map<String, String> input, String prefix) {
   int subLength = prefix.length();
   return input.entrySet().stream().map(e -> 
      Map.entry(e.getKey().substring(subLength), AttributeType.GetByName(e.getValue())));
   }).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
}

Abstract methods in Java

Abstract methods means there is no default implementation for it and an implementing class will provide the details.

Essentially, you would have

abstract class AbstractObject {
   public abstract void method();
}

class ImplementingObject extends AbstractObject {
  public void method() {
    doSomething();
  }
}

So, it's exactly as the error states: your abstract method can not have a body.

There's a full tutorial on Oracle's site at: http://download.oracle.com/javase/tutorial/java/IandI/abstract.html

The reason you would do something like this is if multiple objects can share some behavior, but not all behavior.

A very simple example would be shapes:

You can have a generic graphic object, which knows how to reposition itself, but the implementing classes will actually draw themselves.

(This is taken from the site I linked above)

abstract class GraphicObject {
    int x, y;
    ...
    void moveTo(int newX, int newY) {
        ...
    }
    abstract void draw();
    abstract void resize();
}

class Circle extends GraphicObject {
    void draw() {
        ...
    }
    void resize() {
        ...
    }
}
class Rectangle extends GraphicObject {
    void draw() {
        ...
    }
    void resize() {
        ...
    }
}

How can I send cookies using PHP curl in addition to CURLOPT_COOKIEFILE?

If the cookie is generated from script, then you can send the cookie manually along with the cookie from the file(using cookie-file option). For example:

# sending manually set cookie
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Cookie: test=cookie"));

# sending cookies from file
curl_setopt($ch, CURLOPT_COOKIEFILE, $ckfile);

In this case curl will send your defined cookie along with the cookies from the file.

If the cookie is generated through javascrript, then you have to trace it out how its generated and then you can send it using the above method(through http-header).

The utma utmc, utmz are seen when cookies are sent from Mozilla. You shouldn't bet worry about these things anymore.

Finally, the way you are doing is alright. Just make sure you are using absolute path for the file names(i.e. /var/dir/cookie.txt) instead of relative one.

Always enable the verbose mode when working with curl. It will help you a lot on tracing the requests. Also it will save lot of your times.

curl_setopt($ch, CURLOPT_VERBOSE, true);

What is the minimum length of a valid international phone number?

As per different sources, I think the minimum length in E-164 format depends on country to country. For eg:

  • For Israel: The minimum phone number length (excluding the country code) is 8 digits. - Official Source (Country Code 972)
  • For Sweden : The minimum number length (excluding the country code) is 7 digits. - Official Source? (country code 46)

  • For Solomon Islands its 5 for fixed line phones. - Source (country code 677)

... and so on. So including country code, the minimum length is 9 digits for Sweden and 11 for Israel and 8 for Solomon Islands.

Edit (Clean Solution): Actually, Instead of validating an international phone number by having different checks like length etc, you can use the Google's libphonenumber library. It can validate a phone number in E164 format directly. It will take into account everything and you don't even need to give the country if the number is in valid E164 format. Its pretty good! Taking an example:

String phoneNumberE164Format = "+14167129018"
PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
try {
    PhoneNumber phoneNumberProto = phoneUtil.parse(phoneNumberE164Format, null);
    boolean isValid = phoneUtil.isValidNumber(phoneNumberProto); // returns true if valid
    if (isValid) {
        // Actions to perform if the number is valid
    } else {
        // Do necessary actions if its not valid 
    }
} catch (NumberParseException e) {
    System.err.println("NumberParseException was thrown: " + e.toString());
}

If you know the country for which you are validating the numbers, you don;t even need the E164 format and can specify the country in .parse function instead of passing null.

Force flex item to span full row width

When you want a flex item to occupy an entire row, set it to width: 100% or flex-basis: 100%, and enable wrap on the container.

The item now consumes all available space. Siblings are forced on to other rows.

_x000D_
_x000D_
.parent {
  display: flex;
  flex-wrap: wrap;
}

#range, #text {
  flex: 1;
}

.error {
  flex: 0 0 100%; /* flex-grow, flex-shrink, flex-basis */
  border: 1px dashed black;
}
_x000D_
<div class="parent">
  <input type="range" id="range">
  <input type="text" id="text">
  <label class="error">Error message (takes full width)</label>
</div>
_x000D_
_x000D_
_x000D_

More info: The initial value of the flex-wrap property is nowrap, which means that all items will line up in a row. MDN

How to set a reminder in Android?

Nope, it is more complicated than just calling a method, if you want to transparently add it into the user's calendar.

You've got a couple of choices;

  1. Calling the intent to add an event on the calendar
    This will pop up the Calendar application and let the user add the event. You can pass some parameters to prepopulate fields:

    Calendar cal = Calendar.getInstance();              
    Intent intent = new Intent(Intent.ACTION_EDIT);
    intent.setType("vnd.android.cursor.item/event");
    intent.putExtra("beginTime", cal.getTimeInMillis());
    intent.putExtra("allDay", false);
    intent.putExtra("rrule", "FREQ=DAILY");
    intent.putExtra("endTime", cal.getTimeInMillis()+60*60*1000);
    intent.putExtra("title", "A Test Event from android app");
    startActivity(intent);
    

    Or the more complicated one:

  2. Get a reference to the calendar with this method
    (It is highly recommended not to use this method, because it could break on newer Android versions):

    private String getCalendarUriBase(Activity act) {
    
        String calendarUriBase = null;
        Uri calendars = Uri.parse("content://calendar/calendars");
        Cursor managedCursor = null;
        try {
            managedCursor = act.managedQuery(calendars, null, null, null, null);
        } catch (Exception e) {
        }
        if (managedCursor != null) {
            calendarUriBase = "content://calendar/";
        } else {
            calendars = Uri.parse("content://com.android.calendar/calendars");
            try {
                managedCursor = act.managedQuery(calendars, null, null, null, null);
            } catch (Exception e) {
            }
            if (managedCursor != null) {
                calendarUriBase = "content://com.android.calendar/";
            }
        }
        return calendarUriBase;
    }
    

    and add an event and a reminder this way:

    // get calendar
    Calendar cal = Calendar.getInstance();     
    Uri EVENTS_URI = Uri.parse(getCalendarUriBase(this) + "events");
    ContentResolver cr = getContentResolver();
    
    // event insert
    ContentValues values = new ContentValues();
    values.put("calendar_id", 1);
    values.put("title", "Reminder Title");
    values.put("allDay", 0);
    values.put("dtstart", cal.getTimeInMillis() + 11*60*1000); // event starts at 11 minutes from now
    values.put("dtend", cal.getTimeInMillis()+60*60*1000); // ends 60 minutes from now
    values.put("description", "Reminder description");
    values.put("visibility", 0);
    values.put("hasAlarm", 1);
    Uri event = cr.insert(EVENTS_URI, values);
    
    // reminder insert
    Uri REMINDERS_URI = Uri.parse(getCalendarUriBase(this) + "reminders");
    values = new ContentValues();
    values.put( "event_id", Long.parseLong(event.getLastPathSegment()));
    values.put( "method", 1 );
    values.put( "minutes", 10 );
    cr.insert( REMINDERS_URI, values );
    

    You'll also need to add these permissions to your manifest for this method:

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

Update: ICS Issues

The above examples use the undocumented Calendar APIs, new public Calendar APIs have been released for ICS, so for this reason, to target new android versions you should use CalendarContract.

More infos about this can be found at this blog post.

Bootstrap 3 Slide in Menu / Navbar on Mobile

Bootstrap 4

Create a responsive navbar sidebar "drawer" in Bootstrap 4?
Bootstrap horizontal menu collapse to sidemenu

Bootstrap 3

I think what you're looking for is generally known as an "off-canvas" layout. Here is the standard off-canvas example from the official Bootstrap docs: http://getbootstrap.com/examples/offcanvas/

The "official" example uses a right-side sidebar the toggle off and on separately from the top navbar menu. I also found these off-canvas variations that slide in from the left and may be closer to what you're looking for..

http://www.bootstrapzero.com/bootstrap-template/off-canvas-sidebar http://www.bootstrapzero.com/bootstrap-template/facebook

Unable to start the mysql server in ubuntu

Yes, should try reinstall mysql, but use the --reinstall flag to force a package reconfiguration. So the operating system service configuration is not skipped:

sudo apt --reinstall install mysql-server

How to set thymeleaf th:field value from other variable

It has 2 possible solutions:

1) You can set it in the view by javascript... (not recomended)

<input class="form-control"
       type="text"
       id="tbFormControll"
       th:field="*{clientName}"/>

<script type="text/javascript">
        document.getElementById("tbFormControll").value = "default";
</script>

2) Or the better solution is to set the value in the model, that you attach to the view in GET operation by a controller. You can also change the value in the controller, just make a Java object from $client.name and call setClientName.

public class FormControllModel {
    ...
    private String clientName = "default";
    public String getClientName () {
        return clientName;
    }
    public void setClientName (String value) {
        clientName = value;
    }
    ...
}

I hope it helps.

How return error message in spring mvc @Controller

return new ResponseEntity<>(GenericResponseBean.newGenericError("Error during the calling the service", -1L), HttpStatus.EXPECTATION_FAILED);

How to get the fragment instance from the FragmentActivity?

To get the fragment instance in a class that extends FragmentActivity:

MyclassFragment instanceFragment=
    (MyclassFragment)getSupportFragmentManager().findFragmentById(R.id.idFragment);

To get the fragment instance in a class that extends Fragment:

MyclassFragment instanceFragment =  
    (MyclassFragment)getFragmentManager().findFragmentById(R.id.idFragment);

For Restful API, can GET method use json data?

To answer your question, yes you may pass JSON in the URI as part of a GET request (provided you URL-encode). However, considering your reason for doing this is due to the length of the URI, using JSON will be self-defeating (introducing more characters than required).

I suggest you send your parameters in body of a POST request, either in regular CGI style (param1=val1&param2=val2) or JSON (parsed by your API upon receipt)

Javascript ES6/ES5 find in array and change

One-liner using spread operator.

 const updatedData = originalData.map(x => (x.id === id ? { ...x, updatedField: 1 } : x));

EXCEL VBA, inserting blank row and shifting cells

If you want to just shift everything down you can use:

Rows(1).Insert shift:=xlShiftDown

Similarly to shift everything over:

Columns(1).Insert shift:=xlShiftRight

What is your favorite C programming trick?

Our codebase has a trick similar to

#ifdef DEBUG

#define my_malloc(amt) my_malloc_debug(amt, __FILE__, __LINE__)
void * my_malloc_debug(int amt, char* file, int line)
#else
void * my_malloc(int amt)
#endif
{
    //remember file and line no. for this malloc in debug mode
}

which allows for the tracking of memory leaks in debug mode. I always thought this was cool.

Connect to sqlplus in a shell script and run SQL scripts

If you want to redirect the output to a log file to look for errors or something. You can do something like this.

sqlplus -s <<EOF>> LOG_FILE_NAME user/passwd@host/db
#Your SQL code
EOF

How to send email from SQL Server?

Step 1) Create Profile and Account

You need to create a profile and account using the Configure Database Mail Wizard which can be accessed from the Configure Database Mail context menu of the Database Mail node in Management Node. This wizard is used to manage accounts, profiles, and Database Mail global settings.

Step 2)

RUN:

sp_CONFIGURE 'show advanced', 1
GO
RECONFIGURE
GO
sp_CONFIGURE 'Database Mail XPs', 1
GO
RECONFIGURE
GO

Step 3)

USE msdb
GO
EXEC sp_send_dbmail @profile_name='yourprofilename',
@recipients='[email protected]',
@subject='Test message',
@body='This is the body of the test message.
Congrates Database Mail Received By you Successfully.'

To loop through the table

DECLARE @email_id NVARCHAR(450), @id BIGINT, @max_id BIGINT, @query NVARCHAR(1000)

SELECT @id=MIN(id), @max_id=MAX(id) FROM [email_adresses]

WHILE @id<=@max_id
BEGIN
    SELECT @email_id=email_id 
    FROM [email_adresses]

    set @query='sp_send_dbmail @profile_name=''yourprofilename'',
                        @recipients='''+@email_id+''',
                        @subject=''Test message'',
                        @body=''This is the body of the test message.
                        Congrates Database Mail Received By you Successfully.'''

    EXEC @query
    SELECT @id=MIN(id) FROM [email_adresses] where id>@id

END

Posted this on the following link http://ms-sql-queries.blogspot.in/2012/12/how-to-send-email-from-sql-server.html

Unprotect workbook without password

Try the below code to unprotect the workbook. It works for me just fine in excel 2010 but I am not sure if it will work in 2013.

Sub PasswordBreaker()
    'Breaks worksheet password protection.
    Dim i As Integer, j As Integer, k As Integer
    Dim l As Integer, m As Integer, n As Integer
    Dim i1 As Integer, i2 As Integer, i3 As Integer
    Dim i4 As Integer, i5 As Integer, i6 As Integer
    On Error Resume Next
    For i = 65 To 66: For j = 65 To 66: For k = 65 To 66
    For l = 65 To 66: For m = 65 To 66: For i1 = 65 To 66
    For i2 = 65 To 66: For i3 = 65 To 66: For i4 = 65 To 66
    For i5 = 65 To 66: For i6 = 65 To 66: For n = 32 To 126
    ThisWorkbook.Unprotect Chr(i) & Chr(j) & Chr(k) & _
        Chr(l) & Chr(m) & Chr(i1) & Chr(i2) & Chr(i3) & _
        Chr(i4) & Chr(i5) & Chr(i6) & Chr(n)
    If ThisWorkbook.ProtectStructure = False Then
        MsgBox "One usable password is " & Chr(i) & Chr(j) & _
            Chr(k) & Chr(l) & Chr(m) & Chr(i1) & Chr(i2) & _
            Chr(i3) & Chr(i4) & Chr(i5) & Chr(i6) & Chr(n)
         Exit Sub
    End If
    Next: Next: Next: Next: Next: Next
    Next: Next: Next: Next: Next: Next
End Sub

Regex to accept alphanumeric and some special character in Javascript?

I forgot to mention. This should also accept whitespace.

You could use:

/^[-@.\/#&+\w\s]*$/

Note how this makes use of the character classes \w and \s.

EDIT:- Added \ to escape /

How do I remove a key from a JavaScript object?

If you are using Underscore.js or Lodash, there is a function 'omit' that will do it.
http://underscorejs.org/#omit

var thisIsObject= {
    'Cow' : 'Moo',
    'Cat' : 'Meow',
    'Dog' : 'Bark'
};
_.omit(thisIsObject,'Cow'); //It will return a new object

=> {'Cat' : 'Meow', 'Dog' : 'Bark'}  //result

If you want to modify the current object, assign the returning object to the current object.

thisIsObject = _.omit(thisIsObject,'Cow');

With pure JavaScript, use:

delete thisIsObject['Cow'];

Another option with pure JavaScript.

thisIsObject.cow = undefined;

thisIsObject = JSON.parse(JSON.stringify(thisIsObject ));

Optimal number of threads per core

Hope this makes sense, Check the CPU and Memory utilization and put some threshold value. If the threshold value is crossed,don't allow to create new thread else allow...

Get img thumbnails from Vimeo?

If you are looking for an alternative solution and can manage the vimeo account there is another way, you simply add every video you want to show into an album and then use the API to request the album details - it then shows all the thumbnails and links. It's not ideal but might help.

API end point (playground)

Twitter convo with @vimeoapi

html cellpadding the left side of a cell

I choose to use both methods. Cellpadding on the table as a fallback in case the inline style doesn't stick and inline style for most clients.

_x000D_
_x000D_
<table cellpadding="5">_x000D_
  <tr>_x000D_
    <td style='padding:5px 10px 5px 5px'>Content</td>_x000D_
    <td style='padding:5px 10px 5px 5px'>Content</td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Create a folder inside documents folder in iOS apps

I don't have enough reputation to comment on Manni's answer, but [paths objectAtIndex:0] is the standard way of getting the application's Documents Directory

http://developer.apple.com/library/ios/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/StandardBehaviors/StandardBehaviors.html#//apple_ref/doc/uid/TP40007072-CH4-SW6

Because the NSSearchPathForDirectoriesInDomains function was designed originally for Mac OS X, where there could be more than one of each of these directories, it returns an array of paths rather than a single path. In iOS, the resulting array should contain the single path to the directory. Listing 3-1 shows a typical use of this function.

Listing 3-1 Getting the path to the application’s Documents directory

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];

How to use breakpoints in Eclipse

Here is a video about Debugging with eclipse.

For more details read this page.

Instead of Debugging as Java program, use Debug as Android Application

May help new comers.

Can Windows Containers be hosted on linux?

Windows containers are not running on Linux and also You can't run Linux containers on Windows directly.

Is it possible to create static classes in PHP (like in C#)?

I generally prefer to write regular non static classes and use a factory class to instantiate single ( sudo static ) instances of the object.

This way constructor and destructor work as per normal, and I can create additional non static instances if I wish ( for example a second DB connection )

I use this all the time and is especially useful for creating custom DB store session handlers, as when the page terminates the destructor will push the session to the database.

Another advantage is you can ignore the order you call things as everything will be setup on demand.

class Factory {
    static function &getDB ($construct_params = null)
    {
        static $instance;
        if( ! is_object($instance) )
        {
            include_once("clsDB.php");
            $instance = new clsDB($construct_params);   // constructor will be called
        }
        return $instance;
    }
}

The DB class...

class clsDB {

    $regular_public_variables = "whatever";

    function __construct($construct_params) {...}
    function __destruct() {...}

    function getvar() { return $this->regular_public_variables; }
}

Anywhere you want to use it just call...

$static_instance = &Factory::getDB($somekickoff);

Then just treat all methods as non static ( because they are )

echo $static_instance->getvar();

What’s the best way to get an HTTP response code from a URL?

You should use urllib2, like this:

import urllib2
for url in ["http://entrian.com/", "http://entrian.com/does-not-exist/"]:
    try:
        connection = urllib2.urlopen(url)
        print connection.getcode()
        connection.close()
    except urllib2.HTTPError, e:
        print e.getcode()

# Prints:
# 200 [from the try block]
# 404 [from the except block]

Returning a file to View/Download in ASP.NET MVC

Below code worked for me for getting a pdf file from an API service and response it out to the browser - hope it helps;

public async Task<FileResult> PrintPdfStatements(string fileName)
    {
         var fileContent = await GetFileStreamAsync(fileName);
         var fileContentBytes = ((MemoryStream)fileContent).ToArray();
         return File(fileContentBytes, System.Net.Mime.MediaTypeNames.Application.Pdf);
    }

Receiving "fatal: Not a git repository" when attempting to remote add a Git repo

In command line/CLI, you will get this error if your current directory is NOT the repository. So, you have to first CD into the repo.

Using Switch Statement to Handle Button Clicks

Hi its quite simple to make switch between buttons using switch case:-

 package com.example.browsebutton;


    import android.app.Activity;
    import android.os.Bundle;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.Toast;

        public class MainActivity extends Activity implements OnClickListener {
        Button b1,b2;
            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_main);
                b1=(Button)findViewById(R.id.button1);

                b2=(Button)findViewById(R.id.button2);
                b1.setOnClickListener(this);
                b2.setOnClickListener(this);
            }



            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                 int id=v.getId();
                 switch(id) {
                    case R.id.button1:
                  Toast.makeText(getBaseContext(), "btn1", Toast.LENGTH_LONG).show();
                //Your Operation

                  break;

                    case R.id.button2:
                          Toast.makeText(getBaseContext(), "btn2", Toast.LENGTH_LONG).show();


                          //Your Operation
                          break;
            }

        }}

R data formats: RData, Rda, Rds etc

Rda is just a short name for RData. You can just save(), load(), attach(), etc. just like you do with RData.

Rds stores a single R object. Yet, beyond that simple explanation, there are several differences from a "standard" storage. Probably this R-manual Link to readRDS() function clarifies such distinctions sufficiently.

So, answering your questions:

  • The difference is not about the compression, but serialization (See this page)
  • Like shown in the manual page, you may wanna use it to restore a certain object with a different name, for instance.
  • You may readRDS() and save(), or load() and saveRDS() selectively.

How to find elements with 'value=x'?

If the value is hardcoded in the source of the page using the value attribute then you can

$('#attached_docs :input[value="123"]').remove();

If you want to target elements that have a value of 123, which was set by the user or programmatically then use EDIT works both ways ..

or

$('#attached_docs :input').filter(function(){return this.value=='123'}).remove();

demo http://jsfiddle.net/gaby/RcwXh/2/

Is there a CSS selector for the first direct child only?

Found this question searching on Google. This will return the first child of a element with class container, regardless as to what type the child is.

.container > *:first-child
{
}

How to Populate a DataTable from a Stored Procedure

You don't need to add the columns manually. Just use a DataAdapter and it's simple as:

DataTable table = new DataTable();
using(var con = new SqlConnection(ConfigurationManager.ConnectionStrings["DB"].ConnectionString))
using(var cmd = new SqlCommand("usp_GetABCD", con))
using(var da = new SqlDataAdapter(cmd))
{
   cmd.CommandType = CommandType.StoredProcedure;
   da.Fill(table);
}

Note that you even don't need to open/close the connection. That will be done implicitly by the DataAdapter.

The connection object associated with the SELECT statement must be valid, but it does not need to be open. If the connection is closed before Fill is called, it is opened to retrieve data, then closed. If the connection is open before Fill is called, it remains open.

remove objects from array by object property

Loop in reverse by decrementing i to avoid the problem:

for (var i = arrayOfObjects.length - 1; i >= 0; i--) {
    var obj = arrayOfObjects[i];

    if (listToDelete.indexOf(obj.id) !== -1) {
        arrayOfObjects.splice(i, 1);
    }
}

Or use filter:

var newArray = arrayOfObjects.filter(function(obj) {
    return listToDelete.indexOf(obj.id) === -1;
});

How to play a sound using Swift?

If code doesn't generate any error, but you don't hear sound - create the player as an instance:

   static var player: AVAudioPlayer!

For me the first solution worked when I did this change :)

Element implicitly has an 'any' type because expression of type 'string' can't be used to index

This is what it worked for me. The tsconfig.json has an option noImplicitAny that it was set to true, I just simply set it to false and now I can access properties in objects using strings.

Convert comma separated string to array in PL/SQL

here is another easier option

select to_number(column_value) as IDs from xmltable('1,2,3,4,5');

Insert a string at a specific index

I wanted to compare the method using substring and the method using slice from Base33 and user113716 respectively, to do that I wrote some code

also have a look at this performance comparison, substring, slice

The code I used creates huge strings and inserts the string "bar " multiple times into the huge string

_x000D_
_x000D_
if (!String.prototype.splice) {
    /**
     * {JSDoc}
     *
     * The splice() method changes the content of a string by removing a range of
     * characters and/or adding new characters.
     *
     * @this {String}
     * @param {number} start Index at which to start changing the string.
     * @param {number} delCount An integer indicating the number of old chars to remove.
     * @param {string} newSubStr The String that is spliced in.
     * @return {string} A new string with the spliced substring.
     */
    String.prototype.splice = function (start, delCount, newSubStr) {
        return this.slice(0, start) + newSubStr + this.slice(start + Math.abs(delCount));
    };
}

String.prototype.splice = function (idx, rem, str) {
    return this.slice(0, idx) + str + this.slice(idx + Math.abs(rem));
};


String.prototype.insert = function (index, string) {
    if (index > 0)
        return this.substring(0, index) + string + this.substring(index, this.length);

    return string + this;
};


function createString(size) {
    var s = ""
    for (var i = 0; i < size; i++) {
        s += "Some String "
    }
    return s
}


function testSubStringPerformance(str, times) {
    for (var i = 0; i < times; i++)
        str.insert(4, "bar ")
}

function testSpliceStringPerformance(str, times) {
    for (var i = 0; i < times; i++)
        str.splice(4, 0, "bar ")
}


function doTests(repeatMax, sSizeMax) {
    n = 1000
    sSize = 1000
    for (var i = 1; i <= repeatMax; i++) {
        var repeatTimes = n * (10 * i)
        for (var j = 1; j <= sSizeMax; j++) {
            var actualStringSize = sSize *  (10 * j)
            var s1 = createString(actualStringSize)
            var s2 = createString(actualStringSize)
            var start = performance.now()
            testSubStringPerformance(s1, repeatTimes)
            var end = performance.now()
            var subStrPerf = end - start

            start = performance.now()
            testSpliceStringPerformance(s2, repeatTimes)
            end = performance.now()
            var splicePerf = end - start

            console.log(
                "string size           =", "Some String ".length * actualStringSize, "\n",
                "repeat count          = ", repeatTimes, "\n",
                "splice performance    = ", splicePerf, "\n",
                "substring performance = ", subStrPerf, "\n",
                "difference = ", splicePerf - subStrPerf  // + = splice is faster, - = subStr is faster
                )

        }
    }
}

doTests(1, 100)
_x000D_
_x000D_
_x000D_

The general difference in performance is marginal at best and both methods work just fine (even on strings of length ~~ 12000000)

How and where are Annotations used in Java?

It attaches additional information about code by (a) compiler check or (b) code analysis

**

  • Following are the Built-in annotations:: 2 types

**

Type 1) Annotations applied to java code:

@Override // gives error if signature is wrong while overriding.
Public boolean equals (Object Obj) 

@Deprecated // indicates the deprecated method
Public doSomething()....

@SuppressWarnings() // stops the warnings from printing while compiling.
SuppressWarnings({"unchecked","fallthrough"})

Type 2) Annotations applied to other annotations:

@Retention - Specifies how the marked annotation is stored—Whether in code only, compiled into the class, or available at run-time through reflection.

@Documented - Marks another annotation for inclusion in the documentation.

@Target - Marks another annotation to restrict what kind of java elements the annotation may be applied to

@Inherited - Marks another annotation to be inherited to subclasses of annotated class (by default annotations are not inherited to subclasses).

**

  • Custom Annotations::

** http://en.wikipedia.org/wiki/Java_annotation#Custom_annotations


FOR BETTER UNDERSTANDING TRY BELOW LINK:ELABORATE WITH EXAMPLES


http://www.javabeat.net/2007/08/annotations-in-java-5-0/

How to add one day to a date?

Date today = new Date();
Date tomorrow = new Date(today.getTime() + (1000 * 60 * 60 * 24));

Date has a constructor using the milliseconds since the UNIX-epoch. the getTime()-method gives you that value. So adding the milliseconds for a day, does the trick. If you want to do such manipulations regularly I recommend to define constants for the values.

Important hint: That is not correct in all cases. Read the WARNING comment, below.

How do I apply a CSS class to Html.ActionLink in ASP.NET MVC?

This works for MVC 5

@Html.ActionLink("LinkText", "ActionName", new { id = item.id }, new { @class = "btn btn-success" })

how to Call super constructor in Lombok

Lombok Issue #78 references this page https://www.donneo.de/2015/09/16/lomboks-builder-annotation-and-inheritance/ with this lovely explanation:

@AllArgsConstructor 
public class Parent {   
     private String a; 
}

public class Child extends Parent {
  private String b;

  @Builder
  public Child(String a, String b){
    super(a);
    this.b = b;   
  } 
} 

As a result you can then use the generated builder like this:

Child.builder().a("testA").b("testB").build(); 

The official documentation explains this, but it doesn’t explicitly point out that you can facilitate it in this way.

I also found this works nicely with Spring Data JPA.

Remove lines that contain certain string

bad_words = ['doc:', 'strickland:','\n']

with open('linetest.txt') as oldfile, open('linetestnew.txt', 'w') as newfile:
    for line in oldfile:
        if not any(bad_word in line for bad_word in bad_words):
            newfile.write(line)

The \n is a Unicode escape sequence for a newline.

Task vs Thread differences

Source

Thread

Thread represents an actual OS-level thread, with its own stack and kernel resources. (technically, a CLR implementation could use fibers instead, but no existing CLR does this) Thread allows the highest degree of control; you can Abort() or Suspend() or Resume() a thread (though this is a very bad idea), you can observe its state, and you can set thread-level properties like the stack size, apartment state, or culture.

The problem with Thread is that OS threads are costly. Each thread you have consumes a non-trivial amount of memory for its stack, and adds additional CPU overhead as the processor context-switch between threads. Instead, it is better to have a small pool of threads execute your code as work becomes available.

There are times when there is no alternative Thread. If you need to specify the name (for debugging purposes) or the apartment state (to show a UI), you must create your own Thread (note that having multiple UI threads is generally a bad idea). Also, if you want to maintain an object that is owned by a single thread and can only be used by that thread, it is much easier to explicitly create a Thread instance for it so you can easily check whether code trying to use it is running on the correct thread.

ThreadPool

ThreadPool is a wrapper around a pool of threads maintained by the CLR. ThreadPool gives you no control at all; you can submit work to execute at some point, and you can control the size of the pool, but you can't set anything else. You can't even tell when the pool will start running the work you submit to it.

Using ThreadPool avoids the overhead of creating too many threads. However, if you submit too many long-running tasks to the threadpool, it can get full, and later work that you submit can end up waiting for the earlier long-running items to finish. In addition, the ThreadPool offers no way to find out when a work item has been completed (unlike Thread.Join()), nor a way to get the result. Therefore, ThreadPool is best used for short operations where the caller does not need the result.

Task

Finally, the Task class from the Task Parallel Library offers the best of both worlds. Like the ThreadPool, a task does not create its own OS thread. Instead, tasks are executed by a TaskScheduler; the default scheduler simply runs on the ThreadPool.

Unlike the ThreadPool, Task also allows you to find out when it finishes, and (via the generic Task) to return a result. You can call ContinueWith() on an existing Task to make it run more code once the task finishes (if it's already finished, it will run the callback immediately). If the task is generic, ContinueWith() will pass you the task's result, allowing you to run more code that uses it.

You can also synchronously wait for a task to finish by calling Wait() (or, for a generic task, by getting the Result property). Like Thread.Join(), this will block the calling thread until the task finishes. Synchronously waiting for a task is usually bad idea; it prevents the calling thread from doing any other work, and can also lead to deadlocks if the task ends up waiting (even asynchronously) for the current thread.

Since tasks still run on the ThreadPool, they should not be used for long-running operations, since they can still fill up the thread pool and block new work. Instead, Task provides a LongRunning option, which will tell the TaskScheduler to spin up a new thread rather than running on the ThreadPool.

All newer high-level concurrency APIs, including the Parallel.For*() methods, PLINQ, C# 5 await, and modern async methods in the BCL, are all built on Task.

Conclusion

The bottom line is that Task is almost always the best option; it provides a much more powerful API and avoids wasting OS threads.

The only reasons to explicitly create your own Threads in modern code are setting per-thread options, or maintaining a persistent thread that needs to maintain its own identity.

ERROR 1044 (42000): Access denied for 'root' With All Privileges

If you get an error 1044 (42000) when you try to run SQL commands in MySQL (which installed along XAMPP server) cmd prompt, then here's the solution:

  1. Close your MySQL command prompt.

  2. Open your cmd prompt (from Start menu -> run -> cmd) which will show: C:\Users\User>_

  3. Go to MySQL.exe by Typing the following commands:

C:\Users\User>cd\ C:\>cd xampp C:\xampp>cd mysql C:\xxampp\mysql>cd bin C:\xampp\mysql\bin>mysql -u root

  1. Now try creating a new database by typing:

    mysql> create database employee;
    

    if it shows:

    Query OK, 1 row affected (0.00 sec)
    mysql>
    

    Then congrats ! You are good to go...

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

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

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

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

Using Python's list index() method on a list of tuples or objects?

Those list comprehensions are messy after a while.

I like this Pythonic approach:

from operator import itemgetter

def collect(l, index):
   return map(itemgetter(index), l)

# And now you can write this:
collect(tuple_list,0).index("cherry")   # = 1
collect(tuple_list,1).index("3")        # = 2

If you need your code to be all super performant:

# Stops iterating through the list as soon as it finds the value
def getIndexOfTuple(l, index, value):
    for pos,t in enumerate(l):
        if t[index] == value:
            return pos

    # Matches behavior of list.index
    raise ValueError("list.index(x): x not in list")

getIndexOfTuple(tuple_list, 0, "cherry")   # = 1

How to select data from 30 days?

Short version for easy use:

SELECT * 
FROM [TableName] t
WHERE t.[DateColumnName] >= DATEADD(month, -1, GETDATE())

DATEADD and GETDATE are available in SQL Server starting with 2008 version. MSDN documentation: GETDATE and DATEADD.

How do you manually execute SQL commands in Ruby On Rails using NuoDB

The working command I'm using to execute custom SQL statements is:

results = ActiveRecord::Base.connection.execute("foo")

with "foo" being the sql statement( i.e. "SELECT * FROM table").

This command will return a set of values as a hash and put them into the results variable.

So on my rails application_controller.rb I added this:

def execute_statement(sql)
  results = ActiveRecord::Base.connection.execute(sql)

  if results.present?
    return results
  else
    return nil
  end
end

Using execute_statement will return the records found and if there is none, it will return nil.

This way I can just call it anywhere on the rails application like for example:

records = execute_statement("select * from table")

"execute_statement" can also call NuoDB procedures, functions, and also Database Views.

WinSCP: Permission denied. Error code: 3 Error message from server: Permission denied

You possibly do not have create permissions to the folder. So WinSCP fails to create a temporary file for the transfer.

You have two options:

Read file data without saving it in Flask

I share my solution (assuming everything is already configured to connect to google bucket in flask)

from google.cloud import storage

@app.route('/upload/', methods=['POST'])
def upload():
    if request.method == 'POST':
        # FileStorage object wrapper
        file = request.files["file"]                    
        if file:
            os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = app.config['GOOGLE_APPLICATION_CREDENTIALS']
            bucket_name = "bucket_name" 
            storage_client = storage.Client()
            bucket = storage_client.bucket(bucket_name)
            # Upload file to Google Bucket
            blob = bucket.blob(file.filename) 
            blob.upload_from_string(file.read())

My post

Direct to Google Bucket in flask

Vim: insert the same characters across multiple lines

You might also have a use case where you want to delete a block of text and replace it.

Like this

Hello World

Hello World

To

Hello Cool

Hello Cool

You can just visual block select "World" in both lines.

Type c for change - now you will be in insert mode.

Insert the stuff you want and hit escape.

Both get reflected vertically. It works just like 'I', except that it replaces the block with the new text instead of inserting it.

Bower: ENOGIT Git is not installed or not in the PATH

npm install from git bash did work for me. After rebooting PC.

'NOT NULL constraint failed' after adding to models.py

Since you added a new property to the model, you must first delete the database. Then manage.py migrations then manage.py migrate.

How do I generate a random int number?

The numbers generated by the inbuilt Random class (System.Random) generates pseudo random numbers.

If you want true random numbers, the closest we can get is "secure Pseudo Random Generator" which can be generated by using the Cryptographic classes in C# such as RNGCryptoServiceProvider.

Even so, if you still need true random numbers you will need to use an external source such as devices accounting for radioactive decay as a seed for an random number generator. Since, by definition, any number generated by purely algorithmic means cannot be truly random.

View's getWidth() and getHeight() returns 0

Answer with post is incorrect, because the size might not be recalculated.
Another important thing is that the view and all it ancestors must be visible. For that I use a property View.isShown.

Here is my kotlin function, that can be placed somewhere in utils:

fun View.onInitialized(onInit: () -> Unit) {
    viewTreeObserver.addOnGlobalLayoutListener(object : OnGlobalLayoutListener {
        override fun onGlobalLayout() {
            if (isShown) {
                viewTreeObserver.removeOnGlobalLayoutListener(this)
                onInit()
            }
        }
    })
}

And the usage is:

myView.onInitialized {
    Log.d(TAG, "width is: " + myView.width)
}

HTML.ActionLink vs Url.Action in ASP.NET Razor

I used the code below to create a Button and it worked for me.

<input type="button" value="PDF" onclick="location.href='@Url.Action("Export","tblOrder")'"/>

Maximum size for a SQL Server Query? IN clause? Is there a Better Approach

Every SQL batch has to fit in the Batch Size Limit: 65,536 * Network Packet Size.

Other than that, your query is limited by runtime conditions. It will usually run out of stack size because x IN (a,b,c) is nothing but x=a OR x=b OR x=c which creates an expression tree similar to x=a OR (x=b OR (x=c)), so it gets very deep with a large number of OR. SQL 7 would hit a SO at about 10k values in the IN, but nowdays stacks are much deeper (because of x64), so it can go pretty deep.

Update

You already found Erland's article on the topic of passing lists/arrays to SQL Server. With SQL 2008 you also have Table Valued Parameters which allow you to pass an entire DataTable as a single table type parameter and join on it.

XML and XPath is another viable solution:

SELECT ...
FROM Table
JOIN (
   SELECT x.value(N'.',N'uniqueidentifier') as guid
   FROM @values.nodes(N'/guids/guid') t(x)) as guids
 ON Table.guid = guids.guid;

How to copy a file to multiple directories using the gnu cp command

To use copying with xargs to directories using wildcards on Mac OS, the only solution that worked for me with spaces in the directory name is:

find ./fs*/* -type d -print0 | xargs -0 -n 1 cp test 

Where test is the file to copy
And ./fs*/* the directories to copy to

The problem is that xargs sees spaces as a new argument, the solutions to change the delimiter character using -d or -E is unfortunately not properly working on Mac OS.

error: Error parsing XML: not well-formed (invalid token) ...?

I had same problem. you can't use left < arrow in text property like as android:text="< Go back" in your xml file. Remove any < arrow from you xml code.

Hope It will helps you.

Using G++ to compile multiple .cpp and .h files

Now that I've separated the classes to .h and .cpp files do I need to use a makefile or can I still use the "g++ main.cpp" command?

Compiling several files at once is a poor choice if you are going to put that into the Makefile.

Normally in a Makefile (for GNU/Make), it should suffice to write that:

# "all" is the name of the default target, running "make" without params would use it
all: executable1

# for C++, replace CC (c compiler) with CXX (c++ compiler) which is used as default linker
CC=$(CXX)

# tell which files should be used, .cpp -> .o make would do automatically
executable1: file1.o file2.o

That way make would be properly recompiling only what needs to be recompiled. One can also add few tweaks to generate the header file dependencies - so that make would also properly rebuild what's need to be rebuilt due to the header file changes.

error CS0103: The name ' ' does not exist in the current context

Simply move the declaration outside of the if block.

@{
string currentstore=HttpContext.Current.Request.ServerVariables["HTTP_HOST"];
string imgsrc="";
if (currentstore == "www.mydomain.com")
    {
    <link href="/path/to/my/stylesheets/styles1-print.css" rel="stylesheet" type="text/css" />
    imgsrc="/content/images/uploaded/store1_logo.jpg";
    }
else
    {
    <link href="/path/to/my/stylesheets/styles2-print.css" rel="stylesheet" type="text/css" />
    imgsrc="/content/images/uploaded/store2_logo.gif";
    }
}

<a href="@Url.RouteUrl("HomePage")" class="logo"><img  alt="" src="@imgsrc"></a>

You could make it a bit cleaner.

@{
string currentstore=HttpContext.Current.Request.ServerVariables["HTTP_HOST"];
string imgsrc="/content/images/uploaded/store2_logo.gif";
if (currentstore == "www.mydomain.com")
    {
    <link href="/path/to/my/stylesheets/styles1-print.css" rel="stylesheet" type="text/css" />
    imgsrc="/content/images/uploaded/store1_logo.jpg";
    }
else
    {
    <link href="/path/to/my/stylesheets/styles2-print.css" rel="stylesheet" type="text/css" />
    }
}

Difference between require, include, require_once and include_once?

include() will throw a warning if it can't include the file, but the rest of the script will run.

require() will throw an E_COMPILE_ERROR and halt the script if it can't include the file.

The include_once() and require_once() functions will not include the file a second time if it has already been included.

See the following documentation pages:

What is the official name for a credit card's 3 digit code?

It's got a number of names. Most likely you've heard it as either Card Security Code (CSC) or Card Verification Value (CVV).

Card Security Code

No notification sound when sending notification from firebase in android

I was also having a problem with notifications that had to emit sound, when the app was in foreground everything worked correctly, however when the app was in the background the sound just didn't come out.

The notification was sent by the server through FCM, that is, the server mounted the JSON of the notification and sent it to FCM, which then sends the notification to the apps. Even if I put the sound tag, the sound does not come out in the backgound.

enter image description here

Even putting the sound tag it didn't work.

enter image description here

After so much searching I found the solution on a github forum. I then noticed that there were two problems in my case:

1 - It was missing to send the channel_id tag, important to work in API level 26+

enter image description here

2 - In the Android application, for this specific case where notifications were being sent directly from the server, I had to configure the channel id in advance, so in my main Activity I had to configure the channel so that Android knew what to do when notification arrived.

In JSON sent by the server:

   {
  "title": string,
  "body": string,
  "icon": string,
  "color": string,
  "sound": mysound,

  "channel_id": videocall,
  //More stuff here ...
 }

In your main Activity:

 @Background
    void createChannel(){
            Uri sound = Uri.parse("android.resource://" + getApplicationContext().getPackageName() + "/" + R.raw.app_note_call);
            NotificationChannel mChannel;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                mChannel = new NotificationChannel("videocall", "VIDEO CALL", NotificationManager.IMPORTANCE_HIGH);
                mChannel.setLightColor(Color.GRAY);
                mChannel.enableLights(true);
                mChannel.setDescription("VIDEO CALL");
                AudioAttributes audioAttributes = new AudioAttributes.Builder()
                        .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                        .setUsage(AudioAttributes.USAGE_ALARM)
                        .build();
                mChannel.setSound(sound, audioAttributes);

                NotificationManager notificationManager =
                        (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
                notificationManager.createNotificationChannel(mChannel);
            }
    }

This finally solved my problem, I hope it helps someone not to waste 2 days like I did. I don't know if it is necessary for everything I put in the code, but this is the way. I also didn't find the github forum link to credit the answer anymore, because what I did was the same one that was posted there.

Hide HTML element by id

If you want to do it via javascript rather than CSS you can use:

var link = document.getElementById('nav-ask');
link.style.display = 'none'; //or
link.style.visibility = 'hidden';

depending on what you want to do.

Getting list of parameter names inside python function

If you also want the values you can use the inspect module

import inspect

def func(a, b, c):
    frame = inspect.currentframe()
    args, _, _, values = inspect.getargvalues(frame)
    print 'function name "%s"' % inspect.getframeinfo(frame)[2]
    for i in args:
        print "    %s = %s" % (i, values[i])
    return [(i, values[i]) for i in args]

>>> func(1, 2, 3)
function name "func"
    a = 1
    b = 2
    c = 3
[('a', 1), ('b', 2), ('c', 3)]

what is the difference between const_iterator and iterator?

Performance wise there is no difference. The only purpose of having const_iterator over iterator is to manage the accessesibility of the container on which the respective iterator runs. You can understand it more clearly with an example:

std::vector<int> integers{ 3, 4, 56, 6, 778 };

If we were to read & write the members of a container we will use iterator:

for( std::vector<int>::iterator it = integers.begin() ; it != integers.end() ; ++it )
       {*it = 4;  std::cout << *it << std::endl; }

If we were to only read the members of the container integers you might wanna use const_iterator which doesn't allow to write or modify members of container.

for( std::vector<int>::const_iterator it = integers.begin() ; it != integers.end() ; ++it )
       { cout << *it << endl; }

NOTE: if you try to modify the content using *it in second case you will get an error because its read-only.

How to try convert a string to a Guid

If all you want is some very basic error checking, you could just check the length of the string.

              string guidStr = "";
              if( guidStr.Length == Guid.Empty.ToString().Length )
                 Guid g = new Guid( guidStr );

Why can't Visual Studio find my DLL?

try "configuration properties -> debugging -> environment" and set the PATH variable in run-time

How to add a button dynamically using jquery

Try this:

<script type="text/javascript">

function test()
{
    if($('input#field').length==0)
    {
       $('<input type="button" id="field"/>').appendTo('body');
     }
}
</script>

Parse json string using JSON.NET

If your keys are dynamic I would suggest deserializing directly into a DataTable:

    class SampleData
    {
        [JsonProperty(PropertyName = "items")]
        public System.Data.DataTable Items { get; set; }
    }

    public void DerializeTable()
    {
        const string json = @"{items:["
            + @"{""Name"":""AAA"",""Age"":""22"",""Job"":""PPP""},"
            + @"{""Name"":""BBB"",""Age"":""25"",""Job"":""QQQ""},"
            + @"{""Name"":""CCC"",""Age"":""38"",""Job"":""RRR""}]}";
        var sampleData = JsonConvert.DeserializeObject<SampleData>(json);
        var table = sampleData.Items;

        // write tab delimited table without knowing column names
        var line = string.Empty;
        foreach (DataColumn column in table.Columns)            
            line += column.ColumnName + "\t";                       
        Console.WriteLine(line);

        foreach (DataRow row in table.Rows)
        {
            line = string.Empty;
            foreach (DataColumn column in table.Columns)                
                line += row[column] + "\t";                                   
            Console.WriteLine(line);
        }

        // Name   Age   Job    
        // AAA    22    PPP    
        // BBB    25    QQQ    
        // CCC    38    RRR    
    }

You can determine the DataTable column names and types dynamically once deserialized.

How to Lock the data in a cell in excel using vba

You can also do it on the worksheet level captured in the worksheet's change event. If that suites your needs better. Allows for dynamic locking based on values, criteria, ect...

Private Sub Worksheet_Change(ByVal Target As Range)

    'set your criteria here
    If Target.Column = 1 Then

        'must disable events if you change the sheet as it will
        'continually trigger the change event
        Application.EnableEvents = False
        Application.Undo
        Application.EnableEvents = True

        MsgBox "You cannot do that!"
    End If
End Sub

Rails raw SQL example

I know this is old... But I was having the same problem today and found a solution:

Model.find_by_sql

If you want to instantiate the results:

Client.find_by_sql("
  SELECT * FROM clients
  INNER JOIN orders ON clients.id = orders.client_id
  ORDER BY clients.created_at desc
")
# => [<Client id: 1, first_name: "Lucas" >, <Client id: 2, first_name: "Jan">...]

Model.connection.select_all('sql').to_hash

If you just want a hash of values:

Client.connection.select_all("SELECT first_name, created_at FROM clients
   WHERE id = '1'").to_hash
# => [
  {"first_name"=>"Rafael", "created_at"=>"2012-11-10 23:23:45.281189"},
  {"first_name"=>"Eileen", "created_at"=>"2013-12-09 11:22:35.221282"}
]

Result object:

select_all returns a result object. You can do magic things with it.

result = Post.connection.select_all('SELECT id, title, body FROM posts')
# Get the column names of the result:
result.columns
# => ["id", "title", "body"]

# Get the record values of the result:
result.rows
# => [[1, "title_1", "body_1"],
      [2, "title_2", "body_2"],
      ...
     ]

# Get an array of hashes representing the result (column => value):
result.to_hash
# => [{"id" => 1, "title" => "title_1", "body" => "body_1"},
      {"id" => 2, "title" => "title_2", "body" => "body_2"},
      ...
     ]

# ActiveRecord::Result also includes Enumerable.
result.each do |row|
  puts row['title'] + " " + row['body']
end

Sources:

  1. ActiveRecord - Findinig by SQL.
  2. Ruby on Rails - Active Record Result .

What does `m_` variable prefix mean?

In Clean Code: A Handbook of Agile Software Craftsmanship there is an explicit recommendation against the usage of this prefix:

You also don't need to prefix member variables with m_ anymore. Your classes and functions should be small enough that you don't need them.

There is also an example (C# code) of this:

Bad practice:

public class Part
{
    private String m_dsc; // The textual description

    void SetName(string name)
    {
        m_dsc = name;
    }
}

Good practice:

public class Part
{
    private String description;

    void SetDescription(string description)
    {
        this.description = description;
    }
}

We count with language constructs to refer to member variables in the case of explicitly ambiguity (i.e., description member and description parameter): this.

What is the meaning of git reset --hard origin/master?

git reset --hard origin/master

says: throw away all my staged and unstaged changes, forget everything on my current local branch and make it exactly the same as origin/master.

You probably wanted to ask this before you ran the command. The destructive nature is hinted at by using the same words as in "hard reset".

JavaScript - Get Browser Height

With JQuery you can try this $(window).innerHeight() (Works for me on Chrome, FF and IE). With bootstrap modal I used something like the following;

$('#YourModal').on('show.bs.modal', function () {
    $('.modal-body').css('height', $(window).innerHeight() * 0.7);
});

Could not find com.google.android.gms:play-services:3.1.59 3.2.25 4.0.30 4.1.32 4.2.40 4.2.42 4.3.23 4.4.52 5.0.77 5.0.89 5.2.08 6.1.11 6.1.71 6.5.87

Check if you also installed the "Google Repository". If not, you also have to install the "Google Repository" in your SDK Manager.

Also be aware that there might be 2 SDK installations - one coming from AndroidStudio and one you might have installed. Better consolidate this to one installation - this is a common pitfall - that you have it installed in one installation but it fails when you build with the other installation.

Example of how to access SDK Manager for Google Repository

How to import Angular Material in project?

You should consider using a SharedModule for the essential material components of your app, and then import every single module you need to use into your feature modules. I wrote an article on medium explaining how to import Angular material, check it out:

https://medium.com/@benmohamehdi/how-to-import-angular-material-angular-best-practices-80d3023118de

npm ERR! network getaddrinfo ENOTFOUND

for some reason my error kept pointing to the "proxy" property in the config file. Which was misleading. During my troubleshooting I was trying different values for the proxy and https-proxy properties, but would only get the error stating to make sure the proxy config was set properly, and pointing to an older value.

Using, NPM CONFIG LS -L command lists all the properties and values in the config file. I was then able to see the value in question was matching the https-proxy, therefore using the https-proxy. So I changed the proxy (my company uses different ones) and then it worked. figured I would add this, as with these subtle confusing errors, every perspective on it helps.

NPM vs. Bower vs. Browserify vs. Gulp vs. Grunt vs. Webpack

Yarn is a recent package manager that probably deserves to be mentioned.
So, here it is: https://yarnpkg.com/

As far as I know it can fetch both npm and bower dependencies and has other appreciated features.

Get UTC time in seconds

I believe +%s is seconds since epoch. It's timezone invariant.

How do I capture all of my compiler's output to a file?

Try make 2> file. Compiler warnings come out on the standard error stream, not the standard output stream. If my suggestion doesn't work, check your shell manual for how to divert standard error.

How to make a countdown timer in Android?

Here's the solution I used in Kotlin

private fun startTimer()
{
    Log.d(TAG, ":startTimer: timeString = '$timeString'")

    object : CountDownTimer(TASK_SWITCH_TIMER, 250)
    {
        override fun onTick(millisUntilFinished: Long)
        {
            val secondsUntilFinished : Long = 
            Math.ceil(millisUntilFinished.toDouble()/1000).toLong()
            val timeString = "${TimeUnit.SECONDS.toMinutes(secondsUntilFinished)}:" +
                    "%02d".format(TimeUnit.SECONDS.toSeconds(secondsUntilFinished))
            Log.d(TAG, ":startTimer::CountDownTimer:millisUntilFinished = $ttlseconds")
            Log.d(TAG, ":startTimer::CountDownTimer:millisUntilFinished = $millisUntilFinished")
        }

        @SuppressLint("SetTextI18n")
        override fun onFinish()
        {
            timerTxtVw.text = "0:00"
            gameStartEndVisibility(true)
        }
    }.start()
}

How to list the files inside a JAR file?

I've ported acheron55's answer to Java 7 and closed the FileSystem object. This code works in IDE's, in jar files and in a jar inside a war on Tomcat 7; but note that it does not work in a jar inside a war on JBoss 7 (it gives FileSystemNotFoundException: Provider "vfs" not installed, see also this post). Furthermore, like the original code, it is not thread safe, as suggested by errr. For these reasons I have abandoned this solution; however, if you can accept these issues, here is my ready-made code:

import java.io.IOException;
import java.net.*;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Collections;

public class ResourceWalker {

    public static void main(String[] args) throws URISyntaxException, IOException {
        URI uri = ResourceWalker.class.getResource("/resources").toURI();
        System.out.println("Starting from: " + uri);
        try (FileSystem fileSystem = (uri.getScheme().equals("jar") ? FileSystems.newFileSystem(uri, Collections.<String, Object>emptyMap()) : null)) {
            Path myPath = Paths.get(uri);
            Files.walkFileTree(myPath, new SimpleFileVisitor<Path>() { 
                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    System.out.println(file);
                    return FileVisitResult.CONTINUE;
                }
            });
        }
    }
}

IntelliJ show JavaDocs tooltip on mouse over

A note for Android Studio (2.3.3 at least) users, because this page came up for my google search "android studio hover javadoc", and android studio is based on Intellij:

See File->Settings->Editor->General: "show quick documentation on mouse moves", rather than File->Settings->Editor->General->Code Completion "Autopopup documentation in (ms) for explicitly invoked completion" and "Autopopup in (ms)", which has been previously talked about.

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

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

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

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

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

See here for source

if variable contains

The fastest way to check if a string contains another string is using indexOf:

if (code.indexOf('ST1') !== -1) {
    // string code has "ST1" in it
} else {
    // string code does not have "ST1" in it
}

If you can decode JWT, how are they secure?

Let's discuss from the very beginning:

JWT is a very modern, simple and secure approach which extends for Json Web Tokens. Json Web Tokens are a stateless solution for authentication. So there is no need to store any session state on the server, which of course is perfect for restful APIs. Restful APIs should always be stateless, and the most widely used alternative to authentication with JWTs is to just store the user's log-in state on the server using sessions. But then of course does not follow the principle that says that restful APIs should be stateless and that's why solutions like JWT became popular and effective.

So now let's know how authentication actually works with Json Web Tokens. Assuming we already have a registered user in our database. So the user's client starts by making a post request with the username and the password, the application then checks if the user exists and if the password is correct, then the application will generate a unique Json Web Token for only that user.

The token is created using a secret string that is stored on a server. Next, the server then sends that JWT back to the client which will store it either in a cookie or in local storage. enter image description here

Just like this, the user is authenticated and basically logged into our application without leaving any state on the server.

So the server does in fact not know which user is actually logged in, but of course, the user knows that he's logged in because he has a valid Json Web Token which is a bit like a passport to access protected parts of the application.

So again, just to make sure you got the idea. A user is logged in as soon as he gets back his unique valid Json Web Token which is not saved anywhere on the server. And so this process is therefore completely stateless.

Then, each time a user wants to access a protected route like his user profile data, for example. He sends his Json Web Token along with a request, so it's a bit like showing his passport to get access to that route.

Once the request hits the server, our app will then verify if the Json Web Token is actually valid and if the user is really who he says he is, well then the requested data will be sent to the client and if not, then there will be an error telling the user that he's not allowed to access that resource. enter image description here

All this communication must happen over https, so secure encrypted Http in order to prevent that anyone can get access to passwords or Json Web Tokens. Only then we have a really secure system.

enter image description here

So a Json Web Token looks like left part of this screenshot which was taken from the JWT debugger at jwt.io. So essentially, it's an encoding string made up of three parts. The header, the payload and the signature Now the header is just some metadata about the token itself and the payload is the data that we can encode into the token, any data really that we want. So the more data we want to encode here the bigger the JWT. Anyway, these two parts are just plain text that will get encoded, but not encrypted.

So anyone will be able to decode them and to read them, we cannot store any sensitive data in here. But that's not a problem at all because in the third part, so in the signature, is where things really get interesting. The signature is created using the header, the payload, and the secret that is saved on the server.

And this whole process is then called signing the Json Web Token. The signing algorithm takes the header, the payload, and the secret to create a unique signature. So only this data plus the secret can create this signature, all right? Then together with the header and the payload, these signature forms the JWT, which then gets sent to the client. enter image description here

Once the server receives a JWT to grant access to a protected route, it needs to verify it in order to determine if the user really is who he claims to be. In other words, it will verify if no one changed the header and the payload data of the token. So again, this verification step will check if no third party actually altered either the header or the payload of the Json Web Token.

So, how does this verification actually work? Well, it is actually quite straightforward. Once the JWT is received, the verification will take its header and payload, and together with the secret that is still saved on the server, basically create a test signature.

But the original signature that was generated when the JWT was first created is still in the token, right? And that's the key to this verification. Because now all we have to do is to compare the test signature with the original signature. And if the test signature is the same as the original signature, then it means that the payload and the header have not been modified. enter image description here

Because if they had been modified, then the test signature would have to be different. Therefore in this case where there has been no alteration of the data, we can then authenticate the user. And of course, if the two signatures are actually different, well, then it means that someone tampered with the data. Usually by trying to change the payload. But that third party manipulating the payload does of course not have access to the secret, so they cannot sign the JWT. So the original signature will never correspond to the manipulated data. And therefore, the verification will always fail in this case. And that's the key to making this whole system work. It's the magic that makes JWT so simple, but also extremely powerful.

How to solve "java.io.IOException: error=12, Cannot allocate memory" calling Runtime#exec()?

You can use the Tanuki wrapper to spawn a process with POSIX spawn instead of fork. http://wrapper.tanukisoftware.com/doc/english/child-exec.html

The WrapperManager.exec() function is an alternative to the Java-Runtime.exec() which has the disadvantage to use the fork() method, which can become on some platforms very memory expensive to create a new process.

How to convert a string to character array in c (or) how to extract a single char form string?

In this simple way

char str [10] = "IAmCute";
printf ("%c",str[4]);

Wait until all jQuery Ajax requests are done?

I highly recommend using $.when() if you're starting from scratch.

Even though this question has over million answers, I still didn't find anything useful for my case. Let's say you have to deal with an existing codebase, already making some ajax calls and don't want to introduce the complexity of promises and/or redo the whole thing.

We can easily take advantage of jQuery .data, .on and .trigger functions which have been a part of jQuery since forever.

Codepen

The good stuff about my solution is:

  • it's obvious what the callback exactly depends on

  • the function triggerNowOrOnLoaded doesn't care if the data has been already loaded or we're still waiting for it

  • it's super easy to plug it into an existing code

_x000D_
_x000D_
$(function() {_x000D_
_x000D_
  // wait for posts to be loaded_x000D_
  triggerNowOrOnLoaded("posts", function() {_x000D_
    var $body = $("body");_x000D_
    var posts = $body.data("posts");_x000D_
_x000D_
    $body.append("<div>Posts: " + posts.length + "</div>");_x000D_
  });_x000D_
_x000D_
_x000D_
  // some ajax requests_x000D_
  $.getJSON("https://jsonplaceholder.typicode.com/posts", function(data) {_x000D_
    $("body").data("posts", data).trigger("posts");_x000D_
  });_x000D_
_x000D_
  // doesn't matter if the `triggerNowOrOnLoaded` is called after or before the actual requests _x000D_
  $.getJSON("https://jsonplaceholder.typicode.com/users", function(data) {_x000D_
    $("body").data("users", data).trigger("users");_x000D_
  });_x000D_
_x000D_
_x000D_
  // wait for both types_x000D_
  triggerNowOrOnLoaded(["posts", "users"], function() {_x000D_
    var $body = $("body");_x000D_
    var posts = $body.data("posts");_x000D_
    var users = $body.data("users");_x000D_
_x000D_
    $body.append("<div>Posts: " + posts.length + " and Users: " + users.length + "</div>");_x000D_
  });_x000D_
_x000D_
  // works even if everything has already loaded!_x000D_
  setTimeout(function() {_x000D_
_x000D_
    // triggers immediately since users have been already loaded_x000D_
    triggerNowOrOnLoaded("users", function() {_x000D_
      var $body = $("body");_x000D_
      var users = $body.data("users");_x000D_
_x000D_
      $body.append("<div>Delayed Users: " + users.length + "</div>");_x000D_
    });_x000D_
_x000D_
  }, 2000); // 2 seconds_x000D_
_x000D_
});_x000D_
_x000D_
// helper function_x000D_
function triggerNowOrOnLoaded(types, callback) {_x000D_
  types = $.isArray(types) ? types : [types];_x000D_
_x000D_
  var $body = $("body");_x000D_
_x000D_
  var waitForTypes = [];_x000D_
  $.each(types, function(i, type) {_x000D_
_x000D_
    if (typeof $body.data(type) === 'undefined') {_x000D_
      waitForTypes.push(type);_x000D_
    }_x000D_
  });_x000D_
_x000D_
  var isDataReady = waitForTypes.length === 0;_x000D_
  if (isDataReady) {_x000D_
    callback();_x000D_
    return;_x000D_
  }_x000D_
_x000D_
  // wait for the last type and run this function again for the rest of the types_x000D_
  var waitFor = waitForTypes.pop();_x000D_
  $body.on(waitFor, function() {_x000D_
    // remove event handler - we only want the stuff triggered once_x000D_
    $body.off(waitFor);_x000D_
_x000D_
    triggerNowOrOnLoaded(waitForTypes, callback);_x000D_
  });_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<body>Hi!</body>
_x000D_
_x000D_
_x000D_

Manually map column names with class properties

I know this is a relatively old thread, but I thought I'd throw what I did out there.

I wanted attribute-mapping to work globally. Either you match the property name (aka default) or you match a column attribute on the class property. I also didn't want to have to set this up for every single class I was mapping to. As such, I created a DapperStart class that I invoke on app start:

public static class DapperStart
{
    public static void Bootstrap()
    {
        Dapper.SqlMapper.TypeMapProvider = type =>
        {
            return new CustomPropertyTypeMap(typeof(CreateChatRequestResponse),
                (t, columnName) => t.GetProperties().FirstOrDefault(prop =>
                    {
                        return prop.Name == columnName || prop.GetCustomAttributes(false).OfType<ColumnAttribute>()
                                   .Any(attr => attr.Name == columnName);
                    }
                ));
        };
    }
}

Pretty simple. Not sure what issues I'll run into yet as I just wrote this, but it works.

Two submit buttons in one form

Define name as array.

<form action='' method=POST>
    (...) some input fields (...)
    <input type=submit name=submit[save] value=Save>
    <input type=submit name=submit[delete] value=Delete>
</form>

Example server code (PHP):

if (isset($_POST["submit"])) {
    $sub = $_POST["submit"];

    if (isset($sub["save"])) {
        // save something;
    } elseif (isset($sub["delete"])) {
        // delete something
    }
}

elseif very important, because both will be parsed if not. Enjoy.

How to print something when running Puppet client?

Easier way, use notice. e.g notice("foo.pp works") or notice($foo)

Get selected key/value of a combo box using jQuery

I assume by "key" and "value" you mean:

<select>
    <option value="KEY">VALUE</option>
</select>

If that's the case, this will get you the "VALUE":

$(this).find('option:selected').text();

And you can get the "KEY" like this:

$(this).find('option:selected').val();

"While .. End While" doesn't work in VBA?

While constructs are terminated not with an End While but with a Wend.

While counter < 20
    counter = counter + 1
Wend

Note that this information is readily available in the documentation; just press F1. The page you link to deals with Visual Basic .NET, not VBA. While (no pun intended) there is some degree of overlap in syntax between VBA and VB.NET, one can't just assume that the documentation for the one can be applied directly to the other.

Also in the VBA help file:

Tip The Do...Loop statement provides a more structured and flexible way to perform looping.

WCF service maxReceivedMessageSize basicHttpBinding issue

When using HTTPS instead of ON the binding, put it IN the binding with the httpsTransport tag:

    <binding name="MyServiceBinding">
      <security defaultAlgorithmSuite="Basic256Rsa15" 
                authenticationMode="MutualCertificate" requireDerivedKeys="true" 
                securityHeaderLayout="Lax" includeTimestamp="true" 
                messageProtectionOrder="SignBeforeEncrypt" 
                messageSecurityVersion="WSSecurity10WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10"
                requireSignatureConfirmation="false">
        <localClientSettings detectReplays="true" />
        <localServiceSettings detectReplays="true" />
        <secureConversationBootstrap keyEntropyMode="CombinedEntropy" />
      </security>
      <textMessageEncoding messageVersion="Soap11WSAddressing10">
        <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" 
                      maxArrayLength="2147483647" maxBytesPerRead="4096" 
                      maxNameTableCharCount="16384"/>
      </textMessageEncoding>
      <httpsTransport maxReceivedMessageSize="2147483647" 
                      maxBufferSize="2147483647" maxBufferPoolSize="2147483647" 
                      requireClientCertificate="false" />
    </binding>

Could not install packages due to an EnvironmentError: [WinError 5] Access is denied:

Using an elevated command prompt worked wonders. All you have to do is run

pip install <package-name>

With an administrative privilege.

jQuery UI Slider (setting programmatically)

None of the above answers worked for me, perhaps they were based on an older version of the framework?

All I needed to do was set the value of the underlying control, then call the refresh method, as below:

$("#slider").val(50);
$("#slider").slider("refresh");

How to compare only date components from DateTime in EF?

you can use DbFunctions.TruncateTime() method for this.

e => DbFunctions.TruncateTime(e.FirstDate.Value) == DbFunctions.TruncateTime(SecondDate);

Paramiko's SSHClient with SFTP

If you have a SSHClient, you can also use open_sftp():

import paramiko


# lets say you have SSH client...
client = paramiko.SSHClient()

sftp = client.open_sftp()

# then you can use upload & download as shown above
...

How to use 'find' to search for files created on a specific date?

It's two steps but I like to do it this way:

First create a file with a particular date/time. In this case, the file is 2008-10-01 at midnight

touch -t 0810010000 /tmp/t

Now we can find all files that are newer or older than the above file (going by file modified date. You can also use -anewer for accessed and -cnewer file status changed).

find / -newer /tmp/t
find / -not -newer /tmp/t

You could also look at files between certain dates by creating two files with touch

touch -t 0810010000 /tmp/t1
touch -t 0810011000 /tmp/t2

This will find files between the two dates & times

find / -newer /tmp/t1 -and -not -newer /tmp/t2

Purpose of __repr__ method?

Implement repr for every class you implement. There should be no excuse. Implement str for classes which you think readability is more important of non-ambiguity.

Refer this link: https://www.pythoncentral.io/what-is-the-difference-between-str-and-repr-in-python/

Can't compare naive and aware datetime.now() <= challenge.datetime_end

Just:

dt = datetimeObject.strftime(format) # format = your datetime format ex) '%Y %d %m'
dt = datetime.datetime.strptime(dt,format)

So do this:

start_time = challenge.datetime_start.strftime('%Y %d %m %H %M %S')
start_time = datetime.datetime.strptime(start_time,'%Y %d %m %H %M %S')

end_time = challenge.datetime_end.strftime('%Y %d %m %H %M %S')
end_time = datetime.datetime.strptime(end_time,'%Y %d %m %H %M %S')

and then use start_time and end_time

Can't install any packages in Node.js using "npm install"

The repository is not down, it looks like they've changed how they host files (I guess they have restored some old code):

Now you have to add the /package-name/ before the -

Eg:

http://registry.npmjs.org/-/npm-1.1.48.tgz
http://registry.npmjs.org/npm/-/npm-1.1.48.tgz

There are 3 ways to solve it:

  • Use a complete mirror:
  • Use a public proxy:

    --registry http://165.225.128.50:8000

  • Host a local proxy:

    https://github.com/hughsk/npm-quickfix

git clone https://github.com/hughsk/npm-quickfix.git
cd npm-quickfix
npm set registry http://localhost:8080/
node index.js

I'd personally go with number 3 and revert to npm set registry http://registry.npmjs.org/ as soon as this get resolved.

Stay tuned here for more info: https://github.com/isaacs/npm/issues/2694

ASP.NET Core form POST results in a HTTP 415 Unsupported Media Type response

This is my case: it's run Environment: AspNet Core 2.1 Controller:

public class MyController
{
    // ...

    [HttpPost]
    public ViewResult Search([FromForm]MySearchModel searchModel)
    {
        // ...
        return View("Index", viewmodel);
    }
}

View:

<form method="post" asp-controller="MyController" asp-action="Search">
    <input name="MySearchModelProperty" id="MySearchModelProperty" />
    <input type="submit" value="Search" />
</form>

Reading value from console, interactively

Please use readline-sync, this lets you working with synchronous console withouts callbacks hells. Even works with passwords:

_x000D_
_x000D_
var favFood = read.question('What is your favorite food? ', {_x000D_
  hideEchoBack: true // The typed text on screen is hidden by `*` (default). _x000D_
});
_x000D_
_x000D_
_x000D_

Remove scrollbar from iframe

Add this in your css to hide just the horizontal scroll bar

iframe{
    overflow-x:hidden;
}

PHP Get Highest Value from Array

greatestValue=> try this its very easy

$a=array(10,20,52,105,56,89,96);
$c=0;
foreach($a as $b)
{
if($b>$c)
$c=$b;

}
echo $c;

Why is Thread.Sleep so harmful

Sleep is used in cases where independent program(s) that you have no control over may sometimes use a commonly used resource (say, a file), that your program needs to access when it runs, and when the resource is in use by these other programs your program is blocked from using it. In this case, where you access the resource in your code, you put your access of the resource in a try-catch (to catch the exception when you can't access the resource), and you put this in a while loop. If the resource is free, the sleep never gets called. But if the resource is blocked, then you sleep for an appropriate amount of time, and attempt to access the resource again (this why you're looping). However, bear in mind that you must put some kind of limiter on the loop, so it's not a potentially infinite loop. You can set your limiting condition to be N number of attempts (this is what I usually use), or check the system clock, add a fixed amount of time to get a time limit, and quit attempting access if you hit the time limit.

Android Bluetooth Example

I have also used following link as others have suggested you for bluetooth communication.

http://developer.android.com/guide/topics/connectivity/bluetooth.html

The thing is all you need is a class BluetoothChatService.java

this class has following threads:

  1. Accept
  2. Connecting
  3. Connected

Now when you call start function of the BluetoothChatService like:

mChatService.start();

It starts accept thread which means it will start looking for connection.

Now when you call

mChatService.connect(<deviceObject>,false/true);

Here first argument is device object that you can get from paired devices list or when you scan for devices you will get all the devices in range you can pass that object to this function and 2nd argument is a boolean to make secure or insecure connection.

connect function will start connecting thread which will look for any device which is running accept thread.

When such a device is found both accept thread and connecting thread will call connected function in BluetoothChatService:

connected(mmSocket, mmDevice, mSocketType);

this method starts connected thread in both the devices: Using this socket object connected thread obtains the input and output stream to the other device. And calls read function on inputstream in a while loop so that it's always trying read from other device so that whenever other device send a message this read function returns that message.

BluetoothChatService also has a write method which takes byte[] as input and calls write method on connected thread.

mChatService.write("your message".getByte());

write method in connected thread just write this byte data to outputsream of the other device.

public void write(byte[] buffer) {
   try {
       mmOutStream.write(buffer);
    // Share the sent message back to the UI Activity
    // mHandler.obtainMessage(
    // BluetoothGameSetupActivity.MESSAGE_WRITE, -1, -1,
    // buffer).sendToTarget();
    } catch (IOException e) {
    Log.e(TAG, "Exception during write", e);
     }
}

Now to communicate between two devices just call write function on mChatService and handle the message that you will receive on the other device.