Programs & Examples On #Jspec

jSpec is a JavaScript BDD Framework.

How to get a cookie from an AJAX response?

Similar to yebmouxing I could not the

 xhr.getResponseHeader('Set-Cookie');

method to work. It would only return null even if I had set HTTPOnly to false on my server.

I too wrote a simple js helper function to grab the cookies from the document. This function is very basic and only works if you know the additional info (lifespan, domain, path, etc. etc.) to add yourself:

function getCookie(cookieName){
  var cookieArray = document.cookie.split(';');
  for(var i=0; i<cookieArray.length; i++){
    var cookie = cookieArray[i];
    while (cookie.charAt(0)==' '){
      cookie = cookie.substring(1);
    }
    cookieHalves = cookie.split('=');
    if(cookieHalves[0]== cookieName){
      return cookieHalves[1];
    }
  }
  return "";
}

Upload Progress Bar in PHP

Implementation of the upload progress bar is easy and doesn't require any additional PHP extension, JavaScript or Flash. But you need PHP 5.4 and newer.

You have to enable collecting of the upload progress information by setting the directive session.upload_progress.enabled to On in php.ini.

Then add a hidden input to the HTML upload form just before any other file inputs. HTML attribute name of that hidden input should be the same as the value of the directive session.upload_progress.name from php.ini (eventually preceded by session.upload_progress.prefix). The value attribute is up to you, it will be used as part of the session key.

HTML form could looks like this:

<form action="upload.php" method="POST" enctype="multipart/form-data">
   <input type="hidden" name="<?php echo ini_get('session.upload_progress.prefix').ini_get('session.upload_progress.name'); ?>" value="myupload" />
   <input type="file" name="file1" />
   <input type="submit" />
</form>

When you send this form, PHP should create a new key in the $_SESSION superglobal structure which will be populated with the upload status information. The key is concatenated name and value of the hidden input.

In PHP you can take a look at populated upload information:

var_dump($_SESSION[
    ini_get('session.upload_progress.prefix')
   .ini_get('session.upload_progress.name')
   .'_myupload'
]);

The output will look similarly to the following:

$_SESSION["upload_progress_myupload"] = array(
  "start_time" => 1234567890,   // The request time
  "content_length" => 57343257, // POST content length
  "bytes_processed" => 54321,   // Amount of bytes received and processed
  "done" => false,              // true when the POST handler has finished, successfully or not
  "files" => array(
    0 => array(
      "field_name" => "file1",    // Name of the <input /> field
      // The following 3 elements equals those in $_FILES
      "name" => "filename.ext",
      "tmp_name" => "/tmp/phpxxxxxx",
      "error" => 0,
      "done" => false,            // True when the POST handler has finished handling this file
      "start_time" => 1234567890, // When this file has started to be processed
      "bytes_processed" => 54321, // Number of bytes received and processed for this file
    )
  )
);

There is all the information needed to create a progress bar — you have the information if the upload is still in progress, the information how many bytes is going to be transferred in total and how many bytes has been transferred already.

To present the upload progress to the user, write an another PHP script than the uploading one, which will only look at the upload information in the session and return it in the JSON format, for example. This script can be called periodically, for example every second, using AJAX and information presented to the user.

You are even able to cancel the upload by setting the $_SESSION[$key]['cancel_upload'] to true.

For detailed information, additional settings and user's comments see PHP manual.

How to fix the height of a <div> element?

You can also use min-height and max-height. It was very useful for me

error: package com.android.annotations does not exist

Open gradle.properties and use following code:

android.useAndroidX=false
android.enableJetifier=false

or U can use these dependencies too:

implementation 'androidx.appcompat:appcompat:1.0.2'
 implementation 'androidx.annotation:annotation:1.0.2'

Looping through the content of a file in Bash

@Peter: This could work out for you-

echo "Start!";for p in $(cat ./pep); do
echo $p
done

This would return the output-

Start!
RKEKNVQ
IPKKLLQK
QYFHQLEKMNVK
IPKKLLQK
GDLSTALEVAIDCYEK
QYFHQLEKMNVKIPENIYR
RKEKNVQ
VLAKHGKLQDAIN
ILGFMK
LEDVALQILL

Oracle client and networking components were not found

Technology used: Windows 7, UFT 32 bit, Data Source ODBC pointing out to 32 bit C:\Windows\System32\odbcad32.exe, Oracle client with both versions installed 32 bit and 64 bit.

What worked for me:

1.Start -> search for Edit the system environment variables
2.System Variables -> Edit Path
3.Place the path for Oracle client 32 bit in front of the path for Oracle Client 64 bit.

Ex:

C:\APP\ORACLE\product\11.2.0\client_32\bin;C:\APP\ORACLE\product\11.2.0\client_64\bin

Call a function with argument list in python

You need to use arguments unpacking..

def wrapper(func, *args):
    func(*args)

def func1(x):
    print(x)

def func2(x, y, z):
    print x+y+z

wrapper(func1, 1)
wrapper(func2, 1, 2, 3)

Storage permission error in Marshmallow

Seems user has declined the permission and app tries to write to external disk, causing error.

@Override
public void onRequestPermissionsResult(int requestCode,
        String permissions[], int[] grantResults) {
    switch (requestCode) {
        case MY_PERMISSIONS_REQUEST_READ_CONTACTS: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                // permission was granted, yay! Do the
                // contacts-related task you need to do.

            } else {

                // permission denied, boo! Disable the
                // functionality that depends on this permission.
            }
            return;
        }

        // other 'case' lines to check for other
        // permissions this app might request
    }
}

Check https://developer.android.com/training/permissions/requesting.html

This video will give you a better idea about UX, handling Runtime permissions https://www.youtube.com/watch?v=iZqDdvhTZj0

Public free web services for testing soap client

There is a bunch on here:

http://www.webservicex.net/WS/wscatlist.aspx

Just google for "Free WebService" or "Open WebService" and you'll find tons of open SOAP endpoints.

Remember, you can get a WSDL from any ASMX endpoint by adding ?WSDL to the url.

&& (AND) and || (OR) in IF statements

Short circuit here means that the second condition won't be evaluated.

If ( A && B ) will result in short circuit if A is False.

If ( A && B ) will not result in short Circuit if A is True.

If ( A || B ) will result in short circuit if A is True.

If ( A || B ) will not result in short circuit if A is False.

Write HTML string in JSON

in json everything is string between double quote ", so you need escape " if it happen in value (only in direct writing) use backslash \

and everything in json file wrapped in {} change your json to

_x000D_
_x000D_
{_x000D_
  [_x000D_
    {_x000D_
      "id": "services.html",_x000D_
      "img": "img/SolutionInnerbananer.jpg",_x000D_
      "html": "<h2 class=\"fg-white\">AboutUs</h2><p class=\"fg-white\">developing and supporting complex IT solutions.Touching millions of lives world wide by bringing in innovative technology</p>"_x000D_
    }_x000D_
  ]_x000D_
}
_x000D_
_x000D_
_x000D_

Difference Between Schema / Database in MySQL

Refering to MySql documentation,

CREATE DATABASE creates a database with the given name. To use this statement, you need the CREATE privilege for the database. CREATE SCHEMA is a synonym for CREATE DATABASE as of MySQL 5.0.2.

Remove excess whitespace from within a string

$str = str_replace(' ','',$str);

Or, replace with underscore, & nbsp; etc etc.

How do I set the proxy to be used by the JVM

To use the system proxy setup:

java -Djava.net.useSystemProxies=true ...

Or programatically:

System.setProperty("java.net.useSystemProxies", "true");

Source: http://docs.oracle.com/javase/7/docs/api/java/net/doc-files/net-properties.html

jQuery - getting custom attribute from selected option

You can also try this one as well with data-myTag

<select id="location">
    <option value="a" data-myTag="123">My option</option>
    <option value="b" data-myTag="456">My other option</option>
</select>

<input type="hidden" id="setMyTag" />

<script>
    $(function() {
        $("#location").change(function(){
           var myTag = $('option:selected', this).data("myTag");

           $('#setMyTag').val(myTag);
        });
    });
</script>

Replace whitespaces with tabs in linux

Use the unexpand(1) program


UNEXPAND(1)                      User Commands                     UNEXPAND(1)

NAME
       unexpand - convert spaces to tabs

SYNOPSIS
       unexpand [OPTION]... [FILE]...

DESCRIPTION
       Convert  blanks in each FILE to tabs, writing to standard output.  With
       no FILE, or when FILE is -, read standard input.

       Mandatory arguments to long options are  mandatory  for  short  options
       too.

       -a, --all
              convert all blanks, instead of just initial blanks

       --first-only
              convert only leading sequences of blanks (overrides -a)

       -t, --tabs=N
              have tabs N characters apart instead of 8 (enables -a)

       -t, --tabs=LIST
              use comma separated LIST of tab positions (enables -a)

       --help display this help and exit

       --version
              output version information and exit
. . .
STANDARDS
       The expand and unexpand utilities conform to IEEE Std 1003.1-2001
       (``POSIX.1'').

How to create bitmap from byte array?

You'll need to get those bytes into a MemoryStream:

Bitmap bmp;
using (var ms = new MemoryStream(imageData))
{
    bmp = new Bitmap(ms);
}

That uses the Bitmap(Stream stream) constructor overload.

UPDATE: keep in mind that according to the documentation, and the source code I've been reading through, an ArgumentException will be thrown on these conditions:

stream does not contain image data or is null.
-or-
stream contains a PNG image file with a single dimension greater than 65,535 pixels.

Modify a Column's Type in sqlite3

If you prefer a GUI, DB Browser for SQLite will do this with a few clicks.

  1. "File" - "Open Database"
  2. In the "Database Structure" tab, click on the table content (not table name), then "Edit" menu, "Modify table", and now you can change the data type of any column with a drop down menu. I changed a 'text' field to 'numeric' in order to retrieve data in a number range.

DB Browser for SQLite is open source and free. For Linux it is available from the repository.

JavaScript to get rows count of a HTML table

You can use the .rows property and check it's .length, like this:

var rowCount = document.getElementById('myTableID').rows.length;

Maximum call stack size exceeded on npm install

npm rebuild will work for sure

C# DataTable.Select() - How do I format the filter criteria to include null?

The way to check for null is to check for it:

DataRow[] myResultSet = myDataTable.Select("[COLUMN NAME] is null");

You can use and and or in the Select statement.

Test if number is odd or even

Check Even Or Odd Number Without Use Condition And Loop Statement.

This work for me..!

_x000D_
_x000D_
$(document).ready(function(){_x000D_
    $("#btn_even_odd").click(function(){_x000D_
        var arr = ['Even','Odd'];_x000D_
        var num_even_odd = $("#num_even_odd").val();_x000D_
        $("#ans_even_odd").html(arr[num_even_odd % 2]);_x000D_
    });_x000D_
});
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
    <title>Check Even Or Odd Number Without Use Condition And Loop Statement.</title>_x000D_
</head>_x000D_
<body>_x000D_
<h4>Check Even Or Odd Number Without Use Condition And Loop Statement.</h4>_x000D_
<table>_x000D_
    <tr>_x000D_
        <th>Enter A Number :</th>_x000D_
        <td><input type="text" name="num_even_odd" id="num_even_odd" placeholder="Enter Only Number"></td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <th>Your Answer Is :</th>_x000D_
        <td id="ans_even_odd" style="font-size:15px;color:gray;font-weight:900;"></td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td><input type="button" name="btn_even_odd" id="btn_even_odd" value="submit"></td>_x000D_
    </tr>_x000D_
</table>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

How do I compare two DateTime objects in PHP 5.2.8?

$elapsed = '2592000';
// Time in the past
$time_past = '2014-07-16 11:35:33';
$time_past = strtotime($time_past);

// Add a month to that time
$time_past = $time_past + $elapsed;

// Time NOW
$time_now = time();

// Check if its been a month since time past
if($time_past > $time_now){
    echo 'Hasnt been a month';    
}else{
    echo 'Been longer than a month';
}

What is <scope> under <dependency> in pom.xml for?

If we don't provide any scope then the default scope is compile, If you want to confirm, simply go to Effective pom tab in eclipse editor, it will show you as compile.

CSS Box Shadow - Top and Bottom Only

After some experimentation I found that a fourth value in the line controls the spread (at least in FF 10). I opposed the vertical offsets and gave them a negative spread.

Here's the working pen: http://codepen.io/gillytech/pen/dlbsx

<html>
<head>
<style type="text/css">

#test {
    width: 500px;
    border: 1px  #CCC solid;
    height: 200px;

    box-shadow: 
        inset 0px 11px 8px -10px #CCC,
        inset 0px -11px 8px -10px #CCC; 
}
</style>
</head>
<body>
    <div id="test"></div>
</body>
</html>

This works perfectly for me!

Testing the type of a DOM element in JavaScript

roenving is correct BUT you need to change the test to:

if(element.nodeType == 1) {
//code
}

because nodeType of 3 is actually a text node and nodeType of 1 is an HTML element. See http://www.w3schools.com/Dom/dom_nodetype.asp

No serializer found for class org.hibernate.proxy.pojo.javassist.Javassist?

I had a similar problem with lazy loading via the hibernate proxy object. Got around it by annotating the class having lazy loaded private properties with:

@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})

I assume you can add the properties on your proxy object that breaks the JSON serialization to that annotation.

The problem is that entities are loaded lazily and serialization happens before they get loaded fully.

Hibernate.initialize(<your getter method>);

Communicating between a fragment and an activity - best practices

There are severals ways to communicate between activities, fragments, services etc. The obvious one is to communicate using interfaces. However, it is not a productive way to communicate. You have to implement the listeners etc.

My suggestion is to use an event bus. Event bus is a publish/subscribe pattern implementation.

You can subscribe to events in your activity and then you can post that events in your fragments etc.

Here on my blog post you can find more detail about this pattern and also an example project to show the usage.

IndexError: tuple index out of range ----- Python

A tuple consists of a number of values separated by commas. like

>>> t = 12345, 54321, 'hello!'
>>> t[0]
12345

tuple are index based (and also immutable) in Python.

Here in this case x = rows[1][1] + " " + rows[1][2] have only two index 0, 1 available but you are trying to access the 3rd index.

Warning: mysqli_connect(): (HY000/1045): Access denied for user 'username'@'localhost' (using password: YES)

mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);

use DB_HOST instead of DB_SERVER

Issue with background color in JavaFX 8

Both these work for me. Maybe post a complete example?

import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.ToggleButton;
import javafx.scene.layout.Background;
import javafx.scene.layout.BackgroundFill;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.CornerRadii;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;

public class PaneBackgroundTest extends Application {

    @Override
    public void start(Stage primaryStage) {
        BorderPane root = new BorderPane();
        VBox vbox = new VBox();
        root.setCenter(vbox);

        ToggleButton toggle = new ToggleButton("Toggle color");
        HBox controls = new HBox(5, toggle);
        controls.setAlignment(Pos.CENTER);
        root.setBottom(controls);

//        vbox.styleProperty().bind(Bindings.when(toggle.selectedProperty())
//                .then("-fx-background-color: cornflowerblue;")
//                .otherwise("-fx-background-color: white;"));

        vbox.backgroundProperty().bind(Bindings.when(toggle.selectedProperty())
                .then(new Background(new BackgroundFill(Color.CORNFLOWERBLUE, CornerRadii.EMPTY, Insets.EMPTY)))
                .otherwise(new Background(new BackgroundFill(Color.WHITE, CornerRadii.EMPTY, Insets.EMPTY))));

        Scene scene = new Scene(root, 300, 250);

        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

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

}

Get only records created today in laravel

I’ve seen people doing it with raw queries, like this:

$q->where(DB::raw("DATE(created_at) = '".date('Y-m-d')."'"));

Or without raw queries by datetime, like this:

$q->where('created_at', '>=', date('Y-m-d').' 00:00:00'));

Luckily, Laravel Query Builder offers a more Eloquent solution:

$q->whereDate('created_at', '=', date('Y-m-d'));

Or, of course, instead of PHP date() you can use Carbon:

$q->whereDate('created_at', '=', Carbon::today()->toDateString());

It’s not only whereDate. There are three more useful functions to filter out dates:

$q->whereDay('created_at', '=', date('d'));
$q->whereMonth('created_at', '=', date('m'));
$q->whereYear('created_at', '=', date('Y'));

How do I add a tool tip to a span element?

the "title" attribute will be used as the text for tooltip by the browser, if you want to apply style to it consider using some plugins

Compiling php with curl, where is curl installed?

Try just --with-curl, without specifying a location, and see if it'll find it by itself.

What is the best way to get the count/length/size of an iterator?

There is no more efficient way, if all you have is the iterator. And if the iterator can only be used once, then getting the count before you get the iterator's contents is ... problematic.

The solution is either to change your application so that it doesn't need the count, or to obtain the count by some other means. (For example, pass a Collection rather than Iterator ...)

How to change Toolbar home icon color

This code works for me:

public static Drawable changeBackArrowColor(Context context, int color) {
    String resName;
    int res;

    resName = Build.VERSION.SDK_INT >= 23 ? "abc_ic_ab_back_material" : "abc_ic_ab_back_mtrl_am_alpha";
    res = context.getResources().getIdentifier(resName, "drawable", context.getPackageName());

    final Drawable upArrow = context.getResources().getDrawable(res);
    upArrow.setColorFilter(color, PorterDuff.Mode.SRC_ATOP);

    return upArrow;
}

...

getSupportActionBar().setHomeAsUpIndicator(changeBackArrowColor(this, Color.rgb(50, 50, 50)));               
supportInvalidateOptionsMenu();

Also, if you want to change the toolbar text color:

Spannable spannableString = new SpannableString(t);
spannableString.setSpan(new ForegroundColorSpan(Color.rgb(50, 50, 50)), 0, t.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
toolbar.setText(spannableString);

Working from API 19 through 25.

How can I avoid getting this MySQL error Incorrect column specifier for column COLUMN NAME?

Quoting the doc:

Some attributes do not apply to all data types. AUTO_INCREMENT applies only to integer and floating-point types. DEFAULT does not apply to the BLOB or TEXT types.

In your case, you're trying to apply AUTO_INCREMENT modifier to char column. To solve this, either drop AUTO_INCREMENT altogether (that means you'll have to generate a unique id on the application level) or just change topic_id type to the relevant integer one.

As a sidenote, it makes little sense using char(36) to store the posts count, so that column's type probably has to be changed as well. It looks like you're going this way to prevent integer overflow - but if you're dealing with more than 18446744073709551615 posts (the biggest number that can be stored in BIGINT UNSIGNED column) in a single topic, you have far bigger problem on your side probably. )

Can I automatically increment the file build version when using Visual Studio?

Maybe, for this task, you can use code like this:

    private bool IncreaseFileVersionBuild()
    {
        if (System.Diagnostics.Debugger.IsAttached)
        {
            try
            {
                var fi = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory).Parent.Parent.GetDirectories("Properties")[0].GetFiles("AssemblyInfo.cs")[0];
                var ve = System.Diagnostics.FileVersionInfo.GetVersionInfo(System.Reflection.Assembly.GetExecutingAssembly().Location);
                string ol = ve.FileMajorPart.ToString() + "." + ve.FileMinorPart.ToString() + "." + ve.FileBuildPart.ToString() + "." + ve.FilePrivatePart.ToString();
                string ne = ve.FileMajorPart.ToString() + "." + ve.FileMinorPart.ToString() + "." + (ve.FileBuildPart + 1).ToString() + "." + ve.FilePrivatePart.ToString();
                System.IO.File.WriteAllText(fi.FullName, System.IO.File.ReadAllText(fi.FullName).Replace("[assembly: AssemblyFileVersion(\"" + ol + "\")]", "[assembly: AssemblyFileVersion(\"" + ne + "\")]"));
                return true;
            }
            catch
            {
                return false;
            }
        }
        return false;
    }

and call it from form loading.
With this code you can update any part of file info in AssemblyInfo.cs (but you must use "standard" directory structure).

laravel 5.5 The page has expired due to inactivity. Please refresh and try again

In my case, there was 'space' before <?php in one of my config file. This solved my issue.

A KeyValuePair in Java

Android programmers could use BasicNameValuePair

Update:

BasicNameValuePair is now deprecated (API 22). Use Pair instead.

Example usage:

Pair<Integer, String> simplePair = new Pair<>(42, "Second");
Integer first = simplePair.first; // 42
String second = simplePair.second; // "Second"

Java command not found on Linux

I found the best way for me was to download unzip then symlink your new usr/java/jre-version/bin/java to your main bin as java.

How to disable postback on an asp Button (System.Web.UI.WebControls.Button)

You just need to return false from the

_x000D_
_x000D_
function jsFunction() {
  try {
    // Logic goes here
    return false; // true for postback and false for not postback
  } catch (e) {
    alert(e.message);
    return false;
  }
}
_x000D_
<asp:button runat="server" id="btnSubmit" OnClientClick="return jsFunction()" />
_x000D_
_x000D_
_x000D_

JavaScript function like below.

Note*: Always use try-catch blocks and return false from catch block to prevent incorrect calculation in javaScript function.

Is there a real solution to debug cordova apps

If you can use an Android 4.4+ device, then you can use Chrome Remote Debugging even on the app's internal WebView. It's a much better debugger than Weinre, but the key is using the recent Android version.

Recent Cordova builds automatically enable this kind of debugging as long as it's a debug build (it's turned off in --release builds).

How to run Pip commands from CMD

Newer versions of Python come with py, the Python Launcher, which is always in the PATH.

Here is how to invoke pip via py:

py -m pip install <packagename>

py allows having several versions of Python on the same machine.

As an example, here is how to invoke the pip from Python 2.7:

py -2.7 -m pip install <packagename>

How do I convert speech to text?

Dragon NaturallySpeaking seems to support MP3 input.

If you want an open source version (I think there are some Asterisk integration projects based on this one).

How do I detect when someone shakes an iPhone?

I finally made it work using code examples from this Undo/Redo Manager Tutorial.
This is exactly what you need to do:

  • Set the applicationSupportsShakeToEdit property in the App's Delegate:
  • 
        - (void)applicationDidFinishLaunching:(UIApplication *)application {
    
            application.applicationSupportsShakeToEdit = YES;
    
            [window addSubview:viewController.view];
            [window makeKeyAndVisible];
    }
    

  • Add/Override canBecomeFirstResponder, viewDidAppear: and viewWillDisappear: methods in your View Controller:
  • 
    -(BOOL)canBecomeFirstResponder {
        return YES;
    }
    
    -(void)viewDidAppear:(BOOL)animated {
        [super viewDidAppear:animated];
        [self becomeFirstResponder];
    }
    
    - (void)viewWillDisappear:(BOOL)animated {
        [self resignFirstResponder];
        [super viewWillDisappear:animated];
    }
    

  • Add the motionEnded method to your View Controller:
  • 
    - (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
    {
        if (motion == UIEventSubtypeMotionShake)
        {
            // your code
        }
    }
    

    What's the difference between Apache's Mesos and Google's Kubernetes

    Mesos and Kubernetes both are container orchestration tools.

    When you say "Google Kubernetes"?

    Google Kubernetes Engine provides a managed environment for deploying, managing, and scaling your containerized applications using Google infrastructure.

    Kubernetes is an open-source system for automating deployment, scaling, and management of containerized applications.” Kubernetes was built by Google based on their experience running containers in production over the last decade.

    The major components in a Kubernetes cluster are:

    pods — a way to group containers together replication controllers — a way to handle the lifecycle of containers labels — a way to find and query containers, and services — a set of containers performing a common function

    Mesos is an open-source cluster management project by Apache, designed to scale to very large clusters, from hundreds to thousands of hosts. Mesos supports diverse kinds of workloads such as Hadoop tasks, cloud native applications etc. It gives you the ability to run both containerized, and non-containerized workloads in a distributed manner.

    It was initially written as a research project at Berkeley and was later adopted by Twitter as an answer to Google’s Borg (Kubernetes’ predecessor). To combat its high degree of complexity (Mesos is super complicated and hard to manage!), Mesosphere came into the picture to try and make Mesos into something regular human beings can use.

    Mesosphere supplied the superb Marathon “plugin” to Mesos, which provides users with an easy way to manage container orchestration over Mesos.

    In mid-2016, DC/OS (Data Center Operating System) — an open source project backed by Mesosphere — was introduced, which simplifies Mesos even further and allows you to deploy your own Mesos cluster, with Marathon, in a matter of minutes.

    Now, if we compare kubernetes and Mesos(DC/OS)

    kubernetes is a cluster manager for containers while mesos is a distributed system kernel that will make your cluster look like one giant computer system to all supported frameworks and apps that are built to be run on mesos.

    Mesos was born for a world where you own a lot of physical resources to create a big static computing cluster. The great thing about it is that lots of modern scalable data processing application runs very well on Mesos (Hadoop, Kafka, Spark) and it is nice because you can run them all on the same basic resource pool, along with your new age container packaged apps.

    Mesos cluster also runs alongside the Marathon cluster. Marathon, created by Mesosphere, is designed to start, monitor and scale long-running applications, including cloud native apps. Clients interact with Marathon through a REST API.

    Also, a point to be noted is that you can actually run Kubernetes on top of DC/OS and schedule containers with it instead of using Marathon. This implies the biggest difference of all — DC/OS, as it name suggests, is more similar to an operating system rather than an orchestration framework. You can run non-containerized, stateful workloads on it. Container scheduling is handled by the Marathon.

    Executing periodic actions in Python

    Here's a nice implementation using the Thread class: http://g-off.net/software/a-python-repeatable-threadingtimer-class

    the code below is a little more quick and dirty:

    from threading import Timer
    from time import sleep
    
    def hello():
        print "hello, world"
        t = Timer(3,hello)
        t.start()
    
    t = Timer(3, hello)
    t.start() # after 3 seconds, "hello, world" will be printed
    
    # timer will wake up ever 3 seconds, while we do something else
    while True:
        print "do something else"
        sleep(10)
    

    How to use WHERE IN with Doctrine 2

    and for completion the string solution

    $qb->andWhere('foo.field IN (:string)');
    $qb->setParameter('string', array('foo', 'bar'), \Doctrine\DBAL\Connection::PARAM_STR_ARRAY);
    

    How to find MAC address of an Android device programmatically

    private fun getMac(): String? =
            try {
                NetworkInterface.getNetworkInterfaces()
                        .toList()
                        .find { networkInterface -> networkInterface.name.equals("wlan0", ignoreCase = true) }
                        ?.hardwareAddress
                        ?.joinToString(separator = ":") { byte -> "%02X".format(byte) }
            } catch (ex: Exception) {
                ex.printStackTrace()
                null
            }
    

    StringStream in C#

    You can use a StringWriter to write values to a string. It provides a stream-like syntax (though does not derive from Stream) which works with an underlying StringBuilder.

    read input separated by whitespace(s) or newline...?

    Just use:

    your_type x;
    while (std::cin >> x)
    {
        // use x
    }
    

    operator>> will skip whitespace by default. You can chain things to read several variables at once:

    if (std::cin >> my_string >> my_number)
        // use them both
    

    getline() reads everything on a single line, returning that whether it's empty or contains dozens of space-separated elements. If you provide the optional alternative delimiter ala getline(std::cin, my_string, ' ') it still won't do what you seem to want, e.g. tabs will be read into my_string.

    Probably not needed for this, but a fairly common requirement that you may be interested in sometime soon is to read a single newline-delimited line, then split it into components...

    std::string line;
    while (std::getline(std::cin, line))
    {
        std::istringstream iss(line);
        first_type first_on_line;
        second_type second_on_line;
        third_type third_on_line;
        if (iss >> first_on_line >> second_on_line >> third_on_line)
            ...
    }
    

    How to show/hide JPanels in a JFrame?

    You can hide a JPanel by calling setVisible(false). For example:

    public static void main(String args[]){
        JFrame f = new JFrame();
        f.setLayout(new BorderLayout());
        final JPanel p = new JPanel();
        p.add(new JLabel("A Panel"));
        f.add(p, BorderLayout.CENTER);
    
        //create a button which will hide the panel when clicked.
        JButton b = new JButton("HIDE");
        b.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
                    p.setVisible(false);
            }
        });
    
        f.add(b,BorderLayout.SOUTH);
        f.pack();
        f.setVisible(true);
    }
    

    How do I debug "Error: spawn ENOENT" on node.js?

    NOTE: This error is almost always caused because the command does not exist, because the working directory does not exist, or from a windows-only bug.

    I found a particular easy way to get the idea of the root cause of:

    Error: spawn ENOENT
    

    The problem of this error is, there is really little information in the error message to tell you where the call site is, i.e. which executable/command is not found, especially when you have a large code base where there are a lot of spawn calls. On the other hand, if we know the exact command that cause the error then we can follow @laconbass' answer to fix the problem.

    I found a very easy way to spot which command cause the problem rather than adding event listeners everywhere in your code as suggested in @laconbass' answer. The key idea is to wrap the original spawn call with a wrapper which prints the arguments send to the spawn call.

    Here is the wrapper function, put it at the top of the index.js or whatever your server's starting script.

    (function() {
        var childProcess = require("child_process");
        var oldSpawn = childProcess.spawn;
        function mySpawn() {
            console.log('spawn called');
            console.log(arguments);
            var result = oldSpawn.apply(this, arguments);
            return result;
        }
        childProcess.spawn = mySpawn;
    })();
    

    Then the next time you run your application, before the uncaught exception's message you will see something like that:

    spawn called
    { '0': 'hg',
      '1': [],
      '2':
       { cwd: '/* omitted */',
         env: { IP: '0.0.0.0' },
         args: [] } }
    

    In this way you can easily know which command actually is executed and then you can find out why nodejs cannot find the executable to fix the problem.

    The ternary (conditional) operator in C

    • Some of the more obscure operators in C exist solely because they allow implementation of various function-like macros as a single expression that returns a result. I would say that this is the main purpose why the ?: and , operators are allowed to exist, even though their functionality is otherwise redundant.

      Lets say we wish to implement a function-like macro that returns the largest of two parameters. It would then be called as for example:

      int x = LARGEST(1,2);
      

      The only way to implement this as a function-like macro would be

      #define LARGEST(x,y) ((x) > (y) ? (x) : (y))
      

      It wouldn't be possible with an if ... else statement, since it does not return a result value. Note)

    • The other purpose of ?: is that it in some cases actually increases readability. Most often if...else is more readable, but not always. Take for example long, repetitive switch statements:

      switch(something)
      {
        case A: 
          if(x == A)
          {
            array[i] = x;
          }
          else
          {
            array[i] = y;
          }
          break;
      
        case B: 
          if(x == B)
          {
            array[i] = x;
          }
          else
          {
            array[i] = y;
          }
          break;
        ...
      }
      

      This can be replaced with the far more readable

      switch(something)
      {
        case A: array[i] = (x == A) ? x : y; break;
        case B: array[i] = (x == B) ? x : y; break;
        ...
      }
      
    • Please note that ?: does never result in faster code than if-else. That's some strange myth created by confused beginners. In case of optimized code, ?: gives identical performance as if-else in the vast majority of the cases.

      If anything, ?: can be slower than if-else, because it comes with mandatory implicit type promotions, even of the operand which is not going to be used. But ?: can never be faster than if-else.


    Note) Now of course someone will argue and wonder why not use a function. Indeed if you can use a function, it is always preferable over a function-like macro. But sometimes you can't use functions. Suppose for example that x in the example above is declared at file scope. The initializer must then be a constant expression, so it cannot contain a function call. Other practical examples of where you have to use function-like macros involve type safe programming with _Generic or "X macros".

    jquery $(window).width() and $(window).height() return different values when viewport has not been resized

    Note that if the problem is being caused by appearing scrollbars, putting

    body {
      overflow: hidden;
    }
    

    in your CSS might be an easy fix (if you don't need the page to scroll).

    Default behavior of "git push" without a branch specified

    git push origin will push all changes on the local branches that have matching remote branches at origin As for git push

    Works like git push <remote>, where <remote> is the current branch's remote (or origin, if no remote is configured for the current branch).

    From the Examples section of the git-push man page

    PreparedStatement setNull(..)

    You could also consider using preparedStatement.setObject(index,value,type);

    "This SqlTransaction has completed; it is no longer usable."... configuration error?

    Also check for any long running processes executed from your .NET app against the DB. For example you may be calling a stored procedure or query which does not have enough time to finish which can show in your logs as:

    • Execution Timeout Expired. The timeout period elapsed prior to completion of the operation or the server is not responding.

      • This SqlTransaction has completed; it is no longer usable.

    Check the command timeout settings Try to run a trace (profiler) and see what is happening on the DB side...

    Using Notepad++ to validate XML against an XSD

    1. In Notepad++ go to Plugins > Plugin manager > Show Plugin Manager then find Xml Tools plugin. Tick the box and click Install

      enter image description here

    2. Open XML document you want to validate and click Ctrl+Shift+Alt+M (Or use Menu if this is your preference Plugins > XML Tools > Validate Now).
      Following dialog will open: enter image description here

    3. Click on .... Point to XSD file and I am pretty sure you'll be able to handle things from here.

    Hope this saves you some time.

    EDIT: Plugin manager was not included in some versions of Notepad++ because many users didn't like commercials that it used to show. If you want to keep an older version, however still want plugin manager, you can get it on github, and install it by extracting the archive and copying contents to plugins and updates folder.
    In version 7.7.1 plugin manager is back under a different guise... Plugin Admin so now you can simply update notepad++ and have it back.

    enter image description here

    How to display UTF-8 characters in phpMyAdmin?

    If you're using PDO don't forget to initiate it with UTF8:

     $con = new PDO('mysql:host=' . $server . ';dbname=' . $db . ';charset=UTF8', $user, $pass,  array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
    

    (just spent 5 hours to figure this out, hope it will save someone precious time...)

    Get the first N elements of an array?

    array_slice() is best thing to try, following are the examples:

    <?php
    $input = array("a", "b", "c", "d", "e");
    
    $output = array_slice($input, 2);      // returns "c", "d", and "e"
    $output = array_slice($input, -2, 1);  // returns "d"
    $output = array_slice($input, 0, 3);   // returns "a", "b", and "c"
    
    // note the differences in the array keys
    print_r(array_slice($input, 2, -1));
    print_r(array_slice($input, 2, -1, true));
    ?>
    

    mingw-w64 threads: posix vs win32

    GCC comes with a compiler runtime library (libgcc) which it uses for (among other things) providing a low-level OS abstraction for multithreading related functionality in the languages it supports. The most relevant example is libstdc++'s C++11 <thread>, <mutex>, and <future>, which do not have a complete implementation when GCC is built with its internal Win32 threading model. MinGW-w64 provides a winpthreads (a pthreads implementation on top of the Win32 multithreading API) which GCC can then link in to enable all the fancy features.

    I must stress this option does not forbid you to write any code you want (it has absolutely NO influence on what API you can call in your code). It only reflects what GCC's runtime libraries (libgcc/libstdc++/...) use for their functionality. The caveat quoted by @James has nothing to do with GCC's internal threading model, but rather with Microsoft's CRT implementation.

    To summarize:

    • posix: enable C++11/C11 multithreading features. Makes libgcc depend on libwinpthreads, so that even if you don't directly call pthreads API, you'll be distributing the winpthreads DLL. There's nothing wrong with distributing one more DLL with your application.
    • win32: No C++11 multithreading features.

    Neither have influence on any user code calling Win32 APIs or pthreads APIs. You can always use both.

    Simple 3x3 matrix inverse code (C++)

    Why don't you try to code it yourself? Take it as a challenge. :)

    For a 3×3 matrix

    alt text
    (source: wolfram.com)

    the matrix inverse is

    alt text
    (source: wolfram.com)

    I'm assuming you know what the determinant of a matrix |A| is.

    Images (c) Wolfram|Alpha and mathworld.wolfram (06-11-09, 22.06)

    How to change the timeout on a .NET WebClient object

    As Sohnee says, using System.Net.HttpWebRequest and set the Timeout property instead of using System.Net.WebClient.

    You can't however set an infinite timeout value (it's not supported and attempting to do so will throw an ArgumentOutOfRangeException).

    I'd recommend first performing a HEAD HTTP request and examining the Content-Length header value returned to determine the number of bytes in the file you're downloading and then setting the timeout value accordingly for subsequent GET request or simply specifying a very long timeout value that you would never expect to exceed.

    How do I remove a file from the FileList

    If you want to delete only several of the selected files: you can't. The File API Working Draft you linked to contains a note:

    The HTMLInputElement interface [HTML5] has a readonly FileList attribute, […]
    [emphasis mine]

    Reading a bit of the HTML 5 Working Draft, I came across the Common input element APIs. It appears you can delete the entire file list by setting the value property of the input object to an empty string, like:

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

    BTW, the article Using files from web applications might also be of interest.

    Using tr to replace newline with space

    Best guess is you are on windows and your line ending settings are set for windows. See this topic: How to change line-ending settings

    or use:

    tr '\r\n' ' '
    

    clear form values after submission ajax

    it works: call this function after ajax success and send your form id as it's paramete. something like this:

    This function clear all input fields value including button, submit, reset, hidden fields

    function resetForm(formid) {
     $('#' + formid + ' :input').each(function(){  
      $(this).val('').attr('checked',false).attr('selected',false);
     });
    }
    

    * This function clears all input fields value except button, submit, reset, hidden fields * */

     function resetForm(formid) {
       $(':input','#'+formid) .not(':button, :submit, :reset, :hidden') .val('')
      .removeAttr('checked') .removeAttr('selected');
      }
    

    example:

    <script>
       (function($){
           function processForm( e ){
               $.ajax({
                   url: 'insert.php',
                   dataType: 'text',
                   type: 'post',
                   contentType: 'application/x-www-form-urlencoded',
                   data: $(this).serialize(),
                   success: function( data, textStatus, jQxhr ){
                    $('#alertt').fadeIn(2000);
                    $('#alertt').html( data );
                    $('#alertt').fadeOut(3000);
                   resetForm('userInf');
                },
                error: function( jqXhr, textStatus, errorThrown ){
                    console.log( errorThrown );
                }
            });
    
            e.preventDefault();
        }
    
        $('#userInf').submit( processForm );
    })(jQuery);
    
     function resetForm(formid) {
    $(':input','#'+formid) .not(':button, :submit, :reset, :hidden') .val('')
      .removeAttr('checked') .removeAttr('selected');
     }
      </script>
    

    How to remove Left property when position: absolute?

    left:auto;
    

    This will default the left back to the browser default.


    So if you have your Markup/CSS as:

    <div class="myClass"></div>
    
    .myClass
    {
      position:absolute;
      left:0;
    }
    

    When setting RTL, you could change to:

    <div class="myClass rtl"></div>
    
    .myClass
    {
      position:absolute;
      left:0;
    }
    .myClass.rtl
    {
      left:auto;
      right:0;
    }
    

    How Do I Take a Screen Shot of a UIView?

    I created this extension for save a screen shot from UIView

    extension UIView {
    func saveImageFromView(path path:String) {
        UIGraphicsBeginImageContextWithOptions(bounds.size, false, UIScreen.mainScreen().scale)
        drawViewHierarchyInRect(bounds, afterScreenUpdates: true)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        UIImageJPEGRepresentation(image, 0.4)?.writeToFile(path, atomically: true)
    
    }}
    

    call:

    let pathDocuments = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).first!
    let pathImage = "\(pathDocuments)/\(user!.usuarioID.integerValue).jpg"
    reportView.saveImageFromView(path: pathImage)
    

    If you want to create a png must change:

    UIImageJPEGRepresentation(image, 0.4)?.writeToFile(path, atomically: true)
    

    by

    UIImagePNGRepresentation(image)?.writeToFile(path, atomically: true)
    

    How to filter specific apps for ACTION_SEND intent (and set a different text for each app)

    Thanks to @dacoinminster. I make some modifications to his answer including package names of the popular apps and sorting of those apps.

    List<Intent> targetShareIntents = new ArrayList<Intent>();
    Intent shareIntent = new Intent();
    shareIntent.setAction(Intent.ACTION_SEND);
    shareIntent.setType("text/plain");
    PackageManager pm = getActivity().getPackageManager();
    List<ResolveInfo> resInfos = pm.queryIntentActivities(shareIntent, 0);
    if (!resInfos.isEmpty()) {
        System.out.println("Have package");
        for (ResolveInfo resInfo : resInfos) {
            String packageName = resInfo.activityInfo.packageName;
            Log.i("Package Name", packageName);
    
            if (packageName.contains("com.twitter.android") || packageName.contains("com.facebook.katana")
                    || packageName.contains("com.whatsapp") || packageName.contains("com.google.android.apps.plus")
                    || packageName.contains("com.google.android.talk") || packageName.contains("com.slack")
                    || packageName.contains("com.google.android.gm") || packageName.contains("com.facebook.orca")
                    || packageName.contains("com.yahoo.mobile") || packageName.contains("com.skype.raider")
                    || packageName.contains("com.android.mms")|| packageName.contains("com.linkedin.android")
                    || packageName.contains("com.google.android.apps.messaging")) {
                Intent intent = new Intent();
    
                intent.setComponent(new ComponentName(packageName, resInfo.activityInfo.name));
                intent.putExtra("AppName", resInfo.loadLabel(pm).toString());
                intent.setAction(Intent.ACTION_SEND);
                intent.setType("text/plain");
                intent.putExtra(Intent.EXTRA_TEXT, "https://website.com/");
                intent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.share_text));
                intent.setPackage(packageName);
                targetShareIntents.add(intent);
            }
        }
        if (!targetShareIntents.isEmpty()) {
            Collections.sort(targetShareIntents, new Comparator<Intent>() {
                @Override
                public int compare(Intent o1, Intent o2) {
                    return o1.getStringExtra("AppName").compareTo(o2.getStringExtra("AppName"));
                }
            });
            Intent chooserIntent = Intent.createChooser(targetShareIntents.remove(0), "Select app to share");
            chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, targetShareIntents.toArray(new Parcelable[]{}));
            startActivity(chooserIntent);
        } else {
            Toast.makeText(getActivity(), "No app to share.", Toast.LENGTH_LONG).show();
        }
    }
    

    How to convert all tables in database to one collation?

    Taking the answer from @Petr Stastny a step further by adding a password variable. I'd prefer if it actually took it in like a regular password rather than as an argument, but it's working for what I needed.

    #!/bin/bash
    
    # mycollate.sh <database> <password> [<charset> <collation>]
    # changes MySQL/MariaDB charset and collation for one database - all tables and
    # all columns in all tables
    
    DB="$1"
    PW="$2"
    CHARSET="$3"
    COLL="$4"
    
    [ -n "$DB" ] || exit 1
    [ -n "$PW" ]
    [ -n "$CHARSET" ] || CHARSET="utf8mb4"
    [ -n "$COLL" ] || COLL="utf8mb4_bin"
    
    PW="--password=""$PW"
    
    echo $DB
    echo "ALTER DATABASE $DB CHARACTER SET $CHARSET COLLATE $COLL;" | mysql -u root "$PW"
    
    echo "USE $DB; SHOW TABLES;" | mysql -s "$PW" | (
        while read TABLE; do
            echo $DB.$TABLE
            echo "ALTER TABLE $TABLE CONVERT TO CHARACTER SET $CHARSET COLLATE $COLL;" | mysql "$PW" $DB
        done
    )
    
    PW="pleaseEmptyMeNow"
    

    php: loop through json array

    Set the second function parameter to true if you require an associative array

    Some versions of php require a 2nd paramter of true if you require an associative array

    $json  = '[{"var1":"9","var2":"16","var3":"16"},{"var1":"8","var2":"15","var3":"15"}]';
    $array = json_decode( $json, true );
    

    How to see indexes for a database or table in MySQL?

    You could use this query to get the no of indexes as well as the index names of each table in specified database.

    SELECT TABLE_NAME,
           COUNT(1) index_count,
           GROUP_CONCAT(DISTINCT(index_name) SEPARATOR ',\n ') indexes
    FROM INFORMATION_SCHEMA.STATISTICS
    WHERE TABLE_SCHEMA = 'mydb'
          AND INDEX_NAME != 'primary'
    GROUP BY TABLE_NAME
    ORDER BY COUNT(1) DESC;
    

    How to import the class within the same directory or sub directory?

    In your main.py:

    from user import Class
    

    where Class is the name of the class you want to import.

    If you want to call a method of Class, you can call it using:

    Class.method

    Note that there should be an empty __init__.py file in the same directory.

    How to add column if not exists on PostgreSQL?

    You can do it by following way.

    ALTER TABLE tableName drop column if exists columnName; 
    ALTER TABLE tableName ADD COLUMN columnName character varying(8);
    

    So it will drop the column if it is already exists. And then add the column to particular table.

    ADB - Android - Getting the name of the current activity

    You can use this command,

    adb shell dumpsys activity
    

    You can find current activity name in activity stack.

    Output :-

     Sticky broadcasts:
     * Sticky action android.intent.action.BATTERY_CHANGED:
       Intent: act=android.intent.action.BATTERY_CHANGED flg=0x60000000
         Bundle[{icon-small=17302169, present=true, scale=100, level=50, technology=Li-ion, status=2, voltage=0, plugged=1, health=2, temperature=0}]
     * Sticky action android.net.thrott.THROTTLE_ACTION:
       Intent: act=android.net.thrott.THROTTLE_ACTION
         Bundle[{level=-1}]
     * Sticky action android.intent.action.NETWORK_SET_TIMEZONE:
       Intent: act=android.intent.action.NETWORK_SET_TIMEZONE flg=0x20000000
         Bundle[mParcelledData.dataSize=68]
     * Sticky action android.provider.Telephony.SPN_STRINGS_UPDATED:
       Intent: act=android.provider.Telephony.SPN_STRINGS_UPDATED flg=0x20000000
         Bundle[mParcelledData.dataSize=156]
     * Sticky action android.net.thrott.POLL_ACTION:
       Intent: act=android.net.thrott.POLL_ACTION
         Bundle[{cycleRead=0, cycleStart=1349893800000, cycleEnd=1352572200000, cycleWrite=0}]
     * Sticky action android.intent.action.SIM_STATE_CHANGED:
       Intent: act=android.intent.action.SIM_STATE_CHANGED flg=0x20000000
         Bundle[mParcelledData.dataSize=116]
     * Sticky action android.intent.action.SIG_STR:
       Intent: act=android.intent.action.SIG_STR flg=0x20000000
         Bundle[{EvdoSnr=-1, CdmaDbm=-1, GsmBitErrorRate=-1, CdmaEcio=-1, EvdoDbm=-1, GsmSignalStrength=7, EvdoEcio=-1, isGsm=true}]
     * Sticky action android.intent.action.SERVICE_STATE:
       Intent: act=android.intent.action.SERVICE_STATE flg=0x20000000
         Bundle[{cdmaRoamingIndicator=0, operator-numeric=310260, networkId=0, state=0, emergencyOnly=false, operator-alpha-short=Android, radioTechnology=3, manual=false, cssIndicator=false, operator-alpha-long=Android, systemId=0, roaming=false, cdmaDefaultRoamingIndicator=0}]
     * Sticky action android.net.conn.CONNECTIVITY_CHANGE:
       Intent: act=android.net.conn.CONNECTIVITY_CHANGE flg=0x30000000
         Bundle[{networkInfo=NetworkInfo: type: mobile[UMTS], state: CONNECTED/CONNECTED, reason: simLoaded, extra: internet, roaming: false, failover: false, isAvailable: true, reason=simLoaded, extraInfo=internet}]
     * Sticky action android.intent.action.NETWORK_SET_TIME:
       Intent: act=android.intent.action.NETWORK_SET_TIME flg=0x20000000
         Bundle[mParcelledData.dataSize=36]
     * Sticky action android.media.RINGER_MODE_CHANGED:
       Intent: act=android.media.RINGER_MODE_CHANGED flg=0x70000000
         Bundle[{android.media.EXTRA_RINGER_MODE=2}]
     * Sticky action android.intent.action.ANY_DATA_STATE:
       Intent: act=android.intent.action.ANY_DATA_STATE flg=0x20000000
         Bundle[{state=CONNECTED, apnType=*, iface=/dev/omap_csmi_tty1, apn=internet, reason=simLoaded}]
    
     Activity stack:
     * TaskRecord{450adb90 #22 A org.chanakyastocktipps.com}
       clearOnBackground=false numActivities=2 rootWasReset=false
       affinity=org.chanakyastocktipps.com
       intent={act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10000000 cmp=org.chanakyastocktipps.com/.ui.SplashScreen}
       realActivity=org.chanakyastocktipps.com/.ui.SplashScreen
       lastActiveTime=15107753 (inactive for 4879s)
       * Hist #2: HistoryRecord{450d7ab0 org.chanakyastocktipps.com/.ui.Profile}
           packageName=org.chanakyastocktipps.com processName=org.chanakyastocktipps.com
           launchedFromUid=10046 app=ProcessRecord{44fa3450 1065:org.chanakyastocktipps.com/10046}
           Intent { cmp=org.chanakyastocktipps.com/.ui.Profile }
           frontOfTask=false task=TaskRecord{450adb90 #22 A org.chanakyastocktipps.com}
           taskAffinity=org.chanakyastocktipps.com
           realActivity=org.chanakyastocktipps.com/.ui.Profile
           base=/data/app/org.chanakyastocktipps.com-1.apk/data/app/org.chanakyastocktipps.com-1.apk data=/data/data/org.chanakyastocktipps.com
           labelRes=0x7f09000b icon=0x7f020065 theme=0x1030007
           stateNotNeeded=false componentSpecified=true isHomeActivity=false
           configuration={ scale=1.0 imsi=310/260 loc=en_US touch=3 keys=2/1/2 nav=3/1 orien=1 layout=18 uiMode=17 seq=3}
           resultTo=HistoryRecord{44f523c0 org.chanakyastocktipps.com/.ui.MainScreen} resultWho=null resultCode=4
           launchFailed=false haveState=false icicle=null
           state=RESUMED stopped=false delayedResume=false finishing=false
           keysPaused=false inHistory=true persistent=false launchMode=0
           fullscreen=true visible=true frozenBeforeDestroy=false thumbnailNeeded=false idle=true
           waitingVisible=false nowVisible=true
       * Hist #1: HistoryRecord{44f523c0 org.chanakyastocktipps.com/.ui.MainScreen}
           packageName=org.chanakyastocktipps.com processName=org.chanakyastocktipps.com
           launchedFromUid=10046 app=ProcessRecord{44fa3450 1065:org.chanakyastocktipps.com/10046}
           Intent { cmp=org.chanakyastocktipps.com/.ui.MainScreen }
           frontOfTask=true task=TaskRecord{450adb90 #22 A org.chanakyastocktipps.com}
           taskAffinity=org.chanakyastocktipps.com
           realActivity=org.chanakyastocktipps.com/.ui.MainScreen
           base=/data/app/org.chanakyastocktipps.com-1.apk/data/app/org.chanakyastocktipps.com-1.apk data=/data/data/org.chanakyastocktipps.com
           labelRes=0x7f09000b icon=0x7f020065 theme=0x1030007
           stateNotNeeded=false componentSpecified=true isHomeActivity=false
           configuration={ scale=1.0 imsi=310/260 loc=en_US touch=3 keys=2/1/2 nav=3/1 orien=1 layout=18 uiMode=17 seq=3}
           launchFailed=false haveState=true icicle=Bundle[mParcelledData.dataSize=1344]
           state=STOPPED stopped=true delayedResume=false finishing=false
           keysPaused=false inHistory=true persistent=false launchMode=0
           fullscreen=true visible=false frozenBeforeDestroy=false thumbnailNeeded=false idle=true
     * TaskRecord{450615a0 #2 A com.android.launcher}
       clearOnBackground=true numActivities=1 rootWasReset=false
       affinity=com.android.launcher
       intent={act=android.intent.action.MAIN cat=[android.intent.category.HOME] flg=0x10000000 cmp=com.android.launcher/com.android.launcher2.Launcher}
       realActivity=com.android.launcher/com.android.launcher2.Launcher
       lastActiveTime=12263090 (inactive for 7724s)
       * Hist #0: HistoryRecord{4505d838 com.android.launcher/com.android.launcher2.Launcher}
           packageName=com.android.launcher processName=com.android.launcher
           launchedFromUid=0 app=ProcessRecord{45062558 129:com.android.launcher/10025}
           Intent { act=android.intent.action.MAIN cat=[android.intent.category.HOME] flg=0x10000000 cmp=com.android.launcher/com.android.launcher2.Launcher }
           frontOfTask=true task=TaskRecord{450615a0 #2 A com.android.launcher}
           taskAffinity=com.android.launcher
           realActivity=com.android.launcher/com.android.launcher2.Launcher
           base=/system/app/Launcher2.apk/system/app/Launcher2.apk data=/data/data/com.android.launcher
           labelRes=0x7f0c0002 icon=0x7f020044 theme=0x7f0d0000
           stateNotNeeded=true componentSpecified=false isHomeActivity=true
           configuration={ scale=1.0 imsi=310/260 loc=en_US touch=3 keys=2/1/2 nav=3/1 orien=1 layout=18 uiMode=17 seq=3}
           launchFailed=false haveState=true icicle=Bundle[mParcelledData.dataSize=3608]
           state=STOPPED stopped=true delayedResume=false finishing=false
           keysPaused=false inHistory=true persistent=false launchMode=2
           fullscreen=true visible=false frozenBeforeDestroy=false thumbnailNeeded=false idle=true
    
     Running activities (most recent first):
       TaskRecord{450adb90 #22 A org.chanakyastocktipps.com}
         Run #2: HistoryRecord{450d7ab0 org.chanakyastocktipps.com/.ui.Profile}
         Run #1: HistoryRecord{44f523c0 org.chanakyastocktipps.com/.ui.MainScreen}
       TaskRecord{450615a0 #2 A com.android.launcher}
         Run #0: HistoryRecord{4505d838 com.android.launcher/com.android.launcher2.Launcher}
    
     mPausingActivity: null
     mResumedActivity: HistoryRecord{450d7ab0 org.chanakyastocktipps.com/.ui.Profile}
     mFocusedActivity: HistoryRecord{450d7ab0 org.chanakyastocktipps.com/.ui.Profile}
     mLastPausedActivity: HistoryRecord{44f523c0 org.chanakyastocktipps.com/.ui.MainScreen}
    
     mCurTask: 22
    
     Running processes (most recent first):
       App  #13: adj=vis  /F 45052120 119:com.android.inputmethod.latin/10003 (service)
                 com.android.inputmethod.latin.LatinIME<=ProcessRecord{44ec2698 59:system/1000}
       PERS #12: adj=sys  /F 44ec2698 59:system/1000 (fixed)
       App  #11: adj=fore /F 44fa3450 1065:org.chanakyastocktipps.com/10046 (top-activity)
       App  #10: adj=bak  /B 44e7c4c0 299:com.svox.pico/10028 (bg-empty)
       App  # 9: adj=bak+1/B 450f7ef0 288:com.dreamreminder.org:feather_system_receiver/10057 (bg-empty)
       App  # 8: adj=bak+2/B 4503cc38 201:com.android.defcontainer/10010 (bg-empty)
       App  # 7: adj=home /B 45062558 129:com.android.launcher/10025 (home)
       App  # 6: adj=bak+3/B 450244d8 276:android.process.media/10002 (bg-empty)
       App  # 5: adj=bak+4/B 44f2b9b8 263:com.android.quicksearchbox/10012 (bg-empty)
       App  # 4: adj=bak+5/B 450beec0 257:com.android.protips/10007 (bg-empty)
       App  # 3: adj=bak+6/B 44ff37b8 270:com.android.music/10022 (bg-empty)
       PERS # 2: adj=core /F 45056818 124:com.android.phone/1001 (fixed)
       App  # 1: adj=bak+7/B 45080c38 238:com.dreamreminder.org/10057 (bg-empty)
       App  # 0: adj=empty/B 4507d030 229:com.android.email/10030 (bg-empty)
    
     PID mappings:
       PID #59: ProcessRecord{44ec2698 59:system/1000}
       PID #119: ProcessRecord{45052120 119:com.android.inputmethod.latin/10003}
       PID #124: ProcessRecord{45056818 124:com.android.phone/1001}
       PID #129: ProcessRecord{45062558 129:com.android.launcher/10025}
       PID #201: ProcessRecord{4503cc38 201:com.android.defcontainer/10010}
       PID #229: ProcessRecord{4507d030 229:com.android.email/10030}
       PID #238: ProcessRecord{45080c38 238:com.dreamreminder.org/10057}
       PID #257: ProcessRecord{450beec0 257:com.android.protips/10007}
       PID #263: ProcessRecord{44f2b9b8 263:com.android.quicksearchbox/10012}
       PID #270: ProcessRecord{44ff37b8 270:com.android.music/10022}
       PID #276: ProcessRecord{450244d8 276:android.process.media/10002}
       PID #288: ProcessRecord{450f7ef0 288:com.dreamreminder.org:feather_system_receiver/10057}
       PID #299: ProcessRecord{44e7c4c0 299:com.svox.pico/10028}
       PID #1065: ProcessRecord{44fa3450 1065:org.chanakyastocktipps.com/10046}
    
     mHomeProcess: ProcessRecord{45062558 129:com.android.launcher/10025}
     mConfiguration: { scale=1.0 imsi=310/260 loc=en_US touch=3 keys=2/1/2 nav=3/1 orien=1 layout=18 uiMode=17 seq=3}
     mConfigWillChange: false
     mSleeping=false mShuttingDown=false
    

    Determine if Android app is being used for the first time

    I suggest to not only store a boolean flag, but the complete version code. This way you can also query at the beginning if it is the first start in a new version. You can use this information to display a "Whats new" dialog, for example.

    The following code should work from any android class that "is a context" (activities, services, ...). If you prefer to have it in a separate (POJO) class, you could consider using a "static context", as described here for example.

    /**
     * Distinguishes different kinds of app starts: <li>
     * <ul>
     * First start ever ({@link #FIRST_TIME})
     * </ul>
     * <ul>
     * First start in this version ({@link #FIRST_TIME_VERSION})
     * </ul>
     * <ul>
     * Normal app start ({@link #NORMAL})
     * </ul>
     * 
     * @author schnatterer
     * 
     */
    public enum AppStart {
        FIRST_TIME, FIRST_TIME_VERSION, NORMAL;
    }
    
    /**
     * The app version code (not the version name!) that was used on the last
     * start of the app.
     */
    private static final String LAST_APP_VERSION = "last_app_version";
    
    /**
     * Finds out started for the first time (ever or in the current version).<br/>
     * <br/>
     * Note: This method is <b>not idempotent</b> only the first call will
     * determine the proper result. Any subsequent calls will only return
     * {@link AppStart#NORMAL} until the app is started again. So you might want
     * to consider caching the result!
     * 
     * @return the type of app start
     */
    public AppStart checkAppStart() {
        PackageInfo pInfo;
        SharedPreferences sharedPreferences = PreferenceManager
                .getDefaultSharedPreferences(this);
        AppStart appStart = AppStart.NORMAL;
        try {
            pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
            int lastVersionCode = sharedPreferences
                    .getInt(LAST_APP_VERSION, -1);
            int currentVersionCode = pInfo.versionCode;
            appStart = checkAppStart(currentVersionCode, lastVersionCode);
            // Update version in preferences
            sharedPreferences.edit()
                    .putInt(LAST_APP_VERSION, currentVersionCode).commit();
        } catch (NameNotFoundException e) {
            Log.w(Constants.LOG,
                    "Unable to determine current app version from pacakge manager. Defenisvely assuming normal app start.");
        }
        return appStart;
    }
    
    public AppStart checkAppStart(int currentVersionCode, int lastVersionCode) {
        if (lastVersionCode == -1) {
            return AppStart.FIRST_TIME;
        } else if (lastVersionCode < currentVersionCode) {
            return AppStart.FIRST_TIME_VERSION;
        } else if (lastVersionCode > currentVersionCode) {
            Log.w(Constants.LOG, "Current version code (" + currentVersionCode
                    + ") is less then the one recognized on last startup ("
                    + lastVersionCode
                    + "). Defenisvely assuming normal app start.");
            return AppStart.NORMAL;
        } else {
            return AppStart.NORMAL;
        }
    }
    

    It could be used from an activity like this:

    public class MainActivity extends Activity {        
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            switch (checkAppStart()) {
            case NORMAL:
                // We don't want to get on the user's nerves
                break;
            case FIRST_TIME_VERSION:
                // TODO show what's new
                break;
            case FIRST_TIME:
                // TODO show a tutorial
                break;
            default:
                break;
            }
    
            // ...
        }
        // ...
    }
    

    The basic logic can be verified using this JUnit test:

    public void testCheckAppStart() {
        // First start
        int oldVersion = -1;
        int newVersion = 1;
        assertEquals("Unexpected result", AppStart.FIRST_TIME,
                service.checkAppStart(newVersion, oldVersion));
    
        // First start this version
        oldVersion = 1;
        newVersion = 2;
        assertEquals("Unexpected result", AppStart.FIRST_TIME_VERSION,
                service.checkAppStart(newVersion, oldVersion));
    
        // Normal start
        oldVersion = 2;
        newVersion = 2;
        assertEquals("Unexpected result", AppStart.NORMAL,
                service.checkAppStart(newVersion, oldVersion));
    }
    

    With a bit more effort you could probably test the android related stuff (PackageManager and SharedPreferences) as well. Anyone interested in writing the test? :)

    Note that the above code will only work properly if you don't mess around with your android:versionCode in AndroidManifest.xml!

    Is it safe to store a JWT in localStorage with ReactJS?

    It is not safe if you use CDN's:

    Malicious JavaScript can be embedded on the page, and Web Storage is compromised. These types of XSS attacks can get everyone’s Web Storage that visits your site, without their knowledge. This is probably why a bunch of organizations advise not to store anything of value or trust any information in web storage. This includes session identifiers and tokens.

    via stormpath

    Any script you require from the outside could potentially be compromised and could grab any JWTS from your client's storage and send personal data back to the attacker's server.

    What is the newline character in the C language: \r or \n?

    What is the newline character in the C language: \r or \n?

    The new-line may be thought of a some char and it has the value of '\n'. C11 5.2.1

    This C new-line comes up in 3 places: C source code, as a single char and as an end-of-line in file I/O when in text mode.

    1. Many compilers will treat source text as ASCII. In that case, codes 10, sometimes 13, and sometimes paired 13,10 as new-line for source code. Had the source code been in another character set, different codes may be used. This new-line typically marks the end of a line of source code (actually a bit more complicated here), // comment, and # directives.

    2. In source code, the 2 characters \ and n represent the char new-line as \n. If ASCII is used, this char would have the value of 10.

    3. In file I/O, in text mode, upon reading the bytes of the input file (and stdin), depending on the environment, when bytes with the value(s) of 10 (Unix), 13,10, (*1) (Windows), 13 (Old Mac??) and other variations are translated in to a '\n'. Upon writing a file (or stdout), the reverse translation occurs.
      Note: File I/O in binary mode makes no translation.

    The '\r' in source code is the carriage return char.

    (*1) A lone 13 and/or 10 may also translate into \n.

    Deep copy in ES6 using the spread syntax

    const a = {
      foods: {
        dinner: 'Pasta'
      }
    }
    let b = JSON.parse(JSON.stringify(a))
    b.foods.dinner = 'Soup'
    console.log(b.foods.dinner) // Soup
    console.log(a.foods.dinner) // Pasta
    

    Using JSON.stringify and JSON.parse is the best way. Because by using the spread operator we will not get the efficient answer when the json object contains another object inside it. we need to manually specify that.

    Processing $http response in service

    When binding the UI to your array you'll want to make sure you update that same array directly by setting the length to 0 and pushing the data into the array.

    Instead of this (which set a different array reference to data which your UI won't know about):

     myService.async = function() {
        $http.get('test.json')
        .success(function (d) {
          data = d;
        });
      };
    

    try this:

     myService.async = function() {
        $http.get('test.json')
        .success(function (d) {
          data.length = 0;
          for(var i = 0; i < d.length; i++){
            data.push(d[i]);
          }
        });
      };
    

    Here is a fiddle that shows the difference between setting a new array vs emptying and adding to an existing one. I couldn't get your plnkr working but hopefully this works for you!

    Tomcat 7 is not running on browser(http://localhost:8080/ )

    There could be a number of reasons, have it as a checklist and go through it

    Is your server running on 8080?I mean that is the default port but it could be configured to run on other.

    Also there is a possibility that the default application is removed/uninstalled that is why it is giving "the requested resource is not available"

    Also it could be a proxy issue. make sure you are not using any proxy in your browser.

    Rounding Bigdecimal values with 2 Decimal Places

    I think that the RoundingMode you are looking for is ROUND_HALF_EVEN. From the javadoc:

    Rounding mode to round towards the "nearest neighbor" unless both neighbors are equidistant, in which case, round towards the even neighbor. Behaves as for ROUND_HALF_UP if the digit to the left of the discarded fraction is odd; behaves as for ROUND_HALF_DOWN if it's even. Note that this is the rounding mode that minimizes cumulative error when applied repeatedly over a sequence of calculations.

    Here is a quick test case:

    BigDecimal a = new BigDecimal("10.12345");
    BigDecimal b = new BigDecimal("10.12556");
    
    a = a.setScale(2, BigDecimal.ROUND_HALF_EVEN);
    b = b.setScale(2, BigDecimal.ROUND_HALF_EVEN);
    
    System.out.println(a);
    System.out.println(b);
    

    Correctly prints:

    10.12
    10.13
    

    UPDATE:

    setScale(int, int) has not been recommended since Java 1.5, when enums were first introduced, and was finally deprecated in Java 9. You should now use setScale(int, RoundingMode) e.g:

    setScale(2, RoundingMode.HALF_EVEN)

    How to ensure that there is a delay before a service is started in systemd?

    This answer on super user I think is a better answer. From https://superuser.com/a/573761/67952

    "But since you asked for a way without using Before and After, you can use:

    Type=idle
    

    which as man systemd.service explains

    Behavior of idle is very similar to simple; however, actual execution of the service program is delayed until all active jobs are dispatched. This may be used to avoid interleaving of output of shell services with the status output on the console. Note that this type is useful only to improve console output, it is not useful as a general unit ordering tool, and the effect of this service type is subject to a 5s time-out, after which the service program is invoked anyway. "

    Need to install urllib2 for Python 3.5.1

    WARNING: Security researches have found several poisoned packages on PyPI, including a package named urllib, which will 'phone home' when installed. If you used pip install urllib some time after June 2017, remove that package as soon as possible.

    You can't, and you don't need to.

    urllib2 is the name of the library included in Python 2. You can use the urllib.request library included with Python 3, instead. The urllib.request library works the same way urllib2 works in Python 2. Because it is already included you don't need to install it.

    If you are following a tutorial that tells you to use urllib2 then you'll find you'll run into more issues. Your tutorial was written for Python 2, not Python 3. Find a different tutorial, or install Python 2.7 and continue your tutorial on that version. You'll find urllib2 comes with that version.

    Alternatively, install the requests library for a higher-level and easier to use API. It'll work on both Python 2 and 3.

    WAMP Server doesn't load localhost

    Solution(s) for this, found in the official wampserver.com forums:

    SOLUTION #1:

    This problem is caused by Windows (7) in combination with any software that also uses port 80 (like Skype or IIS (which is installed on most developer machines)). A video solution can be found here (34.500+ views, damn, this seems to be a big thing ! EDIT: The video now has ~60.000 views ;) )

    To make it short: open command line tool, type "netstat -aon" and look for any lines that end of ":80". Note thatPID on the right side. This is the process id of the software which currently usesport 80. Press AltGr + Ctrl + Del to get into the Taskmanager. Switch to the tab where you can see all services currently running, ordered by PID. Search for that PID you just notices and stop that thing (right click). To prevent this in future, you should config the software's port settings (skype can do that).

    SOLUTION #2:

    left click the wamp icon in the taskbar, go to apache > httpd.conf and edit this file: change "listen to port .... 80" to 8080. Restart. Done !

    SOLUTION #3:

    Port 80 blocked by "Microsoft Web Deployment Service", simply deinstall this, more info here

    By the way, it's not Microsoft's fault, it's a stupid usage of ports by most WAMP stacks.

    IMPORTANT: you have to use localhost or 127.0.0.1 now with port 8080, this means 127.0.0.1:8080 or localhost:8080.

    What is the best project structure for a Python application?

    In my experience, it's just a matter of iteration. Put your data and code wherever you think they go. Chances are, you'll be wrong anyway. But once you get a better idea of exactly how things are going to shape up, you're in a much better position to make these kinds of guesses.

    As far as extension sources, we have a Code directory under trunk that contains a directory for python and a directory for various other languages. Personally, I'm more inclined to try putting any extension code into its own repository next time around.

    With that said, I go back to my initial point: don't make too big a deal out of it. Put it somewhere that seems to work for you. If you find something that doesn't work, it can (and should) be changed.

    How to insert image in mysql database(table)?

    You can try something like this..

    CREATE TABLE 'sample'.'picture' ( 
    'idpicture' INTEGER UNSIGNED NOT NULL AUTO_INCREMENT, 
    'caption' VARCHAR(45) NOT NULL, 
    'img' LONGBLOB NOT NULL, 
     PRIMARY KEY('idpicture')) TYPE = InnoDB;
    

    or refer to the following links for tutorials and sample, that might help you.

    http://forums.mysql.com/read.php?20,17671,27914

    http://mrarrowhead.com/index.php?page=store_images_mysql_php.php

    http://www.hockinson.com/programmer-web-designer-denver-co-usa.php?s=47

    Adding a SVN repository in Eclipse

    I doubt that Subclipse and then SVN can use your Eclipse proxy settings. You'll probably need to set the proxy for your SVN program itself. Trying to check out the files using SVN from the command line should tell you if that works.

    If SVN can't connect either then put the proxy settings in your servers file in your Subversion settings folder (in your home folder).

    If it can't do it even with the proxy settings set, then your firewall is probably blocking the methods and protocols that Subversion needs to use to download the files.

    Can you display HTML5 <video> as a full screen background?

    Use position:fixed on the video, set it to 100% width/height, and put a negative z-index on it so it appears behind everything.

    If you look at VideoJS, the controls are just html elements sitting on top of the video, using z-index to make sure they're above.

    HTML

    <video id="video_background" src="video.mp4" autoplay>
    

    (Add webm and ogg sources to support more browsers)

    CSS

    #video_background {
      position: fixed;
      top: 0;
      left: 0;
      bottom: 0;
      right: 0;
      z-index: -1000;
    }
    

    It'll work in most HTML5 browsers, but probably not iPhone/iPad, where the video needs to be activated, and doesn't like elements over it.

    mysqld: Can't change dir to data. Server doesn't start

    What I did (Windows 10) for a new installation:

    1. Start cmd in admin mode (run as administrator by hitting windows key, typing cmd, right clicking on it and selecting "Run as Administrator"

    2. Change into "MySQL Server X.Y" directory (for me the full path is C:\Program Files\MySQL\MySQL Server 5.7")

    3. using notepad create a my.ini with a mysqld section that points at your data directory

      [mysqld]
      datadir="X:\Your Directory Path and Name"
      
    4. created the directory identified in my.ini above.

    5. change into bin Directory under server directory and execute: mysqld --initialize

    6. Once complete, started the service and it came up fine.

    Is there a splice method for strings?

    I solved my problem using this code, is a somewhat replacement for the missing splice.

    let str = "I need to remove a character from this";
    let pos = str.indexOf("character")
    
    if(pos>-1){
      let result = str.slice(0, pos-2) + str.slice(pos, str.length);
      console.log(result) //I need to remove character from this 
    }
    

    I needed to remove a character before/after a certain word, after you get the position the string is split in two and then recomposed by flexibly removing characters using an offset along pos

    Intellij reformat on file save

    Ctrl + Alt + L is format file (includes the two below)

    Ctrl + Alt + O is optimize imports

    Ctrl + Alt + I will fix indentation on a particular line

    I usually run Ctrl + Alt + L a few times before committing my work. I'd rather it do the cleanup/reformatting at my command instead of automatically.

    Batch / Find And Edit Lines in TXT file

    On a native Windows install, you can either use batch(cmd.exe) or vbscript without the need to get external tools. Here's an example in vbscript:

    Set objFS = CreateObject("Scripting.FileSystemObject")
    strFile = "c:\test\file.txt"
    Set objFile = objFS.OpenTextFile(strFile)
    Do Until objFile.AtEndOfStream
        strLine = objFile.ReadLine
        If InStr(strLine,"ex3")> 0 Then
            strLine = Replace(strLine,"ex3","ex5")
        End If 
        WScript.Echo strLine
    Loop    
    

    Save as myreplace.vbs and on the command line:

    c:\test> cscript /nologo myreplace.vbs  > newfile
    c:\test> ren newfile file.txt
    

    Set background image according to screen resolution

    I know it's too old question but thought to answer, it might will help someone. If you see twitter, you will find something very tricky but pure css approach to achieve this.

    <div class="background"><img src="home-bg.png" /></div>
    Applied CSS
    .background {
        background: none repeat scroll 0 0 #FFFFFF;
        height: 200%;
        left: -50%;
        position: fixed;
        width: 200%;}
    
    .background img{
        bottom: 0;
        display: block;
        left: 0;
        margin: auto;
        min-height: 50%;
        min-width: 50%;
        right: 0;
        top: 0;}
    

    This background images fits to all size. even portrait view of ipad. it always adjust the image in center. if you zoom out; image will remain the same.

    how to File.listFiles in alphabetical order?

    In Java 8:

    Arrays.sort(files, (a, b) -> a.getName().compareTo(b.getName()));
    

    Reverse order:

    Arrays.sort(files, (a, b) -> -a.getName().compareTo(b.getName()));
    

    Update div with jQuery ajax response html

    You are setting the html of #showresults of whatever data is, and then replacing it with itself, which doesn't make much sense ?
    I'm guessing you where really trying to find #showresults in the returned data, and then update the #showresults element in the DOM with the html from the one from the ajax call :

    $('#submitform').click(function () {
        $.ajax({
            url: "getinfo.asp",
            data: {
                txtsearch: $('#appendedInputButton').val()
            },
            type: "GET",
            dataType: "html",
            success: function (data) {
                var result = $('<div />').append(data).find('#showresults').html();
                $('#showresults').html(result);
            },
            error: function (xhr, status) {
                alert("Sorry, there was a problem!");
            },
            complete: function (xhr, status) {
                //$('#showresults').slideDown('slow')
            }
        });
    });
    

    Reverse Contents in Array

    The solution to this question is very easy: Vectors

    std::vector<int> vector;
    for(int i = 0; i < 10;i++)
    {
        vector.push_back(i);
    }
    std::reverse(vector.begin(), vector.end());
    

    Voila! You are done! =)

    Solution details:

    This is the most efficent solution: Swap can't swap 3 values but reverse definitely can. Remember to include algorithm. This is so simple that the compiled code is definitely not needed.

    I think this solves the OP's problem

    If you think there are any errors and problems with this solution please comment below

    What is .Net Framework 4 extended?

    Got this from Bing. Seems Microsoft has removed some features from the core framework and added it to a separate optional(?) framework component.

    To quote from MSDN (http://msdn.microsoft.com/en-us/library/cc656912.aspx)

    The .NET Framework 4 Client Profile does not include the following features. You must install the .NET Framework 4 to use these features in your application:

    * ASP.NET
    * Advanced Windows Communication Foundation (WCF) functionality
    * .NET Framework Data Provider for Oracle
    * MSBuild for compiling
    

    Error in spring application context schema

    use this:

    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd"
    

    Adding a custom header to HTTP request using angular.js

    Basic authentication using HTTP POST method:

    $http({
        method: 'POST',
        url: '/API/authenticate',
        data: 'username=' + username + '&password=' + password + '&email=' + email,
        headers: {
            "Content-Type": "application/x-www-form-urlencoded",
            "X-Login-Ajax-call": 'true'
        }
    }).then(function(response) {
        if (response.data == 'ok') {
            // success
        } else {
            // failed
        }
    });
    

    ...and GET method call with header:

    $http({
        method: 'GET',
        url: '/books',
        headers: {
            'Authorization': 'Basic d2VudHdvcnRobWFuOkNoYW5nZV9tZQ==',
            'Accept': 'application/json',
            "X-Login-Ajax-call": 'true'
        }
    }).then(function(response) {
        if (response.data == 'ok') {
            // success
        } else {
            // failed
        }
    });
    

    Correct way to use get_or_create?

    get_or_create returns a tuple.

    customer.source, created = Source.objects.get_or_create(name="Website")
    

    Percentage Height HTML 5/CSS

    Hi! In order to use percentage(%), you must define the % of it parent element. If you use body{height: 100%} it will not work because it parent have no percentage in height. In that case in order to work that body height you must add this in html{height:100%}

    In other case to get rid of that defining parent percentage you can use

    body{height:100vh}

    vh stands for viewport height

    I think it help

    Extract substring from a string

    substring():

    str.substring(startIndex, endIndex); 
    

    Multiple INNER JOIN SQL ACCESS

    Thanks HansUp for your answer, it is very helpful and it works!

    I found three patterns working in Access, yours is the best, because it works in all cases.

    • INNER JOIN, your variant. I will call it "closed set pattern". It is possible to join more than two tables to the same table with good performance only with this pattern.

      SELECT C_Name, cr.P_FirstName+" "+cr.P_SurName AS ClassRepresentativ, cr2.P_FirstName+" "+cr2.P_SurName AS ClassRepresentativ2nd
      FROM
           ((class
             INNER JOIN person AS cr 
             ON class.C_P_ClassRep=cr.P_Nr
           )
           INNER JOIN person AS cr2
           ON class.C_P_ClassRep2nd=cr2.P_Nr
        )
      

      ;

    • INNER JOIN "chained-set pattern"

      SELECT C_Name, cr.P_FirstName+" "+cr.P_SurName AS ClassRepresentativ, cr2.P_FirstName+" "+cr2.P_SurName AS ClassRepresentativ2nd
      FROM person AS cr
      INNER JOIN ( class 
         INNER JOIN ( person AS cr2
         ) ON class.C_P_ClassRep2nd=cr2.P_Nr
      ) ON class.C_P_ClassRep=cr.P_Nr
      ;
      
    • CROSS JOIN with WHERE

      SELECT C_Name, cr.P_FirstName+" "+cr.P_SurName AS ClassRepresentativ, cr2.P_FirstName+" "+cr2.P_SurName AS ClassRepresentativ2nd
      FROM class, person AS cr, person AS cr2
      WHERE class.C_P_ClassRep=cr.P_Nr AND class.C_P_ClassRep2nd=cr2.P_Nr
      ;
      

    Using ping in c#

    private async void Ping_Click(object sender, RoutedEventArgs e)
    {
        Ping pingSender = new Ping();
        string host = @"stackoverflow.com";
        await Task.Run(() =>{
             PingReply reply = pingSender.Send(host);
             if (reply.Status == IPStatus.Success)
             {
                Console.WriteLine("Address: {0}", reply.Address.ToString());
                Console.WriteLine("RoundTrip time: {0}", reply.RoundtripTime);
                Console.WriteLine("Time to live: {0}", reply.Options.Ttl);
                Console.WriteLine("Don't fragment: {0}", reply.Options.DontFragment);
                Console.WriteLine("Buffer size: {0}", reply.Buffer.Length);
             }
             else
             {
                Console.WriteLine("Address: {0}", reply.Status);
             }
       });           
    }
    

    How to use a variable for the database name in T-SQL?

    Unfortunately you can't declare database names with a variable in that format.

    For what you're trying to accomplish, you're going to need to wrap your statements within an EXEC() statement. So you'd have something like:

    DECLARE @Sql varchar(max) ='CREATE DATABASE ' + @DBNAME
    

    Then call

    EXECUTE(@Sql) or sp_executesql(@Sql)
    

    to execute the sql string.

    How to handle "Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first." on Desktop with Chrome 66?

    I had some issues playing on Android Phone. After few tries I found out that when Data Saver is on there is no auto play:

    There is no autoplay if Data Saver mode is enabled. If Data Saver mode is enabled, autoplay is disabled in Media settings.

    Source

    Simplest way to serve static data from outside the application server in a Java web application

    if anyone not able to resolve his problem with accepted answer, then note these below considerations:

    1. no need to mention localhost:<port> with <img> src attribute.
    2. make sure you are running this project outside eclipse, because eclipse creates context docBase entry on its own inside its local server.xml file.

    org.glassfish.jersey.servlet.ServletContainer ClassNotFoundException

    The jersey-container-servlet actually uses the jersey-container-servlet-core dependency. But if you use maven, that does not really matter. If you just define the jersey-container-servlet usage, it will automatically download the dependency as well.

    But for those who add jar files to their project manually (i.e. without maven) It is important to know that you actually need both jar files. The org.glassfish.jersey.servlet.ServletContainer class is actually part of the core dependency.

    Core dumped, but core file is not in the current directory?

    For fedora25, I could find core file at

    /var/spool/abrt/ccpp-2017-02-16-16:36:51-2974/coredump
    

    where ccpp-2017-02-16-16:36:51-2974" is pattern "%s %c %p %u %g %t %P % as per `/proc/sys/kernel/core_pattern'

    Storing JSON in database vs. having a new column for each key

    Basically, the first model you are using is called as document-based storage. You should have a look at popular NoSQL document-based database like MongoDB and CouchDB. Basically, in document based db's, you store data in json files and then you can query on these json files.

    The Second model is the popular relational database structure.

    If you want to use relational database like MySql then i would suggest you to only use second model. There is no point in using MySql and storing data as in the first model.

    To answer your second question, there is no way to query name like 'foo' if you use first model.

    Remove a parameter to the URL with JavaScript

    Try this. Just pass in the param you want to remove from the URL and the original URL value, and the function will strip it out for you.

    function removeParam(key, sourceURL) {
        var rtn = sourceURL.split("?")[0],
            param,
            params_arr = [],
            queryString = (sourceURL.indexOf("?") !== -1) ? sourceURL.split("?")[1] : "";
        if (queryString !== "") {
            params_arr = queryString.split("&");
            for (var i = params_arr.length - 1; i >= 0; i -= 1) {
                param = params_arr[i].split("=")[0];
                if (param === key) {
                    params_arr.splice(i, 1);
                }
            }
            if (params_arr.length) rtn = rtn + "?" + params_arr.join("&");
        }
        return rtn;
    }
    

    To use it, simply do something like this:

    var originalURL = "http://yourewebsite.com?id=10&color_id=1";
    var alteredURL = removeParam("color_id", originalURL);
    

    The var alteredURL will be the output you desire.

    Hope it helps!

    Html helper for <input type="file" />

    You can also use:

    @using (Html.BeginForm("Upload", "File", FormMethod.Post, new { enctype = "multipart/form-data" }))
    { 
        <p>
            <input type="file" id="fileUpload" name="fileUpload" size="23" />
        </p>
        <p>
            <input type="submit" value="Upload file" /></p> 
    }
    

    Failed to install *.apk on device 'emulator-5554': EOF

    I've ran into this problem many times. Try each of these steps after each step run the APK file if it doesn't work move to the next step:

    1. Run it again. (simply try rerunning it).
    2. Project->Clean (clean the project plus any projects that it relies on).
    3. Right click project in the package explorer then close it. Then close Eclipse. Then reopen both.
    4. Same as the previous step plus Project->Clean.
    5. Restart the AVD.
    6. Delete the AVD. Then go into the folder that holds the AVD in the Android-Sdk folder and delete anything with the AVD's name (a file plus a folder). You may have to restart your computer to get it to delete. Create a new AVD.

    How to delete SQLite database from Android programmatically

    Also from Eclipse you can use DDMS which makes it really easy.

    Just make sure your emulator is running, and then switch to DDMS perspective in Eclipse. You'll have full access to the File Explorer which will allow you to go in and easily delete the entire database.

    How can I create an array/list of dictionaries in python?

    Try this:

    lst = []
    ##use append to add items to the list.
    
    lst.append({'A':0,'C':0,'G':0,'T':0})
    lst.append({'A':1,'C':1,'G':1,'T':1})
    
    ##if u need to add n no of items to the list, use range with append:
    for i in range(n):
        lst.append({'A':0,'C':0,'G':0,'T':0})
    
    print lst
    

    Restart android machine

    You can reboot the device by sending the following broadcast:

    $ adb shell am broadcast -a android.intent.action.BOOT_COMPLETED

    Which type of folder structure should be used with Angular 2?

    I am going to use this one. Very similar to third one shown by @Marin.

    app
    |
    |___ images
    |
    |___ fonts
    |
    |___ css
    |
    |___ *main.ts*
    |   
    |___ *main.component.ts*
    |
    |___ *index.html*
    |
    |___ components
    |   |
    |   |___ shared
    |   |
    |   |___ home
    |   |
    |   |___ about
    |   |
    |   |___ product
    |
    |___ services
    |
    |___ structures
    

    Insert if not exists Oracle

    DECLARE
       tmp NUMBER(3,1);
    BEGIN
      SELECT COUNT(content_id) INTO tmp FROM contents WHERE (condition);
      if tmp != 0 then
        INSERT INTO contents VALUES (...);
      else
        INSERT INTO contents VALUES (...);
      end if;
    END;
    

    I used the code above. It is long, but, simple and worked for me. Similar, to Micheal's code.

    Bootstrap - 5 column layout

    Put some margin-left in all green divs but not in the first

    Can comments be used in JSON?

    Sigh. Why not just add fields, e.g.

    {
        "note1" : "This demonstrates the provision of annotations within a JSON file",
        "field1" : 12,
        "field2" : "some text",
    
        "note2" : "Add more annotations as necessary"
    }
    

    Just make sure your "notex" names don't conflict with any real fields.

    Android Saving created bitmap to directory on sd card

    Hi You can write data to bytes and then create a file in sdcard folder with whatever name and extension you want and then write the bytes to that file. This will save bitmap to sdcard.

    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    _bitmapScaled.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
    
    //you can create a new file name "test.jpg" in sdcard folder.
    File f = new File(Environment.getExternalStorageDirectory()
                            + File.separator + "test.jpg");
    f.createNewFile();
    //write the bytes in file
    FileOutputStream fo = new FileOutputStream(f);
    fo.write(bytes.toByteArray());
    
    // remember close de FileOutput
    fo.close();
    

    Detect if string contains any spaces

    A secondary option would be to check otherwise, with not space (\S), using an expression similar to:

    ^\S+$
    

    Test

    _x000D_
    _x000D_
    function has_any_spaces(regex, str) {_x000D_
     if (regex.test(str) || str === '') {_x000D_
      return false;_x000D_
     }_x000D_
     return true;_x000D_
    }_x000D_
    _x000D_
    const expression = /^\S+$/g;_x000D_
    const string = 'foo  baz bar';_x000D_
    _x000D_
    console.log(has_any_spaces(expression, string));
    _x000D_
    _x000D_
    _x000D_

    Here, we can for instance push strings without spaces into an array:

    _x000D_
    _x000D_
    const regex = /^\S+$/gm;_x000D_
    const str = `_x000D_
    foo_x000D_
    foo baz_x000D_
    bar_x000D_
    foo baz bar_x000D_
    abc_x000D_
    abc abc_x000D_
    abc abc abc_x000D_
    `;_x000D_
    let m, arr = [];_x000D_
    _x000D_
    while ((m = regex.exec(str)) !== null) {_x000D_
     // This is necessary to avoid infinite loops with zero-width matches_x000D_
     if (m.index === regex.lastIndex) {_x000D_
      regex.lastIndex++;_x000D_
     }_x000D_
    _x000D_
     // Here, we push those strings without spaces in an array_x000D_
     m.forEach((match, groupIndex) => {_x000D_
      arr.push(match);_x000D_
     });_x000D_
    }_x000D_
    console.log(arr);
    _x000D_
    _x000D_
    _x000D_


    If you wish to simplify/modify/explore the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.


    RegEx Circuit

    jex.im visualizes regular expressions:

    enter image description here

    How to download image from url

    Try this it worked for me

    Write this in your Controller

    public class DemoController: Controller
    
            public async Task<FileStreamResult> GetLogoImage(string logoimage)
            {
                string str = "" ;
                var filePath = Server.MapPath("~/App_Data/" + SubfolderName);//If subfolder exist otherwise leave.
                // DirectoryInfo dir = new DirectoryInfo(filePath);
                string[] filePaths = Directory.GetFiles(@filePath, "*.*");
                foreach (var fileTemp in filePaths)
                {
                      str= fileTemp.ToString();
                }
                    return File(new MemoryStream(System.IO.File.ReadAllBytes(str)), System.Web.MimeMapping.GetMimeMapping(str), Path.GetFileName(str));
            }
    

    Here is my view

    <div><a href="/DemoController/GetLogoImage?Type=Logo" target="_blank">Download Logo</a></div>
    

    How can two strings be concatenated?

    You can create you own operator :

    '%&%' <- function(x, y)paste0(x,y)
    "new" %&% "operator"
    [1] newoperator`
    

    You can also redefine 'and' (&) operator :

    '&' <- function(x, y)paste0(x,y)
    "dirty" & "trick"
    "dirtytrick"
    

    messing with baseline syntax is ugly, but so is using paste()/paste0() if you work only with your own code you can (almost always) replace logical & and operator with * and do multiplication of logical values instead of using logical 'and &'

    How to interactively (visually) resolve conflicts in SourceTree / git

    When the Resolve Conflicts->Content Menu are disabled, one may be on the Pending files list. We need to select the Conflicted files option from the drop down (top)

    hope it helps

    Determine the path of the executing BASH script

    Contributed by Stephane CHAZELAS on c.u.s. Assuming POSIX shell:

    prg=$0
    if [ ! -e "$prg" ]; then
      case $prg in
        (*/*) exit 1;;
        (*) prg=$(command -v -- "$prg") || exit;;
      esac
    fi
    dir=$(
      cd -P -- "$(dirname -- "$prg")" && pwd -P
    ) || exit
    prg=$dir/$(basename -- "$prg") || exit 
    
    printf '%s\n' "$prg"
    

    How to use XPath contains() here?

    This is a new answer to an old question about a common misconception about contains() in XPath...

    Summary: contains() means contains a substring, not contains a node.

    Detailed Explanation

    This XPath is often misinterpreted:

    //ul[contains(li, 'Model')]
    

    Wrong interpretation: Select those ul elements that contain an li element with Model in it.

    This is wrong because

    1. contains(x,y) expects x to be a string, and
    2. the XPath rule for converting multiple elements to a string is this:

      A node-set is converted to a string by returning the string-value of the node in the node-set that is first in document order. If the node-set is empty, an empty string is returned.

    Right interpretation: Select those ul elements whose first li child has a string-value that contains a Model substring.

    Examples

    XML

    <r>
      <ul id="one">
        <li>Model A</li>
        <li>Foo</li>
      </ul>
      <ul id="two">
        <li>Foo</li>
        <li>Model A</li>
      </ul>
    </r> 
    

    XPaths

    • //ul[contains(li, 'Model')] selects the one ul element.

      Note: The two ul element is not selected because the string-value of the first li child of the two ul is Foo, which does not contain the Model substring.

    • //ul[li[contains(.,'Model')]] selects the one and two ul elements.

      Note: Both ul elements are selected because contains() is applied to each li individually. (Thus, the tricky multiple-element-to-string conversion rule is avoided.) Both ul elements do have an li child whose string value contains the Model substring -- position of the li element no longer matters.

    See also

    How do you create a foreign key relationship in a SQL Server CE (Compact Edition) Database?

    Alan is correct when he says there's designer support. Rhywun is incorrect when he implies you cannot choose the foreign key table. What he means is that in the UI the foreign key table drop down is greyed out - all that means is he has not right clicked on the correct table to add the foreign key to.

    In summary, right click on the foriegn key table and then via the 'Table Properties' > 'Add Relations' option you select the related primary key table.

    I've done it numerous times and it works.

    The representation of if-elseif-else in EL using JSF

    You can use EL if you want to work as IF:

    <h:outputLabel value="#{row==10? '10' : '15'}"/>
    

    Changing styles or classes:

    style="#{test eq testMB.test? 'font-weight:bold' : 'font-weight:normal'}"
    
    class="#{test eq testMB.test? 'divRred' : 'divGreen'}"
    

    How to concatenate strings in windows batch file for loop?

    Try this, with strings:

    set "var=string1string2string3"
    

    and with string variables:

    set "var=%string1%%string2%%string3%"
    

    How to Consolidate Data from Multiple Excel Columns All into One Column

    The formula

    =OFFSET(Sheet1!$A$1,MOD(ROW()-1,COUNT(Sheet1!$A$1:$A$20000)),
        (ROW()-1)/COUNT(Sheet1!$A$1:$A$20000))
    

    placed into each cell of your second workbook will retrieve the appropriate cell from the source sheet. No macros, simple copying from one sheet to another to reformat the results.

    You will need to modify the ranges in the COUNT function to match the maximum number of rows in the source sheet. Adjust for column headers as required.

    If you need something other than a 0 for empty cells, you may prefer to include a conditional.

    A script to reformat the data may well be more efficient, but 20k rows is no longer a real limit in a modern Excel workbook.

    Vue - Deep watching an array of objects and calculating the change?

    Your comparison function between old value and new value is having some issue. It is better not to complicate things so much, as it will increase your debugging effort later. You should keep it simple.

    The best way is to create a person-component and watch every person separately inside its own component, as shown below:

    <person-component :person="person" v-for="person in people"></person-component>
    

    Please find below a working example for watching inside person component. If you want to handle it on parent side, you may use $emit to send an event upwards, containing the id of modified person.

    _x000D_
    _x000D_
    Vue.component('person-component', {_x000D_
        props: ["person"],_x000D_
        template: `_x000D_
            <div class="person">_x000D_
                {{person.name}}_x000D_
                <input type='text' v-model='person.age'/>_x000D_
            </div>`,_x000D_
        watch: {_x000D_
            person: {_x000D_
                handler: function(newValue) {_x000D_
                    console.log("Person with ID:" + newValue.id + " modified")_x000D_
                    console.log("New age: " + newValue.age)_x000D_
                },_x000D_
                deep: true_x000D_
            }_x000D_
        }_x000D_
    });_x000D_
    _x000D_
    new Vue({_x000D_
        el: '#app',_x000D_
        data: {_x000D_
            people: [_x000D_
              {id: 0, name: 'Bob', age: 27},_x000D_
              {id: 1, name: 'Frank', age: 32},_x000D_
              {id: 2, name: 'Joe', age: 38}_x000D_
            ]_x000D_
        }_x000D_
    });
    _x000D_
    <script src="https://unpkg.com/[email protected]/dist/vue.js"></script>_x000D_
    <body>_x000D_
        <div id="app">_x000D_
            <p>List of people:</p>_x000D_
            <person-component :person="person" v-for="person in people"></person-component>_x000D_
        </div>_x000D_
    </body>
    _x000D_
    _x000D_
    _x000D_

    Caused by: org.flywaydb.core.api.FlywayException: Validate failed. Migration Checksum mismatch for migration 2

    simple solution will be change spring.datasource.url=jdbc:h2:file:~/dasboot in application.properties to new file name like : spring.datasource.url=jdbc:h2:file:~/dasboots

    How can I convert string to datetime with format specification in JavaScript?

    Date.parse() is fairly intelligent but I can't guarantee that format will parse correctly.

    If it doesn't, you'd have to find something to bridge the two. Your example is pretty simple (being purely numbers) so a touch of REGEX (or even string.split() -- might be faster) paired with some parseInt() will allow you to quickly make a date.

    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.

    error: package javax.servlet does not exist

    The javax.servlet dependency is missing in your pom.xml. Add the following to the dependencies-Node:

    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.0.1</version>
        <scope>provided</scope>
    </dependency>
    

    Programmatically set the initial view controller using Storyboards

    I created a routing class to handle dynamic navigation and keep clean AppDelegate class, I hope it will help other too.

    //
    //  Routing.swift
    // 
    //
    //  Created by Varun Naharia on 02/02/17.
    //  Copyright © 2017 TechNaharia. All rights reserved.
    //
    
    import Foundation
    import UIKit
    import CoreLocation
    
    class Routing {
    
        class func decideInitialViewController(window:UIWindow){
            let userDefaults = UserDefaults.standard
            if((Routing.getUserDefault("isFirstRun")) == nil)
            {
                Routing.setAnimatedAsInitialViewContoller(window: window)
            }
            else if((userDefaults.object(forKey: "User")) != nil)
            {
                Routing.setHomeAsInitialViewContoller(window: window)
            }
            else
            {
                Routing.setLoginAsInitialViewContoller(window: window)
            }
    
        }
    
        class func setAnimatedAsInitialViewContoller(window:UIWindow) {
            Routing.setUserDefault("Yes", KeyToSave: "isFirstRun")
            let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
            let animatedViewController: AnimatedViewController = mainStoryboard.instantiateViewController(withIdentifier: "AnimatedViewController") as! AnimatedViewController
    
            window.rootViewController = animatedViewController
            window.makeKeyAndVisible()
        }
    
        class func setHomeAsInitialViewContoller(window:UIWindow) {
            let userDefaults = UserDefaults.standard
            let decoded  = userDefaults.object(forKey: "User") as! Data
            User.currentUser = NSKeyedUnarchiver.unarchiveObject(with: decoded) as! User
    
            if(User.currentUser.userId != nil && User.currentUser.userId != "")
            {
                let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
                let homeViewController: HomeViewController = mainStoryboard.instantiateViewController(withIdentifier: "HomeViewController") as! HomeViewController
                let loginViewController: UINavigationController = mainStoryboard.instantiateViewController(withIdentifier: "LoginNavigationViewController") as! UINavigationController
                loginViewController.viewControllers.append(homeViewController)
                window.rootViewController = loginViewController
            }
            window.makeKeyAndVisible()
        }
    
        class func setLoginAsInitialViewContoller(window:UIWindow) {
            let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
            let loginViewController: UINavigationController = mainStoryboard.instantiateViewController(withIdentifier: "LoginNavigationViewController") as! UINavigationController
    
            window.rootViewController = loginViewController
            window.makeKeyAndVisible()
        }
    
      class func setUserDefault(_ ObjectToSave : Any?  , KeyToSave : String)
        {
            let defaults = UserDefaults.standard
    
            if (ObjectToSave != nil)
            {
    
                defaults.set(ObjectToSave, forKey: KeyToSave)
            }
    
            UserDefaults.standard.synchronize()
        }
    
        class func getUserDefault(_ KeyToReturnValye : String) -> Any?
        {
            let defaults = UserDefaults.standard
    
            if let name = defaults.value(forKey: KeyToReturnValye)
            {
                return name as Any
            }
            return nil
        }
    
        class func removetUserDefault(_ KeyToRemove : String)
        {
            let defaults = UserDefaults.standard
            defaults.removeObject(forKey: KeyToRemove)
            UserDefaults.standard.synchronize()
        }
    
    }
    

    And in your AppDelegate call this

     self.window = UIWindow(frame: UIScreen.main.bounds)
     Routing.decideInitialViewController(window: self.window!)
    

    This table does not contain a unique column. Grid edit, checkbox, Edit, Copy and Delete features are not available

    I have been faced this problem.

    The cause is your table don't have a primary key field.

    And I have a simple solution: Set a field to primary key to specific filed that suit with your business logic. For example, I have database thesis_db and field thesis_id, I will press button Primary (key icon) to set thesis_id to become primary key field

    Need to find element in selenium by css

    You can describe your css selection like cascading style sheet dows:

    protected override void When()
    {
       SUT.Browser.FindElements(By.CssSelector("#carousel > a.tiny.button"))
    }
    

    Best way to test exceptions with Assert to ensure they will be thrown

    I'm new here and don't have the reputation to comment or downvote, but wanted to point out a flaw in the example in Andy White's reply:

    try
    {
        SomethingThatCausesAnException();
        Assert.Fail("Should have exceptioned above!");
    }
    catch (Exception ex)
    {
        // whatever logging code
    }
    

    In all unit testing frameworks I am familiar with, Assert.Fail works by throwing an exception, so the generic catch will actually mask the failure of the test. If SomethingThatCausesAnException() does not throw, the Assert.Fail will, but that will never bubble out to the test runner to indicate failure.

    If you need to catch the expected exception (i.e., to assert certain details, like the message / properties on the exception), it's important to catch the specific expected type, and not the base Exception class. That would allow the Assert.Fail exception to bubble out (assuming you aren't throwing the same type of exception that your unit testing framework does), but still allow validation on the exception that was thrown by your SomethingThatCausesAnException() method.

    How do I change the color of radio buttons?

    you can use the checkbox hack as explained in css tricks

    http://css-tricks.com/the-checkbox-hack/

    working example of radio button:

    http://codepen.io/Angelata/pen/Eypnq

    input[type=radio]:checked ~ .check {}
    input[type=radio]:checked ~ .check .inside{}
    

    Works in IE9+, Firefox 3.5+, Safari 1.3+, Opera 6+, Chrome anything.

    How to move a git repository into another directory and make that directory a git repository?

    I am no expert, but I copy the .git folder to a new folder, then invoke: git reset --hard

    Compiling C++ on remote Linux machine - "clock skew detected" warning

    I have had this in the past - due to the clocks being out on the machines. Consider setting up NTP so that all machines have the same time.

    I can't find my git.exe file in my Github folder

    run github that you downloaded, click tools and options symbol(top right), click about github for windows and then open the debug log. under DIAGNOSTICS look for Git Executable Exists:

    How to use Git and Dropbox together?

    Without using third-party integration tools, I could enhance the condition a bit and use DropBox and other similar cloud disk services such as SpiderOak with Git.

    The goal is to avoid the synchronization in the middle of these files modifications, as it can upload a partial state and will then download it back, completely corrupting your git state.

    To avoid this issue, I did:

    1. Bundle my git index in one file using git bundle create my_repo.git --all.
    2. Set a delay for the file monitoring, eg 5 minutes, instead of instantaneous. This reduces the chances DropBox synchronizes a partial state in the middle of a change. It also helps greatly when modifying files on the cloud disk on-the-fly (such as with instantaneous saving note-taking apps).

    It's not perfect as there is no guarantee it won't mess up the git state again, but it helps and for the moment I did not get any issue.

    java.lang.NoClassDefFoundError: org/json/JSONObject

    Add json jar to your classpath

    or use java -classpath json.jar ClassName

    refer this

    Flutter Circle Design

    You can use CustomMultiChildLayout to draw this kind of layouts. Here you can find a tutorial: How to Create Custom Layout Widgets in Flutter.

    Is there a way to include commas in CSV columns without breaking the formatting?

    The problem with the CSV format, is there's not one spec, there are several accepted methods, with no way of distinguishing which should be used (for generate/interpret). I discussed all the methods to escape characters (newlines in that case, but same basic premise) in another post. Basically it comes down to using a CSV generation/escaping process for the intended users, and hoping the rest don't mind.

    Reference spec document.

    Installed Ruby 1.9.3 with RVM but command line doesn't show ruby -v

    You have broken version of RVM. Ubuntu does something to RVM that produces lots of errors, the only safe way of fixing for now is to:

    sudo apt-get --purge remove ruby-rvm
    sudo rm -rf /usr/share/ruby-rvm /etc/rvmrc /etc/profile.d/rvm.sh
    

    open new terminal and validate environment is clean from old RVM settings (should be no output):

    env | grep rvm
    

    if there was output, try to open new terminal, if it does not help then restart your computer.

    install RVM:

    \curl -L https://get.rvm.io | 
      bash -s stable --ruby --autolibs=enable --auto-dotfiles
    

    If you find you need some hand-holding, take a look at Installing Ruby on Ubuntu 12.04, which gives a bit more explanation.

    How to determine whether a year is a leap year?

    A leap year is exactly divisible by 4 except for century years (years ending with 00). The century year is a leap year only if it is perfectly divisible by 400. For example,

    if( (year % 4) == 0):
        if ( (year % 100 ) == 0):
    
            if ( (year % 400) == 0):
    
                print("{0} is a leap year".format(year))
            else:
    
                print("{0} is not a leap year".format(year))
        else:
    
            print("{0} is a leap year".format(year))
    
    else:
    
        print("{0} is not a leap year".format(year))
    

    Remove the first character of a string

    python 2.x

    s = ":dfa:sif:e"
    print s[1:]
    

    python 3.x

    s = ":dfa:sif:e"
    print(s[1:])
    

    both prints

    dfa:sif:e
    

    Using a dictionary to select function to execute

    def p1( ):
        print("in p1")
    
    def p2():
        print("in p2")
    
    myDict={
        "P1": p1,
        "P2": p2
    
    }
    
    name=input("enter P1 or P2")
    

    myDictname

    Sum columns with null values in oracle

    Without group by SUM(NVL(regular, 0) + NVL(overtime, 0)) will thrown an error and to avoid this we can simply use NVL(regular, 0) + NVL(overtime, 0)

    Detecting IE11 using CSS Capability/Feature Detection

    Detecting IE and its versions actually is extremely easy, at least extremely intuitive:

    var uA = navigator.userAgent;
    var browser = null;
    var ieVersion = null;
    
    if (uA.indexOf('MSIE 6') >= 0) {
        browser = 'IE';
        ieVersion = 6;
    }
    if (uA.indexOf('MSIE 7') >= 0) {
        browser = 'IE';
        ieVersion = 7;
    }
    if (document.documentMode) { // as of IE8
        browser = 'IE';
        ieVersion = document.documentMode;
    }
    

    .

    This way, ou're also catching high IE versions in Compatibility Mode/View. Next, its a matter of assigning conditional classes:

    var htmlTag = document.documentElement;
    if (browser == 'IE' && ieVersion <= 11)
        htmlTag.className += ' ie11-';
    

    Invalid date in safari

    How about hijack Date with fix-date? No dependencies, min + gzip = 280 B

    Get width height of remote image from url

    The w and h variables in img.onload function are not in the same scope with those in the getMeta() function. One way to do it, is as follows:

    Fiddle: http://jsfiddle.net/ppanagi/28UES/2/

    function getMeta(varA, varB) {
        if (typeof varB !== 'undefined') {
           alert(varA + ' width ' + varB + ' height');
        } else {
           var img = new Image();
           img.src = varA;
           img.onload = getMeta(this.width, this.height);
        }
    }
    
    
    getMeta("http://snook.ca/files/mootools_83_snookca.png");
    

    How do I get the size of a java.sql.ResultSet?

    I checked the runtime value of the ResultSet interface and found out it was pretty much a ResultSetImpl all the time. ResultSetImpl has a method called getUpdateCount() which returns the value you are looking for.

    This code sample should suffice:
    ResultSet resultSet = executeQuery(sqlQuery);
    double rowCount = ((ResultSetImpl)resultSet).getUpdateCount()

    I realize that downcasting is generally an unsafe procedure but this method hasn't yet failed me.

    fatal error LNK1112: module machine type 'x64' conflicts with target machine type 'X86'

    You probably have one .OBJ or .LIB file that's targeted for x64 (that's the module machine type) while you're linking for x86 (that's the target machine type).

    Use DUMPBIN /HEADERS on your .OBJ files and check for the machine entry in the FILE HEADER VALUES block.

    Reading an image file in C/C++

    You could write your own by looking at the JPEG format.

    That said, try a pre-existing library like CImg, or Boost's GIL. Or for strictly JPEG's, libjpeg. There is also the CxImage class on CodeProject.

    Here's a big list.

    jQuery ajax success error

    You did not provide your validate.php code so I'm confused. You have to pass the data in JSON Format when when mail is success. You can use json_encode(); PHP function for that.

    Add json_encdoe in validate.php in last

    mail($to, $subject, $message, $headers); 
    echo json_encode(array('success'=>'true'));
    

    JS Code

    success: function(data){ 
         if(data.success == true){ 
           alert('success'); 
        } 
    

    Hope it works

    How to change the default charset of a MySQL table?

    The ALTER TABLE MySQL command should do the trick. The following command will change the default character set of your table and the character set of all its columns to UTF8.

    ALTER TABLE etape_prospection CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;
    

    This command will convert all text-like columns in the table to the new character set. Character sets use different amounts of data per character, so MySQL will convert the type of some columns to ensure there's enough room to fit the same number of characters as the old column type.

    I recommend you read the ALTER TABLE MySQL documentation before modifying any live data.

    How to draw an overlay on a SurfaceView used by Camera on Android?

    SurfaceView probably does not work like a regular View in this regard.

    Instead, do the following:

    1. Put your SurfaceView inside of a FrameLayout or RelativeLayout in your layout XML file, since both of those allow stacking of widgets on the Z-axis
    2. Move your drawing logic into a separate custom View class
    3. Add an instance of the custom View class to the layout XML file as a child of the FrameLayout or RelativeLayout, but have it appear after the SurfaceView

    This will cause your custom View class to appear to float above the SurfaceView.

    See here for a sample project that layers popup panels above a SurfaceView used for video playback.

    Postman Chrome: What is the difference between form-data, x-www-form-urlencoded and raw

    These are different Form content types defined by W3C. If you want to send simple text/ ASCII data, then x-www-form-urlencoded will work. This is the default.

    But if you have to send non-ASCII text or large binary data, the form-data is for that.

    You can use Raw if you want to send plain text or JSON or any other kind of string. Like the name suggests, Postman sends your raw string data as it is without modifications. The type of data that you are sending can be set by using the content-type header from the drop down.

    Binary can be used when you want to attach non-textual data to the request, e.g. a video/audio file, images, or any other binary data file.

    Refer to this link for further reading: Forms in HTML documents

    Show diff between commits

    I wrote a script which displays diff between two commits, works well on Ubuntu.

    https://gist.github.com/jacobabrahamb4/a60624d6274ece7a0bd2d141b53407bc

    #!/usr/bin/env python
    import sys, subprocess, os
    
    TOOLS = ['bcompare', 'meld']
    
    def execute(command):
        return subprocess.check_output(command)
    
    def getTool():
        for tool in TOOLS:
            try:
                out = execute(['which', tool]).strip()
                if tool in out:
                    return tool
            except subprocess.CalledProcessError:
                pass
        return None
    
    def printUsageAndExit():
        print 'Usage: python bdiff.py <project> <commit_one> <commit_two>'
        print 'Example: python bdiff.py <project> 0 1'
        print 'Example: python bdiff.py <project> fhejk7fe d78ewg9we'
        print 'Example: python bdiff.py <project> 0 d78ewg9we'
        sys.exit(0)
    
    def getCommitIds(name, first, second):
        commit1 = None
        commit2 = None
        try:
            first_index = int(first) - 1
            second_index = int(second) - 1
            if int(first) < 0 or int(second) < 0:
                print "Cannot handle negative values: "
                sys.exit(0)
            logs = execute(['git', '-C', name, 'log', '--oneline', '--reverse']).splitlines()
            if first_index >= 0:
                commit1 = logs[first_index].split(' ')[0]
            if second_index >= 0:
                commit2 = logs[second_index].split(' ')[0]
        except ValueError:
            if first is not '0':
                commit1 = first
            if second is not '0':
                commit2 = second
        return commit1, commit2
    
    def validateCommitIds(name, commit1, commit2):
        if not commit1 and not commit2:
            print "Nothing to do, exit!"
            return False
        try:
            if commit1:
                execute(['git', '-C', name, 'cat-file', '-t', commit1])
            if commit2:
                execute(['git', '-C', name, 'cat-file', '-t', commit2])
        except subprocess.CalledProcessError:
            return False
        return True
    
    def cleanup(commit1, commit2):
            execute(['rm', '-rf', '/tmp/'+(commit1 if commit1 else '0'), '/tmp/'+(commit2 if commit2 else '0')])
    
    def checkoutCommit(name, commit):
        if commit:
            execute(['git', 'clone', name, '/tmp/'+commit])
            execute(['git', '-C', '/tmp/'+commit, 'checkout', commit])
        else:
            execute(['mkdir', '/tmp/0'])
    
    def compare(tool, commit1, commit2):
            execute([tool, '/tmp/'+(commit1 if commit1 else '0'), '/tmp/'+(commit2 if commit2 else '0')])
    
    if __name__=='__main__':
        tool = getTool()
        if not tool:
            print "No GUI diff tools, install bcompare or meld"
            sys.exit(0)
        if len(sys.argv) is not 4:
            printUsageAndExit()
    
        name, first, second = None, 0, 0
        try:
            name, first, second = sys.argv[1], sys.argv[2], sys.argv[3]
        except IndexError:
            printUsageAndExit()
    
        commit1, commit2 = getCommitIds(name, first, second)
    
        if validateCommitIds(name, commit1, commit2) is False:
            sys.exit(0)
    
        cleanup(commit1, commit2)
    
        try:
            checkoutCommit(name, commit1)
            checkoutCommit(name, commit2)
            compare(tool, commit1, commit2)
        except KeyboardInterrupt:
            pass
        finally:
            cleanup(commit1, commit2)
        sys.exit(0)
    

    How do I set 'semi-bold' font via CSS? Font-weight of 600 doesn't make it look like the semi-bold I see in my Photoshop file

    Select fonts by specifying the weights you need on load

    Font-families consist of several distinct fonts

    For example, extra-bold will make the font look quite different in say, Photoshop, because you're selecting a different font. The same applies to italic font, which can look very different indeed. Setting font-weight:800 or font-style:italic may result in just a best effort of the web browser to fatten or slant the normal font in the family.

    Even though you're loading a font-family, you must specify the weights and styles you need for some web browsers to let you select a different font in the family with font-weight and font-style.

    Example

    This example specifies the light, normal, normal italic, bold, and extra-bold fonts in the font family Open Sans:

    _x000D_
    _x000D_
    <html>_x000D_
      <head>_x000D_
        <link rel="stylesheet"_x000D_
              href="https://fonts.googleapis.com/css?family=Open+Sans:100,400,400i,600,800">_x000D_
        <style>_x000D_
          body {_x000D_
            font-family: 'Open Sans', serif;_x000D_
            font-size: 48px;_x000D_
          }_x000D_
        </style>_x000D_
      </head>_x000D_
      <body>    _x000D_
        <div style="font-weight:400">Didn't work with all the fonts</div>_x000D_
       <div style="font-weight:600">Didn't work with all the fonts</div>_x000D_
       <div style="font-weight:800">Didn't work with all the fonts</div>_x000D_
      </body>_x000D_
    </html>
    _x000D_
    _x000D_
    _x000D_

    Reference

    (Quora warning, please remove if not allowed.)

    https://www.quora.com/How-do-I-make-Open-Sans-extra-bold-once-imported-from-Google-Fonts

    Testing

    Tested working in Firefox 66.0.3 on Mac and Firefox 36.0.1 in Windows.

    Non-Google fonts

    Other fonts must be uploaded to the server, style and weight specified by their individual names.

    System fonts

    Assume nothing, font-wise, about what device is visiting your website or what fonts are installed on its OS.

    (You may use the fall-backs of serif and sans-serif, but you will get the font mapped to these by the individual web browser version used, within the fonts available in the OS version it's running under, and not what you designed.)

    Testing should be done with the font temporarily uninstalled from your system, to be sure that your design is in effect.

    Array Length in Java

    Java arrays are actually fixed in size, and the other answers explain how .length isn't really doing what you'd expect. I'd just like to add that given your question what you might want to be using is an ArrayList, that is an array that can grow and shrink:

    https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html

    Here the .size() method will show you the number of elements in your list, and you can grow this as you add things.

    Counting number of occurrences in column?

    A simpler approach to this

    At the beginning of column B, type

    =UNIQUE(A:A)
    

    Then in column C, use

    =COUNTIF(A:A, B1)
    

    and copy them in all row column C.

    Edit: If that doesn't work for you, try using semicolon instead of comma:

    =COUNTIF(A:A; B1)
    

    Remove elements from collection while iterating

    I would choose the second as you don't have to do a copy of the memory and the Iterator works faster. So you save memory and time.

    how to convert a string date to date format in oracle10g

    You need to use the TO_DATE function.

    SELECT TO_DATE('01/01/2004', 'MM/DD/YYYY') FROM DUAL;
    

    Rename a dictionary key

    For a regular dict, you can use:

    mydict[k_new] = mydict.pop(k_old)
    

    This will move the item to the end of the dict, unless k_new was already existing in which case it will overwrite the value in-place.

    For a Python 3.7+ dict where you additionally want to preserve the ordering, the simplest is to rebuild an entirely new instance. For example, renaming key 2 to 'two':

    >>> d = {0:0, 1:1, 2:2, 3:3}
    >>> {"two" if k == 2 else k:v for k,v in d.items()}
    {0: 0, 1: 1, 'two': 2, 3: 3}
    

    The same is true for an OrderedDict, where you can't use dict comprehension syntax, but you can use a generator expression:

    OrderedDict((k_new if k == k_old else k, v) for k, v in od.items())
    

    Modifying the key itself, as the question asks for, is impractical because keys are hashable which usually implies they're immutable and can't be modified.

    How to receive serial data using android bluetooth

    Take a look at incredible Bluetooth Serial class that has onResume() ability that helped me so much. I hope this helps ;)

    How to add data into ManyToMany field?

    In case someone else ends up here struggling to customize admin form Many2Many saving behaviour, you can't call self.instance.my_m2m.add(obj) in your ModelForm.save override, as ModelForm.save later populates your m2m from self.cleaned_data['my_m2m'] which overwrites your changes. Instead call:

    my_m2ms = list(self.cleaned_data['my_m2ms'])
    my_m2ms.extend(my_custom_new_m2ms)
    self.cleaned_data['my_m2ms'] = my_m2ms
    

    (It is fine to convert the incoming QuerySet to a list - the ManyToManyField does that anyway.)

    Map isn't showing on Google Maps JavaScript API v3 when nested in a div tag

    Add style="width:100%; height:100%;" to the div see what that does

    not to the #map_canvas but the main div

    example

    <body>
        <div style="height:100%; width:100%;">
             <div id="map-canvas"></div>
        </div>
    </body> 
    

    There are some other answers on here the explain why this is necessary

    Java: Replace all ' in a string with \'

    You can use apache's commons-text library (instead of commons-lang):

    Example code:

    org.apache.commons.text.StringEscapeUtils.escapeJava(escapedString);
    

    Dependency:

    compile 'org.apache.commons:commons-text:1.8'
    
    OR
    
    <dependency>
       <groupId>org.apache.commons</groupId>
       <artifactId>commons-text</artifactId>
       <version>1.8</version>
    </dependency>
    

    How to Parse JSON Array with Gson

    you can get List value without using Type object.

    EvalClassName[] evalClassName;
    ArrayList<EvalClassName> list;
    evalClassName= new Gson().fromJson(JSONArrayValue.toString(),EvalClassName[].class);
    list = new ArrayList<>(Arrays.asList(evalClassName));
    

    I have tested it and it is working.

    How do I get a Cron like scheduler in Python?

    I don't know if something like that already exists. It would be easy to write your own with time, datetime and/or calendar modules, see http://docs.python.org/library/time.html

    The only concern for a python solution is that your job needs to be always running and possibly be automatically "resurrected" after a reboot, something for which you do need to rely on system dependent solutions.

    jQuery multiple events to trigger the same function

    You can use bind method to attach function to several events. Just pass the event names and the handler function as in this code:

    $('#foo').bind('mouseenter mouseleave', function() {
      $(this).toggleClass('entered');
    });
    

    Another option is to use chaining support of jquery api.

    There is an error in XML document (1, 41)

    First check the variables declared using proper Datatypes. I had a same problem then I have checked, by mistake I declared SAPUser as int datatype so that the error occurred. One more thing XML file stores its data using concept like array but its first index starts having +1. e.g. if error is in(7,2) then check for 6th line always.....

    Markdown: continue numbered list

    Macmade's solution doesn't work for me anymore on my Jekyll instance on Github Pages anymore but I found this solution on an issue for the kramdown github repo. For OP's example it would look like this:

    1. item 1
    2. item 2
    
    ```
    Code block
    ```
    
    {:start="3"}
    3. item 3
    

    Solved my issues handily.

    How can I change a button's color on hover?

    Seems your selector is wrong, try using:

    a.button:hover{
         background: #383;
    }
    

    Your code

    a.button a:hover
    

    Means it is going to search for an a element inside a with class button.

    How to keep console window open

    Write Console.ReadKey(); in the last line of main() method. This line prevents finishing the console. I hope it would help you.

    How to make inline functions in C#

    Yes, C# supports that. There are several syntaxes available.

    • Anonymous methods were added in C# 2.0:

      Func<int, int, int> add = delegate(int x, int y)
      {
          return x + y;
      };
      Action<int> print = delegate(int x)
      {
          Console.WriteLine(x);
      }
      Action<int> helloWorld = delegate // parameters can be elided if ignored
      {
          Console.WriteLine("Hello world!");
      }
      
    • Lambdas are new in C# 3.0 and come in two flavours.

      • Expression lambdas:

        Func<int, int, int> add = (int x, int y) => x + y; // or...
        Func<int, int, int> add = (x, y) => x + y; // types are inferred by the compiler
        
      • Statement lambdas:

        Action<int> print = (int x) => { Console.WriteLine(x); };
        Action<int> print = x => { Console.WriteLine(x); }; // inferred types
        Func<int, int, int> add = (x, y) => { return x + y; };
        
    • Local functions have been introduced with C# 7.0:

      int add(int x, int y) => x + y;
      void print(int x) { Console.WriteLine(x); }
      

    There are basically two different types for these: Func and Action. Funcs return values but Actions don't. The last type parameter of a Func is the return type; all the others are the parameter types.

    There are similar types with different names, but the syntax for declaring them inline is the same. An example of this is Comparison<T>, which is roughly equivalent to Func<T, T, int>.

    Func<string, string, int> compare1 = (l,r) => 1;
    Comparison<string> compare2 = (l, r) => 1;
    Comparison<string> compare3 = compare1; // this one only works from C# 4.0 onwards
    

    These can be invoked directly as if they were regular methods:

    int x = add(23, 17); // x == 40
    print(x); // outputs 40
    helloWorld(x); // helloWorld has one int parameter declared: Action<int>
                   // even though it does not make any use of it.
    

    Removing cordova plugins from the project

    I do it with this python one-liner:

    python -c "import subprocess as sp;[sp.call('cordova plugin rm ' + p.split()[0], shell=True) for p in sp.check_output('cordova plugin', shell=True).split('\n') if p]"
    

    Obviously it doesn't handle any sort of error conditions, but it gets the job done.

    Simple prime number generator in Python

    def genPrimes():
        primes = []   # primes generated so far
        last = 1      # last number tried
        while True:
            last += 1
            for p in primes:
                if last % p == 0:
                    break
            else:
                primes.append(last)
                yield last
    

    How do I fix a Git detached head?

    A solution without creating a temporary branch.

    How to exit (“fix”) detached HEAD state when you already changed something in this mode and, optionally, want to save your changes:

    1. Commit changes you want to keep. If you want to take over any of the changes you made in detached HEAD state, commit them. Like:

      git commit -a -m "your commit message"
      
    2. Discard changes you do not want to keep. The hard reset will discard any uncommitted changes that you made in detached HEAD state:

      git reset --hard
      

      (Without this, step 3 would fail, complaining about modified uncommitted files in the detached HEAD.)

    3. Check out your branch. Exit detached HEAD state by checking out the branch you worked on before, for example:

      git checkout master
      
    4. Take over your commits. You can now take over the commits you made in detached HEAD state by cherry-picking, as shown in my answer to another question.

      git reflog
      git cherry-pick <hash1> <hash2> <hash3> …
      

    How do I change the value of a global variable inside of a function

    Just reference the variable inside the function; no magic, just use it's name. If it's been created globally, then you'll be updating the global variable.

    You can override this behaviour by declaring it locally using var, but if you don't use var, then a variable name used in a function will be global if that variable has been declared globally.

    That's why it's considered best practice to always declare your variables explicitly with var. Because if you forget it, you can start messing with globals by accident. It's an easy mistake to make. But in your case, this turn around and becomes an easy answer to your question.

    Python send POST with header

    Thanks a lot for your link to the requests module. It's just perfect. Below the solution to my problem.

    import requests
    import json
    
    url = 'https://www.mywbsite.fr/Services/GetFromDataBaseVersionned'
    payload = {
        "Host": "www.mywbsite.fr",
        "Connection": "keep-alive",
        "Content-Length": 129,
        "Origin": "https://www.mywbsite.fr",
        "X-Requested-With": "XMLHttpRequest",
        "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.52 Safari/536.5",
        "Content-Type": "application/json",
        "Accept": "*/*",
        "Referer": "https://www.mywbsite.fr/data/mult.aspx",
        "Accept-Encoding": "gzip,deflate,sdch",
        "Accept-Language": "fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4",
        "Accept-Charset": "ISO-8859-1,utf-8;q=0.7,*;q=0.3",
        "Cookie": "ASP.NET_SessionId=j1r1b2a2v2w245; GSFV=FirstVisit=; GSRef=https://www.google.fr/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&ved=0CHgQFjAA&url=https://www.mywbsite.fr/&ei=FZq_T4abNcak0QWZ0vnWCg&usg=AFQjCNHq90dwj5RiEfr1Pw; HelpRotatorCookie=HelpLayerWasSeen=0; NSC_GSPOUGS!TTM=ffffffff09f4f58455e445a4a423660; GS=Site=frfr; __utma=1.219229010.1337956889.1337956889.1337958824.2; __utmb=1.1.10.1337958824; __utmc=1; __utmz=1.1337956889.1.1.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=(not%20provided)"
    }
    # Adding empty header as parameters are being sent in payload
    headers = {}
    r = requests.post(url, data=json.dumps(payload), headers=headers)
    print(r.content)
    

    What is the difference between DAO and Repository patterns?

    DAO provides abstraction on database/data files or any other persistence mechanism so that, persistence layer could be manipulated without knowing its implementation details.

    Whereas in Repository classes, multiple DAO classes can be used inside a single Repository method to get an operation done from "app perspective". So, instead of using multiple DAO at Domain layer, use repository to get it done. Repository is a layer which may contain some application logic like: If data is available in in-memory cache then fetch it from cache otherwise, fetch data from network and store it in in-memory cache for next time retrieval.

    How to call Stored Procedure in a View?

    create view sampleView as 
    select field1, field2, ... 
    from dbo.MyTableValueFunction
    

    Note that even if your MyTableValueFunction doesn't accept any parameters, you still need to include parentheses after it, i.e.:

    ... from dbo.MyTableValueFunction()
    

    Without the parentheses, you'll get an "Invalid object name" error.

    make an html svg object also a clickable link

    i tried this clean easy method and seems to work in all browsers. Inside the svg file:

    _x000D_
    _x000D_
    <svg>_x000D_
    <a id="anchor" xlink:href="http://www.google.com" target="_top">_x000D_
      _x000D_
    <!--your graphic-->_x000D_
      _x000D_
    </a>_x000D_
    </svg>_x000D_
      
    _x000D_
    _x000D_
    _x000D_

    Pure JavaScript: a function like jQuery's isNumeric()

    There is Javascript function isNaN which will do that.

    isNaN(90)
    =>false
    

    so you can check numeric by

    !isNaN(90)
    =>true
    

    How can I color dots in a xy scatterplot according to column value?

    Try this:

    Dim xrndom As Random
        Dim x As Integer
        xrndom = New Random
    
        Dim yrndom As Random
        Dim y As Integer
        yrndom = New Random
        'chart creation
        Chart1.Series.Add("a")
        Chart1.Series("a").ChartType = DataVisualization.Charting.SeriesChartType.Point
        Chart1.Series("a").MarkerSize = 10
        Chart1.Series.Add("b")
        Chart1.Series("b").ChartType = DataVisualization.Charting.SeriesChartType.Point
        Chart1.Series("b").MarkerSize = 10
        Chart1.Series.Add("c")
        Chart1.Series("c").ChartType = DataVisualization.Charting.SeriesChartType.Point
        Chart1.Series("c").MarkerSize = 10
        Chart1.Series.Add("d")
        Chart1.Series("d").ChartType = DataVisualization.Charting.SeriesChartType.Point
        Chart1.Series("d").MarkerSize = 10
        'color
        Chart1.Series("a").Color = Color.Red
        Chart1.Series("b").Color = Color.Orange
        Chart1.Series("c").Color = Color.Black
        Chart1.Series("d").Color = Color.Green
        Chart1.Series("Chart 1").Color = Color.Blue
    
        For j = 0 To 70
            x = xrndom.Next(0, 70)
            y = xrndom.Next(0, 70)
            'Conditions
            If j < 10 Then
                Chart1.Series("a").Points.AddXY(x, y)
            ElseIf j < 30 Then
                Chart1.Series("b").Points.AddXY(x, y)
            ElseIf j < 50 Then
                Chart1.Series("c").Points.AddXY(x, y)
            ElseIf 50 < j Then
                Chart1.Series("d").Points.AddXY(x, y)
            Else
                Chart1.Series("Chart 1").Points.AddXY(x, y)
            End If
        Next
    

    #1071 - Specified key was too long; max key length is 1000 bytes

    This index size limit seems to be larger on 64 bit builds of MySQL.

    I was hitting this limitation trying to dump our dev database and load it on a local VMWare virt. Finally I realized that the remote dev server was 64 bit and I had created a 32 bit virt. I just created a 64 bit virt and I was able to load the database locally.

    How to resolve "gpg: command not found" error during RVM installation?

    GnuPG (with binary name gpg) is an application used for public key encryption using the OpenPGP protocol, but also verification of signatures (cryptographic signatures, that also can validate the publisher if used correctly). To some extend, you could say it's for OpenPGP what OpenSSL is for X.509 and TLS.

    Unlike most Linux distributions (which make heavy use of GnuPG for ensuring untampered software within their package repositories), Mac OS X does not bring GnuPG with the operating system, so you have to install it on your own.

    Possible sources are:

    • Package manager Homebrew: brew install gnupg gnupg2
    • Package manager MacPorts: sudo port install gnupg gnupg2
    • Install from GPGTools, which also brings GUI applications and integration in Apple Mail

    gpg failed to sign the data fatal: failed to write commit object [Git 2.10.0]

    In my case, none of the solutions were working because I did not manually go into my ~/.gitconfig and remove the following as I created a new key that was no longer my older X.509 key so I removed the following and then my new key began to work.

    [gpg]
        program = gpg
        format = x509
    [gpg "x509"]
        program = smimesign