Programs & Examples On #Midlet

MIDlet is an application that uses the Mobile Information Device Profile (MIDP) of the Connected Limited Device Configuration (CLDC) for the Java ME environment

What's the difference between align-content and align-items?

The main difference is when the height of the elements are not the same! Then you can see how in the row, they are all center\end\start

Using "If cell contains" in VBA excel

This does the same, enhanced with CONTAINS:

Function SingleCellExtract(LookupValue As String, LookupRange As Range, ColumnNumber As Integer, Char As String)
Dim I As Long
Dim xRet As String
For I = 1 To LookupRange.Columns(1).Cells.Count
     If InStr(1, LookupRange.Cells(I, 1), LookupValue) > 0 Then
        If xRet = "" Then
            xRet = LookupRange.Cells(I, ColumnNumber) & Char
        Else
            xRet = xRet & "" & LookupRange.Cells(I, ColumnNumber) & Char
        End If
    End If
Next
SingleCellExtract = Left(xRet, Len(xRet) - 1)
End Function

How to test if a string is JSON or not?

I like best answer but if it is an empty string it returns true. So here's a fix:

function isJSON(MyTestStr){
    try {
        var MyJSON = JSON.stringify(MyTestStr);
        var json = JSON.parse(MyJSON);
        if(typeof(MyTestStr) == 'string')
            if(MyTestStr.length == 0)
                return false;
    }
    catch(e){
        return false;
    }
    return true;
}

return value after a promise

The best way to do this would be to use the promise returning function as it is, like this

lookupValue(file).then(function(res) {
    // Write the code which depends on the `res.val`, here
});

The function which invokes an asynchronous function cannot wait till the async function returns a value. Because, it just invokes the async function and executes the rest of the code in it. So, when an async function returns a value, it will not be received by the same function which invoked it.

So, the general idea is to write the code which depends on the return value of an async function, in the async function itself.

Git Symlinks in Windows

One simple trick we use is to just call git add --all twice in a row.

For example, our Windows 7 commit script calls:

$ git add --all
$ git add --all

The first add treats the link as text and adds the folders for delete.

The second add traverses the link correctly and undoes the delete by restoring the files.

It's less elegant than some of the other proposed solutions but it is a simple fix to some of our legacy environments that got symlinks added.

How to call a function after delay in Kotlin?

There is also an option to use Handler -> postDelayed

 Handler().postDelayed({
                    //doSomethingHere()
                }, 1000)

jQuery how to find an element based on a data-attribute value?

When searching with [data-x=...], watch out, it doesn't work with jQuery.data(..) setter:

$('<b data-x="1">'  ).is('[data-x=1]') // this works
> true

$('<b>').data('x', 1).is('[data-x=1]') // this doesn't
> false

$('<b>').attr('data-x', 1).is('[data-x=1]') // this is the workaround
> true

You can use this instead:

$.fn.filterByData = function(prop, val) {
    return this.filter(
        function() { return $(this).data(prop)==val; }
    );
}

$('<b>').data('x', 1).filterByData('x', 1).length
> 1

how to read xml file from url using php

Your code seems right, check if you have fopen wrappers enabled (allow_url_fopen = On on php.ini)

Also, as mentioned by other answers, you should provide a properly encoded URI or encode it using urlencode() function. You should also check if there is any error fetching the XML string and if there is any parsing error, which you can output using libxml_get_errors() as follows:

<?php
if (($response_xml_data = file_get_contents($map_url))===false){
    echo "Error fetching XML\n";
} else {
   libxml_use_internal_errors(true);
   $data = simplexml_load_string($response_xml_data);
   if (!$data) {
       echo "Error loading XML\n";
       foreach(libxml_get_errors() as $error) {
           echo "\t", $error->message;
       }
   } else {
      print_r($data);
   }
}
?>

If the problem is you can't fetch the XML code maybe it's because you need to include some custom headers in your request, check how to use stream_context_create() to create a custom stream context for use when calling file_get_contents() on example 4 at http://php.net/manual/en/function.file-get-contents.php

How to add message box with 'OK' button?

Since in your situation you only want to notify the user with a short and simple message, a Toast would make for a better user experience.

Toast.makeText(getApplicationContext(), "Data saved", Toast.LENGTH_LONG).show();

Update: A Snackbar is recommended now instead of a Toast for Material Design apps.

If you have a more lengthy message that you want to give the reader time to read and understand, then you should use a DialogFragment. (The documentation currently recommends wrapping your AlertDialog in a fragment rather than calling it directly.)

Make a class that extends DialogFragment:

public class MyDialogFragment extends DialogFragment {
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {

        // Use the Builder class for convenient dialog construction
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle("App Title");
        builder.setMessage("This is an alert with no consequence");
        builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                // You don't have to do anything here if you just 
                // want it dismissed when clicked
            }
        });

        // Create the AlertDialog object and return it
        return builder.create();
    }
}

Then call it when you need it in your activity:

DialogFragment dialog = new MyDialogFragment();
dialog.show(getSupportFragmentManager(), "MyDialogFragmentTag");

See also

enter image description here

efficient way to implement paging

While LINQ-to-SQL will generate an OFFSET clause (possibly emulated using ROW_NUMBER() OVER() as others have mentioned), there is an entirely different, much faster way to perform paging in SQL. This is often called the "seek method" as described in this blog post here.

SELECT TOP 10 first_name, last_name, score
FROM players
WHERE (score < @previousScore)
   OR (score = @previousScore AND player_id < @previousPlayerId)
ORDER BY score DESC, player_id DESC

The @previousScore and @previousPlayerId values are the respective values of the last record from the previous page. This allows you to fetch the "next" page. If the ORDER BY direction is ASC, simply use > instead.

With the above method, you cannot immediately jump to page 4 without having first fetched the previous 40 records. But often, you do not want to jump that far anyway. Instead, you get a much faster query that might be able to fetch data in constant time, depending on your indexing. Plus, your pages remain "stable", no matter if the underlying data changes (e.g. on page 1, while you're on page 4).

This is the best way to implement paging when lazy loading more data in web applications, for instance.

Note, the "seek method" is also called keyset paging.

What is unexpected T_VARIABLE in PHP?

There might be a semicolon or bracket missing a line before your pasted line.

It seems fine to me; every string is allowed as an array index.

How to add/subtract time (hours, minutes, etc.) from a Pandas DataFrame.Index whos objects are of type datetime.time?

The Philippe solution but cleaner:

My subtraction data is: '2018-09-22T11:05:00.000Z'

import datetime
import pandas as pd

df_modified = pd.to_datetime(df_reference.index.values) - datetime.datetime(2018, 9, 22, 11, 5, 0)

Display an image with Python

If you are using matplotlib and want to show the image in your interactive notebook, try the following:

%pylab inline
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
img = mpimg.imread('your_image.png')
imgplot = plt.imshow(img)
plt.show()

jQuery ui dialog change title after load-callback

Using dialog methods:

$('.selectorUsedToCreateTheDialog').dialog('option', 'title', 'My New title');

Or directly, hacky though:

$("span.ui-dialog-title").text('My New Title'); 

For future reference, you can skip google with jQuery. The jQuery API will answer your questions most of the time. In this case, the Dialog API page. For the main library: http://api.jquery.com

Quick way to list all files in Amazon S3 bucket?

AWS CLI can let you see all files of an S3 bucket quickly and help in performing other operations too.

To use AWS CLI follow steps below:

  1. Install AWS CLI.
  2. Configure AWS CLI for using default security credentials and default AWS Region.
  3. To see all files of an S3 bucket use command

    aws s3 ls s3://your_bucket_name --recursive

Reference to use AWS cli for different AWS services: https://docs.aws.amazon.com/cli/latest/reference/

Get lengths of a list in a jinja2 template

I've experienced a problem with length of None, which leads to Internal Server Error: TypeError: object of type 'NoneType' has no len()

My workaround is just displaying 0 if object is None and calculate length of other types, like list in my case:

{{'0' if linked_contacts == None else linked_contacts|length}}

how to bold words within a paragraph in HTML/CSS?

<p><b> BOLD TEXT </b> not in bold </p>;

Include the text you want to be in bold between <b>...</b>

HTML5 Canvas Rotate Image

The other solution works great for square images. Here is a solution that will work for an image of any dimension. The canvas will always fit the image rather than the other solution which may cause portions of the image to be cropped off.

var canvas;

var angleInDegrees=0;

var image=document.createElement("img");
image.onload=function(){

    drawRotated(0);
}
image.src="http://greekgear.files.wordpress.com/2011/07/bob-barker.jpg";

$("#clockwise").click(function(){ 
    angleInDegrees+=90 % 360;
    drawRotated(angleInDegrees);
});

$("#counterclockwise").click(function(){ 
    if(angleInDegrees == 0)
        angleInDegrees = 270;
    else
        angleInDegrees-=90 % 360;
    drawRotated(angleInDegrees);
});

function drawRotated(degrees){
    if(canvas) document.body.removeChild(canvas);

    canvas = document.createElement("canvas");
    var ctx=canvas.getContext("2d");
    canvas.style.width="20%";

    if(degrees == 90 || degrees == 270) {
        canvas.width = image.height;
        canvas.height = image.width;
    } else {
        canvas.width = image.width;
        canvas.height = image.height;
    }

    ctx.clearRect(0,0,canvas.width,canvas.height);
    if(degrees == 90 || degrees == 270) {
        ctx.translate(image.height/2,image.width/2);
    } else {
        ctx.translate(image.width/2,image.height/2);
   }
    ctx.rotate(degrees*Math.PI/180);
    ctx.drawImage(image,-image.width/2,-image.height/2);

    document.body.appendChild(canvas);
}

http://jsfiddle.net/6ZsCz/1588/

Android how to convert int to String?

Normal ways would be Integer.toString(i) or String.valueOf(i).

int i = 5;
String strI = String.valueOf(i);

Or

int aInt = 1;    
String aString = Integer.toString(aInt);

How can I show the table structure in SQL Server query?

On SQL Server 2012, you can use the following stored procedure:

sp_columns '<table name>'

For example, given a database table named users:

sp_columns 'users'

Session timeout in ASP.NET

The Timeout property specifies the time-out period assigned to the Session object for the application, in minutes. If the user does not refresh or request a page within the time-out period, the session ends.

IIS 6.0: The minimum allowed value is 1 minute and the maximum is 1440 minutes.

Session.Timeout = 600;

RecyclerView inside ScrollView is not working

In case setting fixed height for the RecyclerView didn't work for someone (like me), here is what I've added to the fixed height solution:

mRecyclerView.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
    @Override
    public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
        int action = e.getAction();
        switch (action) {
            case MotionEvent.ACTION_MOVE:
                rv.getParent().requestDisallowInterceptTouchEvent(true);
                break;
        }
        return false;
    }

    @Override
    public void onTouchEvent(RecyclerView rv, MotionEvent e) {

    }

    @Override
    public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {

    }
});

Get data from fs.readFile

const fs = require('fs')
function readDemo1(file1) {
    return new Promise(function (resolve, reject) {
        fs.readFile(file1, 'utf8', function (err, dataDemo1) {
            if (err)
                reject(err);
            else
                resolve(dataDemo1);
        });
    });
}
async function copyFile() {

    try {
        let dataDemo1 = await readDemo1('url')
        dataDemo1 += '\n' +  await readDemo1('url')

        await writeDemo2(dataDemo1)
        console.log(dataDemo1)
    } catch (error) {
        console.error(error);
    }
}
copyFile();

function writeDemo2(dataDemo1) {
    return new Promise(function(resolve, reject) {
      fs.writeFile('text.txt', dataDemo1, 'utf8', function(err) {
        if (err)
          reject(err);
        else
          resolve("Promise Success!");
      });
    });
  }

Squash my last X commits together using Git

Based on this article I found this method easier for my usecase.

My 'dev' branch was ahead of 'origin/dev' by 96 commits (so these commits were not pushed to the remote yet).

I wanted to squash these commits into one before pushing the change. I prefere to reset the branch to the state of 'origin/dev' (this will leave all changes from the 96 commits unstaged) and then commit the changes at once:

git reset origin/dev
git add --all
git commit -m 'my commit message'

How does the keyword "use" work in PHP and can I import classes with it?

I agree with Green, Symfony needs namespace, so why not use them ?

This is how an example controller class starts:

namespace Acme\DemoBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class WelcomeController extends Controller { ... }

Getting the base url of the website and globally passing it to twig in Symfony 2

Instead of passing variable to template globally, you can define a base template and render the 'global part' in it. The base template can be inherited.

Example of rendering template From the symfony Documentation:

<div id="sidebar">
  {% render "AcmeArticleBundle:Article:recentArticles" with {'max': 3} %}
</div>

Calculate Age in MySQL (InnoDb)

select floor(datediff (now(), birthday)/365) as age

How to check that an element is in a std::set?

If you were going to add a contains function, it might look like this:

#include <algorithm>
#include <iterator>

template<class TInputIterator, class T> inline
bool contains(TInputIterator first, TInputIterator last, const T& value)
{
    return std::find(first, last, value) != last;
}

template<class TContainer, class T> inline
bool contains(const TContainer& container, const T& value)
{
    // This works with more containers but requires std::begin and std::end
    // from C++0x, which you can get either:
    //  1. By using a C++0x compiler or
    //  2. Including the utility functions below.
    return contains(std::begin(container), std::end(container), value);

    // This works pre-C++0x (and without the utility functions below, but doesn't
    // work for fixed-length arrays.
    //return contains(container.begin(), container.end(), value);
}

template<class T> inline
bool contains(const std::set<T>& container, const T& value)
{
    return container.find(value) != container.end();
}

This works with std::set, other STL containers, and even fixed-length arrays:

void test()
{
    std::set<int> set;
    set.insert(1);
    set.insert(4);
    assert(!contains(set, 3));

    int set2[] = { 1, 2, 3 };
    assert(contains(set2, 3));
}

Edit:

As pointed out in the comments, I unintentionally used a function new to C++0x (std::begin and std::end). Here is the near-trivial implementation from VS2010:

namespace std {

template<class _Container> inline
    typename _Container::iterator begin(_Container& _Cont)
    { // get beginning of sequence
    return (_Cont.begin());
    }

template<class _Container> inline
    typename _Container::const_iterator begin(const _Container& _Cont)
    { // get beginning of sequence
    return (_Cont.begin());
    }

template<class _Container> inline
    typename _Container::iterator end(_Container& _Cont)
    { // get end of sequence
    return (_Cont.end());
    }

template<class _Container> inline
    typename _Container::const_iterator end(const _Container& _Cont)
    { // get end of sequence
    return (_Cont.end());
    }

template<class _Ty,
    size_t _Size> inline
    _Ty *begin(_Ty (&_Array)[_Size])
    { // get beginning of array
    return (&_Array[0]);
    }

template<class _Ty,
    size_t _Size> inline
    _Ty *end(_Ty (&_Array)[_Size])
    { // get end of array
    return (&_Array[0] + _Size);
    }

}

Server cannot set status after HTTP headers have been sent IIS7.5

How about checking this before doing the redirect:

if (!Response.IsRequestBeingRedirected)
{
   //do the redirect
}

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

If you want to keep the height of the DIV absolute, regardless of the amount of text inside use the following:

overflow: hidden;

If a folder does not exist, create it

string root = @"C:\Temp";

string subdir = @"C:\Temp\Mahesh";

// If directory does not exist, create it.

if (!Directory.Exists(root))
{

Directory.CreateDirectory(root);

}

The CreateDirectory is also used to create a sub directory. All you have to do is to specify the path of the directory in which this subdirectory will be created in. The following code snippet creates a Mahesh subdirectory in C:\Temp directory.

// Create sub directory

if (!Directory.Exists(subdir))
{

Directory.CreateDirectory(subdir);

}

How to delete all instances of a character in a string in python?

>>> x = 'it is icy'.replace('i', '', 1)
>>> x
't is icy'

Since your code would only replace the first instance, I assumed that's what you wanted. If you want to replace them all, leave off the 1 argument.

Since you cannot replace the character in the string itself, you have to reassign it back to the variable. (Essentially, you have to update the reference instead of modifying the string.)

Display HTML form values in same page after submit using Ajax

<script type = "text/javascript">
function get_values(input_id)
{
var input = document.getElementById(input_id).value;
document.write(input);
}
</script>

<!--Insert more code here-->


<input type = "text" id = "textfield">
<input type = "button" onclick = "get('textfield')" value = "submit">

Next time you ask a question here, include more detail and what you have tried.

Java default constructor

If a class doesn't have any constructor provided by programmer, then java compiler will add a default constructor with out parameters which will call super class constructor internally with super() call. This is called as default constructor.

In your case, there is no default constructor as you are adding them programmatically. If there are no constructors added by you, then compiler generated default constructor will look like this.

public Module()
{
   super();
}

Note: In side default constructor, it will add super() call also, to call super class constructor.

Purpose of adding default constructor:

Constructor's duty is to initialize instance variables, if there are no instance variables you could choose to remove constructor from your class. But when you are inheriting some class it is your class responsibility to call super class constructor to make sure that super class initializes all its instance variables properly.

That's why if there are no constructors, java compiler will add a default constructor and calls super class constructor.

Does Python have a ternary conditional operator?

a if condition else b

Just memorize this pyramid if you have trouble remembering:

     condition
  if           else
a                   b 

PHP str_replace replace spaces with underscores

Try this instead:

$journalName = preg_replace('/\s+/', '_', $journalName);

Explanation: you are most likely seeing whitespace, not just plain spaces (there is a difference).

How to capitalize first letter of each word, like a 2-word city?

The JavaScript function:

String.prototype.capitalize = function(){
       return this.replace( /(^|\s)([a-z])/g , function(m,p1,p2){ return p1+p2.toUpperCase(); } );
      };

To use this function:

capitalizedString = someString.toLowerCase().capitalize();

Also, this would work on multiple words string.

To make sure the converted City name is injected into the database, lowercased and first letter capitalized, then you would need to use JavaScript before you send it over to server side. CSS simply styles, but the actual data would remain pre-styled. Take a look at this jsfiddle example and compare the alert message vs the styled output.

How to decompile a whole Jar file?

If you happen to have both a bash shell and jad:

JAR=(your jar file name)
unzip -d $JAR.tmp $JAR
pushd $JAR.tmp
for f in `find . -name '*.class'`; do
    jad -d $(dirname $f) -s java -lnc $f
done
popd

I might be a tiny, tiny bit off with that, but it should work more or less as advertised. You should end up with $JAR.tmp containing your decompiled files.

json Uncaught SyntaxError: Unexpected token :

I have spent the last few days trying to figure this out myself. Using the old json dataType gives you cross origin problems, while setting the dataType to jsonp makes the data "unreadable" as explained above. So there are apparently two ways out, the first hasn't worked for me but seems like a potential solution and that I might be doing something wrong. This is explained here [ https://learn.jquery.com/ajax/working-with-jsonp/ ].

The one that worked for me is as follows: 1- download the ajax cross origin plug in [ http://www.ajax-cross-origin.com/ ]. 2- add a script link to it just below the normal jQuery link. 3- add the line "crossOrigin: true," to your ajax function.

Good to go! here is my working code for this:

_x000D_
_x000D_
  $.ajax({_x000D_
      crossOrigin: true,_x000D_
      url : "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-33.86,151.195&radius=5000&type=ATM&keyword=ATM&key=MyKey",_x000D_
      type : "GET",_x000D_
      success:function(data){_x000D_
         console.log(data);_x000D_
      }_x000D_
    })
_x000D_
_x000D_
_x000D_

CSS: background image on background color

really interesting problem, haven't seen it yet. this code works fine for me. tested it in chrome and IE9

<html>
<head>
<style>
body{
    background-image: url('img.jpg');
    background-color: #6DB3F2;
}
</style>
</head>
<body>
</body>
</html>

Rotate an image in image source in html

This CSS seems to work in Safari and Chrome:

div#div2
{
-webkit-transform:rotate(90deg); /* Chrome, Safari, Opera */
transform:rotate(90deg); /* Standard syntax */
}

and in the body:

<div id="div2"><img src="image.jpg"  ></div>

But this (and the .rotate90 example above) pushes the rotated image higher up on the page than if it were un-rotated. Not sure how to control placement of the image relative to text or other rotated images.

How to make an array of arrays in Java

Like this:

String[][] arrays = { array1, array2, array3, array4, array5 };

or

String[][] arrays = new String[][] { array1, array2, array3, array4, array5 };

(The latter syntax can be used in assignments other than at the point of the variable declaration, whereas the shorter syntax only works with declarations.)

How to trap the backspace key using jQuery?

try this one :

 $('html').keyup(function(e){if(e.keyCode == 8)alert('backspace trapped')})  

How do I disable and re-enable a button in with javascript?

you can try with

document.getElementById('btn').disabled = !this.checked"

_x000D_
_x000D_
<input type="submit" name="btn"  id="btn" value="submit" disabled/>_x000D_
_x000D_
<input type="checkbox"  onchange="document.getElementById('btn').disabled = !this.checked"/>
_x000D_
_x000D_
_x000D_

How to do a deep comparison between 2 objects with lodash?

Based on the answer by Adam Boduch, I wrote this function which compares two objects in the deepest possible sense, returning paths that have different values as well as paths missing from one or the other object.

The code was not written with efficiency in mind, and improvements in that regard are most welcome, but here is the basic form:

var compare = function (a, b) {

  var result = {
    different: [],
    missing_from_first: [],
    missing_from_second: []
  };

  _.reduce(a, function (result, value, key) {
    if (b.hasOwnProperty(key)) {
      if (_.isEqual(value, b[key])) {
        return result;
      } else {
        if (typeof (a[key]) != typeof ({}) || typeof (b[key]) != typeof ({})) {
          //dead end.
          result.different.push(key);
          return result;
        } else {
          var deeper = compare(a[key], b[key]);
          result.different = result.different.concat(_.map(deeper.different, (sub_path) => {
            return key + "." + sub_path;
          }));

          result.missing_from_second = result.missing_from_second.concat(_.map(deeper.missing_from_second, (sub_path) => {
            return key + "." + sub_path;
          }));

          result.missing_from_first = result.missing_from_first.concat(_.map(deeper.missing_from_first, (sub_path) => {
            return key + "." + sub_path;
          }));
          return result;
        }
      }
    } else {
      result.missing_from_second.push(key);
      return result;
    }
  }, result);

  _.reduce(b, function (result, value, key) {
    if (a.hasOwnProperty(key)) {
      return result;
    } else {
      result.missing_from_first.push(key);
      return result;
    }
  }, result);

  return result;
}

You can try the code using this snippet (running in full page mode is recommended):

_x000D_
_x000D_
var compare = function (a, b) {_x000D_
_x000D_
  var result = {_x000D_
    different: [],_x000D_
    missing_from_first: [],_x000D_
    missing_from_second: []_x000D_
  };_x000D_
_x000D_
  _.reduce(a, function (result, value, key) {_x000D_
    if (b.hasOwnProperty(key)) {_x000D_
      if (_.isEqual(value, b[key])) {_x000D_
        return result;_x000D_
      } else {_x000D_
        if (typeof (a[key]) != typeof ({}) || typeof (b[key]) != typeof ({})) {_x000D_
          //dead end._x000D_
          result.different.push(key);_x000D_
          return result;_x000D_
        } else {_x000D_
          var deeper = compare(a[key], b[key]);_x000D_
          result.different = result.different.concat(_.map(deeper.different, (sub_path) => {_x000D_
            return key + "." + sub_path;_x000D_
          }));_x000D_
_x000D_
          result.missing_from_second = result.missing_from_second.concat(_.map(deeper.missing_from_second, (sub_path) => {_x000D_
            return key + "." + sub_path;_x000D_
          }));_x000D_
_x000D_
          result.missing_from_first = result.missing_from_first.concat(_.map(deeper.missing_from_first, (sub_path) => {_x000D_
            return key + "." + sub_path;_x000D_
          }));_x000D_
          return result;_x000D_
        }_x000D_
      }_x000D_
    } else {_x000D_
      result.missing_from_second.push(key);_x000D_
      return result;_x000D_
    }_x000D_
  }, result);_x000D_
_x000D_
  _.reduce(b, function (result, value, key) {_x000D_
    if (a.hasOwnProperty(key)) {_x000D_
      return result;_x000D_
    } else {_x000D_
      result.missing_from_first.push(key);_x000D_
      return result;_x000D_
    }_x000D_
  }, result);_x000D_
_x000D_
  return result;_x000D_
}_x000D_
_x000D_
var a_editor = new JSONEditor($('#a')[0], {_x000D_
  name: 'a',_x000D_
  mode: 'code'_x000D_
});_x000D_
var b_editor = new JSONEditor($('#b')[0], {_x000D_
  name: 'b',_x000D_
  mode: 'code'_x000D_
});_x000D_
_x000D_
var a = {_x000D_
  same: 1,_x000D_
  different: 2,_x000D_
  missing_from_b: 3,_x000D_
  missing_nested_from_b: {_x000D_
    x: 1,_x000D_
    y: 2_x000D_
  },_x000D_
  nested: {_x000D_
    same: 1,_x000D_
    different: 2,_x000D_
    missing_from_b: 3_x000D_
  }_x000D_
}_x000D_
_x000D_
var b = {_x000D_
  same: 1,_x000D_
  different: 99,_x000D_
  missing_from_a: 3,_x000D_
  missing_nested_from_a: {_x000D_
    x: 1,_x000D_
    y: 2_x000D_
  },_x000D_
  nested: {_x000D_
    same: 1,_x000D_
    different: 99,_x000D_
    missing_from_a: 3_x000D_
  }_x000D_
}_x000D_
_x000D_
a_editor.set(a);_x000D_
b_editor.set(b);_x000D_
_x000D_
var result_editor = new JSONEditor($('#result')[0], {_x000D_
  name: 'result',_x000D_
  mode: 'view'_x000D_
});_x000D_
_x000D_
var do_compare = function() {_x000D_
  var a = a_editor.get();_x000D_
  var b = b_editor.get();_x000D_
  result_editor.set(compare(a, b));_x000D_
}
_x000D_
#objects {} #objects section {_x000D_
  margin-bottom: 10px;_x000D_
}_x000D_
#objects section h1 {_x000D_
  background: #444;_x000D_
  color: white;_x000D_
  font-family: monospace;_x000D_
  display: inline-block;_x000D_
  margin: 0;_x000D_
  padding: 5px;_x000D_
}_x000D_
.jsoneditor-outer, .ace_editor {_x000D_
min-height: 230px !important;_x000D_
}_x000D_
button:hover {_x000D_
  background: orangered;_x000D_
}_x000D_
button {_x000D_
  cursor: pointer;_x000D_
  background: red;_x000D_
  color: white;_x000D_
  text-align: left;_x000D_
  font-weight: bold;_x000D_
  border: 5px solid crimson;_x000D_
  outline: 0;_x000D_
  padding: 10px;_x000D_
  margin: 10px 0px;_x000D_
}
_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/jsoneditor/5.5.10/jsoneditor.min.css" rel="stylesheet" />_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jsoneditor/5.5.10/jsoneditor.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="objects">_x000D_
  <section>_x000D_
    <h1>a (first object)</h1>_x000D_
    <div id="a"></div>_x000D_
  </section>_x000D_
  <section>_x000D_
    <h1>b (second object)</h1>_x000D_
    <div id="b"></div>_x000D_
  </section>_x000D_
  <button onClick="do_compare()">compare</button>_x000D_
  <section>_x000D_
    <h1>result</h1>_x000D_
    <div id="result"></div>_x000D_
  </section>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Using a cursor with dynamic SQL in a stored procedure

this code can be useful for you.

example of cursor use in sql server

DECLARE sampleCursor CURSOR FOR 
      SELECT K.Id FROM TableA K WHERE ....;
OPEN sampleCursor
FETCH NEXT FROM sampleCursor INTO @Id
WHILE @@FETCH_STATUS <> -1
BEGIN

UPDATE TableB
   SET 
      ...

Sending HTML Code Through JSON

All these answers didn't work for me.

But this one did:

json_encode($array, JSON_HEX_QUOT | JSON_HEX_TAG);

Thanks to this answer.

Using <style> tags in the <body> with other HTML

Because this is HTML is not valid does not have any affect on the outcome ... it just means that the HTML does adhere to the standard (merely for organizational purposes). For the sake of being valid it could have been written this way:

<html>
<head>
<style type="text/css">
  p.first {color:blue}
  p.second {color:green}
</style>
</head>
<body>
<p class="first" style="color:green;">Hello World</p>
<p class="second" style="color:blue;">Hello World</p>

My guess is that the browser applies the last style it comes across.

What's the difference between SCSS and Sass?

The Sass .sass file is visually different from .scss file, e.g.

Example.sass - sass is the older syntax

$color: red

=my-border($color)
  border: 1px solid $color

body
  background: $color
  +my-border(green)

Example.scss - sassy css is the new syntax as of Sass 3

$color: red;

@mixin my-border($color) {
  border: 1px solid $color;
}

body {
  background: $color;
  @include my-border(green);
}

Any valid CSS document can be converted to Sassy CSS (SCSS) simply by changing the extension from .css to .scss.

Regular expression to match any character being repeated more than 10 times

={10,}

matches = that is repeated 10 or more times.

From an array of objects, extract value of a property as array

It is better to use some sort of libraries like lodash or underscore for cross browser assurance.

In Lodash you can get values of a property in array by following method

_.map(objArray,"foo")

and in Underscore

_.pluck(objArray,"foo")

Both will return

[1, 2, 3]

GetFiles with multiple extensions

I'm not sure if that is possible. The MSDN GetFiles reference says a search pattern, not a list of search patterns.

I might be inclined to fetch each list separately and "foreach" them into a final list.

Is if(document.getElementById('something')!=null) identical to if(document.getElementById('something'))?

jquery will provide you with this and more ...

if($("#something").val()){ //do stuff}

It took me a couple of days to pick it up, but it provides you with you with so much more functionality. An example below.

jQuery(document).ready(function() {
    /* finds closest element with class divright/left and 
    makes all checkboxs inside that div class the same as selectAll...
    */
        $("#selectAll").click(function() {
        $(this).closest('.divright').find(':checkbox').attr('checked', this.checked);
    });
});

Copying files from one directory to another in Java

Copy file from one directory to another directory...

FileChannel source=new FileInputStream(new File("source file path")).getChannel();
FileChannel desti=new FileOutputStream(new File("destination file path")).getChannel();
desti.transferFrom(source, 0, source.size());
source.close();
desti.close();

Grab a segment of an array in Java without creating a new array on heap

This is a little more lightweight than Arrays.copyOfRange - no range or negative

public static final byte[] copy(byte[] data, int pos, int length )
{
    byte[] transplant = new byte[length];

    System.arraycopy(data, pos, transplant, 0, length);

    return transplant;
}

How do you generate a random double uniformly distributed between 0 and 1 from C++?

An old school solution like:

double X=((double)rand()/(double)RAND_MAX);

Should meet all your criteria (portable, standard and fast). obviously the random number generated has to be seeded the standard procedure is something like:

srand((unsigned)time(NULL));

Adding three months to a date in PHP

Following should work

$d = strtotime("+1 months",strtotime("2015-05-25"));
echo   date("Y-m-d",$d); // This will print **2015-06-25** 

How to modify a text file?

As mentioned by Adam you have to take your system limitations into consideration before you can decide on approach whether you have enough memory to read it all into memory replace parts of it and re-write it.

If you're dealing with a small file or have no memory issues this might help:

Option 1) Read entire file into memory, do a regex substitution on the entire or part of the line and replace it with that line plus the extra line. You will need to make sure that the 'middle line' is unique in the file or if you have timestamps on each line this should be pretty reliable.

# open file with r+b (allow write and binary mode)
f = open("file.log", 'r+b')   
# read entire content of file into memory
f_content = f.read()
# basically match middle line and replace it with itself and the extra line
f_content = re.sub(r'(middle line)', r'\1\nnew line', f_content)
# return pointer to top of file so we can re-write the content with replaced string
f.seek(0)
# clear file content 
f.truncate()
# re-write the content with the updated content
f.write(f_content)
# close file
f.close()

Option 2) Figure out middle line, and replace it with that line plus the extra line.

# open file with r+b (allow write and binary mode)
f = open("file.log" , 'r+b')   
# get array of lines
f_content = f.readlines()
# get middle line
middle_line = len(f_content)/2
# overwrite middle line
f_content[middle_line] += "\nnew line"
# return pointer to top of file so we can re-write the content with replaced string
f.seek(0)
# clear file content 
f.truncate()
# re-write the content with the updated content
f.write(''.join(f_content))
# close file
f.close()

What do \t and \b do?

The C standard (actually C99, I'm not up to date) says:

Alphabetic escape sequences representing nongraphic characters in the execution character set are intended to produce actions on display devices as follows:

\b (backspace) Moves the active position to the previous position on the current line. [...]

\t (horizontal tab) Moves the active position to the next horizontal tabulation position on the current line. [...]

Both just move the active position, neither are supposed to write any character on or over another character. To overwrite with a space you could try: puts("foo\b \tbar"); but note that on some display devices - say a daisy wheel printer - the o will show the transparent space.

installing python packages without internet and using source code as .tar.gz and .whl

This is how I handle this case:

On the machine where I have access to Internet:

mkdir keystone-deps
pip download python-keystoneclient -d "/home/aviuser/keystone-deps"
tar cvfz keystone-deps.tgz keystone-deps

Then move the tar file to the destination machine that does not have Internet access and perform the following:

tar xvfz keystone-deps.tgz
cd keystone-deps
pip install python_keystoneclient-2.3.1-py2.py3-none-any.whl -f ./ --no-index

You may need to add --no-deps to the command as follows:

pip install python_keystoneclient-2.3.1-py2.py3-none-any.whl -f ./ --no-index --no-deps

Can't pickle <type 'instancemethod'> when using multiprocessing Pool.map()

There's another short-cut you can use, although it can be inefficient depending on what's in your class instances.

As everyone has said the problem is that the multiprocessing code has to pickle the things that it sends to the sub-processes it has started, and the pickler doesn't do instance-methods.

However, instead of sending the instance-method, you can send the actual class instance, plus the name of the function to call, to an ordinary function that then uses getattr to call the instance-method, thus creating the bound method in the Pool subprocess. This is similar to defining a __call__ method except that you can call more than one member function.

Stealing @EricH.'s code from his answer and annotating it a bit (I retyped it hence all the name changes and such, for some reason this seemed easier than cut-and-paste :-) ) for illustration of all the magic:

import multiprocessing
import os

def call_it(instance, name, args=(), kwargs=None):
    "indirect caller for instance methods and multiprocessing"
    if kwargs is None:
        kwargs = {}
    return getattr(instance, name)(*args, **kwargs)

class Klass(object):
    def __init__(self, nobj, workers=multiprocessing.cpu_count()):
        print "Constructor (in pid=%d)..." % os.getpid()
        self.count = 1
        pool = multiprocessing.Pool(processes = workers)
        async_results = [pool.apply_async(call_it,
            args = (self, 'process_obj', (i,))) for i in range(nobj)]
        pool.close()
        map(multiprocessing.pool.ApplyResult.wait, async_results)
        lst_results = [r.get() for r in async_results]
        print lst_results

    def __del__(self):
        self.count -= 1
        print "... Destructor (in pid=%d) count=%d" % (os.getpid(), self.count)

    def process_obj(self, index):
        print "object %d" % index
        return "results"

Klass(nobj=8, workers=3)

The output shows that, indeed, the constructor is called once (in the original pid) and the destructor is called 9 times (once for each copy made = 2 or 3 times per pool-worker-process as needed, plus once in the original process). This is often OK, as in this case, since the default pickler makes a copy of the entire instance and (semi-) secretly re-populates it—in this case, doing:

obj = object.__new__(Klass)
obj.__dict__.update({'count':1})

—that's why even though the destructor is called eight times in the three worker processes, it counts down from 1 to 0 each time—but of course you can still get into trouble this way. If necessary, you can provide your own __setstate__:

    def __setstate__(self, adict):
        self.count = adict['count']

in this case for instance.

Can the Android drawable directory contain subdirectories?

I've wrote an eclipse plugin which allows to create virtual subfolder by separating the file name with two underscores __. The project is in early stages, but don't worry it won't crash your IDE

more details can be found here, feel free to fork and send pull requests:

https://github.com/kirill578/Android-Sorted-Res-Folder

enter image description here

Regular expression which matches a pattern, or is an empty string

\b matches a word boundary. I think you can use ^$ for empty string.

Pure CSS to make font-size responsive based on dynamic amount of characters

I used smth like this:

1.style.fontSize = 15.6/(document.getElementById("2").innerHTML.length)+ 'vw'

Where: 1 - parent div Id and 2 - Id of div with my text

How to sort a NSArray alphabetically?

Another easy method to sort an array of strings consists by using the NSString description property this way:

NSSortDescriptor *valueDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"description" ascending:YES];
arrayOfSortedStrings = [arrayOfNotSortedStrings sortedArrayUsingDescriptors:@[valueDescriptor]];

Protecting cells in Excel but allow these to be modified by VBA script

Try using

Worksheet.Protect "Password", UserInterfaceOnly := True

If the UserInterfaceOnly parameter is set to true, VBA code can modify protected cells.

Android: How to create a Dialog without a title?

After a bunch of hacking, I got this to work:

            Window window = dialog.getWindow();
            View view = window.getDecorView();
            final int topPanelId = getResources().getIdentifier( "topPanel", "id", "android" );
            LinearLayout topPanel = (LinearLayout) view.findViewById(topPanelId);
            topPanel.setVisibility(View.GONE);

Using a scanner to accept String input and storing in a String Array

//go through this code I have made several changes in it//

import java.util.Scanner;

public class addContact {
public static void main(String [] args){

//declare arrays
String [] contactName = new String [12];
String [] contactPhone = new String [12];
String [] contactAdd1 = new String [12];
String [] contactAdd2 = new String [12];
int i=0;
String name = "0";
String phone = "0";
String add1 = "0";
String add2 = "0";
//method of taken input
Scanner input = new Scanner(System.in);

//while name field is empty display prompt etc.
while (i<11)
{
    i++;
System.out.println("Enter contacts name: "+ i);
name = input.nextLine();
name += contactName[i];
}


while (i<12)
{
    i++;
System.out.println("Enter contacts addressline1:");
add1 = input.nextLine();
add1 += contactAdd1[i];
}

while (i<12)
{
    i++;
System.out.println("Enter contacts addressline2:");
add2 = input.nextLine();
add2 += contactAdd2[i];
}

while (i<12)
{
    i++;
System.out.println("Enter contact phone number: ");
phone = input.nextLine();
phone += contactPhone[i];
}

}   
}

About "*.d.ts" in TypeScript

d stands for Declaration Files:

When a TypeScript script gets compiled there is an option to generate a declaration file (with the extension .d.ts) that functions as an interface to the components in the compiled JavaScript. In the process the compiler strips away all function and method bodies and preserves only the signatures of the types that are exported. The resulting declaration file can then be used to describe the exported virtual TypeScript types of a JavaScript library or module when a third-party developer consumes it from TypeScript.

The concept of declaration files is analogous to the concept of header file found in C/C++.

declare module arithmetics {
    add(left: number, right: number): number;
    subtract(left: number, right: number): number;
    multiply(left: number, right: number): number;
    divide(left: number, right: number): number;
}

Type declaration files can be written by hand for existing JavaScript libraries, as has been done for jQuery and Node.js.

Large collections of declaration files for popular JavaScript libraries are hosted on GitHub in DefinitelyTyped and the Typings Registry. A command-line utility called typings is provided to help search and install declaration files from the repositories.

How to get/generate the create statement for an existing hive table?

Steps to generate Create table DDLs for all the tables in the Hive database and export into text file to run later:

step 1)
create a .sh file with the below content, say hive_table_ddl.sh

#!/bin/bash
rm -f tableNames.txt
rm -f HiveTableDDL.txt
hive -e "use $1; show tables;" > tableNames.txt  
wait
cat tableNames.txt |while read LINE
   do
   hive -e "use $1;show create table $LINE;" >>HiveTableDDL.txt
   echo  -e "\n" >> HiveTableDDL.txt
   done
rm -f tableNames.txt
echo "Table DDL generated"

step 2)

Run the above shell script by passing 'db name' as paramanter

>bash hive_table_dd.sh <<databasename>>

output :

All the create table statements of your DB will be written into the HiveTableDDL.txt

Get data type of field in select statement in ORACLE

I found a not-very-intuitive way to do this by using DUMP()

SELECT DUMP(A.NAME), 
       DUMP(A.surname), 
       DUMP(B.ordernum) 
FROM   customer A 
       JOIN orders B 
         ON A.id = B.id

It will return something like:

'Typ=1 Len=2: 0,48' for each column.

Type=1 means VARCHAR2/NVARCHAR2
Type=2 means NUMBER/FLOAT
Type=12 means DATE, etc.

You can refer to this oracle doc for information Datatype Code
or this for a simple mapping Oracle Type Code Mappings

Select Specific Columns from Spark DataFrame

i liked dehasis approach, because it allowed me to select, rename and convert columns in one step. However I had to adjust it to make it work for me in PySpark:

from pyspark.sql.functions import col

spark.read.csv(path).select(
      col('_c0').alias("stn").cast('String'),
      col('_c1').alias("wban").cast('String'),
      col('_c2').alias("lat").cast('Double'),
      col('_c3').alias("lon").cast('Double')
    )
      .where('_c2.isNotNull && '_c3.isNotNull && '_c2 =!= 0.0 && '_c3 =!= 0.0)

wget: unable to resolve host address `http'

The DNS server seems out of order. You can use another DNS server such as 8.8.8.8. Put nameserver 8.8.8.8 to the first line of /etc/resolv.conf.

What issues should be considered when overriding equals and hashCode in Java?

One gotcha I have found is where two objects contain references to each other (one example being a parent/child relationship with a convenience method on the parent to get all children).
These sorts of things are fairly common when doing Hibernate mappings for example.

If you include both ends of the relationship in your hashCode or equals tests it's possible to get into a recursive loop which ends in a StackOverflowException.
The simplest solution is to not include the getChildren collection in the methods.

What's the fastest way to read a text file line-by-line?

There's a good topic about this in Stack Overflow question Is 'yield return' slower than "old school" return?.

It says:

ReadAllLines loads all of the lines into memory and returns a string[]. All well and good if the file is small. If the file is larger than will fit in memory, you'll run out of memory.

ReadLines, on the other hand, uses yield return to return one line at a time. With it, you can read any size file. It doesn't load the whole file into memory.

Say you wanted to find the first line that contains the word "foo", and then exit. Using ReadAllLines, you'd have to read the entire file into memory, even if "foo" occurs on the first line. With ReadLines, you only read one line. Which one would be faster?

Catch multiple exceptions at once?

I want to suggest shortest answer (one more functional style):

        Catch<FormatException, OverflowException>(() =>
            {
                WebId = new Guid(queryString["web"]);
            },
            exception =>
            {
                WebId = Guid.Empty;
            });

For this you need to create several "Catch" method overloads, similar to System.Action:

    [DebuggerNonUserCode]
    public static void Catch<TException1, TException2>(Action tryBlock,
        Action<Exception> catchBlock)
    {
        CatchMany(tryBlock, catchBlock, typeof(TException1), typeof(TException2));
    }

    [DebuggerNonUserCode]
    public static void Catch<TException1, TException2, TException3>(Action tryBlock,
        Action<Exception> catchBlock)
    {
        CatchMany(tryBlock, catchBlock, typeof(TException1), typeof(TException2), typeof(TException3));
    }

and so on as many as you wish. But you need to do it once and you can use it in all your projects (or, if you created a nuget package we could use it too).

And CatchMany implementation:

    [DebuggerNonUserCode]
    public static void CatchMany(Action tryBlock, Action<Exception> catchBlock,
        params Type[] exceptionTypes)
    {
        try
        {
            tryBlock();
        }
        catch (Exception exception)
        {
            if (exceptionTypes.Contains(exception.GetType())) catchBlock(exception);
            else throw;
        }
    }

p.s. I haven't put null checks for code simplicity, consider to add parameter validations.

p.s.2 If you want to return a value from the catch, it's necessary to do same Catch methods, but with returns and Func instead of Action in parameters.

Convert a date format in epoch

Create Common Method to Convert String to Date format

public static void main(String[] args) throws Exception {
    long test = ConvertStringToDate("May 26 10:41:23", "MMM dd hh:mm:ss");
    long test2 = ConvertStringToDate("Tue, Jun 06 2017, 12:30 AM", "EEE, MMM dd yyyy, hh:mm a");
    long test3 = ConvertStringToDate("Jun 13 2003 23:11:52.454 UTC", "MMM dd yyyy HH:mm:ss.SSS zzz");
}

private static long ConvertStringToDate(String dateString, String format) {
    try {
        return new SimpleDateFormat(format).parse(dateString).getTime();
    } catch (ParseException e) {}
    return 0;
}

How to pass argument to Makefile from command line?

You probably shouldn't do this; you're breaking the basic pattern of how Make works. But here it is:

action:
        @echo action $(filter-out $@,$(MAKECMDGOALS))

%:      # thanks to chakrit
    @:    # thanks to William Pursell

EDIT:
To explain the first command,

$(MAKECMDGOALS) is the list of "targets" spelled out on the command line, e.g. "action value1 value2".

$@ is an automatic variable for the name of the target of the rule, in this case "action".

filter-out is a function that removes some elements from a list. So $(filter-out bar, foo bar baz) returns foo baz (it can be more subtle, but we don't need subtlety here).

Put these together and $(filter-out $@,$(MAKECMDGOALS)) returns the list of targets specified on the command line other than "action", which might be "value1 value2".

Access parent's parent from javascript object

If I'm reading your question correctly, objects in general are agnostic about where they are contained. They don't know who their parents are. To find that information, you have to parse the parent data structure. The DOM has ways of doing this for us when you're talking about element objects in a document, but it looks like you're talking about vanilla objects.

Return value from a VBScript function

To return a value from a VBScript function, assign the value to the name of the function, like this:

Function getNumber
    getNumber = "423"
End Function

CSS z-index not working (position absolute)

I solved my z-index problem by making the body wrapper z-index:-1 and the body z-index:-2, and the other divs z-index:1.

And then the later divs didn't work unless I had z-index 200+. Even though I had position:relative on each element, with the body at default z-index it wouldn't work.

Hope this helps somebody.

How to get the error message from the error code returned by GetLastError()?

GetLastError returns a numerical error code. To obtain a descriptive error message (e.g., to display to a user), you can call FormatMessage:

// This functions fills a caller-defined character buffer (pBuffer)
// of max length (cchBufferLength) with the human-readable error message
// for a Win32 error code (dwErrorCode).
// 
// Returns TRUE if successful, or FALSE otherwise.
// If successful, pBuffer is guaranteed to be NUL-terminated.
// On failure, the contents of pBuffer are undefined.
BOOL GetErrorMessage(DWORD dwErrorCode, LPTSTR pBuffer, DWORD cchBufferLength)
{
    if (cchBufferLength == 0)
    {
        return FALSE;
    }

    DWORD cchMsg = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
                                 NULL,  /* (not used with FORMAT_MESSAGE_FROM_SYSTEM) */
                                 dwErrorCode,
                                 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
                                 pBuffer,
                                 cchBufferLength,
                                 NULL);
    return (cchMsg > 0);
}

In C++, you can simplify the interface considerably by using the std::string class:

#include <Windows.h>
#include <system_error>
#include <memory>
#include <string>
typedef std::basic_string<TCHAR> String;

String GetErrorMessage(DWORD dwErrorCode)
{
    LPTSTR psz{ nullptr };
    const DWORD cchMsg = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM
                                         | FORMAT_MESSAGE_IGNORE_INSERTS
                                         | FORMAT_MESSAGE_ALLOCATE_BUFFER,
                                       NULL, // (not used with FORMAT_MESSAGE_FROM_SYSTEM)
                                       dwErrorCode,
                                       MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
                                       reinterpret_cast<LPTSTR>(&psz),
                                       0,
                                       NULL);
    if (cchMsg > 0)
    {
        // Assign buffer to smart pointer with custom deleter so that memory gets released
        // in case String's c'tor throws an exception.
        auto deleter = [](void* p) { ::LocalFree(p); };
        std::unique_ptr<TCHAR, decltype(deleter)> ptrBuffer(psz, deleter);
        return String(ptrBuffer.get(), cchMsg);
    }
    else
    {
        auto error_code{ ::GetLastError() };
        throw std::system_error( error_code, std::system_category(),
                                 "Failed to retrieve error message string.");
    }
}

NOTE: These functions also work for HRESULT values. Just change the first parameter from DWORD dwErrorCode to HRESULT hResult. The rest of the code can remain unchanged.


These implementations provide the following improvements over the existing answers:

  • Complete sample code, not just a reference to the API to call.
  • Provides both C and C++ implementations.
  • Works for both Unicode and MBCS project settings.
  • Takes the error code as an input parameter. This is important, as a thread's last error code is only valid at well defined points. An input parameter allows the caller to follow the documented contract.
  • Implements proper exception safety. Unlike all of the other solutions that implicitly use exceptions, this implementation will not leak memory in case an exception is thrown while constructing the return value.
  • Proper use of the FORMAT_MESSAGE_IGNORE_INSERTS flag. See The importance of the FORMAT_MESSAGE_IGNORE_INSERTS flag for more information.
  • Proper error handling/error reporting, unlike some of the other answers, that silently ignore errors.


This answer has been incorporated from Stack Overflow Documentation. The following users have contributed to the example: stackptr, Ajay, Cody Gray?, IInspectable.

How to enter a series of numbers automatically in Excel

Enter the formula =ROW() into any cell and that cell will show the row number as its value.

If you want 1001, 1002 etc just enter =1000+ROW()

Difference between object and class in Scala

A class is a definition, a description. It defines a type in terms of methods and composition of other types.

An object is a singleton -- an instance of a class which is guaranteed to be unique. For every object in the code, an anonymous class is created, which inherits from whatever classes you declared object to implement. This class cannot be seen from Scala source code -- though you can get at it through reflection.

There is a relationship between object and class. An object is said to be the companion-object of a class if they share the same name. When this happens, each has access to methods of private visibility in the other. These methods are not automatically imported, though. You either have to import them explicitly, or prefix them with the class/object name.

For example:

class X {
  // class X can see private members of object X
  // Prefix to call
  def m(x: Int) = X.f(x)

  // Import and use
  import X._
  def n(x: Int) = f(x)

  private def o = 2
}

object X {
  private def f(x: Int) = x * x

  // object X can see private members of class X
  def g(x: X) = {
    import x._
    x.o * o // fully specified and imported
   }
}

Do something if screen width is less than 960 px

You might want to combine it with a resize event:

 $(window).resize(function() {
  if ($(window).width() < 960) {
     alert('Less than 960');
  }
 else {
    alert('More than 960');
 }
});

For R.J.:

var eventFired = 0;

if ($(window).width() < 960) {
    alert('Less than 960');

}
else {
    alert('More than 960');
    eventFired = 1;
}

$(window).on('resize', function() {
    if (!eventFired) {
        if ($(window).width() < 960) {
            alert('Less than 960 resize');
        } else {
            alert('More than 960 resize');
        }
    }
});

I tried http://api.jquery.com/off/ with no success so I went with the eventFired flag.

formatFloat : convert float number to string

Try this

package main

import "fmt"
import "strconv"

func FloatToString(input_num float64) string {
    // to convert a float number to a string
    return strconv.FormatFloat(input_num, 'f', 6, 64)
}

func main() {
    fmt.Println(FloatToString(21312421.213123))
}

If you just want as many digits precision as possible, then the special precision -1 uses the smallest number of digits necessary such that ParseFloat will return f exactly. Eg

strconv.FormatFloat(input_num, 'f', -1, 64)

Personally I find fmt easier to use. (Playground link)

fmt.Printf("x = %.6f\n", 21312421.213123)

Or if you just want to convert the string

fmt.Sprintf("%.6f", 21312421.213123)

VB.net: Date without time

FormatDateTime(Now, DateFormat.ShortDate)

Accessing JPEG EXIF rotation data in JavaScript on the client side

If you only want the orientation tag and nothing else and don't like to include another huge javascript library I wrote a little code that extracts the orientation tag as fast as possible (It uses DataView and readAsArrayBuffer which are available in IE10+, but you can write your own data reader for older browsers):

_x000D_
_x000D_
function getOrientation(file, callback) {_x000D_
    var reader = new FileReader();_x000D_
    reader.onload = function(e) {_x000D_
_x000D_
        var view = new DataView(e.target.result);_x000D_
        if (view.getUint16(0, false) != 0xFFD8)_x000D_
        {_x000D_
            return callback(-2);_x000D_
        }_x000D_
        var length = view.byteLength, offset = 2;_x000D_
        while (offset < length) _x000D_
        {_x000D_
            if (view.getUint16(offset+2, false) <= 8) return callback(-1);_x000D_
            var marker = view.getUint16(offset, false);_x000D_
            offset += 2;_x000D_
            if (marker == 0xFFE1) _x000D_
            {_x000D_
                if (view.getUint32(offset += 2, false) != 0x45786966) _x000D_
                {_x000D_
                    return callback(-1);_x000D_
                }_x000D_
_x000D_
                var little = view.getUint16(offset += 6, false) == 0x4949;_x000D_
                offset += view.getUint32(offset + 4, little);_x000D_
                var tags = view.getUint16(offset, little);_x000D_
                offset += 2;_x000D_
                for (var i = 0; i < tags; i++)_x000D_
                {_x000D_
                    if (view.getUint16(offset + (i * 12), little) == 0x0112)_x000D_
                    {_x000D_
                        return callback(view.getUint16(offset + (i * 12) + 8, little));_x000D_
                    }_x000D_
                }_x000D_
            }_x000D_
            else if ((marker & 0xFF00) != 0xFF00)_x000D_
            {_x000D_
                break;_x000D_
            }_x000D_
            else_x000D_
            { _x000D_
                offset += view.getUint16(offset, false);_x000D_
            }_x000D_
        }_x000D_
        return callback(-1);_x000D_
    };_x000D_
    reader.readAsArrayBuffer(file);_x000D_
}_x000D_
_x000D_
// usage:_x000D_
var input = document.getElementById('input');_x000D_
input.onchange = function(e) {_x000D_
    getOrientation(input.files[0], function(orientation) {_x000D_
        alert('orientation: ' + orientation);_x000D_
    });_x000D_
}
_x000D_
<input id='input' type='file' />
_x000D_
_x000D_
_x000D_

values:

-2: not jpeg
-1: not defined

enter image description here

For those using Typescript, you can use the following code:

export const getOrientation = (file: File, callback: Function) => {
  var reader = new FileReader();

  reader.onload = (event: ProgressEvent) => {

    if (! event.target) {
      return;
    }

    const file = event.target as FileReader;
    const view = new DataView(file.result as ArrayBuffer);

    if (view.getUint16(0, false) != 0xFFD8) {
        return callback(-2);
    }

    const length = view.byteLength
    let offset = 2;

    while (offset < length)
    {
        if (view.getUint16(offset+2, false) <= 8) return callback(-1);
        let marker = view.getUint16(offset, false);
        offset += 2;

        if (marker == 0xFFE1) {
          if (view.getUint32(offset += 2, false) != 0x45786966) {
            return callback(-1);
          }

          let little = view.getUint16(offset += 6, false) == 0x4949;
          offset += view.getUint32(offset + 4, little);
          let tags = view.getUint16(offset, little);
          offset += 2;
          for (let i = 0; i < tags; i++) {
            if (view.getUint16(offset + (i * 12), little) == 0x0112) {
              return callback(view.getUint16(offset + (i * 12) + 8, little));
            }
          }
        } else if ((marker & 0xFF00) != 0xFF00) {
            break;
        }
        else {
            offset += view.getUint16(offset, false);
        }
    }
    return callback(-1);
  };

  reader.readAsArrayBuffer(file);
}

How can I strip first and last double quotes?

If string is always as you show:

string[1:-1]

Javascript Array inside Array - how can I call the child array name?

There is no way to know that the two members of the options array came from variables named size and color.

They are also not necessarily called that exclusively, any variable could also point to that array.

var notSize = size;

console.log(options[0]); // It is `size` or `notSize`?

One thing you can do is use an object there instead...

var options = {
    size: size,
    color: color
}

Then you could access options.size or options.color.

Disabling buttons on react native

This seems like the kind of thing that could be solved using a Higher Order Component. I could be wrong though because I'm struggling to understand it 100% myself, but maybe it'll be helpful to you (here's a couple links)...

SQLite select where empty?

There are several ways, like:

where some_column is null or some_column = ''

or

where ifnull(some_column, '') = ''

or

where coalesce(some_column, '') = ''

of

where ifnull(length(some_column), 0) = 0

How to deploy a war file in Tomcat 7

1.Generate a war file from your application
2. open tomcat manager, go down the page
3. Click on browse to deploy the war.
4. choose your war file. There you go!

How can I read the client's machine/computer name from the browser?

Well you could get the ip address using asp.net, then do a reverse DNS lookup on the ip to get the hostname.

From the ASP.NET Developer's cookbook ... Performing a Reverse-DNS Lookup.

Custom date format with jQuery validation plugin

You can create your own custom validation method using the addMethod function. Say you wanted to validate "dd/mm/yyyy":

$.validator.addMethod(
    "australianDate",
    function(value, element) {
        // put your own logic here, this is just a (crappy) example
        return value.match(/^\d\d?\/\d\d?\/\d\d\d\d$/);
    },
    "Please enter a date in the format dd/mm/yyyy."
);

And then on your form add:

$('#myForm')
    .validate({
        rules : {
            myDate : {
                australianDate : true
            }
        }
    })
;

Oracle: Import CSV file

From Oracle 18c you could use Inline External Tables:

Inline external tables enable the runtime definition of an external table as part of a SQL statement, without creating the external table as persistent object in the data dictionary.

With inline external tables, the same syntax that is used to create an external table with a CREATE TABLE statement can be used in a SELECT statement at runtime. Specify inline external tables in the FROM clause of a query block. Queries that include inline external tables can also include regular tables for joins, aggregation, and so on.

INSERT INTO target_table(time_id, prod_id, quantity_sold, amount_sold)
SELECT time_id, prod_id, quantity_sold, amount_sold
FROM   EXTERNAL (   
    (time_id        DATE NOT NULL,     
     prod_id        INTEGER NOT NULL,
     quantity_sold  NUMBER(10,2),
     amount_sold    NUMBER(10,2))     
    TYPE ORACLE_LOADER     
    DEFAULT DIRECTORY data_dir1
    ACCESS PARAMETERS (
      RECORDS DELIMITED BY NEWLINE
      FIELDS TERMINATED BY '|')     
   LOCATION ('sales_9.csv') REJECT LIMIT UNLIMITED) sales_external;

How to work with string fields in a C struct?

I think this solution uses less code and is easy to understand even for newbie.

For string field in struct, you can use pointer and reassigning the string to that pointer will be straightforward and simpler.

Define definition of struct:

typedef struct {
  int number;
  char *name;
  char *address;
  char *birthdate;
  char gender;
} Patient;

Initialize variable with type of that struct:

Patient patient;
patient.number = 12345;
patient.address = "123/123 some road Rd.";
patient.birthdate = "2020/12/12";
patient.gender = "M";

It is that simple. Hope this answer helps many developers.

GROUP_CONCAT comma separator - MySQL

Looks like you're missing the SEPARATOR keyword in the GROUP_CONCAT function.

GROUP_CONCAT(artists.artistname SEPARATOR '----')

The way you've written it, you're concatenating artists.artistname with the '----' string using the default comma separator.

What is default color for text in textview?

Actually the color TextView is:

android:textColor="@android:color/tab_indicator_text"

or

#808080

R define dimensions of empty data frame

It might help the solution given in another forum, Basically is: i.e.

Cols <- paste("A", 1:5, sep="")
DF <- read.table(textConnection(""), col.names = Cols,colClasses = "character")

> str(DF)
'data.frame':   0 obs. of  5 variables:
$ A1: chr
$ A2: chr
$ A3: chr
$ A4: chr
$ A5: chr

You can change the colClasses to fit your needs.

Original link is https://stat.ethz.ch/pipermail/r-help/2008-August/169966.html

Where to find "Microsoft.VisualStudio.TestTools.UnitTesting" missing dll?

I got this problem after moving a project and deleting it's packages folder. Nuget was showning that MSTest.TestAdapter and MSTest.TestFramework v 1.3.2 was installed. The fix seemed to be to open VS as administrator and build After that I was able to re-open and build without having admin priviledge.

Get all messages from Whatsapp

Yes, it must be ways to get msgs from WhatsApp, since there are some tools available on the market help WhatsApp users to backup WhatsApp chat history to their computer, I know this from here. Therefore, you must be able to implement such kind of app. Maybe you can find these tool on the market to see how they work.

Could not find the main class, program will exit

Ha, I found what the problem was. I made my program using jdk1.7, but I had jre6 installed. I went and upgraded to jre7, and now it works fine :)

The

java -jar jarname.jar

line was working in the command prompt because my java path was set to the jdk folder.

Why is the Android emulator so slow? How can we speed up the Android emulator?

Emulators are slow. There's really nothing you can do about it, but there are alternatives to the emulator.

  1. Genymotion - Preferred

  2. VirtualBox

  3. BlueStacks

  4. YouWave

  5. Windows Android Emulator

  6. Jar of Beans

  7. Andy

To make your emulator faster, you can host a GPU and use a lighter Android version (Android 2.3 (Gingerbread)). Developing on a Mac would be better. Why use an emulator, BTW? Using a real phone makes more sense.

How to convert an int value to string in Go?

It is interesting to note that strconv.Itoa is shorthand for

func FormatInt(i int64, base int) string

with base 10

For Example:

strconv.Itoa(123)

is equivalent to

strconv.FormatInt(int64(123), 10)

Search code inside a Github project

While @VonC's answer works for some repositories, unfortunately for many repositories you can't right now. Github is simply not indexing them (as commented originally by @emddudley). They haven't stated this anywhere on their website, but they will tell you if you ask support:

From: Tim Pease
We have stopped adding newly pushed code into our codesearch index. The volume of code has outgrown our current search index, and we are working on moving to a more scalable search architecture. I'm sorry for the annoyance. We do not have an estimate for when this new search index will be up and running, but when it is ready a blog post will be published (https://github.com/blog).

Annoyingly there is no way to tell which repositories are not indexed other than the lack of results (which also could be from a bad query).

There also is no way to track this issue other than waiting for them to blog it (or watching here on SO).

From: Tim Pease
I am afraid our issue tracker is internal, but we can notify you as soon as the new search index is up and running.

How to set a primary key in MongoDB?

One way of achieving this behaviour is by setting the value to _id (which is reserved for a primary key in MongoDB) field based on the custom fields you want to treat as primary key.
i.e. If I want employee_id as the primary key then at the time of creating document in MongoDB; assign _id value same as that of employee_id.

Split string, convert ToList<int>() in one line

On Unity3d, int.Parse doesn't work well. So I use like bellow.

List<int> intList = new List<int>( Array.ConvertAll(sNumbers.Split(','),
 new Converter<string, int>((s)=>{return Convert.ToInt32(s);}) ) );

Hope this help for Unity3d Users.

Create table in SQLite only if it doesn't exist already

From http://www.sqlite.org/lang_createtable.html:

CREATE TABLE IF NOT EXISTS some_table (id INTEGER PRIMARY KEY AUTOINCREMENT, ...);

Android: where are downloaded files saved?

In my experience all the files which i have downloaded from internet,gmail are stored in

/sdcard/download

on ics

/sdcard/Download

You can access it using

Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);

Global variables in Java

Understanding the problem

I consider the qualification of global variable as a variable that could be accessed and changed anywhere in the code without caring about static/instance call or passing any reference from one class to another.

Usually if you have class A

public class A {
    private int myVar;

    public A(int myVar) {
        this.myVar = myVar;
    }

    public int getMyVar() {
        return myVar;
    }

    public void setMyVar(int mewVar) {
        this.myVar = newVar;
    }
}

and want to access and update myvar in a class B,

public class B{

    private A a;

    public void passA(A a){
        this.a = a;
    }

    public void changeMyVar(int newVar){
        a.setMyvar(newVar);
    }
}

you will need to have a reference of an instance of the class A and update the value in the class B like this:

int initialValue = 2;
int newValue = 3;
A a = new A(initialValue);
B b = new B();
b.passA(a);
b.changeMyVar(newValue);
assertEquals(a.getMyVar(),newValue); // true

Solution

So my solution to this, (even if i'm not sure if it's a good practice), is to use a singleton:


public class Globals {
    private static Globals globalsInstance = new Globals();

    public static Globals getInstance() {
        return globalsInstance;
    }

    private int myVar = 2;

    private Globals() {
    }

    public int getMyVar() {
        return myVar;
    }

    public void setMyVar(int myVar) {
        this.myVar = myVar;
    }
}

Now you can get the Global unique instance anywhere with:

Globals globals = Globals.getInstance();
// and read and write to myVar with the getter and setter like 
int myVar = globals.getMyVar();
global.setMyVar(3);

add elements to object array

You can try

Subject[] subjects = new Subject[2];
subjects[0] = new Subject{....};
subjects[1] = new Subject{....};

alternatively you can use List

List<Subject> subjects = new List<Subject>();
subjects.add(new Subject{....});
subjects.add(new Subject{....});

Check string for palindrome

Go, Java:

public boolean isPalindrome (String word) {
    String myWord = word.replaceAll("\\s+","");
    String reverse = new StringBuffer(myWord).reverse().toString();
    return reverse.equalsIgnoreCase(myWord);
}

isPalindrome("Never Odd or Even"); // True
isPalindrome("Never Odd or Even1"); // False

Modular multiplicative inverse function in Python

You might also want to look at the gmpy module. It is an interface between Python and the GMP multiple-precision library. gmpy provides an invert function that does exactly what you need:

>>> import gmpy
>>> gmpy.invert(1234567, 1000000007)
mpz(989145189)

Updated answer

As noted by @hyh , the gmpy.invert() returns 0 if the inverse does not exist. That matches the behavior of GMP's mpz_invert() function. gmpy.divm(a, b, m) provides a general solution to a=bx (mod m).

>>> gmpy.divm(1, 1234567, 1000000007)
mpz(989145189)
>>> gmpy.divm(1, 0, 5)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: not invertible
>>> gmpy.divm(1, 4, 8)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: not invertible
>>> gmpy.divm(1, 4, 9)
mpz(7)

divm() will return a solution when gcd(b,m) == 1 and raises an exception when the multiplicative inverse does not exist.

Disclaimer: I'm the current maintainer of the gmpy library.

Updated answer 2

gmpy2 now properly raises an exception when the inverse does not exists:

>>> import gmpy2

>>> gmpy2.invert(0,5)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: invert() no inverse exists

Writing Unicode text to a text file?

In case of writing in python3

>>> a = u'bats\u00E0'
>>> print a
batsĂ 
>>> f = open("/tmp/test", "w")
>>> f.write(a)
>>> f.close()
>>> data = open("/tmp/test").read()
>>> data
'batsĂ '

In case of writing in python2:

>>> a = u'bats\u00E0'
>>> f = open("/tmp/test", "w")
>>> f.write(a)

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe0' in position 4: ordinal not in range(128)

To avoid this error you would have to encode it to bytes using codecs "utf-8" like this:

>>> f.write(a.encode("utf-8"))
>>> f.close()

and decode the data while reading using the codecs "utf-8":

>>> data = open("/tmp/test").read()
>>> data.decode("utf-8")
u'bats\xe0'

And also if you try to execute print on this string it will automatically decode using the "utf-8" codecs like this

>>> print a
batsĂ 

JUNIT Test class in Eclipse - java.lang.ClassNotFoundException

This happened to me when I was dragging and dropping test classes to different packages. I just did the following

  1. Saved the class in a text editor.
  2. Deleted the offending class from eclipse project explorer.
  3. Re-created the class.

Bingo! I can now run the test!

Why write <script type="text/javascript"> when the mime type is set by the server?

It allows browsers to determine if they can handle the scripting/style language before making a request for the script or stylesheet (or, in the case of embedded script/style, identify which language is being used).

This would be much more important if there had been more competition among languages in browser space, but VBScript never made it beyond IE and PerlScript never made it beyond an IE specific plugin while JSSS was pretty rubbish to begin with.

The draft of HTML5 makes the attribute optional.

warning: Insecure world writable dir /usr/local/bin in PATH, mode 040777

I have had the same issue in OSX. It can be fixed by running Disk Utilities to Repair Permissions. I agree with Peter Nixey: in my case it is caused when my 3G dongle installs or reinstalls its driver. Repairing Permissions afterward fixes the issue.

Matplotlib scatter plot with different text at each data point

You may also use pyplot.text (see here).

def plot_embeddings(M_reduced, word2Ind, words):
    """ 
        Plot in a scatterplot the embeddings of the words specified in the list "words".
        Include a label next to each point.
    """
    for word in words:
        x, y = M_reduced[word2Ind[word]]
        plt.scatter(x, y, marker='x', color='red')
        plt.text(x+.03, y+.03, word, fontsize=9)
    plt.show()

M_reduced_plot_test = np.array([[1, 1], [-1, -1], [1, -1], [-1, 1], [0, 0]])
word2Ind_plot_test = {'test1': 0, 'test2': 1, 'test3': 2, 'test4': 3, 'test5': 4}
words = ['test1', 'test2', 'test3', 'test4', 'test5']
plot_embeddings(M_reduced_plot_test, word2Ind_plot_test, words)

enter image description here

How can I change the Y-axis figures into percentages in a barplot?

ggplot2 and scales packages can do that:

y <- c(12, 20)/100
x <- c(1, 2)

library(ggplot2)
library(scales)
myplot <- qplot(as.factor(x), y, geom="bar")
myplot + scale_y_continuous(labels=percent)

It seems like the stat() option has been taken off, causing the error message. Try this:

library(scales)

myplot <- ggplot(mtcars, aes(factor(cyl))) + 
          geom_bar(aes(y = (..count..)/sum(..count..))) + 
          scale_y_continuous(labels=percent)

myplot

What is the height of Navigation Bar in iOS 7?

There is a difference between the navigation bar and the status bar. The confusing part is that it looks like one solid feature at the top of the screen, but the areas can actually be separated into two distinct views; a status bar and a navigation bar. The status bar spans from y=0 to y=20 points and the navigation bar spans from y=20 to y=64 points. So the navigation bar (which is where the page title and navigation buttons go) has a height of 44 points, but the status bar and navigation bar together have a total height of 64 points.

Here is a great resource that addresses this question along with a number of other sizing idiosyncrasies in iOS7: http://ivomynttinen.com/blog/the-ios-7-design-cheat-sheet/

Flutter: RenderBox was not laid out

I had a simmilar problem, but in my case I was put a row in the leading of the Listview, and it was consumming all the space, of course. I just had to take the Row out of the leading, and it was solved. I would recomend to check if the problem is a widget larger than its containner can have.

How to pass parameters to a modal?

Alternatively you can create a new scope and pass through params via the scope option

var scope = $rootScope.$new();
 scope.params = {editId: $scope.editId};
    $modal.open({
        scope: scope,
        templateUrl: 'template.html',
        controller: 'Controller',
    });

In your modal controller pass in $scope, you then do not need to pass in and itemsProvider or what ever resolve you named it

modalController = function($scope) {
    console.log($scope.params)
}

Java keytool easy way to add server cert from url/port

There were a few ways I found to do this:

    java InstallCert [host]:[port] 
    keytool -exportcert -keystore jssecacerts -storepass changeit -file output.cert
    keytool -importcert -keystore [DESTINATION_KEYSTORE] -file output.cert

pod has unbound PersistentVolumeClaims

You have to define a PersistentVolume providing disc space to be consumed by the PersistentVolumeClaim.

When using storageClass Kubernetes is going to enable "Dynamic Volume Provisioning" which is not working with the local file system.


To solve your issue:

  • Provide a PersistentVolume fulfilling the constraints of the claim (a size >= 100Mi)
  • Remove the storageClass-line from the PersistentVolumeClaim
  • Remove the StorageClass from your cluster

How do these pieces play together?

At creation of the deployment state-description it is usually known which kind (amount, speed, ...) of storage that application will need.
To make a deployment versatile you'd like to avoid a hard dependency on storage. Kubernetes' volume-abstraction allows you to provide and consume storage in a standardized way.

The PersistentVolumeClaim is used to provide a storage-constraint alongside the deployment of an application.

The PersistentVolume offers cluster-wide volume-instances ready to be consumed ("bound"). One PersistentVolume will be bound to one claim. But since multiple instances of that claim may be run on multiple nodes, that volume may be accessed by multiple nodes.

A PersistentVolume without StorageClass is considered to be static.

"Dynamic Volume Provisioning" alongside with a StorageClass allows the cluster to provision PersistentVolumes on demand. In order to make that work, the given storage provider must support provisioning - this allows the cluster to request the provisioning of a "new" PersistentVolume when an unsatisfied PersistentVolumeClaim pops up.


Example PersistentVolume

In order to find how to specify things you're best advised to take a look at the API for your Kubernetes version, so the following example is build from the API-Reference of K8S 1.17:

apiVersion: v1
kind: PersistentVolume
metadata:
  name: ckan-pv-home
  labels:
    type: local
spec:
  capacity:
    storage: 100Mi
  hostPath:
    path: "/mnt/data/ckan"

The PersistentVolumeSpec allows us to define multiple attributes. I chose a hostPath volume which maps a local directory as content for the volume. The capacity allows the resource scheduler to recognize this volume as applicable in terms of resource needs.


Additional Resources:

"Find next" in Vim

The most useful shortcut in Vim, IMHO, is the * key.

Put the cursor on a word and hit the * key and you will jump to the next instance of that word.

The # key does the same, but it jumps to the previous instance of the word.

It is truly a time saver.

TempData keep() vs peek()

TempData is also a dictionary object that stays for the time of an HTTP Request. So, TempData can be used to maintain data between one controller action to the other controller action.

TempData is used to check the null values each time. TempData contain two method keep() and peek() for maintain data state from one controller action to others.

When TempDataDictionary object is read, At the end of request marks as deletion to current read object.

The keep() and peek() method is used to read the data without deletion the current read object.

You can use Peek() when you always want to hold/prevent the value for another request. You can use Keep() when prevent/hold the value depends on additional logic.

Overloading in TempData.Peek() & TempData.Keep() as given below.

TempData.Keep() have 2 overloaded methods.

  1. void keep() : That menace all the data not deleted on current request completion.

  2. void keep(string key) : persist the specific item in TempData with help of name.

TempData.Peek() no overloaded methods.

  1. object peek(string key) : return an object that contain items with specific key without making key for deletion.

Example for return type of TempData.Keep() & TempData.Peek() methods as given below.

public void Keep(string key) { _retainedKeys.Add(key); }

public object Peek(string key) { object value = values; return value; }

How to find a parent with a known class in jQuery?

Use .parentsUntil()

$(".d").parentsUntil(".a");

How to prevent page from reloading after form submit - JQuery

The <button> element, when placed in a form, will submit the form automatically unless otherwise specified. You can use the following 2 strategies:

  1. Use <button type="button"> to override default submission behavior
  2. Use event.preventDefault() in the onSubmit event to prevent form submission

Solution 1:

  • Advantage: simple change to markup
  • Disadvantage: subverts default form behavior, especially when JS is disabled. What if the user wants to hit "enter" to submit?

Insert extra type attribute to your button markup:

<button id="button" type="button" value="send" class="btn btn-primary">Submit</button>

Solution 2:

  • Advantage: form will work even when JS is disabled, and respects standard form UI/UX such that at least one button is used for submission

Prevent default form submission when button is clicked. Note that this is not the ideal solution because you should be in fact listening to the submit event, not the button click event:

$(document).ready(function () {
  // Listen to click event on the submit button
  $('#button').click(function (e) {

    e.preventDefault();

    var name = $("#name").val();
    var email = $("#email").val();

    $.post("process.php", {
      name: name,
      email: email
    }).complete(function() {
        console.log("Success");
      });
  });
});

Better variant:

In this improvement, we listen to the submit event emitted from the <form> element:

$(document).ready(function () {
  // Listen to submit event on the <form> itself!
  $('#main').submit(function (e) {

    e.preventDefault();

    var name = $("#name").val();
    var email = $("#email").val();

    $.post("process.php", {
      name: name,
      email: email
    }).complete(function() {
        console.log("Success");
      });
  });
});

Even better variant: use .serialize() to serialize your form, but remember to add name attributes to your input:

The name attribute is required for .serialize() to work, as per jQuery's documentation:

For a form element's value to be included in the serialized string, the element must have a name attribute.

<input type="text" id="name" name="name" class="form-control mb-2 mr-sm-2 mb-sm-0" id="inlineFormInput" placeholder="Jane Doe">
<input type="text" id="email" name="email" class="form-control" id="inlineFormInputGroup" placeholder="[email protected]">

And then in your JS:

$(document).ready(function () {
  // Listen to submit event on the <form> itself!
  $('#main').submit(function (e) {

    // Prevent form submission which refreshes page
    e.preventDefault();

    // Serialize data
    var formData = $(this).serialize();

    // Make AJAX request
    $.post("process.php", formData).complete(function() {
      console.log("Success");
    });
  });
});

Keyboard shortcut to "untab" (move a block of code to the left) in eclipse / aptana?

This workaround works most of the time. It uses eclipse's 'smart insert' features instead:

  1. Control X to erase the selected block of text, and keep it for pasting.
  2. Control+Shift Enter, to open a new line for editing above the one you are at.
  3. You might want to adjust the tabbing position at this point. This is where tabbing will start, unless you are at the beginning of the line.
  4. Control V to paste back the buffer.

Hope this helps until Shift+TAB is implemented in Eclipse.

Why can't I make a vector of references?

By their very nature, references can only be set at the time they are created; i.e., the following two lines have very different effects:

int & A = B;   // makes A an alias for B
A = C;         // assigns value of C to B.

Futher, this is illegal:

int & D;       // must be set to a int variable.

However, when you create a vector, there is no way to assign values to it's items at creation. You are essentially just making a whole bunch of the last example.

Can't use Swift classes inside Objective-C

XCode 11.3.1:

When I want to use an Swift inner class in a objc code, it does not compile for ther error "undefined symbol"(for bother inner class and outer class), I checked the generated "-swift.h" header and both classes are there.

After trying for hours I convert the inner class to a normal class and it compiles.

I clean the project, delete the DerivedData folder and it compiles.

How to get Locale from its String representation in Java?

If you are using Spring framework in your project you can also use:

org.springframework.util.StringUtils.parseLocaleString("en_US");

Documentation:

Parse the given String representation into a Locale

insert a NOT NULL column to an existing table

Alter TABLE 'TARGET' add 'ShouldAddColumn' Integer Not Null default "0"

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)

Installing mysql-server solved the issue

sudo apt-get install mysql-server

Assign JavaScript variable to Java Variable in JSP

As JavaScript is client side and JSP is Server side.

So Javascript does not execute until it gets to the browser, But Java executes on the server. So, Java does not know the value of the JavaScript variable.

However you assign value of Java variable to JavaScript variable.

Detect Close windows event by jQuery

There is no specific event for capturing browser close event. But we can detect by the browser positions XY.

<script type="text/javascript">
$(document).ready(function() {
  $(document).mousemove(function(e) {
    if(e.pageY <= 5)
    {
        //this condition would occur when the user brings their cursor on address bar 
        //do something here 
    }
  });
});
</script>

how to overwrite css style

You can create one more class naming

.flex-control-thumbs-without-width li {
width: auto;
float: initial; or none
}

Add this class whenever you need to override like below,

<li class="flex-control-thumbs flex-control-thumbs-without-width"> </li>

And do remove whenever you don't need for other <li>

How to read specific lines from a file (by line number)?

file = '/path/to/file_to_be_read.txt'
with open(file) as f:
    print f.readlines()[26]
    print f.readlines()[30]

Using the with statement, this opens the file, prints lines 26 and 30, then closes the file. Simple!

Capture key press without placing an input element on the page?

Detect key press, including key combinations:

window.addEventListener('keydown', function (e) {
  if (e.ctrlKey && e.keyCode == 90) {
    // Ctrl + z pressed
  }
});

Benefit here is that you are not overwriting any global properties, but instead merely introducing a side effect. Not good, but definitely a whole lot less nefarious than other suggestions on here.

regex string replace

Your character class (the part in the square brackets) is saying that you want to match anything except 0-9 and a-z and +. You aren't explicit about how many a-z or 0-9 you want to match, but I assume the + means you want to replace strings of at least one alphanumeric character. It should read instead:

str = str.replace(/[^-a-z0-9]+/g, "");

Also, if you need to match upper-case letters along with lower case, you should use:

str = str.replace(/[^-a-zA-Z0-9]+/g, "");

How to change lowercase chars to uppercase using the 'keyup' event?

The only issue with changing user input on the fly like this is how disconcerting it can look to the end user (they'll briefly see the lowercase chars jump to uppercase).

What you may want to consider instead is applying the following CSS style to the input field:

text-transform: uppercase;

That way, any text entered always appears in uppercase. The only drawback is that this is a purely visual change - the value of the input control (when viewed in the code behind) will retain the case as it was originally entered.

Simple to get around this though, force the input val() .toUpperCase(); then you've got the best of both worlds.

How to read a single character from the user?

This is NON-BLOCKING, reads a key and and stores it in keypress.key.

import Tkinter as tk


class Keypress:
    def __init__(self):
        self.root = tk.Tk()
        self.root.geometry('300x200')
        self.root.bind('<KeyPress>', self.onKeyPress)

    def onKeyPress(self, event):
        self.key = event.char

    def __eq__(self, other):
        return self.key == other

    def __str__(self):
        return self.key

in your programm

keypress = Keypress()

while something:
   do something
   if keypress == 'c':
        break
   elif keypress == 'i': 
       print('info')
   else:
       print("i dont understand %s" % keypress)

What's a "static method" in C#?

From another point of view: Consider that you want to make some changes on a single String. for example you want to make the letters Uppercase and so on. you make another class named "Tools" for these actions. there is no meaning of making instance of "Tools" class because there is not any kind of entity available inside that class (compare to "Person" or "Teacher" class). So we use static keyword in order to use "Tools" class without making any instance of that, and when you press dot after class name ("Tools") you can have access to the methods you want.

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

namespace ConsoleApplication1
{
class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(Tools.ToUpperCase("Behnoud Sherafati"));
        Console.ReadKey();
    }
}

public static class Tools
{
    public static string ToUpperCase(string str)
    {
        return str.ToUpper();

    }
}
}

HTTP Basic Authentication credentials passed in URL and encryption

Yes, it will be encrypted.

You'll understand it if you simply check what happens behind the scenes.

  1. The browser or application will first break down the URL and try to get the IP of the host using a DNS Query. ie: A DNS request will be made to find the IP address of the domain (www.example.com). Please note that no other information will be sent via this request.
  2. The browser or application will initiate a SSL connection with the IP address received from the DNS request. Certificates will be exchanged and this happens at the transport level. No application level information will be transferred at this point. Remember that the Basic authentication is part of HTTP and HTTP is an application level protocol. Not a transport layer task.
  3. After establishing the SSL connection, now the necessary data will be passed to the server. ie: The path or the URL, the parameters and basic authentication username and password.

App store link for "rate/review this app"

Everything, written above is correct. Just a sample to insert into the app and change {YOUR APP ID} to actual app id, taken from iTunesconnect to show the Review page. Please note, as it was commented above, that it is not working on the Simulator - just the device.
- Correcting because of ios 7 changes.

NSString * appId = @"{YOUR APP ID}";
NSString * theUrl = [NSString  stringWithFormat:@"itms-apps://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?id=%@&onlyLatestVersion=true&pageNumber=0&sortOrdering=1&type=Purple+Software",appId];
if ([[UIDevice currentDevice].systemVersion integerValue] > 6) theUrl = [NSString stringWithFormat:@"itms-apps://itunes.apple.com/app/id%@",appId];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:theUrl]];

How does C#'s random number generator work?

You can use Random.Next(int maxValue):

Return: A 32-bit signed integer greater than or equal to zero, and less than maxValue; that is, the range of return values ordinarily includes zero but not maxValue. However, if maxValue equals zero, maxValue is returned.

var r = new Random();
// print random integer >= 0 and  < 100
Console.WriteLine(r.Next(100));

For this case however you could use Random.Next(int minValue, int maxValue), like this:

// print random integer >= 1 and < 101
Console.WriteLine(r.Next(1, 101);)
// or perhaps (if you have this specific case)
Console.WriteLine(r.Next(100) + 1);

Check if selected dropdown value is empty using jQuery

You need to use .change() event as well as using # to target element by id:

$('#EventStartTimeMin').change(function() {
    if($(this).val()===""){ 
        console.log('empty');    
    }
});

Fiddle Demo

Getting value from JQUERY datepicker

To position the datepicker next to the input field you could use following code.

$('#datepicker').datepicker({
    beforeShow: function(input, inst)
    {
        inst.dpDiv.css({marginLeft: input.offsetWidth + 'px'});
    }
});

Python strip() multiple characters?

strip only strips characters from the very front and back of the string.

To delete a list of characters, you could use the string's translate method:

import string
name = "Barack (of Washington)"
table = string.maketrans( '', '', )
print name.translate(table,"(){}<>")
# Barack of Washington

add/remove active class for ul list with jquery?

Try this,

 $('.nav-list li').click(function() {

    $('.nav-list li.active').removeClass('active');
    $(this).addClass('active');
});

In your context $(this) will points to the UL element not the Li. Hence you are not getting the expected results.

How to get the full path of running process?

For others, if you want to find another process of the same executable, you can use:

public bool tryFindAnotherInstance(out Process process) {
    Process thisProcess = Process.GetCurrentProcess();
    string thisFilename = thisProcess.MainModule.FileName;
    int thisPId = thisProcess.Id;
    foreach (Process p in Process.GetProcesses())
    {
        try
        {
            if (p.MainModule.FileName == thisFilename && thisPId != p.Id)
            {
                process = p;
                return true;
            }
        }
        catch (Exception)
        {

        }
    }
    process = default;
    return false;
}

When do I need to use a semicolon vs a slash in Oracle SQL?

Almost all Oracle deployments are done through SQL*Plus (that weird little command line tool that your DBA uses). And in SQL*Plus a lone slash basically means "re-execute last SQL or PL/SQL command that I just executed".

See

http://ss64.com/ora/syntax-sqlplus.html

Rule of thumb would be to use slash with things that do BEGIN .. END or where you can use CREATE OR REPLACE.

For inserts that need to be unique use

INSERT INTO my_table ()
SELECT <values to be inserted>
FROM dual
WHERE NOT EXISTS (SELECT 
                  FROM my_table
                  WHERE <identify data that you are trying to insert>)

How could others, on a local network, access my NodeJS app while it's running on my machine?

I had the same question and solved the problem. In my case, the Windows Firewall (not the router) was blocking the V8 machine I/O on the hosting machine.

  1. Go to windows button
  2. Search "Firewall"
  3. Choose "Allow programs to communicate through Firewall"
  4. Click Change Setup
  5. Tick all of "Evented I/O for V8 Javascript" OR "Node.js: Server-side Javascript"

My guess is that "Evented I/O for V8 Javascript" is the I/O process that node.js communicates to outside world and we need to free it before it can send packets outside of the local computer. After enabling this program to communicate over Windows firewall, I could use any port numbers to listen.

Programmatically extract contents of InstallShield setup.exe

The free and open-source program called cabextract will list and extract the contents of not just .cab-files, but Macrovision's archives too:

% cabextract /tmp/QLWREL.EXE
Extracting cabinet: /tmp/QLWREL.EXE
  extracting ikernel.dll
  extracting IsProBENT.tlb
  ....
  extracting IScript.dll
  extracting iKernel.rgs

All done, no errors.

Execute Python script via crontab

Put your script in a file foo.py starting with

#!/usr/bin/python

Then give execute permission to that script using

chmod a+x foo.py

and use the full path of your foo.py file in your crontab.

See documentation of execve(2) which is handling the shebang.

IPC performance: Named Pipe vs Socket

Keep in mind that sockets does not necessarily mean IP (and TCP or UDP). You can also use UNIX sockets (PF_UNIX), which offer a noticeable performance improvement over connecting to 127.0.0.1

What is the ultimate postal code and zip regex?

Trying to cover the whole world with one regular expression is not completely possible, and certainly not feasible or recommended.

Not to toot my own horn, but I've written some pretty thorough regular expressions which you may find helpful.

  • Canadian postal codes

    Basic validation:
    ^[ABCEGHJ-NPRSTVXY]{1}[0-9]{1}[ABCEGHJ-NPRSTV-Z]{1}[ ]?[0-9]{1}[ABCEGHJ-NPRSTV-Z]{1}[0-9]{1}$
    
    Extended validation:
    ^(A(0[ABCEGHJ-NPR]|1[ABCEGHK-NSV-Y]|2[ABHNV]|5[A]|8[A])|B(0[CEHJ-NPRSTVW]|1[ABCEGHJ-NPRSTV-Y]|2[ABCEGHJNRSTV-Z]|3[ABEGHJ-NPRSTVZ]|4[ABCEGHNPRV]|5[A]|6[L]|9[A])|C(0[AB]|1[ABCEN])|E(1[ABCEGHJNVWX]|2[AEGHJ-NPRSV]|3[ABCELNVYZ]|4[ABCEGHJ-NPRSTV-Z]|5[ABCEGHJ-NPRSTV]|6[ABCEGHJKL]|7[ABCEGHJ-NP]|8[ABCEGJ-NPRST]|9[ABCEGH])|G(0[ACEGHJ-NPRSTV-Z]|1[ABCEGHJ-NPRSTV-Y]|2[ABCEGJ-N]|3[ABCEGHJ-NZ]|4[ARSTVWXZ]|5[ABCHJLMNRTVXYZ]|6[ABCEGHJKLPRSTVWXZ]|7[ABGHJKNPSTXYZ]|8[ABCEGHJ-NPTVWYZ]|9[ABCHNPRTX])|H(0[HM]|1[ABCEGHJ-NPRSTV-Z]|2[ABCEGHJ-NPRSTV-Z]|3[ABCEGHJ-NPRSTV-Z]|4[ABCEGHJ-NPRSTV-Z]|5[AB]|7[ABCEGHJ-NPRSTV-Y]|8[NPRSTYZ]|9[ABCEGHJKPRSWX])|J(0[ABCEGHJ-NPRSTV-Z]|1[ACEGHJ-NRSTXZ]|2[ABCEGHJ-NRSTWXY]|3[ABEGHLMNPRTVXYZ]|4[BGHJ-NPRSTV-Z]|5[ABCJ-MRTV-Z]|6[AEJKNRSTVWYXZ]|7[ABCEGHJ-NPRTV-Z]|8[ABCEGHLMNPRTVXYZ]|9[ABEHJLNTVXYZ])|K(0[ABCEGHJ-M]|1[ABCEGHJ-NPRSTV-Z]|2[ABCEGHJ-MPRSTVW]|4[ABCKMPR]|6[AHJKTV]|7[ACGHK-NPRSV]|8[ABHNPRV]|9[AHJKLV])|L(0[[ABCEGHJ-NPRS]]|1[ABCEGHJ-NPRSTV-Z]|2[AEGHJMNPRSTVW]|3[BCKMPRSTVXYZ]|4[ABCEGHJ-NPRSTV-Z]|5[ABCEGHJ-NPRSTVW]|6[ABCEGHJ-MPRSTV-Z]|7[ABCEGJ-NPRST]|8[EGHJ-NPRSTVW]|9[ABCGHK-NPRSTVWYZ])|M(1[BCEGHJ-NPRSTVWX]|2[HJ-NPR]|3[ABCHJ-N]|4[ABCEGHJ-NPRSTV-Y]|5[ABCEGHJ-NPRSTVWX]|6[ABCEGHJ-NPRS]|7[AY]|8[V-Z]|9[ABCLMNPRVW])|N(0[ABCEGHJ-NPR]|1[ACEGHKLMPRST]|2[ABCEGHJ-NPRTVZ]|3[ABCEHLPRSTVWY]|4[BGKLNSTVWXZ]|5[ACHLPRV-Z]|6[ABCEGHJ-NP]|7[AGLMSTVWX]|8[AHMNPRSTV-Y]|9[ABCEGHJKVY])|P(0[ABCEGHJ-NPRSTV-Y]|1[ABCHLP]|2[ABN]|3[ABCEGLNPY]|4[NPR]|5[AEN]|6[ABC]|7[ABCEGJKL]|8[NT]|9[AN])|R(0[ABCEGHJ-M]|1[ABN]|2[CEGHJ-NPRV-Y]|3[ABCEGHJ-NPRSTV-Y]|4[AHJKL]|5[AGH]|6[MW]|7[ABCN]|8[AN]|9[A])|S(0[ACEGHJ-NP]|2[V]|3[N]|4[AHLNPRSTV-Z]|6[HJKVWX]|7[HJ-NPRSTVW]|9[AHVX])|T(0[ABCEGHJ-MPV]|1[ABCGHJ-MPRSV-Y]|2[ABCEGHJ-NPRSTV-Z]|3[ABCEGHJ-NPRZ]|4[ABCEGHJLNPRSTVX]|5[ABCEGHJ-NPRSTV-Z]|6[ABCEGHJ-NPRSTVWX]|7[AENPSVXYZ]|8[ABCEGHLNRSVWX]|9[ACEGHJKMNSVWX])|V(0[ABCEGHJ-NPRSTVWX]|1[ABCEGHJ-NPRSTV-Z]|2[ABCEGHJ-NPRSTV-Z]|3[ABCEGHJ-NRSTV-Y]|4[ABCEGK-NPRSTVWXZ]|5[ABCEGHJ-NPRSTV-Z]|6[ABCEGHJ-NPRSTV-Z]|7[ABCEGHJ-NPRSTV-Y]|8[ABCGJ-NPRSTV-Z]|9[ABCEGHJ-NPRSTV-Z])|X(0[ABCGX]|1[A])|Y(0[AB]|1[A]))[ ]?[0-9]{1}[ABCEGHJ-NPRSTV-Z]{1}[0-9]{1}$
    
  • US ZIP codes

    ^[0-9]{5}(-[0-9]{4})?$
    
  • UK post codes

    ^([A-PR-UWYZ]([0-9]{1,2}|([A-HK-Y][0-9]|[A-HK-Y][0-9]([0-9]|[ABEHMNPRV-Y]))|[0-9][A-HJKS-UW])\ [0-9][ABD-HJLNP-UW-Z]{2}|(GIR\ 0AA)|(SAN\ TA1)|(BFPO\ (C\/O\ )?[0-9]{1,4})|((ASCN|BBND|[BFS]IQQ|PCRN|STHL|TDCU|TKCA)\ 1ZZ))$
    

It is not possible to guarantee accuracy without actually mailing something to an address and having the person let you know when they receive it, but we can narrow things by down by eliminating cases that we know are bad.

Return HTTP status code 201 in flask

you can also use flask_api for sending response

from flask_api import status

@app.route('/your-api/')
def empty_view(self):
    content = {'your content here'}
    return content, status.HTTP_201_CREATED

you can find reference here http://www.flaskapi.org/api-guide/status-codes/

Anaconda Installed but Cannot Launch Navigator

For people from Brazil

There is a security software called Warsaw (used for home banking) that must be uninstalled! After you can install it back again.

After thousand times trying, installing, uninstalling, cleanning-up the regedit that finally solved the problem.

When use ResponseEntity<T> and @RestController for Spring RESTful applications

To complete the answer from Sotorios Delimanolis.

It's true that ResponseEntity gives you more flexibility but in most cases you won't need it and you'll end up with these ResponseEntity everywhere in your controller thus making it difficult to read and understand.

If you want to handle special cases like errors (Not Found, Conflict, etc.), you can add a HandlerExceptionResolver to your Spring configuration. So in your code, you just throw a specific exception (NotFoundException for instance) and decide what to do in your Handler (setting the HTTP status to 404), making the Controller code more clear.

Match everything except for specified strings

If you want to make sure that the string is neither red, green nor blue, caskey's answer is it. What is often wanted, however, is to make sure that the line does not contain red, green or blue anywhere in it. For that, anchor the regular expression with ^ and include .* in the negative lookahead:

^(?!.*(red|green|blue))

Also, suppose that you want lines containing the word "engine" but without any of those colors:

^(?!.*(red|green|blue)).*engine

You might think you can factor the .* to the head of the regular expression:

^.*(?!red|green|blue)engine     # Does not work

but you cannot. You have to have both instances of .* for it to work.

Facebook API "This app is in development mode"

App Review > Make {Your App} public? > Yes

Click app review and Turn on the Make your app Public toggle. Save changes

Conditionally formatting if multiple cells are blank (no numerics throughout spreadsheet )

The steps you took are not appropriate because the cell you want formatted is not the trigger cell (presumably won't normally be blank). In your case you want formatting to apply to one set of cells according to the status of various other cells. I suggest with data layout as shown in the image (and with thanks to @xQbert for a start on a suitable formula) you select ColumnA and:

HOME > Styles - Conditional Formatting, New Rule..., Use a formula to determine which cells to format and Format values where this formula is true::

=AND(LEN(E1)*LEN(F1)*LEN(G1)*LEN(H1)=0,NOT(ISBLANK(A1)))

Format..., select formatting, OK, OK.

SO22487695 example

where I have filled yellow the cells that are triggering the red fill result.

Making href (anchor tag) request POST instead of GET?

Using jQuery it is very simple assuming the URL you wish to post to is on the same server or has implemented CORS

$(function() {
  $("#employeeLink").on("click",function(e) {
    e.preventDefault(); // cancel the link itself
    $.post(this.href,function(data) {
      $("#someContainer").html(data);
    });
  });
});

If you insist on using frames which I strongly discourage, have a form and submit it with the link

<form action="employee.action" method="post" target="myFrame" id="myForm"></form>

and use (in plain JS)

 window.addEventListener("load",function() {
   document.getElementById("employeeLink").addEventListener("click",function(e) {
     e.preventDefault(); // cancel the link
     document.getElementById("myForm").submit(); // but make sure nothing has name or ID="submit"
   });
 });

Without a form we need to make one

 window.addEventListener("load",function() {
   document.getElementById("employeeLink").addEventListener("click",function(e) {
     e.preventDefault(); // cancel the actual link
     var myForm = document.createElement("form");
     myForm.action=this.href;// the href of the link
     myForm.target="myFrame";
     myForm.method="POST";
     myForm.submit();
   });
 });

Why is my power operator (^) not working?

include math.h and compile with gcc test.c -lm

How to center an iframe horizontally?

Add display:block; to your iframe css.

_x000D_
_x000D_
div, iframe {
    width: 100px;
    height: 50px;
    margin: 0 auto;
    background-color: #777;
}

iframe {
    display: block;
    border-style:none;
}
_x000D_
<div>div</div>
<iframe src="data:,iframe"></iframe>
_x000D_
_x000D_
_x000D_

How to get the list of files in a directory in a shell script?

$ pwd; ls -l
/home/victoria/test
total 12
-rw-r--r-- 1 victoria victoria    0 Apr 23 11:31  a
-rw-r--r-- 1 victoria victoria    0 Apr 23 11:31  b
-rw-r--r-- 1 victoria victoria    0 Apr 23 11:31  c
-rw-r--r-- 1 victoria victoria    0 Apr 23 11:32 'c d'
-rw-r--r-- 1 victoria victoria    0 Apr 23 11:31  d
drwxr-xr-x 2 victoria victoria 4096 Apr 23 11:32  dir_a
drwxr-xr-x 2 victoria victoria 4096 Apr 23 11:32  dir_b
-rw-r--r-- 1 victoria victoria    0 Apr 23 11:32 'e; f'

$ find . -type f
./c
./b
./a
./d
./c d
./e; f

$ find . -type f | sed 's/^\.\///g' | sort
a
b
c
c d
d
e; f

$ find . -type f | sed 's/^\.\///g' | sort > tmp

$ cat tmp
a
b
c
c d
d
e; f

Variations

$ pwd
/home/victoria

$ find $(pwd) -maxdepth 1 -type f -not -path '*/\.*' | sort
/home/victoria/new
/home/victoria/new1
/home/victoria/new2
/home/victoria/new3
/home/victoria/new3.md
/home/victoria/new.md
/home/victoria/package.json
/home/victoria/Untitled Document 1
/home/victoria/Untitled Document 2

$ find . -maxdepth 1 -type f -not -path '*/\.*' | sed 's/^\.\///g' | sort
new
new1
new2
new3
new3.md
new.md
package.json
Untitled Document 1
Untitled Document 2

Notes:

  • . : current folder
  • remove -maxdepth 1 to search recursively
  • -type f : find files, not directories (d)
  • -not -path '*/\.*' : do not return .hidden_files
  • sed 's/^\.\///g' : remove the prepended ./ from the result list

CSS how to make scrollable list

Another solution would be as below where the list is placed under a drop-down button.

  <button class="btn dropdown-toggle btn-primary btn-sm" data-toggle="dropdown"
    >Markets<span class="caret"></span></button>

    <ul class="dropdown-menu", style="height:40%; overflow:hidden; overflow-y:scroll;">
      {{ form.markets }}
    </ul>

How do you share constants in NodeJS modules?

ES6 way.

export in foo.js

const FOO = 'bar';
module.exports = {
  FOO
}

import in bar.js

const {FOO} = require('foo');

How do I do top 1 in Oracle?

To select the first row from a table and to select one row from a table are two different tasks and need a different query. There are many possible ways to do so. Four of them are:

First

select  max(Fname) from MyTbl;

Second

select  min(Fname) from MyTbl;

Third

select  Fname from MyTbl  where rownum = 1;

Fourth

select  max(Fname) from MyTbl where rowid=(select  max(rowid) from MyTbl)

In OS X Lion, LANG is not set to UTF-8, how to fix it?

This is a headbreaker for a long time. I see now it's OSX.. i change it system-wide and it works perfect

When i add this the LANG in Centos6 and Fedora is also my preferred LANG. You can also "uncheck" export or set locale in terminal settings (OSX) /etc/profile

export LC_ALL=en_US.UTF-8
export LANG=en_US.UTF-8

How to build a query string for a URL in C#?

Here is an implementation which uses very basic language features. It's part of a class which we have to port and maintain in Objective C so we choose to have more lines of code but easier to port and understand by a programmer that isn't very familiar with C#.

        /// <summary>
        /// Builds a complete http url with query strings.
        /// </summary>
        /// <param name="pHostname"></param>
        /// <param name="pPort"></param>
        /// <param name="pPage">ex "/index.html" or index.html</param>
        /// <param name="pGetParams">a Dictionary<string,string> collection containing the key value pairs.  Pass null if there are none.</param>
        /// <returns>a string of the form: http://[pHostname]:[pPort/[pPage]?key1=val1&key2=val2...</returns>

  static public string buildURL(string pHostname, int pPort, string pPage, Dictionary<string,string> pGetParams)
        {
            StringBuilder sb = new StringBuilder(200);
            sb.Append("http://");
            sb.Append(pHostname);
            if( pPort != 80 ) {
                sb.Append(pPort);
            }
            // Allows page param to be passed in with or without leading slash.
            if( !pPage.StartsWith("/") ) {
                sb.Append("/");
            }
            sb.Append(pPage);

            if (pGetParams != null && pGetParams.Count > 0)
            {
                sb.Append("?");
                foreach (KeyValuePair<string, string> kvp in pGetParams)
                {
                    sb.Append(kvp.Key);
                    sb.Append("=");
                    sb.Append( System.Web.HttpUtility.UrlEncode(kvp.Value) );
                    sb.Append("&");
                }
                sb.Remove(sb.Length - 1, 1); // Remove the final '&'
            }
            return sb.ToString();
        }

scp copy directory to another server with private key auth

The command looks quite fine. Could you try to run -v (verbose mode) and then we can figure out what it is wrong on the authentication?

Also as mention in the other answer, maybe could be this issue - that you need to convert the keys (answered already here): How to convert SSH keypairs generated using PuttyGen(Windows) into key-pairs used by ssh-agent and KeyChain(Linux) OR http://winscp.net/eng/docs/ui_puttygen (depending what you need)

Return HTML content as a string, given URL. Javascript Function

In some websites, XMLHttpRequest may send you something like <script src="#"></srcipt>. In that case, try using a HTML document like the script under:

<html>
  <body>
    <iframe src="website.com"></iframe>
    <script src="your_JS"></script>
  </body>
</html>

Now you can use JS to get some text out of the HTML, such as getElementbyId.

But this may not work for some websites with cross-domain blocking.

What does "where T : class, new()" mean?

It's called a 'constraint' on the generic parameter T. It means that T must be a reference type (a class) and that it must have a public default constructor.

Unable to import path from django.urls

For those who are using python 2.7, python2.7 don't support django 2 so you can't install django.urls. If you are already using python 3.6 so you need to upgrade django to latest version which is greater than 2.

  • On PowerShell

    pip install -U django

  • Verification

>

PS C:\Users\xyz> python
Python 3.6.6 |Anaconda, Inc.| (default, Jul 25 2018, 15:27:00) [MSC v.1910 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.

>>> from django.urls import path
>>>

As next prompt came, it means it is installed now and ready to use.

How to send and receive JSON data from a restful webservice using Jersey API

The above problem can be solved by adding the following dependencies in your project, as i was facing the same problem.For more detail answer to this solution please refer link SEVERE:MessageBodyWriter not found for media type=application/xml type=class java.util.HashMap

    <dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-mapper-asl</artifactId>
        <version>1.9.0</version>
    </dependency>


    <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.9.2</version>
    </dependency>   


    <dependency>
        <groupId>org.glassfish.jersey.media</groupId>
        <artifactId>jersey-media-json-jackson</artifactId>
        <version>2.25</version>
    </dependency>

jQuery - getting custom attribute from selected option

Simpler syntax if one form.

var option = $('option:selected').attr('mytag')

... if more than one form.

var option = $('select#myform option:selected').attr('mytag')

git clone: Authentication failed for <URL>

  1. Go to Control Panel\All Control Panel Items\Credential Manager and select Generic Credentials.
  2. Remove all the credential with your company domain name.
  3. Git clone repository from git bash terminal once again and it will ask for password and username. Insert it again and you are all set!

Curl to return http status code along with the response

Append a line "http_code:200" at the end, and then grep for the keyword "http_code:" and extract the response code.

result=$(curl -w "\nhttp_code:%{http_code}" http://localhost)

echo "result: ${result}"   #the curl result with "http_code:" at the end

http_code=$(echo "${result}" | grep 'http_code:' | sed 's/http_code://g') 

echo "HTTP_CODE: ${http_code}"  #the http response code

In this case, you can still use the non-silent mode / verbose mode to get more information about the request such as the curl response body.

What is a simple C or C++ TCP server and client example?

Here are some examples for:

1) Simple
2) Fork
3) Threads

based server:

http://www.martinbroadhurst.com/server-examples.html

MySQL Insert query doesn't work with WHERE clause

You can do conditional INSERT based on user input. This query will do insert only if input vars '$userWeight' and '$userDesiredWeight' are not blank

INSERT INTO Users(weight, desiredWeight )
select '$userWeight', '$userDesiredWeight'  
FROM (select 1 a ) dummy
WHERE '$userWeight' != '' AND '$userDesiredWeight'!='';

How to see data from .RData file?

You can also import the data via the "Import Dataset" tab in RStudio, under "global environment." Use the text data option in the drop down list and select your .RData file from the folder. Once the import is complete, it will display the data in the console. Hope this helps.

How to add an object to an ArrayList in Java

You have to use new operator here to instantiate. For example:

Contacts.add(new Data(name, address, contact));

C#: easiest way to populate a ListBox from a List

This also could be easiest way to add items in ListBox.

for (int i = 0; i < MyList.Count; i++)
{
        listBox1.Items.Add(MyList.ElementAt(i));
}

Further improvisation of this code can add items at runtime.

How do browser cookie domains work?

Will www.example.com be able to set cookie for .com?

No, but example.com.fr may be able to set a cookie for example2.com.fr. Firefox protects against this by maintaining a list of TLDs: http://securitylabs.websense.com/content/Blogs/3108.aspx

Apparently Internet Explorer doesn't allow two-letter domains to set cookies, which I suppose explains why o2.ie simply redirects to o2online.ie. I'd often wondered that.

Showing empty view when ListView is empty

I had this problem. I had to make my class extend ListActivity rather than Activity, and rename my list in the XML to android:id="@android:id/list"

SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified

In my case I searched for services. Then found a service called "SQL Server(SQLEXPRESS). Then right click on that. Select properties. Then click start. That's all. Solved the issue.

SQL ON DELETE CASCADE, Which Way Does the Deletion Occur?

Cascade will work when you delete something on table Courses. Any record on table BookCourses that has reference to table Courses will be deleted automatically.

But when you try to delete on table BookCourses only the table itself is affected and not on the Courses

follow-up question: why do you have CourseID on table Category?

Maybe you should restructure your schema into this,

CREATE TABLE Categories 
(
  Code CHAR(4) NOT NULL PRIMARY KEY,
  CategoryName VARCHAR(63) NOT NULL UNIQUE
);

CREATE TABLE Courses 
(
  CourseID INT NOT NULL PRIMARY KEY,
  BookID INT NOT NULL,
  CatCode CHAR(4) NOT NULL,
  CourseNum CHAR(3) NOT NULL,
  CourseSec CHAR(1) NOT NULL,
);

ALTER TABLE Courses
ADD FOREIGN KEY (CatCode)
REFERENCES Categories(Code)
ON DELETE CASCADE;

Import XXX cannot be resolved for Java SE standard classes

If by chance you have deleted JRE SYSTEM LIBRARY, then go to your JRE installation and add jars from there.

Eg:- C:\Program Files (x86)\Java\jre7\lib ---add jars from here

C:\Program Files (x86)\Java\jre7\lib\ext ---add jars from here

Meaning of tilde in Linux bash (not home directory)

On my machine, because of the way I have things set up, doing:

cd ~             # /work1/jleffler
cd ~jleffler     # /u/jleffler

The first pays attention to the value of environment variable $HOME; I deliberately set my $HOME to a local file system instead of an NFS-mounted file system. The second reads from the password file (approximately; NIS complicates things a bit) and finds that the password file says my home directory is /u/jleffler and changes to that directory.

The annoying stuff is that most software behaves as above (and the POSIX specification for the shell requires this behaviour). I use some software (and I don't have much choice about using it) that treats the information from the password file as the current value of $HOME, which is wrong.

Applying this to the question - as others have pointed out, 'cd ~x' goes to the home directory of user 'x', and more generally, whenever tilde expansion is done, ~x means the home directory of user 'x' (and it is an error if user 'x' does not exist).


It might be worth mentioning that:

cd ~-       # Change to previous directory ($OLDPWD)
cd ~+       # Change to current directory ($PWD)

I can't immediately find a use for '~+', unless you do some weird stuff with moving symlinks in the path leading to the current directory.

You can also do:

cd -

That means the same as ~-.

Disabling enter key for form

I checked all the above solutions, they don't work. The only possible solution is to catch 'onkeydown' event for each input of the form. You need to attach disableAllInputs to onload of the page or via jquery ready()

/*
 * Prevents default behavior of pushing enter button. This method doesn't work,
 * if bind it to the 'onkeydown' of the document|form, or to the 'onkeypress' of
 * the input. So method should be attached directly to the input 'onkeydown'
 */
function preventEnterKey(e) {
    // W3C (Chrome|FF) || IE
    e = e || window.event;
    var keycode = e.which || e.keyCode;
    if (keycode == 13) { // Key code of enter button
        // Cancel default action
        if (e.preventDefault) { // W3C
            e.preventDefault();
        } else { // IE
            e.returnValue = false;
        }
        // Cancel visible action
        if (e.stopPropagation) { // W3C
            e.stopPropagation();
        } else { // IE
            e.cancelBubble = true;
        }
        // We don't need anything else
        return false;
    }
}
/* Disable enter key for all inputs of the document */
function disableAllInputs() {
    try {
        var els = document.getElementsByTagName('input');
        if (els) {
            for ( var i = 0; i < els.length; i++) {
                els[i].onkeydown = preventEnterKey;
            }
        }
    } catch (e) {
    }
}