Programs & Examples On #Execcommand

Executes a command on the current document, current selection, or the given range.

In reactJS, how to copy text to clipboard?

Your code should work perfectly, I use it the same way. Only make sure that if the click event is triggered from within a pop up screen like a bootstrap modal or something, the created element has to be within that modal otherwise it won't copy. You could always give the id of an element within that modal (as a second parameter) and retrieve it with getElementById, then append the newly created element to that one instead of the document. Something like this:

copyToClipboard = (text, elementId) => {
  const textField = document.createElement('textarea');
  textField.innerText = text;
  const parentElement = document.getElementById(elementId);
  parentElement.appendChild(textField);
  textField.select();
  document.execCommand('copy');
  parentElement.removeChild(textField);
}

Copy output of a JavaScript variable to the clipboard

Very useful. I modified it to copy a JavaScript variable value to clipboard:

function copyToClipboard(val){
    var dummy = document.createElement("input");
    dummy.style.display = 'none';
    document.body.appendChild(dummy);

    dummy.setAttribute("id", "dummy_id");
    document.getElementById("dummy_id").value=val;
    dummy.select();
    document.execCommand("copy");
    document.body.removeChild(dummy);
}

Force browser to download image files on click

In 2020 I use Blob to make local copy of image, which browser will download as a file. You can test it on this site.

enter image description here

(function(global) {
  const next = () => document.querySelector('.search-pagination__button-text').click();
  const uuid = () => Math.random().toString(36).substring(7);
  const toBlob = (src) => new Promise((res) => {
    const img = document.createElement('img');
    const c = document.createElement("canvas");
    const ctx = c.getContext("2d");
    img.onload = ({target}) => {
      c.width = target.naturalWidth;
      c.height = target.naturalHeight;
      ctx.drawImage(target, 0, 0);
      c.toBlob((b) => res(b), "image/jpeg", 0.75);
    };
    img.crossOrigin = "";
    img.src = src;
  });
  const save = (blob, name = 'image.png') => {
    const a = document.createElement("a");
    a.href = URL.createObjectURL(blob);
    a.target = '_blank';
    a.download = name;
    a.click();
  };
  global.download = () => document.querySelectorAll('.search-content__gallery-results figure > img[src]').forEach(async ({src}) => save(await toBlob(src), `${uuid()}.png`));
  global.next = () => next();
})(window);

TypeError: document.getElementbyId is not a function

JavaScript is case-sensitive. The b in getElementbyId should be capitalized.

var content = document.getElementById("edit").innerHTML;

How to save a base64 image to user's disk using JavaScript?

HTML5 download attribute

Just to allow user to download the image or other file you may use the HTML5 download attribute.

Static file download

<a href="/images/image-name.jpg" download>
<!-- OR -->
<a href="/images/image-name.jpg" download="new-image-name.jpg"> 

Dynamic file download

In cases requesting image dynamically it is possible to emulate such download.

If your image is already loaded and you have the base64 source then:

function saveBase64AsFile(base64, fileName) {
    var link = document.createElement("a");

    document.body.appendChild(link); // for Firefox

    link.setAttribute("href", base64);
    link.setAttribute("download", fileName);
    link.click();
}

Otherwise if image file is downloaded as Blob you can use FileReader to convert it to Base64:

function saveBlobAsFile(blob, fileName) {
    var reader = new FileReader();

    reader.onloadend = function () {    
        var base64 = reader.result ;
        var link = document.createElement("a");

        document.body.appendChild(link); // for Firefox

        link.setAttribute("href", base64);
        link.setAttribute("download", fileName);
        link.click();
    };

    reader.readAsDataURL(blob);
}

Firefox

The anchor tag you are creating also needs to be added to the DOM in Firefox, in order to be recognized for click events (Link).

IE is not supported: Caniuse link

What's the fastest way in Python to calculate cosine similarity given sparse matrix data?

def norm(vector):
    return sqrt(sum(x * x for x in vector))    

def cosine_similarity(vec_a, vec_b):
        norm_a = norm(vec_a)
        norm_b = norm(vec_b)
        dot = sum(a * b for a, b in zip(vec_a, vec_b))
        return dot / (norm_a * norm_b)

This method seems to be somewhat faster than using sklearn's implementation if you pass in one pair of vectors at a time.

How can I reduce the waiting (ttfb) time

If you are using PHP, try using <?php flush(); ?> after </head> and before </body> or whatever section you want to output quickly (like the header or content). It will output the actually code without waiting for php to end. Don't use this function all the time, or the speed increase won't be noticable.

More info

How can I do GUI programming in C?

A C compiler itself won't provide you with GUI functionality, but there are plenty of libraries for that sort of thing. The most popular is probably GTK+, but it may be a little too complicated if you are just starting out and want to quickly get a GUI up and running.

For something a little simpler, I would recommend IUP. With it, you can use a simple GUI definition language called LED to layout controls (but you can do it with pure C, if you want to).

Reusing output from last command in Bash

I have an idea that I don't have time to try to implement immediately.

But what if you do something like the following:

$ MY_HISTORY_FILE = `get_temp_filename`
$ MY_HISTORY_FILE=$MY_HISTORY_FILE bash -i 2>&1 | tee $MY_HISTORY_FILE
$ some_command
$ cat $MY_HISTORY_FILE
$ # ^You'll want to filter that down in practice!

There might be issues with IO buffering. Also the file might get too huge. One would have to come up with a solution to these problems.

Understanding timedelta

Because timedelta is defined like:

class datetime.timedelta([days,] [seconds,] [microseconds,] [milliseconds,] [minutes,] [hours,] [weeks])

All arguments are optional and default to 0.

You can easily say "Three days and four milliseconds" with optional arguments that way.

>>> datetime.timedelta(days=3, milliseconds=4)
datetime.timedelta(3, 0, 4000)
>>> datetime.timedelta(3, 0, 0, 4) #no need for that.
datetime.timedelta(3, 0, 4000)

And for str casting, it returns a nice formatted value instead of __repr__ to improve readability. From docs:

str(t) Returns a string in the form [D day[s], ][H]H:MM:SS[.UUUUUU], where D is negative for negative t. (5)

>>> datetime.timedelta(seconds = 42).__repr__()
'datetime.timedelta(0, 42)'
>>> datetime.timedelta(seconds = 42).__str__()
'0:00:42'

Checkout documentation:

http://docs.python.org/library/datetime.html#timedelta-objects

How to use the TextWatcher class in Android?

For Kotlin use KTX extension function: (It uses TextWatcher as previous answers)

yourEditText.doOnTextChanged { text, start, count, after -> 
        // action which will be invoked when the text is changing
    }


import core-KTX:

implementation "androidx.core:core-ktx:1.2.0"

How to place a file on classpath in Eclipse?

One option is to place your properties file in the src/ directory of your project. This will copy it to the "classes" (along with your .class files) at build time. I often do this for web projects.

bs4.FeatureNotFound: Couldn't find a tree builder with the features you requested: lxml. Do you need to install a parser library?

Blank parameter will result in a warning for best available.
soup = BeautifulSoup(html)

---------------/UserWarning: No parser was explicitly specified, so I'm using the best available HTML parser for this system ("html5lib"). This usually isn't a problem, but if you run this code on another system, or in a different virtual environment, it may use a different parser and behave differently.----------------------/

python --version Python 3.7.7

PyCharm 19.3.4 CE

Git error: src refspec master does not match any error: failed to push some refs

One classic root cause for this message is:

  • when the repo has been initialized (git init lis4368/assignments),
  • but no commit has ever been made

Ie, if you don't have added and committed at least once, there won't be a local master branch to push to.

Try first to create a commit:

  • either by adding (git add .) then git commit -m "first commit"
    (assuming you have the right files in place to add to the index)
  • or by create a first empty commit: git commit --allow-empty -m "Initial empty commit"

And then try git push -u origin master again.

See "Why do I need to explicitly push a new branch?" for more.

Spring Boot java.lang.NoClassDefFoundError: javax/servlet/Filter

The configuration here is working for me:

configurations {
    customProvidedRuntime
}

dependencies {
    compile(
        // Spring Boot dependencies
    )

    customProvidedRuntime('org.springframework.boot:spring-boot-starter-tomcat')
}

war {
    classpath = files(configurations.runtime.minus(configurations.customProvidedRuntime))
}

springBoot {
    providedConfiguration = "customProvidedRuntime"
}

Javascript - User input through HTML input tag to set a Javascript variable?

Late reading this, but.. The way I read your question, you only need to change two lines of code:

Accept user input, function writes back on screen.

<input type="text" id="userInput"=> give me input</input>
<button onclick="test()">Submit</button>

<!-- add this line for function to write into -->
<p id="demo"></p>   

<script type="text/javascript">
function test(){
    var userInput = document.getElementById("userInput").value;
    document.getElementById("demo").innerHTML = userInput;
}
</script>

How do you exit from a void function in C++?

You mean like this?

void foo ( int i ) {
    if ( i < 0 ) return; // do nothing
    // do something
}

Python json.loads shows ValueError: Extra data

My json file was formatted exactly as the one in the question but none of the solutions here worked out. Finally I found a workaround on another Stackoverflow thread. Since this post is the first link in Google search, I put the that answer here so that other people come to this post in the future will find it more easily.

As it's been said there the valid json file needs "[" in the beginning and "]" in the end of file. Moreover, after each json item instead of "}" there must be a "},". All brackets without quotations! This piece of code just modifies the malformed json file into its correct format.

https://stackoverflow.com/a/51919788/2772087

How to remove special characters from a string?

To Remove Special character

String t2 = "!@#$%^&*()-';,./?><+abdd";

t2 = t2.replaceAll("\\W+","");

Output will be : abdd.

This works perfectly.

FIX CSS <!--[if lt IE 8]> in IE

If you want this to work in IE 8 and below, use

<!--[if lte IE 8]>

lte meaning "Less than or equal".

For more on conditional comments, see e.g. the quirksmode.org page.

Add shadow to custom shape on Android

Old question, but Elevation, available with Material Design now provides a shadow to any views.

<TextView
android:id="@+id/myview"
...
android:elevation="2dp"
android:background="@drawable/myrect" />

See the docs at https://developer.android.com/training/material/shadows-clipping.html

How do I disable "missing docstring" warnings at a file-level in Pylint?

No. Pylint doesn't currently let you discriminate between doc-string warnings.

However, you can use Flake8 for all Python code checking along with the doc-string extension to ignore this warning.

Install the doc-string extension with pip (internally, it uses pydocstyle).

pip install flake8_docstrings

You can then just use the --ignore D100 switch. For example, flake8 file.py --ignore D100

How to get the caller class in Java

SecurityManager has a protected method getClassContext

By creating a utility class which extends SecurityManager, you can access this.

public class CallingClass extends SecurityManager {
    public static final CallingClass INSTANCE = new CallingClass();

    public Class[] getCallingClasses() {
        return getClassContext();
    }
}

Use CallingClass.INSTANCE.getCallingClasses() to retrieve the calling classes.

There is also a small library (disclaimer: mine) WhoCalled which exposes this information. It uses Reflection.getCallerClass when available, else falls back to SecurityManager.

How do I convert a float to an int in Objective C?

In support of unwind, remember that Objective-C is a superset of C, rather than a completely new language.

Anything you can do in regular old ANSI C can be done in Objective-C.

How do I do top 1 in Oracle?

If you want just a first selected row, you can:

select fname from MyTbl where rownum = 1

You can also use analytic functions to order and take the top x:

select max(fname) over (rank() order by some_factor) from MyTbl

Adobe Acrobat Pro make all pages the same dimension

The page sizes are looking different in your PDF because the images were originally set to different DPI (even if images are identical HxW in pixels). The good news is - it's only a display issue - and can be fixed easily.

An image with a higher DPI value would display smaller in a PDF (displays at the 'print-size' of the image). To avoid this, open each image in an image editor like GIMP or Photoshop. Open relevant image print control dialog box and set a suitable uniform DPI info for all the images. Remake the PDF with these new images. If in the new PDF images are too big - redo the DPI setting for each to a higher value. If in the new PDF pages are too small to read on-screen without zooming, again - redo DPI adjustment, this time put a lower DPI value. Ideally, 150 DPI should be good enough for images of 2500X2500 pixel - on a 17 inch monitor set to 1366x768 resolution.

BTW, the PDF file shall print each page at the specified DPI of that page. If all images are same DPI, you'll get a uniform printing.

Hope this helps :)

How to display Toast in Android?

If you want to write a simple toast in your activity: Toast.makeText(getApplicationContext(),"Hello",Toast.LENGTH_SHORT).show();

1.Showing TextView in Toast:---

TextView tv = new TextView(this); tv.setText("Hello!"); tv.setTextSize(30); tv.setTextColor(Color.RED); tv.setBackgroundColor(Color.YELLOW);

2.Showing Image as Toast:--

ImageView iv = new ImageView(this); iv.setImageResource(R.drawable.blonde); Toast t = new Toast(this); t.setView(iv); t.setDuration(Toast.LENGTH_LONG); t.show();

3.showing Layout as Toast:--

LayoutInflater li = getLayoutInflater(); View view = li.inflate(R.layout.my_toast_layout,null,false); Toast t = new Toast(this); t.setView(view); t.setDuration(Toast.LENGTH_LONG); t.show();

** If you want to write the toast in your Async then: private Activity activity; private android.content.Context context; this.activity = activity; this.context = context; Toast.makeText(context, "Hello", Toast.LENGTH_SHORT).show();

How to find MAC address of an Android device programmatically

It's Working

    package com.keshav.fetchmacaddress;
    
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.util.Log;
    
    import java.net.InetAddress;
    import java.net.NetworkInterface;
    import java.net.SocketException;
    import java.net.UnknownHostException;
    import java.util.Collections;
    import java.util.List;
    
    public class MainActivity extends AppCompatActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            Log.e("keshav","getMacAddr -> " +getMacAddr());
        }
    
        public static String getMacAddr() {
            try {
                List<NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces());
                for (NetworkInterface nif : all) {
                    if (!nif.getName().equalsIgnoreCase("wlan0")) continue;
    
                    byte[] macBytes = nif.getHardwareAddress();
                    if (macBytes == null) {
                        return "";
                    }
    
                    StringBuilder res1 = new StringBuilder();
                    for (byte b : macBytes) {
                        // res1.append(Integer.toHexString(b & 0xFF) + ":");
                        res1.append(String.format("%02X:",b)); 
                    }
    
                    if (res1.length() > 0) {
                        res1.deleteCharAt(res1.length() - 1);
                    }
                    return res1.toString();
                }
            } catch (Exception ex) {
                //handle exception
            }
            return "";
        }
    }

UPDATE 1

This answer got a bug where a byte that in hex form got a single digit, will not appear with a "0" before it. The append to res1 has been changed to take care of it.

 StringBuilder res1 = new StringBuilder();
                for (byte b : macBytes) {
                    // res1.append(Integer.toHexString(b & 0xFF) + ":");
                    res1.append(String.format("%02X:",b)); 
                }

Escape string for use in Javascript regex

Short 'n Sweet

function escapeRegExp(string) {
  return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}

Example

escapeRegExp("All of these should be escaped: \ ^ $ * + ? . ( ) | { } [ ]");

>>> "All of these should be escaped: \\ \^ \$ \* \+ \? \. \( \) \| \{ \} \[ \] "

(NOTE: the above is not the original answer; it was edited to show the one from MDN. This means it does not match what you will find in the code in the below npm, and does not match what is shown in the below long answer. The comments are also now confusing. My recommendation: use the above, or get it from MDN, and ignore the rest of this answer. -Darren,Nov 2019)

Install

Available on npm as escape-string-regexp

npm install --save escape-string-regexp

Note

See MDN: Javascript Guide: Regular Expressions

Other symbols (~`!@# ...) MAY be escaped without consequence, but are not required to be.

.

.

.

.

Test Case: A typical url

escapeRegExp("/path/to/resource.html?search=query");

>>> "\/path\/to\/resource\.html\?search=query"

The Long Answer

If you're going to use the function above at least link to this stack overflow post in your code's documentation so that it doesn't look like crazy hard-to-test voodoo.

var escapeRegExp;

(function () {
  // Referring to the table here:
  // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/regexp
  // these characters should be escaped
  // \ ^ $ * + ? . ( ) | { } [ ]
  // These characters only have special meaning inside of brackets
  // they do not need to be escaped, but they MAY be escaped
  // without any adverse effects (to the best of my knowledge and casual testing)
  // : ! , = 
  // my test "~!@#$%^&*(){}[]`/=?+\|-_;:'\",<.>".match(/[\#]/g)

  var specials = [
        // order matters for these
          "-"
        , "["
        , "]"
        // order doesn't matter for any of these
        , "/"
        , "{"
        , "}"
        , "("
        , ")"
        , "*"
        , "+"
        , "?"
        , "."
        , "\\"
        , "^"
        , "$"
        , "|"
      ]

      // I choose to escape every character with '\'
      // even though only some strictly require it when inside of []
    , regex = RegExp('[' + specials.join('\\') + ']', 'g')
    ;

  escapeRegExp = function (str) {
    return str.replace(regex, "\\$&");
  };

  // test escapeRegExp("/path/to/res?search=this.that")
}());

Responsive Google Map?

Here a standard CSS solution + JS for the map's height resizing

CSS

#map_canvas {
   width: 100%;
}

JS

// On Resize
$(window).resize(function(){ 
    $('#map_canvas').height($( window ).height());

JsFiddle demo : http://jsfiddle.net/3VKQ8/33/

Why do you create a View in a database?

Views can be a godsend when when doing reporting on legacy databases. In particular, you can use sensical table names instead of cryptic 5 letter names (where 2 of those are a common prefix!), or column names full of abbreviations that I'm sure made sense at the time.

Perform an action in every sub-directory using Bash

A version that avoids creating a sub-process:

for D in *; do
    if [ -d "${D}" ]; then
        echo "${D}"   # your processing here
    fi
done

Or, if your action is a single command, this is more concise:

for D in *; do [ -d "${D}" ] && my_command; done

Or an even more concise version (thanks @enzotib). Note that in this version each value of D will have a trailing slash:

for D in */; do my_command; done

MySQL and GROUP_CONCAT() maximum length

The correct parameter to set the maximum length is:

SET @@group_concat_max_len = value_numeric;

value_numeric must be > 1024; by default the group_concat_max_len value is 1024.

How can I create an array with key value pairs?

$data =array();
$data['user_code']  = 'JOY' ;
$data['user_name']  = 'JOY' ;
$data['user_email'] = '[email protected]';

Principal Component Analysis (PCA) in Python

This is a job for numpy.

And here's a tutorial demonstrating how pincipal component analysis can be done using numpy's built-in modules like mean,cov,double,cumsum,dot,linalg,array,rank.

http://glowingpython.blogspot.sg/2011/07/principal-component-analysis-with-numpy.html

Notice that scipy also has a long explanation here - https://github.com/scikit-learn/scikit-learn/blob/babe4a5d0637ca172d47e1dfdd2f6f3c3ecb28db/scikits/learn/utils/extmath.py#L105

with the scikit-learn library having more code examples - https://github.com/scikit-learn/scikit-learn/blob/babe4a5d0637ca172d47e1dfdd2f6f3c3ecb28db/scikits/learn/utils/extmath.py#L105

What is the difference between & and && in Java?

all answers are great, and it seems that no more answer is needed but I just wonted to point out something about && operator called dependent condition

In expressions using operator &&, a condition—we’ll call this the dependent condition—may require another condition to be true for the evaluation of the dependent condition to be meaningful.

In this case, the dependent condition should be placed after the && operator to prevent errors.

Consider the expression (i != 0) && (10 / i == 2). The dependent condition (10 / i == 2) must appear after the && operator to prevent the possibility of division by zero.

another example (myObject != null) && (myObject.getValue() == somevaluse)

and another thing: && and || are called short-circuit evaluation because the second argument is executed or evaluated only if the first argument does not suffice to determine the value of the expression

References: Java™ How To Program (Early Objects), Tenth Edition

Java Date - Insert into database

Granted, PreparedStatement will make your code better, but to answer your question you need to tell the DBMS the format of your string representation of the Date. In Oracle (you don't name your database vendor) a string date is converted to Date using the TO_DATE() function:

INSERT INTO TABLE_NAME(
  date_column
)values(
  TO_DATE('06/06/2006', 'mm/dd/yyyy')
)

What's the difference between '$(this)' and 'this'?

Yeah, by using $(this), you enabled jQuery functionality for the object. By just using this, it only has generic Javascript functionality.

How do I convert Int/Decimal to float in C#?

You can just do a cast

int val1 = 1;
float val2 = (float)val1;

or

decimal val3 = 3;
float val4 = (float)val3;

Disabling swap files creation in vim

I found the answer here:

vim -n <file>

opens file without swapfile.

In addition:

set dir=/tmp

in .vimrc creates the swapfiles in /tmp.

Change icon on click (toggle)

Try this:

$('#click_advance').click(function(){
  $('#display_advance').toggle('1000');
  icon = $(this).find("i");
  icon.hasClass("icon-circle-arrow-down"){
    icon.addClass("icon-circle-arrow-up").removeClass("icon-circle-arrow-down");
  }else{
    icon.addClass("icon-circle-arrow-down").removeClass("icon-circle-arrow-up");
  }
})

or even better, as Kevin said:

$('#click_advance').click(function(){
  $('#display_advance').toggle('1000');
  icon = $(this).find("i");
  icon.toggleClass("icon-circle-arrow-up icon-circle-arrow-down")
})

How do I make a C++ macro behave like a function?

C++11 brought us lambdas, which can be incredibly useful in this situation:

#define MACRO(X,Y)                              \
    [&](x_, y_) {                               \
        cout << "1st arg is:" << x_ << endl;    \
        cout << "2nd arg is:" << y_ << endl;    \
        cout << "Sum is:" << (x_ + y_) << endl; \
    }((X), (Y))

You keep the generative power of macros, but have a comfy scope from which you can return whatever you want (including void). Additionally, the issue of evaluating macro parameters multiple times is avoided.

How do you uninstall MySQL from Mac OS X?

I also had entries in:

/Library/Receipts/InstallHistory.plist

that i had to delete.

How to change value of a request parameter in laravel

If you use custom requests for validation, for replace data for validation, or to set default data (for checkboxes or other) use override method prepareForValidation().

namespace App\Http\Requests\Admin\Category;
    
class CategoryRequest extends AbstractRequest
{
    protected function prepareForValidation()
    {
        if ( ! $this->get('url')) {
            $this->merge([
                'url' => $this->get('name'),
            ]);
        }
        $this->merge([
            'url'    => \Str::slug($this->get('url')),
            'active' => (int)$this->get('active'),
        ]);
    }
}

I hope this information will be useful to somebody.

Why does writeObject throw java.io.NotSerializableException and how do I fix it?

java.io.NotSerializableException can occur when you serialize an inner class instance because:

serializing such an inner class instance will result in serialization of its associated outer class instance as well

Serialization of inner classes (i.e., nested classes that are not static member classes), including local and anonymous classes, is strongly discouraged

Ref: The Serializable Interface

How can I rollback a git repository to a specific commit?

git reset --hard <old-commit-id>
git push -f <remote-name> <branch-name>

Note: As written in comments below, Using this is dangerous in a collaborative environment: you're rewriting history

What does -> mean in C++?

It's to access a member function or member variable of an object through a pointer, as opposed to a regular variable or reference.

For example: with a regular variable or reference, you use the . operator to access member functions or member variables.

std::string s = "abc";
std::cout << s.length() << std::endl;

But if you're working with a pointer, you need to use the -> operator:

std::string* s = new std::string("abc");
std::cout << s->length() << std::endl;

It can also be overloaded to perform a specific function for a certain object type. Smart pointers like shared_ptr and unique_ptr, as well as STL container iterators, overload this operator to mimic native pointer semantics.

For example:

std::map<int, int>::iterator it = mymap.begin(), end = mymap.end();
for (; it != end; ++it)
    std::cout << it->first << std::endl;

SQL Call Stored Procedure for each Row without using a cursor

This is a variation of n3rds solution above. No sorting by using ORDER BY is needed, as MIN() is used.

Remember that CustomerID (or whatever other numerical column you use for progress) must have a unique constraint. Furthermore, to make it as fast as possible CustomerID must be indexed on.

-- Declare & init
DECLARE @CustomerID INT = (SELECT MIN(CustomerID) FROM Sales.Customer); -- First ID
DECLARE @Data1 VARCHAR(200);
DECLARE @Data2 VARCHAR(200);

-- Iterate over all customers
WHILE @CustomerID IS NOT NULL
BEGIN  

  -- Get data based on ID
  SELECT @Data1 = Data1, @Data2 = Data2
    FROM Sales.Customer
    WHERE [ID] = @CustomerID ;

  -- call your sproc
  EXEC dbo.YOURSPROC @Data1, @Data2

  -- Get next customerId
  SELECT @CustomerID = MIN(CustomerID)
    FROM Sales.Customer
    WHERE CustomerID > @CustomerId 

END

I use this approach on some varchars I need to look over, by putting them in a temporary table first, to give them an ID.

PHP checkbox set to check based on database value

Use checked="checked" attribute if you want your checkbox to be checked.

Spring REST Service: how to configure to remove null objects in json response

As of Jackson 2.0, @JsonSerialize(include = xxx) has been deprecated in favour of @JsonInclude

How do you transfer or export SQL Server 2005 data to Excel

If you are looking for ad-hoc items rather than something that you would put into SSIS. From within SSMS simply highlight the results grid, copy, then paste into excel, it isn't elegant, but works. Then you can save as native .xls rather than .csv

Match linebreaks - \n or \r\n?

In Python:

# as Peter van der Wal's answer
re.split(r'\r\n|\r|\n', text, flags=re.M) 

or more rigorous:

# https://docs.python.org/3/library/stdtypes.html#str.splitlines
str.splitlines()

android pinch zoom

I implemented a pinch zoom for my TextView, using this tutorial. The resulting code is this:

private GestureDetector gestureDetector;
private View.OnTouchListener gestureListener;

and in onCreate():

    // Zoom handlers
    gestureDetector = new GestureDetector(new MyGestureDetector());
    gestureListener = new View.OnTouchListener() {

        // We can be in one of these 2 states
        static final int NONE = 0;
        static final int ZOOM = 1;
        int mode = NONE;

        static final int MIN_FONT_SIZE = 10;
        static final int MAX_FONT_SIZE = 50;

        float oldDist = 1f;

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            TextView textView = (TextView) findViewById(R.id.text);

            switch (event.getAction() & MotionEvent.ACTION_MASK) {
                case MotionEvent.ACTION_POINTER_DOWN:
                    oldDist = spacing(event);
                    Log.d(TAG, "oldDist=" + oldDist);
                    if (oldDist > 10f) {
                       mode = ZOOM;
                       Log.d(TAG, "mode=ZOOM" );
                    }
                    break;
                case MotionEvent.ACTION_POINTER_UP:
                    mode = NONE;
                    break;
                case MotionEvent.ACTION_MOVE:
                    if (mode == ZOOM) {
                        float newDist = spacing(event);
                        // If you want to tweak font scaling, this is the place to go.
                        if (newDist > 10f) {
                            float scale = newDist / oldDist;

                            if (scale > 1) {
                                scale = 1.1f;
                            } else if (scale < 1) {
                                scale = 0.95f;
                            }

                            float currentSize = textView.getTextSize() * scale;
                            if ((currentSize < MAX_FONT_SIZE && currentSize > MIN_FONT_SIZE)
                                    ||(currentSize >= MAX_FONT_SIZE && scale < 1)
                                    || (currentSize <= MIN_FONT_SIZE && scale > 1)) {
                                textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, currentSize);
                            }
                        }
                    }
                    break;
                }
            return false;
        }

Magic constants 1.1 and 0.95 were chosen empirically (using scale variable for this purpose made my TextView behave kind of weird).

How to ignore certain files in Git

You should write something like

*.class

into your .gitignore file.

How to create and show common dialog (Error, Warning, Confirmation) in JavaFX 2.0?

Recently released JDK 1.8.0_40 added support for JavaFX dialogs, alerts, etc. For example, to show a confirmation dialog, one would use the Alert class:

Alert alert = new Alert(AlertType.CONFIRMATION, "Delete " + selection + " ?", ButtonType.YES, ButtonType.NO, ButtonType.CANCEL);
alert.showAndWait();

if (alert.getResult() == ButtonType.YES) {
    //do stuff
}

Here's a list of added classes in this release:

How can I create objects while adding them into a vector?

I know the thread is already all, but as I was checking through I've come up with a solution (code listed below). Hope it can help.

#include <iostream>
#include <vector>

class Box
{
    public:

    static int BoxesTotal;
    static int BoxesEver;
    int Id;

    Box()
    {
        ++BoxesTotal;
        ++BoxesEver;
        Id = BoxesEver;
        std::cout << "Box (" << Id << "/" << BoxesTotal << "/" << BoxesEver << ") initialized." << std::endl;
    }

    ~Box()
    {
        std::cout << "Box (" << Id << "/" << BoxesTotal << "/" << BoxesEver << ") ended." << std::endl;
        --BoxesTotal;
    }

};

int Box::BoxesTotal = 0;
int Box::BoxesEver = 0;

int main(int argc, char* argv[])
{
    std::cout << "Objects (Boxes) example." << std::endl;
    std::cout << "------------------------" << std::endl;

    std::vector <Box*> BoxesTab;

    Box* Indicator;
    for (int i = 1; i<4; ++i)
    {
        std::cout << "i = " << i << ":" << std::endl;
        Box* Indicator = new(Box);
        BoxesTab.push_back(Indicator);
        std::cout << "Adres Blowera: " <<  BoxesTab[i-1] << std::endl;
    }

    std::cout << "Summary" << std::endl;
    std::cout << "-------" << std::endl;
    for (int i=0; i<3; ++i)
    {
        std::cout << "Adres Blowera: " <<  BoxesTab[i] << std::endl;
    }

    std::cout << "Deleting" << std::endl;
    std::cout << "--------" << std::endl;
    for (int i=0; i<3; ++i)
    {
        std::cout << "Deleting Box: " << i+1 << " (" <<  BoxesTab[i] << ") " << std::endl;
        Indicator = (BoxesTab[i]);
        delete(Indicator);
    }

    return 0;
}

And the result it produces is:

Objects (Boxes) example.
------------------------
i = 1:
Box (1/1/1) initialized.
Adres Blowera: 0xdf8ca0
i = 2:
Box (2/2/2) initialized.
Adres Blowera: 0xdf8ce0
i = 3:
Box (3/3/3) initialized.
Adres Blowera: 0xdf8cc0
Summary
-------
Adres Blowera: 0xdf8ca0
Adres Blowera: 0xdf8ce0
Adres Blowera: 0xdf8cc0
Deleting
--------
Deleting Box: 1 (0xdf8ca0) 
Box (1/3/3) ended.
Deleting Box: 2 (0xdf8ce0) 
Box (2/2/3) ended.
Deleting Box: 3 (0xdf8cc0) 
Box (3/1/3) ended.

git returns http error 407 from proxy after CONNECT

I had the same problem in a Windows environment.

I just resolved with NTLM-APS (a Windows NT authentication proxy server)

Configure your NTML proxy and set Git to it:

git config --global http.proxy http://<username>:<userpsw>@localhost:<port>

How do I connect to a Websphere Datasource with a given JNDI name?

You need to define a resource reference in your application and then map that logical resource reference to the physical resource (data source) during deployment.

In your web.xml, add the following configuration (modifying the names and properties as appropriate):

<resource-ref>
    <description>Resource reference to my database</description>
    <res-ref-name>jdbc/MyDB</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
    <res-sharing-scope>Shareable</res-sharing-scope>
</resource-ref>

Then, during application deployment, WAS will prompt you to map this resource reference (jdbc/MyDB) to the data source you created in WAS.

In your code, you can obtain the DataSource similar to how you've shown it in your example; however, the JNDI name you'll use to look it up should actually be the resource reference's name you defined (res-ref-name), rather than the JNDI name of the physical data source. Also, you'll need to prefix the res-ref-name with the application naming context (java:comp/env/).

Context ctx = new InitialContext();
DataSource dataSource = (DataSource) ctx.lookup("java:comp/env/jdbc/MyDB");

How do I write a Windows batch script to copy the newest file from a directory?

Bash:

 find -type f -printf "%T@ %p \n" \
     | sort  \
     | tail -n 1  \
     | sed -r "s/^\S+\s//;s/\s*$//" \
     | xargs -iSTR cp STR newestfile

where "newestfile" will become the newestfile

alternatively, you could do newdir/STR or just newdir

Breakdown:

  1. list all files in {time} {file} format.
  2. sort them by time
  3. get the last one
  4. cut off the time, and whitespace from the start/end
  5. copy resulting value

Important

After running this once, the newest file will be whatever you just copied :p ( assuming they're both in the same search scope that is ). So you may have to adjust which filenumber you copy if you want this to work more than once.

Find if current time falls in a time range

Try using the TimeRange object in C# to complete your goal.

TimeRange timeRange = new TimeRange();
timeRange = TimeRange.Parse("13:00-14:00");

bool IsNowInTheRange = timeRange.IsIn(DateTime.Now.TimeOfDay);
Console.Write(IsNowInTheRange);

Here is where I got that example of using TimeRange

How can I render a list select box (dropdown) with bootstrap?

Another way without using the .form-control is this:

  $(".dropdown-menu li a").click(function(){
        $(this).parents(".btn-group").find('.btn').html($(this).text() + ' <span class="caret"></span>');
        $(this).parents(".btn-group").find('.btn').val($(this).data('value'));
      });

_x000D_
_x000D_
$(".dropdown-menu li a").click(function(){_x000D_
  $(this).parents(".btn-group").find('.btn').html($(this).text() + ' <span class="caret"></span>');_x000D_
  $(this).parents(".btn-group").find('.btn').val($(this).data('value'));_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
_x000D_
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>_x000D_
_x000D_
_x000D_
<div class="btn-group">_x000D_
  <button  type="button" class="btn btn-info dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">_x000D_
                  Test <span class="caret"> </span>_x000D_
  </button>_x000D_
  <ul class="dropdown-menu">_x000D_
    <li><a href='#'>test 1</a></li>_x000D_
    <li><a href='#'>test 2</a></li>_x000D_
    <li><a href='#'>test 3</a></li>_x000D_
  </ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Get a substring of a char*

Assuming you know the position and the length of the substring:

char *buff = "this is a test string";
printf("%.*s", 4, buff + 10);

You could achieve the same thing by copying the substring to another memory destination, but it's not reasonable since you already have it in memory.

This is a good example of avoiding unnecessary copying by using pointers.

jQuery: how to find first visible input/select/textarea excluding buttons?

Why not just target the ones you want (demo)?

$('form').find('input[type=text],textarea,select').filter(':visible:first');

Edit

Or use jQuery :input selector to filter form descendants.

$('form').find('*').filter(':input:visible:first');

Location of ini/config files in linux/unix?

Newer Applications

Follow XDG Base Directory Specification usually ~/.config/yourapp/* can be INF, JSON, YML or whatever format floats your boat, and whatever files... yourapp should match your executable name, or be namespaced with your organization/company/username/handle to ~/.config/yourorg/yourapp/*

Older Applications

Per-user configuration, usually right in your home directory...

  • ~/.yourapp file for a single file
  • ~/.yourapp/ for multiple files + data usually in ~/.yourapp/config

Global configurations are generally in /etc/appname file or /etc/appname/ directory.

Global App data: /var/lib/yourapp/

Cache data: /var/cache/

Log data: /var/log/yourapp/


Some additional info from tutorialhelpdesk.com

The directory structure of Linux/other Unix-like systems and directory details.

In Windows, almost all programs install their files (all files) in the directory named: 'Program Files' Such is not the case in Linux. The directory system categorizes all installed files. All configuration files are in /etc, all binary files are in /bin or /usr/bin or /usr/local/bin. Here is the entire directory structure along with what they contain:

/ - Root directory that forms the base of the file system. All files and directories are logically contained inside the root directory regardless of their physical locations.

/bin - Contains the executable programs that are part of the Linux operating system. Many Linux commands, such as cat, cp, ls, more, and tar, are locate in /bin

/boot - Contains the Linux kernel and other files needed by LILO and GRUB boot managers.

/dev - Contains all device files. Linux treats each device as a special file. All such files are located in /dev.

/etc - Contains most system configuration files and the initialisation scripts in /etc/rc.d subdirectory.

/home - Home directory is the parent to the home directories of users.

/lib - Contains library files, including loadable driver modules needed to boot the system.

/lost+found - Directory for lost files. Every disk partition has a lost+found directory.

/media - Directory for mounting files systems on removable media like CD-ROM drives, floppy disks, and Zip drives.

/mnt - A directory for temporarily mounted filesystems.

/opt - Optional software packages copy/install files here.

/proc - A special directory in a virtual filesystem. It contains the information about various aspects of a Linux system.

/root - Home directory of the root user.

/sbin - Contains administrative binary files. Commands such as mount, shutdown, umount, reside here.

/srv - Contains data for services (HTTP, FTP, etc.) offered by the system.

/sys - A special directory that contains information about the devices, as seen by the Linux kernel.

/tmp - Temporary directory which can be used as a scratch directory (storage for temporary files). The contents of this directory are cleared each time the system boots.

/usr - Contains subdirectories for many programs such as the X Window System.

/usr/bin - Contains executable files for many Linux commands. It is not part of the core Linux operating system.

/usr/include - Contains header files for C and C++ programming languages

/usr/lib - Contains libraries for C and C++ programming languages.

/usr/local - Contains local files. It has a similar directories as /usr contains.

/usr/sbin - Contains administrative commands.

/usr/share - Contains files that are shared, like, default configuration files, images, documentation, etc.

/usr/src - Contains the source code for the Linux kernel.

/var - Contains various system files such as log, mail directories, print spool, etc. which tend to change in numbers and size over time.

/var/cache - Storage area for cached data for applications.

/var/lib - Contains information relating to the current state of applications. Programs modify this when they run.

/var/lock - Contains lock files which are checked by applications so that a resource can be used by one application only.

/var/log - Contains log files for different applications.

/var/mail - Contains users' emails.

/var/opt - Contains variable data for packages stored in /opt directory.

/var/run - Contains data describing the system since it was booted.

/var/spool - Contains data that is waiting for some kind of processing.

/var/tmp - Contains temporary files preserved between system reboots.

How do I find out which settings.xml file maven is using

Use the Maven debug option, ie mvn -X :

Apache Maven 3.0.3 (r1075438; 2011-02-28 18:31:09+0100)
Maven home: /usr/java/apache-maven-3.0.3
Java version: 1.6.0_12, vendor: Sun Microsystems Inc.
Java home: /usr/java/jdk1.6.0_12/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "linux", version: "2.6.32-32-generic", arch: "i386", family: "unix"
[INFO] Error stacktraces are turned on.
[DEBUG] Reading global settings from /usr/java/apache-maven-3.0.3/conf/settings.xml
[DEBUG] Reading user settings from /home/myhome/.m2/settings.xml
...

In this output, you can see that the settings.xml is loaded from /home/myhome/.m2/settings.xml.

How to add a Hint in spinner in XML

In the adapter you can set the first item as disabled. Below is the sample code

@Override
public boolean isEnabled(int position) {
    if (position == 0) {
        // Disable the first item from Spinner
        // First item will be use for hint
        return false;
    } else {
        return true;
    }
}

And set the first item to grey color.

@Override
public View getDropDownView(int position, View convertView,
                                    ViewGroup parent) {
    View view = super.getDropDownView(position, convertView, parent);
    TextView tv = (TextView) view;
    if (position == 0) {
        // Set the hint text color gray
        tv.setTextColor(Color.GRAY);
    } else {
        tv.setTextColor(Color.BLACK);
    }
    return view;
}

And if the user selects the first item then do nothing.

@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
    String selectedItemText = (String) parent.getItemAtPosition(position);
    // If user change the default selection
    // First item is disable and it is used for hint
    if (position > 0) {
        // Notify the selected item text
        Toast.makeText(getApplicationContext(), "Selected : " + selectedItemText, Toast.LENGTH_SHORT).show();
    }
}

Refer the below link for detail.

How to add a hint to Spinner in Android

Converting a JS object to an array using jQuery

If you know the maximum index in you object you can do the following:

_x000D_
_x000D_
var myObj = {_x000D_
    1: ['c', 'd'],_x000D_
    2: ['a', 'b']_x000D_
  },_x000D_
  myArr;_x000D_
_x000D_
myObj.length = 3; //max index + 1_x000D_
myArr = Array.prototype.slice.apply(myObj);_x000D_
console.log(myArr); //[undefined, ['c', 'd'], ['a', 'b']]
_x000D_
_x000D_
_x000D_

HTML table needs spacing between columns, not rows

In most cases it could be better to pad the columns only on the right so just the spacing between the columns gets padded, and the first column is still aligned with the table.

CSS:

.padding-table-columns td
{
    padding:0 5px 0 0; /* Only right padding*/
}

HTML:

<table className="padding-table-columns">
  <tr>
    <td>Cell one</td>
     <!-- There will be a 5px space here-->
    <td>Cell two</td>
     <!-- There will be an invisible 5px space here-->
  </tr>
</table>

Javascript string replace with regex to strip off illegal characters

You need to wrap them all in a character class. The current version means replace this sequence of characters with an empty string. When wrapped in square brackets it means replace any of these characters with an empty string.

var cleanString = dirtyString.replace(/[\|&;\$%@"<>\(\)\+,]/g, "");

TypeScript: casting HTMLElement

Just to clarify, this is correct.

Cannot convert 'NodeList' to 'HTMLScriptElement[]'

as a NodeList is not an actual array (e.g. it doesn't contain .forEach, .slice, .push, etc...).

Thus if it did convert to HTMLScriptElement[] in the type system, you'd get no type errors if you tried to call Array.prototype members on it at compile time, but it would fail at run time.

Run local python script on remote server

It is possible using ssh. Python accepts hyphen(-) as argument to execute the standard input,

cat hello.py | ssh [email protected] python -

Run python --help for more info.

'git status' shows changed files, but 'git diff' doesn't

I've just run in a similar issue. git diff file showed nothing because I added file to the Git index with some part of its name in uppercase: GeoJSONContainer.js.

Afterwards, I've renamed it to GeoJsonContainer.js and changes stopped being tracked. git diff GeoJsonContainer.js was showing nothing. I had to remove the file from the index with a force flag, and add the file again:

git rm -f GeoJSONContainer.js
git add GeoJSONContainer.js

How to actually search all files in Visual Studio

So the answer seems to be to NOT use the Solution Explorer search box.

Rather, open any file in the solution, then use the control-f search pop-up to search all files by:

  1. selecting "Find All" from the "--> Find Next / <-- Find Previous" selector
  2. selecting "Current Project" or "Entire Solution" from the selector that normally says just "Current Document".

AngularJS : Custom filters and ng-repeat

If you still want a custom filter you can pass in the search model to the filter:

<article data-ng-repeat="result in results | cartypefilter:search" class="result">

Where definition for the cartypefilter can look like this:

app.filter('cartypefilter', function() {
  return function(items, search) {
    if (!search) {
      return items;
    }

    var carType = search.carType;
    if (!carType || '' === carType) {
      return items;
    }

    return items.filter(function(element, index, array) {
      return element.carType.name === search.carType;
    });

  };
});

http://plnkr.co/edit/kBcUIayO8tQsTTjTA2vO?p=preview

How to export and import a .sql file from command line with options?

You can use this script to export or import any database from terminal given at this link: https://github.com/Ridhwanluthra/mysql_import_export_script/blob/master/mysql_import_export_script.sh

echo -e "Welcome to the import/export database utility\n"
echo -e "the default location of mysqldump file is: /opt/lampp/bin/mysqldump\n"
echo -e "the default location of mysql file is: /opt/lampp/bin/mysql\n"
read -p 'Would like you like to change the default location [y/n]: ' location_change
read -p "Please enter your username: " u_name
read -p 'Would you like to import or export a database: [import/export]: ' action
echo

mysqldump_location=/opt/lampp/bin/mysqldump
mysql_location=/opt/lampp/bin/mysql

if [ "$action" == "export" ]; then
    if [ "$location_change" == "y" ]; then
        read -p 'Give the location of mysqldump that you want to use: ' mysqldump_location
        echo
    else
        echo -e "Using default location of mysqldump\n"
    fi
    read -p 'Give the name of database in which you would like to export: ' db_name
    read -p 'Give the complete path of the .sql file in which you would like to export the database: ' sql_file
    $mysqldump_location -u $u_name -p $db_name > $sql_file
elif [ "$action" == "import" ]; then
    if [ "$location_change" == "y" ]; then
        read -p 'Give the location of mysql that you want to use: ' mysql_location
        echo
    else
        echo -e "Using default location of mysql\n"
    fi
    read -p 'Give the complete path of the .sql file you would like to import: ' sql_file
    read -p 'Give the name of database in which to import this file: ' db_name
    $mysql_location -u $u_name -p $db_name < $sql_file
else
    echo "please select a valid command"
fi

Delete a database in phpMyAdmin

Go to operations tab for the selected database and click "Drop the database (DROP)" to delete it.

How to get the command line args passed to a running process on unix/linux systems?

try ps -n in a linux terminal. This will show:

1.All processes RUNNING, their command line and their PIDs

  1. The program intiate the processes.

Afterwards you will know which process to kill

List the queries running on SQL Server

SELECT
    p.spid, p.status, p.hostname, p.loginame, p.cpu, r.start_time, r.command,
    p.program_name, text 
FROM
    sys.dm_exec_requests AS r,
    master.dbo.sysprocesses AS p 
    CROSS APPLY sys.dm_exec_sql_text(p.sql_handle)
WHERE
    p.status NOT IN ('sleeping', 'background') 
AND r.session_id = p.spid

Label word wrapping

Just set Label AutoSize property to False. Then the text will be wrapped and you can re-size the control manually to show the text.

How to test an Internet connection with bash?

If your goal is to actually check for Internet access, many of the existing answers to this question are flawed. A few things you should be aware of:

  1. It's possible for your computer to be connected to a network without that network having internet access
  2. It's possible for a server to be down without the entire internet being inaccessible
  3. It's possible for a captive portal to return an HTTP response for an arbitrary URL even if you don't have internet access

With that in mind, I believe the best strategy is to contact several sites over an HTTPS connection and return true if any of those sites responds.

For example:

connected_to_internet() {
  test_urls="\
  https://www.google.com/ \
  https://www.microsoft.com/ \
  https://www.cloudflare.com/ \
  "

  processes="0"
  pids=""

  for test_url in $test_urls; do
    curl --silent --head "$test_url" > /dev/null &
    pids="$pids $!"
    processes=$(($processes + 1))
  done

  while [ $processes -gt 0 ]; do
    for pid in $pids; do
      if ! ps | grep "^[[:blank:]]*$pid[[:blank:]]" > /dev/null; then
        # Process no longer running
        processes=$(($processes - 1))
        pids=$(echo "$pids" | sed --regexp-extended "s/(^| )$pid($| )/ /g")

        if wait $pid; then
          # Success! We have a connection to at least one public site, so the
          # internet is up. Ignore other exit statuses.
          kill -TERM $pids > /dev/null 2>&1 || true
          wait $pids
          return 0
        fi
      fi
    done
    # wait -n $pids # Better than sleep, but not supported on all systems
    sleep 0.1
  done

  return 1
}

Usage:

if connected_to_internet; then
  echo "Connected to internet"
else
  echo "No internet connection"
fi

Some notes about this approach:

  1. It is robust against all the false positives and negatives I outlined above
  2. The requests all happen in parallel to maximize speed
  3. It will return false if you technically have internet access but DNS is non-functional or your network settings are otherwise messed up, which I think is a reasonable thing to do in most cases

Nth word in a string variable

echo $STRING | cut -d " " -f $N

Using a string variable as a variable name

You can use setattr

name  = 'varname'
value = 'something'

setattr(self, name, value) #equivalent to: self.varname= 'something'

print (self.varname)
#will print 'something'

But, since you should inform an object to receive the new variable, this only works inside classes or modules.

How to do an INNER JOIN on multiple columns

if mysql is okay for you:

SELECT flights.*, 
       fromairports.city as fromCity, 
       toairports.city as toCity
FROM flights
LEFT JOIN (airports as fromairports, airports as toairports)
ON (fromairports.code=flights.fairport AND toairports.code=flights.tairport )
WHERE flights.fairport = '?' OR fromairports.city = '?'

edit: added example to filter the output for code or city

Adding system header search path to Xcode

Follow up to Eonil's answer related to project level settings. With the target selected and the Build Settings tab selected, there may be no listing under Search Paths for Header Search Paths. In this case, you can change to "All" from "Basic" in the search bar and Header Search Paths will show up in the Search Paths section.

Automatically size JPanel inside JFrame

If the BorderLayout option provided by our friends doesnot work, try adding ComponentListerner to the JFrame and implement the componentResized(event) method. When the JFrame object will be resized, this method will be called. So if you write the the code to set the size of the JPanel in this method, you will achieve the intended result.

Ya, I know this 'solution' is not good but use it as a safety net. ;)

How does one make random number between range for arc4random_uniform()?

The answer is just 1 line code:

let randomNumber = arc4random_uniform(8999) + 1000 //for 4 digit random number
let randomNumber = arc4random_uniform(899999999) + 100000000 //for 9 digit random number
let randomNumber = arc4random_uniform(89) + 10    //for 2 digit random number
let randomNumber = arc4random_uniform(899) + 100  //for 3 digit random number

The alternate solution is:

    func generateRandomNumber(numDigits: Int) -> Int{
    var place = 1
    var finalNumber = 0;
    var finanum = 0;
    for var i in 0 ..< numDigits {
        place *= 10
        let randomNumber = arc4random_uniform(10)         
        finalNumber += Int(randomNumber) * place
        finanum = finalNumber / 10
           i += 1
    }
    return finanum
}

Although the drawback is that number cannot start from 0.

Android Writing Logs to text File

microlog4android works for me but the documentation is pretty poor. All they need to add is a this is a quick start tutorial.

Here is a quick tutorial I found.

  1. Add the following static variable in your main Activity:

    private static final Logger logger = LoggerFactory.getLogger();
    
  2. Add the following to your onCreate() method:

    PropertyConfigurator.getConfigurator(this).configure();
    
  3. Create a file named microlog.properties and store it in assets directory

  4. Edit the microlog.properties file as follows:

    microlog.level=DEBUG
    microlog.appender=LogCatAppender;FileAppender
    microlog.formatter=PatternFormatter
    microlog.formatter.PatternFormatter.pattern=%c [%P] %m %T
    
  5. Add logging statements like this:

    logger.debug("M4A");
    

For each class you create a logger object as specified in 1)

6.You may be add the following permission:

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

Here is the source for tutorial

How to check if an NSDictionary or NSMutableDictionary contains a key?

objectForKey will return nil if a key doesn't exist.

CSS display:inline property with list-style-image: property on <li> tags

You want style image and Nav with float to each other then use like this

ol.widgets ul
{
list-style-image:url('some-img.gif');
}
ol.widgets ul li
{
float:left;
}

How to resize Twitter Bootstrap modal dynamically based on the content

For Bootstrap 2 Auto adjust model height dynamically

  //Auto adjust modal height on open 
  $('#modal').on('shown',function(){
     var offset = 0;
     $(this).find('.modal-body').attr('style','max-height:'+($(window).height()-offset)+'px !important;');
  });

Algorithm to randomly generate an aesthetically-pleasing color palette

Converting to another palette is a far superior way to do this. There's a reason they do that: other palettes are 'perceptual' - that is, they put similar seeming colors close together, and adjusting one variable changes the color in a predictable manner. None of that is true for RGB, where there's no obvious relationship between colors that "go well together".

How to configure welcome file list in web.xml

I guess what you want is your index servlet to act as the welcome page, so change to:

<welcome-file-list>
   <welcome-file>index</welcome-file>
</welcome-file-list>

So that the index servlet will be used. Note, you'll need a servlet spec 2.4 container to be able to do this.

Note also, @BalusC gets my vote, for your index servlet on its own is superfluous.

Maven: The packaging for this project did not assign a file to the build artifact

TL;DR To fix this issue, invoke packaging plugin before, e.g. for jar packaging use maven-jar-plugin , as following:

mvn jar:jar install:install

Or

mvn jar:jar deploy:deploy 

If you actually needed to deploy.

Gotcha This approach won't work if you have multi-module project with different packagings (ear/war/jar/zip) – even worse, wrong artifacts will be installed/deployed! In such case use reactor options to only build the deployable module (e.g. the war).


Explanation

In some cases you actually want to run directly a install:install or deploy:deploy goal (that is, from the maven-deploy-plugin, the deploy goal, not the Maven deploy phase) and you would end up in the annoying The packaging for this project did not assign a file to the build artifact.

A classic example is a CI job (a Jenkins or Bamboo job, e.g.) where in different steps you want to execute/care about different aspects:

  • A first step would be a mvn clean install, performing tests and test coverage
  • A second step would be a Sonarqube analysis based on a quality profile, e.g. mvn sonar:sonar plus further options
  • Then, and only after successful tests execution and quality gate passed, you want to deploy to your Maven enterprise repository the final project artifacts, yet you don't want to re-run mvn deploy, because it would again execute previous phases (and compile, test, etc.) and you want your build to be effective but yet fast.

Yes, you could speed up this last step at least skipping tests (compilation and execution, via -Dmaven.test.skip=true) or play with a particular profile (to skip as many plugins as possible), but it is much easier and clear to simply run mvn deploy:deploy then.

But it would fail with the error above, because as also specified by the plugin FAQ:

During the packaging-phase all gathered and placed in context. With this mechanism Maven can ensure that the maven-install-plugin and maven-deploy-plugin are copying/uploading the same set of files. So when you only execute deploy:deploy, then there are no files put in the context and there is nothing to deploy.

Indeed, the deploy:deploy needs some runtime information placed in the build context by previous phases (or previous plugins/goals executions).

It has also reported as a potential bug: MDEPLOY-158: deploy:deploy does not work for only Deploying artifact to Maven Remote repo

But then rejected as not a problem.

The deployAtEnd configuration option of the maven-deploy-plugin won't help neither in certain scenarios because we have intermediate job steps to execute:

Whether every project should be deployed during its own deploy-phase or at the end of the multimodule build. If set to true and the build fails, none of the reactor projects is deployed. (experimental)

So, how to fix it?
Simply run the following in such a similar third/last step:

mvn jar:jar deploy:deploy

The maven-jar-plugin will not re-create any jar as part of your build, thanks to its forceCreation option set to false by default:

Require the jar plugin to build a new JAR even if none of the contents appear to have changed. By default, this plugin looks to see if the output jar exists and inputs have not changed. If these conditions are true, the plugin skips creation of the jar.

But it will nicely populate the build context for us and make deploy:deploy happy. No tests to skip, no profiles to add. Just what you need: speed.


Additional note: if you are using the build-helper-maven-plugin, buildnumber-maven-plugin or any other similar plugin to generate meta-data later on used by the maven-jar-plugin (e.g. entries for the Manifest file), you most probably have executions linked to the validate phase and you still want to have them during the jar:jar build step (and yet keep a fast execution). In this case the almost harmless overhead is to invoke the validate phase as following:

mvn validate jar:jar deploy:deploy

Yet another additional note: if you have not jar but, say, war packaging, use war:war before install/deploy instead.

Gotcha as pointed out above, check behavior in multi module projects.

ANTLR: Is there a simple example?

ANTLR mega tutorial by Gabriele Tomassetti is very helpful

It has grammar examples, examples of visitors in different languages (Java, JavaScript, C# and Python) and many other things. Highly recommended.

EDIT: other useful articles by Gabriele Tomassetti on ANTLR

How to return a struct from a function in C++?

As pointed out by others, define studentType outside the function. One more thing, even if you do that, do not create a local studentType instance inside the function. The instance is on the function stack and will not be available when you try to return it. One thing you can however do is create studentType dynamically and return the pointer to it outside the function.

How do I center floated elements?

text-align: center;
float: none;

Catching multiple exception types in one catch block

A great way is to use set_exception_handler.

Warning!!! with PHP 7, you might get a white screen of death for fatal errors. For example, if you call a method on a non-object you would normally get Fatal error: Call to a member function your_method() on null and you would expect to see this if error reporting is on.

The above error will NOT be caught with catch(Exception $e). The above error will NOT trigger any custom error handler set by set_error_handler.

You must use catch(Error $e){ } to catch errors in PHP7. . This could help:

class ErrorHandler{
    public static function excep_handler($e)
    {
        print_r($e);
    }
}
set_exception_handler(array('ErrorHandler','excep_handler'));

How can I remove the decimal part from JavaScript number?

toFixed will behave like round.

For a floor like behavior use %:

var num = 3.834234;
var floored_num = num - (num % 1); // floored_num will be 3

How to `wget` a list of URLs in a text file?

If you're on OpenWrt or using some old version of wget which doesn't gives you -i option:

#!/bin/bash
input="text_file.txt"
while IFS= read -r line
do
  wget $line
done < "$input"

Furthermore, if you don't have wget, you can use curl or whatever you use for downloading individual files.

Eclipse "Invalid Project Description" when creating new project from existing source

This problem drives me crazy as well but I know what the cause of it is. The problem is that eclipse is not smart enough to create a folder with the same name of your project within your workspace folder if it is custom.

The way to solve this is to make sure all of your projects are in a folder with the name that matches your Project Name, otherwise it will dump all of your project files straight into the directory. The reason why you end up seeing that error is because it thinks you are putting a project inside another project (probably reads the project config file).

I noticed this is especially a problem when not using the default workspace path. The way I solve this problem is to just add the Project Name to the end of location. So let's say you are putting a project named "HelloWorld" into /Users/name/Documents/projects/android/, you would want to manually add "HelloWorld" to the end of it, like this: /Users/name/Documents/projects/android/HelloWorld. This would ensure that the project is put in it's own folder called "HelloWorld" and not inside some other project. Be sure that if there are any projects not within folders into a folder of the same name as the project to solve the errors.

How to delete a row from GridView?

My solution:

protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
    myobj.myconnection();// connection created
    string mystr = "Delete table_name where water_id= '" + GridView1.DataKeys[e.RowIndex].Value + "'";// query
    sqlcmd = new SqlCommand(mystr, myobj.mycon);
    sqlcmd.ExecuteNonQuery();
    fillgrid();
}

Is it possible to get all arguments of a function as single object inside that function?

In ES6, use Array.from:

function foo()
  {
  foo.bar = Array.from(arguments);
  foo.baz = foo.bar.join();
  }

foo(1,2,3,4,5,6,7);
foo.bar // Array [1, 2, 3, 4, 5, 6, 7]
foo.baz // "1,2,3,4,5,6,7"

For non-ES6 code, use JSON.stringify and JSON.parse:

function foo()
  {
  foo.bar = JSON.stringify(arguments); 
  foo.baz = JSON.parse(foo.bar); 
  }

/* Atomic Data */
foo(1,2,3,4,5,6,7);
foo.bar // "{"0":1,"1":2,"2":3,"3":4,"4":5,"5":6,"6":7}"
foo.baz // [object Object]

/* Structured Data */
foo({1:2},[3,4],/5,6/,Date())
foo.bar //"{"0":{"1":2},"1":[3,4],"2":{},"3":"Tue Dec 17 2013 16:25:44 GMT-0800 (Pacific Standard Time)"}"
foo.baz // [object Object]

If preservation is needed instead of stringification, use the internal structured cloning algorithm.

If DOM nodes are passed, use XMLSerializer as in an unrelated question.

with (new XMLSerializer()) {serializeToString(document.documentElement) }

If running as a bookmarklet, you may need to wrap the each structured data argument in an Error constructor for JSON.stringify to work properly.

References

Git Clone from GitHub over https with two-factor authentication

It generally comes to mind that you have set up two-factor authentication, after a few password trials and maybe a password reset. So, how can we git clone a private repository using two-factor authentication? It is simple, using access tokens.

How to Authenticate Git using Access Tokens

  1. Go to https://github.com/settings/tokens
  2. Click Generate New Token button on top right.
  3. Give your token a descriptive name.
  4. Set all required permissions for the token.
  5. Click Generate token button at the bottom.
  6. Copy the generated token to a safe place.
  7. Use this token instead of password when you use git clone.

Wow, it works!

MySQL pivot table query with dynamic columns

Here's stored procedure, which will generate the table based on data from one table and column and data from other table and column.

The function 'sum(if(col = value, 1,0)) as value ' is used. You can choose from different functions like MAX(if()) etc.

delimiter //

  create procedure myPivot(
    in tableA varchar(255),
    in columnA varchar(255),
    in tableB varchar(255),
    in columnB varchar(255)
)
begin
  set @sql = NULL;
    set @sql = CONCAT('select group_concat(distinct concat(
            \'SUM(IF(', 
        columnA, 
        ' = \'\'\',',
        columnA,
        ',\'\'\', 1, 0)) AS \'\'\',',
        columnA, 
            ',\'\'\'\') separator \', \') from ',
        tableA, ' into @sql');
    -- select @sql;

    PREPARE stmt FROM @sql;
    EXECUTE stmt;

    DEALLOCATE PREPARE stmt;
    -- select @sql;

    SET @sql = CONCAT('SELECT p.', 
        columnB, 
        ', ', 
        @sql, 
        ' FROM ', tableB, ' p GROUP BY p.',
        columnB,'');

    -- select @sql;

    /* */
    PREPARE stmt FROM @sql;
    EXECUTE stmt;
    /* */
    DEALLOCATE PREPARE stmt;
end//

delimiter ;

What is the correct target for the JAVA_HOME environment variable for a Linux OpenJDK Debian-based distribution?

The standard Ubuntu install seems to put the various Java versions in /usr/lib/jvm. The javac, java you find in your path will softlink to this.

There's no issue with installing your own Java version anywhere you like, as long as you set the JAVA_HOME environment variable and make sure to have the new Java bin on your path.

A simple way to do this is to have the Java home exist as a softlink, so that if you want to upgrade or switch versions you only have to change the directory that this points to - e.g.:

/usr/bin/java --> /opt/jdk/bin/java,

/opt/jdk --> /opt/jdk1.6.011

Sending a JSON to server and retrieving a JSON in return, without JQuery

Using new api fetch:

_x000D_
_x000D_
const dataToSend = JSON.stringify({"email": "[email protected]", "password": "101010"});
let dataReceived = ""; 
fetch("", {
    credentials: "same-origin",
    mode: "same-origin",
    method: "post",
    headers: { "Content-Type": "application/json" },
    body: dataToSend
})
    .then(resp => {
        if (resp.status === 200) {
            return resp.json()
        } else {
            console.log("Status: " + resp.status)
            return Promise.reject("server")
        }
    })
    .then(dataJson => {
        dataReceived = JSON.parse(dataJson)
    })
    .catch(err => {
        if (err === "server") return
        console.log(err)
    })

console.log(`Received: ${dataReceived}`)                
_x000D_
_x000D_
_x000D_ You need to handle when server sends other status rather than 200(ok), you should reject that result because if you were to left it in blank, it will try to parse the json but there isn't, so it will throw an error

How to check the version of GitLab?

The easiest way is to paste the following command:

cat /opt/gitlab/version-manifest.txt | head -n 1

and there you get the version installed. :)

Getting ssh to execute a command in the background on target machine

It appeared quite convenient for me to have a remote tmux session using the tmux new -d <shell cmd> syntax like this:

ssh someone@elsewhere 'tmux new -d sleep 600'

This will launch new session on elsewhere host and ssh command on local machine will return to shell almost instantly. You can then ssh to the remote host and tmux attach to that session. Note that there's nothing about local tmux running, only remote!

Also, if you want your session to persist after the job is done, simply add a shell launcher after your command, but don't forget to enclose in quotes:

ssh someone@elsewhere 'tmux new -d "~/myscript.sh; bash"'

python plot normal distribution

If you prefer to use a step by step approach you could consider a solution like follows

import numpy as np
import matplotlib.pyplot as plt

mean = 0; std = 1; variance = np.square(std)
x = np.arange(-5,5,.01)
f = np.exp(-np.square(x-mean)/2*variance)/(np.sqrt(2*np.pi*variance))

plt.plot(x,f)
plt.ylabel('gaussian distribution')
plt.show()

How to add a custom button to the toolbar that calls a JavaScript function?

Also there is a nice way allowing one to add the button without creating plugin.

html:

<textarea id="container">How are you!</textarea>

javascript:

editor = CKEDITOR.replace('container'); // bind editor

editor.addCommand("mySimpleCommand", { // create named command
    exec: function(edt) {
        alert(edt.getData());
    }
});

editor.ui.addButton('SuperButton', { // add new button and bind our command
    label: "Click me",
    command: 'mySimpleCommand',
    toolbar: 'insert',
    icon: 'https://avatars1.githubusercontent.com/u/5500999?v=2&s=16'
});

Check out how it works here: DEMO

PG COPY error: invalid input syntax for integer

I got this error when loading '|' separated CSV file although there were no '"' characters in my input file. It turned out that I forgot to specify FORMAT:

COPY ... FROM ... WITH (FORMAT CSV, DELIMITER '|').

Excel Reference To Current Cell

Create a named formula called THIS_CELL

  1. In the current worksheet, select cell A1 (this is important!)

  2. Open Name Manager (Ctl+F3)

  3. Click New...

  4. Enter "THIS_CELL" (or just "THIS", which is my preference) into Name:

  5. Enter the following formula into Refers to:

    =!A1

    NOTE: Be sure cell A1 is selected. This formula is relative to the ActiveCell.

  6. Under Scope: select Workbook.

  7. Click OK and close the Name Manager

Use the formula in the worksheet exactly as you wanted

=CELL("width",THIS_CELL)

EDIT: Better solution than using INDIRECT()

It's worth noting that the solution I've given should be preferred over any solution using the INDIRECT() function for two reasons:

  1. It is nonvolatile, while INDIRECT() is a volatile Excel function, and as a result will dramatically slow down workbook calculation when it is used a lot.
  2. It is much simpler, and does not require converting an address (in the form of ROW() COLUMN()) to a range reference to an address and back to a range reference again.

EDIT: Also see this question for more information on workbook-scoped, sheet dependent named ranges.

EDIT: Also see @imix's answer below for a variation on this idea (using RC style references). In that case, you could use =!RC for the THIS_CELL named range formula, or just use RC directly.

Check if MySQL table exists or not

You can try this

$query = mysql_query("SELECT * FROM $this_table") or die (mysql_error());

or this

$query = mysql_query("SELECT * FROM $this_table") or die ("Table does not exists!");

or this

$query = mysql_query("SELECT * FROM $this_table");

if(!$query)
   echo "The ".$this_table." does not exists";

Hope it helps!

LINQ query to find if items in a list are contained in another list

List<string> l = new List<string> { "@bob.com", "@tom.com" };
List<string> l2 = new List<string> { "[email protected]", "[email protected]" };
List<string> myboblist= (l2.Where (i=>i.Contains("bob")).ToList<string>());
foreach (var bob in myboblist)
    Console.WriteLine(bob.ToString());

Reading a text file using OpenFileDialog in windows forms

Here's one way:

Stream myStream = null;
OpenFileDialog theDialog = new OpenFileDialog();
theDialog.Title = "Open Text File";
theDialog.Filter = "TXT files|*.txt";
theDialog.InitialDirectory = @"C:\";
if (theDialog.ShowDialog() == DialogResult.OK)
{
    try
    {
        if ((myStream = theDialog.OpenFile()) != null)
        {
            using (myStream)
            {
                // Insert code to read the stream here.
            }
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
    }
}

Modified from here:MSDN OpenFileDialog.OpenFile

EDIT Here's another way more suited to your needs:

private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
    OpenFileDialog theDialog = new OpenFileDialog();
    theDialog.Title = "Open Text File";
    theDialog.Filter = "TXT files|*.txt";
    theDialog.InitialDirectory = @"C:\";
    if (theDialog.ShowDialog() == DialogResult.OK)
    {
        string filename = theDialog.FileName;

        string[] filelines = File.ReadAllLines(filename);

        List<Employee> employeeList = new List<Employee>();
        int linesPerEmployee = 4;
        int currEmployeeLine = 0;
        //parse line by line into instance of employee class
        Employee employee = new Employee();
        for (int a = 0; a < filelines.Length; a++)
        {

            //check if to move to next employee
            if (a != 0 && a % linesPerEmployee == 0)
            {
                employeeList.Add(employee);
                employee = new Employee();
                currEmployeeLine = 1;
            }

            else
            {
                currEmployeeLine++;
            }
            switch (currEmployeeLine)
            {
                case 1:
                    employee.EmployeeNum = Convert.ToInt32(filelines[a].Trim());
                    break;
                case 2:
                    employee.Name = filelines[a].Trim();
                    break;
                case 3:
                    employee.Address = filelines[a].Trim();
                    break;
                case 4:
                    string[] splitLines = filelines[a].Split(' ');

                    employee.Wage = Convert.ToDouble(splitLines[0].Trim());
                    employee.Hours = Convert.ToDouble(splitLines[1].Trim());
                    break;


            }

        }
        //Test to see if it works
        foreach (Employee emp in employeeList)
        {
            MessageBox.Show(emp.EmployeeNum + Environment.NewLine +
                emp.Name + Environment.NewLine +
                emp.Address + Environment.NewLine +
                emp.Wage + Environment.NewLine +
                emp.Hours + Environment.NewLine);
        }
    }
}

How to reset AUTO_INCREMENT in MySQL?

You can reset the counter with:

ALTER TABLE tablename AUTO_INCREMENT = 1

For InnoDB you cannot set the auto_increment value lower or equal to the highest current index. (quote from ViralPatel):

Note that you cannot reset the counter to a value less than or equal to any that have already been used. For MyISAM, if the value is less than or equal to the maximum value currently in the AUTO_INCREMENT column, the value is reset to the current maximum plus one. For InnoDB, if the value is less than the current maximum value in the column, no error occurs and the current sequence value is not changed.

See How to Reset an MySQL AutoIncrement using a MAX value from another table? on how to dynamically get an acceptable value.

How to iterate object keys using *ngFor

Angular 6.0.0

https://github.com/angular/angular/blob/master/CHANGELOG.md#610-2018-07-25

introduced a KeyValuePipe

See also https://angular.io/api/common/KeyValuePipe

@Component({
  selector: 'keyvalue-pipe',
  template: `<span>
    <p>Object</p>
    <div *ngFor="let item of object | keyvalue">
      {{item.key}}:{{item.value}}
    </div>
    <p>Map</p>
    <div *ngFor="let item of map | keyvalue">
      {{item.key}}:{{item.value}}
    </div>
  </span>`
})
export class KeyValuePipeComponent {
  object: {[key: number]: string} = {2: 'foo', 1: 'bar'};
  map = new Map([[2, 'foo'], [1, 'bar']]);
}

original

You can use a pipe

@Pipe({ name: 'keys',  pure: false })
export class KeysPipe implements PipeTransform {
    transform(value: any, args: any[] = null): any {
        return Object.keys(value)//.map(key => value[key]);
    }
}
<div *ngFor="let key of objs | keys">

See also How to iterate object keys using *ngFor?

How to change owner of PostgreSql database?

Frank Heikens answer will only update database ownership. Often, you also want to update ownership of contained objects (including tables). Starting with Postgres 8.2, REASSIGN OWNED is available to simplify this task.

IMPORTANT EDIT!

Never use REASSIGN OWNED when the original role is postgres, this could damage your entire DB instance. The command will update all objects with a new owner, including system resources (postgres0, postgres1, etc.)


First, connect to admin database and update DB ownership:

psql
postgres=# REASSIGN OWNED BY old_name TO new_name;

This is a global equivalent of ALTER DATABASE command provided in Frank's answer, but instead of updating a particular DB, it change ownership of all DBs owned by 'old_name'.

The next step is to update tables ownership for each database:

psql old_name_db
old_name_db=# REASSIGN OWNED BY old_name TO new_name;

This must be performed on each DB owned by 'old_name'. The command will update ownership of all tables in the DB.

Warn user before leaving web page with unsaved changes

Tested Eli Grey's universal solution, only worked after I simplified the code to

  'use strict';
  (() => {
    const modified_inputs = new Set();
    const defaultValue = 'defaultValue';
    // store default values
    addEventListener('beforeinput', evt => {
      const target = evt.target;
      if (!(defaultValue in target.dataset)) {
        target.dataset[defaultValue] = ('' + (target.value || target.textContent)).trim();
      }
    });

    // detect input modifications
    addEventListener('input', evt => {
      const target = evt.target;
      let original = target.dataset[defaultValue];

      let current = ('' + (target.value || target.textContent)).trim();

      if (original !== current) {
        if (!modified_inputs.has(target)) {
          modified_inputs.add(target);
        }
      } else if (modified_inputs.has(target)) {
        modified_inputs.delete(target);
      }
    });

    addEventListener(
      'saved',
      function(e) {
        modified_inputs.clear()
      },
      false
    );

    addEventListener('beforeunload', evt => {
      if (modified_inputs.size) {
        const unsaved_changes_warning = 'Changes you made may not be saved.';
        evt.returnValue = unsaved_changes_warning;
        return unsaved_changes_warning;
      }
    });

  })();

The modifications to his is deleted the usage of target[defaultValue] and only use target.dataset[defaultValue] to store the real default value.

And I added a 'saved' event listener where the 'saved' event will be triggered by yourself on your saving action succeeded.

But this 'universal' solution only works in browsers, not works in app's webview, for example, wechat browsers.

To make it work in wechat browsers(partially) also, another improvements again:

  'use strict';
  (() => {
    const modified_inputs = new Set();
    const defaultValue = 'defaultValue';
    // store default values
    addEventListener('beforeinput', evt => {
      const target = evt.target;
      if (!(defaultValue in target.dataset)) {
        target.dataset[defaultValue] = ('' + (target.value || target.textContent)).trim();
      }
    });

    // detect input modifications
    addEventListener('input', evt => {
      const target = evt.target;
      let original = target.dataset[defaultValue];

      let current = ('' + (target.value || target.textContent)).trim();

      if (original !== current) {
        if (!modified_inputs.has(target)) {
          modified_inputs.add(target);
        }
      } else if (modified_inputs.has(target)) {
        modified_inputs.delete(target);
      }

      if(modified_inputs.size){
        const event = new Event('needSave')
        window.dispatchEvent(event);
      }
    });

    addEventListener(
      'saved',
      function(e) {
        modified_inputs.clear()
      },
      false
    );

    addEventListener('beforeunload', evt => {
      if (modified_inputs.size) {
        const unsaved_changes_warning = 'Changes you made may not be saved.';
        evt.returnValue = unsaved_changes_warning;
        return unsaved_changes_warning;
      }
    });

    const ua = navigator.userAgent.toLowerCase();

    if(/MicroMessenger/i.test(ua)) {
      let pushed = false

      addEventListener('needSave', evt => {
        if(!pushed) {
          pushHistory();

          window.addEventListener("popstate", function(e) {
            if(modified_inputs.size) {
              var cfi = confirm('???????????' + JSON.stringify(e));
              if (cfi) {
                modified_inputs.clear()
                history.go(-1)
              }else{
                e.preventDefault();
                e.stopPropagation();
              }
            }
          }, false);
        }

        pushed = true
      });
    }

    function pushHistory() {
      var state = {
        title: document.title,
        url: "#flag"
      };
      window.history.pushState(state, document.title, "#flag");
    }
  })();

Reading PDF content with itextsharp dll in VB.NET or C#

LGPL / FOSS iTextSharp 4.x

var pdfReader = new PdfReader(path); //other filestream etc
byte[] pageContent = _pdfReader .GetPageContent(pageNum); //not zero based
byte[] utf8 = Encoding.Convert(Encoding.Default, Encoding.UTF8, pageContent);
string textFromPage = Encoding.UTF8.GetString(utf8);

None of the other answers were useful to me, they all seem to target the AGPL v5 of iTextSharp. I could never find any reference to SimpleTextExtractionStrategy or LocationTextExtractionStrategy in the FOSS version.

Something else that might be very useful in conjunction with this:

const string PdfTableFormat = @"\(.*\)Tj";
Regex PdfTableRegex = new Regex(PdfTableFormat, RegexOptions.Compiled);

List<string> ExtractPdfContent(string rawPdfContent)
{
    var matches = PdfTableRegex.Matches(rawPdfContent);

    var list = matches.Cast<Match>()
        .Select(m => m.Value
            .Substring(1) //remove leading (
            .Remove(m.Value.Length - 4) //remove trailing )Tj
            .Replace(@"\)", ")") //unencode parens
            .Replace(@"\(", "(")
            .Trim()
        )
        .ToList();
    return list;
}

This will extract the text-only data from the PDF if the text displayed is Foo(bar) it will be encoded in the PDF as (Foo\(bar\))Tj, this method would return Foo(bar) as expected. This method will strip out lots of additional information such as location coordinates from the raw pdf content.

Spring MVC - HttpMediaTypeNotAcceptableException

in my case favorPathExtension(false) helped me

@Configuration
public class WebMvcConfiguration extends WebMvcConfigurerAdapter {

@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
    configurer
            .setUseSuffixPatternMatch(false);  // to use special character in path variables, for example, `[email protected]`
}

@Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
    configurer
            .favorPathExtension(false); // to  avoid HttpMediaTypeNotAcceptableException on standalone tomcat
}

}

java- reset list iterator to first element of the list

This is an alternative solution, but one could argue it doesn't add enough value to make it worth it:

import com.google.common.collect.Iterables;
...
Iterator<String> iter = Iterables.cycle(list).iterator();
if(iter.hasNext()) {
    str = iter.next();
}

Calling hasNext() will reset the iterator cursor to the beginning if it's a the end.

Make an image follow mouse pointer

Ok, here's a simple box that follows the cursor

Doing the rest is a simple case of remembering the last cursor position and applying a formula to get the box to move other than exactly where the cursor is. A timeout would also be handy if the box has a limited acceleration and must catch up to the cursor after it stops moving. Replacing the box with an image is simple CSS (which can replace most of the setup code for the box). I think the actual thinking code in the example is about 8 lines.

Select the right image (use a sprite) to orientate the rocket.

Yeah, annoying as hell. :-)

_x000D_
_x000D_
function getMouseCoords(e) {
  var e = e || window.event;
  document.getElementById('container').innerHTML = e.clientX + ', ' +
    e.clientY + '<br>' + e.screenX + ', ' + e.screenY;
}


var followCursor = (function() {
  var s = document.createElement('div');
  s.style.position = 'absolute';
  s.style.margin = '0';
  s.style.padding = '5px';
  s.style.border = '1px solid red';
  s.textContent = ""

  return {
    init: function() {
      document.body.appendChild(s);
    },

    run: function(e) {
      var e = e || window.event;
      s.style.left = (e.clientX - 5) + 'px';
      s.style.top = (e.clientY - 5) + 'px';
      getMouseCoords(e);
    }
  };
}());

window.onload = function() {
  followCursor.init();
  document.body.onmousemove = followCursor.run;
}
_x000D_
#container {
  width: 1000px;
  height: 1000px;
  border: 1px solid blue;
}
_x000D_
<div id="container"></div>
_x000D_
_x000D_
_x000D_

How can I access the MySQL command line with XAMPP for Windows?

Ajay,

The reason that you can't see the other tables is that you need to log in as 'root' in order to see them

mysql -h localhost -u root

android:layout_height 50% of the screen size

You can use android:weightSum="2" on the parent layout combined with android:layout_height="1" on the child layout.

           <LinearLayout
                android:layout_height="match_parent"
                android:layout_width="wrap_content"
                android:weightSum="2"
                >

                <ImageView
                    android:layout_height="1"
                    android:layout_width="wrap_content" />

            </LinearLayout>

Get all dates between two dates in SQL Server

DECLARE @FirstDate DATE = '2018-01-01'
DECLARE @LastDate Date = '2018-12-31'
DECLARE @tbl TABLE(ID INT IDENTITY(1,1) PRIMARY KEY,CurrDate date)
INSERT @tbl VALUES( @FirstDate)
WHILE @FirstDate < @LastDate
BEGIN
SET @FirstDate = DATEADD( day,1, @FirstDate)
INSERT @tbl VALUES( @FirstDate)
END
INSERT @tbl VALUES( @LastDate) 

SELECT * FROM @tbl

overlay two images in android to set an imageview

You can use the code below to solve the problem or download demo here

Create two functions to handle each.

First, the canvas is drawn and the images are drawn on top of each other from point (0,0)

On button click

public void buttonMerge(View view) {

        Bitmap bigImage = BitmapFactory.decodeResource(getResources(), R.drawable.img1);
        Bitmap smallImage = BitmapFactory.decodeResource(getResources(), R.drawable.img2);
        Bitmap mergedImages = createSingleImageFromMultipleImages(bigImage, smallImage);

        img.setImageBitmap(mergedImages);
    }

Function to create an overlay.

private Bitmap createSingleImageFromMultipleImages(Bitmap firstImage, Bitmap secondImage){

    Bitmap result = Bitmap.createBitmap(firstImage.getWidth(), firstImage.getHeight(), firstImage.getConfig());
    Canvas canvas = new Canvas(result);
    canvas.drawBitmap(firstImage, 0f, 0f, null);
    canvas.drawBitmap(secondImage, 10, 10, null);
    return result;
}

Read more

java.net.UnknownHostException: Unable to resolve host "<url>": No address associated with hostname and End of input at character 0 of

If reconnecting the WiFi doesn't work for you, try reboot your device.

This works for me. Hope it helps.

How do I configure PyCharm to run py.test tests?

It's poorly documented to be sure. Once you get add a new configuration from defaults, you will be in the realm of running the "/Applications/PyCharm CE.app/Contents/helpers/pycharm/pytestrunner.py" script. It's not documented and has its own ideas of command line arguments.

You can:

  1. Try to play around, reverse the script, and see if you can somehow get py.test to accept arguments. It might work; it didn't in the first half hour for me.
  2. Just run "py.test *.py" from a console.

Oddly, you will find it hard to find any discussion as JetBrains does a good job of bombing Google algorithms with its own pages.

Check if a key exists inside a json object

function to check undefined and null objects

function elementCheck(objarray, callback) {
        var list_undefined = "";
        async.forEachOf(objarray, function (item, key, next_key) {
            console.log("item----->", item);
            console.log("key----->", key);
            if (item == undefined || item == '') {
                list_undefined = list_undefined + "" + key + "!!  ";
                next_key(null);
            } else {
                next_key(null);
            }
        }, function (next_key) {
            callback(list_undefined);
        })
    }

here is an easy way to check whether object sent is contain undefined or null

var objarray={
"passenger_id":"59b64a2ad328b62e41f9050d",
"started_ride":"1",
"bus_id":"59b8f920e6f7b87b855393ca",
"route_id":"59b1333c36a6c342e132f5d5",
"start_location":"",
"stop_location":""
}
elementCheck(objarray,function(list){
console.log("list");
)

How can I generate a tsconfig.json file?

$ npm run tsc -- --init
This worked for the below package.json

  "devDependencies": {
    "@types/jasmine": "^3.6.2",
    "@types/node": "^14.14.19",
    "jasmine": "^3.6.3",
    "protractor": "^7.0.0",
    "typescript": "^4.1.3"
  },

How do I compile a .c file on my Mac?

You'll need to get a compiler. The easiest way is probably to install XCode development environment from the CDs/DVDs you got with your Mac, which will give you gcc. Then you should be able compile it like

gcc -o mybinaryfile mysourcefile.c

write a shell script to ssh to a remote machine and execute commands

You can follow this approach :

  • Connect to remote machine using Expect Script. If your machine doesn't support expect you can download the same. Writing Expect script is very easy (google to get help on this)
  • Put all the action which needs to be performed on remote server in a shell script.
  • Invoke remote shell script from expect script once login is successful.

Using CSS how to change only the 2nd column of a table

You could designate a class for each cell in the second column.

<table>
<tr><td>Column 1</td><td class="col2">Col 2</td></tr>
<tr><td>Column 1</td><td class="col2">Col 2</td></tr>
<tr><td>Column 1</td><td class="col2">Col 2</td></tr>
<tr><td>Column 1</td><td class="col2">Col 2</td></tr>
</table>

Entity Framework Refresh context?

EF 6

In my scenario, Entity Framework was not picking up the newly updated data. The reason might be the data was updated outside of its scope. Refreshing data after fetching resolved my issue.

private void RefreshData(DBEntity entity)
{
    if (entity == null) return;

    ((IObjectContextAdapter)DbContext).ObjectContext.RefreshAsync(RefreshMode.StoreWins, entity);
}

private void RefreshData(List<DBEntity> entities)
{
    if (entities == null || entities.Count == 0) return;

    ((IObjectContextAdapter)DbContext).ObjectContext.RefreshAsync(RefreshMode.StoreWins, entities);
}

Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints

            using (var tbl = new DataTable())
            using (var rdr = cmd.ExecuteReader())
            {
                tbl.BeginLoadData();

                try
                {
                    tbl.Load(rdr);
                }
                catch (ConstraintException ex)
                {
                    rdr.Close();
                    tbl.Clear();

                    // clear constraints, source of exceptions
                    // note: column schema already loaded!
                    tbl.Constraints.Clear();
                    tbl.Load(cmd.ExecuteReader());
                }
                finally
                {
                    tbl.EndLoadData();
                }
            }

How can I switch to another branch in git?

If you want the branch to track the remote branch, which is very important if you're going to commit changes to the branch and pull changes etc, you need to add a -t for the actual checkout like so: git checkout -t branchname

How to get today's Date?

If you want midnight (0:00am) for the current date, you can just use the default constructor and zero out the time portions:

Date today = new Date();
today.setHours(0); today.setMinutes(0); today.setSeconds(0);

edit: update with Calendar since those methods are deprecated

Calendar today = Calendar.getInstance();
today.clear(Calendar.HOUR); today.clear(Calendar.MINUTE); today.clear(Calendar.SECOND);
Date todayDate = today.getTime();

How to pass an object into a state using UI-router?

No, the URL will always be updated when params are passed to transitionTo.

This happens on state.js:698 in ui-router.

unique combinations of values in selected columns in pandas data frame and count

I haven't done time test with this but it was fun to try. Basically convert two columns to one column of tuples. Now convert that to a dataframe, do 'value_counts()' which finds the unique elements and counts them. Fiddle with zip again and put the columns in order you want. You can probably make the steps more elegant but working with tuples seems more natural to me for this problem

b = pd.DataFrame({'A':['yes','yes','yes','yes','no','no','yes','yes','yes','no'],'B':['yes','no','no','no','yes','yes','no','yes','yes','no']})

b['count'] = pd.Series(zip(*[b.A,b.B]))
df = pd.DataFrame(b['count'].value_counts().reset_index())
df['A'], df['B'] = zip(*df['index'])
df = df.drop(columns='index')[['A','B','count']]

JQuery, select first row of table

This is a better solution, using:

$("table tr:first-child").has('img')

SQLSTATE[HY000] [1045] Access denied for user 'username'@'localhost' using CakePHP

If you use MAMP, you might have to set the socket: unix_socket: /Applications/MAMP/tmp/mysql/mysql.sock

How to close off a Git Branch?

We request that the developer asking for the pull request state that they would like the branch deleted. Most of the time this is the case. There are times when a branch is needed (e.g. copying the changes to another release branch).

My fingers have memorized our process:

git checkout <feature-branch>
git pull
git checkout <release-branch>
git pull
git merge --no-ff <feature-branch>
git push
git tag -a branch-<feature-branch> -m "Merge <feature-branch> into <release-branch>"
git push --tags
git branch -d <feature-branch>
git push origin :<feature-branch>

A branch is for work. A tag marks a place in time. By tagging each branch merge we can resurrect a branch if that is needed. The branch tags have been used several times to review changes.

What is the difference between null=True and blank=True in Django?

The default values of null and blank are False.

Null: It is database-related. Defines if a given database column will accept null values or not.

Blank: It is validation-related. It will be used during forms validation, when calling form.is_valid().

That being said, it is perfectly fine to have a field with null=True and blank=False. Meaning on the database level the field can be NULL, but in the application level it is a required field.

Now, where most developers get it wrong: Defining null=True for string-based fields such as CharField and TextField. Avoid doing that. Otherwise, you will end up having two possible values for “no data”, that is: None and an empty string. Having two possible values for “no data” is redundant. The Django convention is to use the empty string, not NULL.

How to send HTTP request in java?

I know others will recommend Apache's http-client, but it adds complexity (i.e., more things that can go wrong) that is rarely warranted. For a simple task, java.net.URL will do.

URL url = new URL("http://www.y.com/url");
InputStream is = url.openStream();
try {
  /* Now read the retrieved document from the stream. */
  ...
} finally {
  is.close();
}

PHP AES encrypt / decrypt

$sDecrypted and $sEncrypted were undefined in your code. See a solution that works (but is not secure!):


STOP!

This example is insecure! Do not use it!


$Pass = "Passwort";
$Clear = "Klartext";        

$crypted = fnEncrypt($Clear, $Pass);
echo "Encrypred: ".$crypted."</br>";

$newClear = fnDecrypt($crypted, $Pass);
echo "Decrypred: ".$newClear."</br>";        

function fnEncrypt($sValue, $sSecretKey)
{
    return rtrim(
        base64_encode(
            mcrypt_encrypt(
                MCRYPT_RIJNDAEL_256,
                $sSecretKey, $sValue, 
                MCRYPT_MODE_ECB, 
                mcrypt_create_iv(
                    mcrypt_get_iv_size(
                        MCRYPT_RIJNDAEL_256, 
                        MCRYPT_MODE_ECB
                    ), 
                    MCRYPT_RAND)
                )
            ), "\0"
        );
}

function fnDecrypt($sValue, $sSecretKey)
{
    return rtrim(
        mcrypt_decrypt(
            MCRYPT_RIJNDAEL_256, 
            $sSecretKey, 
            base64_decode($sValue), 
            MCRYPT_MODE_ECB,
            mcrypt_create_iv(
                mcrypt_get_iv_size(
                    MCRYPT_RIJNDAEL_256,
                    MCRYPT_MODE_ECB
                ), 
                MCRYPT_RAND
            )
        ), "\0"
    );
}

But there are other problems in this code which make it insecure, in particular the use of ECB (which is not an encryption mode, only a building block on top of which encryption modes can be defined). See Fab Sa's answer for a quick fix of the worst problems and Scott's answer for how to do this right.

Allow only numbers to be typed in a textbox

You could subscribe for the onkeypress event:

<input type="text" class="textfield" value="" id="extra7" name="extra7" onkeypress="return isNumber(event)" />

and then define the isNumber function:

function isNumber(evt) {
    evt = (evt) ? evt : window.event;
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    if (charCode > 31 && (charCode < 48 || charCode > 57)) {
        return false;
    }
    return true;
}

You can see it in action here.

PHP Email sending BCC

You have $headers .= '...'; followed by $headers = '...';; the second line is overwriting the first.

Just put the $headers .= "Bcc: $emailList\r\n"; say after the Content-type line and it should be fine.

On a side note, the To is generally required; mail servers might mark your message as spam otherwise.

$headers  = "From: [email protected]\r\n" .
  "X-Mailer: php\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$headers .= "Bcc: $emailList\r\n";

How to check if a char is equal to an empty space?

Since char is a primitive type, you can just write c == ' '.
You only need to call equals() for reference types like String or Character.

How can I get a collection of keys in a JavaScript dictionary?

Simply use Object.keys():

_x000D_
_x000D_
var driversCounter = {_x000D_
                      "one": 1,_x000D_
                      "two": 2,_x000D_
                      "three": 3,_x000D_
                      "four": 4,_x000D_
                      "five": 5_x000D_
                     }_x000D_
console.log(Object.keys(driversCounter));
_x000D_
_x000D_
_x000D_

How to print Unicode character in C++?

'1060' is four characters, and won't compile under the standard. You should just treat the character as a number, if your wide characters match 1:1 with Unicode (check your locale settings).

int main (){
    wchar_t f = 1060;
    wcout << f << endl;
}

How to move an element down a litte bit in html

You can use vertical-align to move items vertically.

Example:

<div>This is an <span style="vertical-align: -20px;">example</span></div>

This will move the span containing the word 'example' downwards 20 pixels compared to the rest of the text.

The intended use for this property is to align elements of different height (e.g. images with different sizes) along a set line. vertical-align: top will for instance align all images on a line with the top of each image aligning with each other. vertical-align: middle will align all images so that the middle of the images align with each other, regardless of the height of each image.

You can see visual examples in this CodePen by Chris Coyier.

Hope that helps!

How could I convert data from string to long in c#

If you want to get the integer part of that number you must first convert it to a floating number then cast to long.

long l1 = (long)Convert.ToDouble("1100.25");

You can use Math class to round up the number as you like, or just truncate...

Compile c++14-code with g++

G++ does support C++14 both via -std=c++14 and -std=c++1y. The latter was the common name for the standard before it was known in which year it would be released. In older versions (including yours) only the latter is accepted as the release year wasn't known yet when those versions were released.

I used "sudo apt-get install g++" which should automatically retrieve the latest version, is that correct?

It installs the latest version available in the Ubuntu repositories, not the latest version that exists.

The latest GCC version is 5.2.

Resize external website content to fit iFrame width

What you can do is set specific width and height to your iframe (for example these could be equal to your window dimensions) and then applying a scale transformation to it. The scale value will be the ratio between your window width and the dimension you wanted to set to your iframe.

E.g.

<iframe width="1024" height="768" src="http://www.bbc.com" style="-webkit-transform:scale(0.5);-moz-transform-scale(0.5);"></iframe>

Adding items to a JComboBox

You can use any Object as an item. In that object you can have several fields you need. In your case the value field. You have to override the toString() method to represent the text. In your case "item text". See the example:

public class AnyObject {

    private String value;
    private String text;

    public AnyObject(String value, String text) {
        this.value = value;
        this.text = text;
    }

...

    @Override
    public String toString() {
        return text;
    }
}

comboBox.addItem(new AnyObject("item_value", "item text"));

Unsupported operand type(s) for +: 'int' and 'str'

You're trying to concatenate a string and an integer, which is incorrect.

Change print(numlist.pop(2)+" has been removed") to any of these:

Explicit int to str conversion:

print(str(numlist.pop(2)) + " has been removed")

Use , instead of +:

print(numlist.pop(2), "has been removed")

String formatting:

print("{} has been removed".format(numlist.pop(2)))

Virtual Memory Usage from Java under Linux, too much memory used

Sun's java 1.4 has the following arguments to control memory size:

-Xmsn Specify the initial size, in bytes, of the memory allocation pool. This value must be a multiple of 1024 greater than 1MB. Append the letter k or K to indicate kilobytes, or m or M to indicate megabytes. The default value is 2MB. Examples:

           -Xms6291456
           -Xms6144k
           -Xms6m

-Xmxn Specify the maximum size, in bytes, of the memory allocation pool. This value must a multiple of 1024 greater than 2MB. Append the letter k or K to indicate kilobytes, or m or M to indicate megabytes. The default value is 64MB. Examples:

           -Xmx83886080
           -Xmx81920k
           -Xmx80m

http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/java.html

Java 5 and 6 have some more. See http://java.sun.com/javase/technologies/hotspot/vmoptions.jsp

How can I convert a DateTime to an int?

dateDate.Ticks

should give you what you're looking for.

The value of this property represents the number of 100-nanosecond intervals that have elapsed since 12:00:00 midnight, January 1, 0001, which represents DateTime.MinValue. It does not include the number of ticks that are attributable to leap seconds.

DateTime.Ticks


If you're really looking for the Linux Epoch time (seconds since Jan 1, 1970), the accepted answer for this question should be relevant.


But if you're actually trying to "compress" a string representation of the date into an int, you should ask yourself why aren't you just storing it as a string to begin with. If you still want to do it after that, Stecya's answer is the right one. Keep in mind it won't fit into an int, you'll have to use a long.

round up to 2 decimal places in java?

Well this one works...

double roundOff = Math.round(a * 100.0) / 100.0;

Output is

123.14

Or as @Rufein said

 double roundOff = (double) Math.round(a * 100) / 100;

this will do it for you as well.

How do I add an existing directory tree to a project in Visual Studio?

You can also drag and drop the folder from Windows Explorer onto your Visual Studio solution window.

Rails 4 Authenticity Token

If you're using jQuery with rails, be wary of allowing entry to methods without verifying the authenticity token.

jquery-ujs can manage the tokens for you

You should have it already as part of the jquery-rails gem, but you might need to include it in application.js with

//= require jquery_ujs

That's all you need - your ajax call should now work

For more information, see: https://github.com/rails/jquery-ujs

Difference between git stash pop and git stash apply

Quick Answer:

git stash pop -> remove from the stash list

git stash apply -> keep it in the stash list

Convert JSON array to Python list

Tested on Ideone.


import json
array = '{"fruits": ["apple", "banana", "orange"]}'
data  = json.loads(array)
fruits_list = data['fruits']
print fruits_list

The application has stopped unexpectedly: How to Debug?

I'm an Eclipse/Android beginner as well, but hopefully my simple debugging process can help...

You set breakpoints in Eclipse by right-clicking next to the line you want to break at and selecting "Toggle Breakpoint". From there you'll want to select "Debug" rather than the standard "Run", which will allow you to step through and so on. Use the filters provided by LogCat (referenced in your tutorial) so you can target the messages you want rather than wading through all the output. That will (hopefully) go a long way in helping you make sense of your errors.

As for other good tutorials, I was searching around for a few myself, but didn't manage to find any gems yet.

How can I comment a single line in XML?

No, there is no way to comment a line in XML and have the comment end automatically on a linebreak.

XML has only one definition for a comment:

'<!--' ((Char - '-') | ('-' (Char - '-')))* '-->'

XML forbids -- in comments to maintain compatibility with SGML.

Seeding the random number generator in Javascript

No, but here's a simple pseudorandom generator, an implementation of Multiply-with-carry I adapted from Wikipedia (has been removed since):

var m_w = 123456789;
var m_z = 987654321;
var mask = 0xffffffff;

// Takes any integer
function seed(i) {
    m_w = (123456789 + i) & mask;
    m_z = (987654321 - i) & mask;
}

// Returns number between 0 (inclusive) and 1.0 (exclusive),
// just like Math.random().
function random()
{
    m_z = (36969 * (m_z & 65535) + (m_z >> 16)) & mask;
    m_w = (18000 * (m_w & 65535) + (m_w >> 16)) & mask;
    var result = ((m_z << 16) + (m_w & 65535)) >>> 0;
    result /= 4294967296;
    return result;
}

EDIT: fixed seed function by making it reset m_z
EDIT2: Serious implementation flaws have been fixed

Can I use if (pointer) instead of if (pointer != NULL)?

Yes, you can. In fact, I prefer to use if(pointer) because it's simpler to read and write once you get used to it.

Also note that C++11 introduced nullptr which is preferred over NULL.

RequestDispatcher.forward() vs HttpServletResponse.sendRedirect()

Simply difference between Forward(ServletRequest request, ServletResponse response) and sendRedirect(String url) is

forward():

  1. The forward() method is executed in the server side.
  2. The request is transfer to other resource within same server.
  3. It does not depend on the client’s request protocol since the forward () method is provided by the servlet container.
  4. The request is shared by the target resource.
  5. Only one call is consumed in this method.
  6. It can be used within server.
  7. We cannot see forwarded message, it is transparent.
  8. The forward() method is faster than sendRedirect() method.
  9. It is declared in RequestDispatcher interface.

sendRedirect():

  1. The sendRedirect() method is executed in the client side.
  2. The request is transfer to other resource to different server.
  3. The sendRedirect() method is provided under HTTP so it can be used only with HTTP clients.
  4. New request is created for the destination resource.
  5. Two request and response calls are consumed.
  6. It can be used within and outside the server.
  7. We can see redirected address, it is not transparent.
  8. The sendRedirect() method is slower because when new request is created old request object is lost.
  9. It is declared in HttpServletResponse.

Predicate in Java

I'm assuming you're talking about com.google.common.base.Predicate<T> from Guava.

From the API:

Determines a true or false value for a given input. For example, a RegexPredicate might implement Predicate<String>, and return true for any string that matches its given regular expression.

This is essentially an OOP abstraction for a boolean test.

For example, you may have a helper method like this:

static boolean isEven(int num) {
   return (num % 2) == 0; // simple
}

Now, given a List<Integer>, you can process only the even numbers like this:

    List<Integer> numbers = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
    for (int number : numbers) {
        if (isEven(number)) {
            process(number);
        }
    }

With Predicate, the if test is abstracted out as a type. This allows it to interoperate with the rest of the API, such as Iterables, which have many utility methods that takes Predicate.

Thus, you can now write something like this:

    Predicate<Integer> isEven = new Predicate<Integer>() {
        @Override public boolean apply(Integer number) {
            return (number % 2) == 0;
        }               
    };
    Iterable<Integer> evenNumbers = Iterables.filter(numbers, isEven);

    for (int number : evenNumbers) {
        process(number);
    }

Note that now the for-each loop is much simpler without the if test. We've reached a higher level of abtraction by defining Iterable<Integer> evenNumbers, by filter-ing using a Predicate.

API links


On higher-order function

Predicate allows Iterables.filter to serve as what is called a higher-order function. On its own, this offers many advantages. Take the List<Integer> numbers example above. Suppose we want to test if all numbers are positive. We can write something like this:

static boolean isAllPositive(Iterable<Integer> numbers) {
    for (Integer number : numbers) {
        if (number < 0) {
            return false;
        }
    }
    return true;
}

//...
if (isAllPositive(numbers)) {
    System.out.println("Yep!");
}

With a Predicate, and interoperating with the rest of the libraries, we can instead write this:

Predicate<Integer> isPositive = new Predicate<Integer>() {
    @Override public boolean apply(Integer number) {
        return number > 0;
    }       
};

//...
if (Iterables.all(numbers, isPositive)) {
    System.out.println("Yep!");
}

Hopefully you can now see the value in higher abstractions for routines like "filter all elements by the given predicate", "check if all elements satisfy the given predicate", etc make for better code.

Unfortunately Java doesn't have first-class methods: you can't pass methods around to Iterables.filter and Iterables.all. You can, of course, pass around objects in Java. Thus, the Predicate type is defined, and you pass objects implementing this interface instead.

See also

How to check if a column exists in a datatable

For Multiple columns you can use code similar to one given below.I was just going through this and found answer to check multiple columns in Datatable.

 private bool IsAllColumnExist(DataTable tableNameToCheck, List<string> columnsNames)
    {
        bool iscolumnExist = true;
        try
        {
            if (null != tableNameToCheck && tableNameToCheck.Columns != null)
            {
                foreach (string columnName in columnsNames)
                {
                    if (!tableNameToCheck.Columns.Contains(columnName))
                    {
                        iscolumnExist = false;
                        break;
                    }
                }
            }
            else
            {
                iscolumnExist = false;
            }
        }            
        catch (Exception ex)
        {

        }
        return iscolumnExist;
    }

Lining up labels with radio buttons in bootstrap

This is all nicely lined up including the field label. Lining up the field label was the tricky part.

enter image description here

HTML Code:

<div class="form-group">
    <label class="control-label col-md-5">Create a</label>
    <div class="col-md-7">
        <label class="radio-inline control-label">
            <input checked="checked" id="TaskLog_TaskTypeId" name="TaskLog.TaskTypeId" type="radio" value="2"> Task
        </label>
        <label class="radio-inline control-label">
            <input id="TaskLog_TaskTypeId" name="TaskLog.TaskTypeId" type="radio" value="1"> Note
        </label>
    </div>
</div>

CSHTML / Razor Code:

<div class="form-group">
    @Html.Label("Create a", htmlAttributes: new { @class = "control-label col-md-5" })
    <div class="col-md-7">
        <label class="radio-inline control-label">
            @Html.RadioButtonFor(model => model.TaskTypeId, Model.TaskTaskTypeId) Task
        </label>
        <label class="radio-inline control-label">
            @Html.RadioButtonFor(model => model.TaskTypeId, Model.NoteTaskTypeId) Note
        </label>
    </div>
</div>

concatenate char array in C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *name = "hello";

int main(void) {
  char *ext = ".txt";
  int len   = strlen(name) + strlen(ext) + 1;
  char *n2  = malloc(len);
  char *n2a = malloc(len);

  if (n2 == NULL || n2a == NULL)
    abort();

  strlcpy(n2, name, len);
  strlcat(n2, ext, len);
  printf("%s\n", n2);

  /* or for conforming C99 ...  */
  strncpy(n2a, name, len);
  strncat(n2a, ext, len - strlen(n2a));
  printf("%s\n", n2a);

  return 0; // this exits, otherwise free n2 && n2a
}

PHP - Failed to open stream : No such file or directory

There are many reasons why one might run into this error and thus a good checklist of what to check first helps considerably.

Let's consider that we are troubleshooting the following line:

require "/path/to/file"


Checklist


1. Check the file path for typos

  • either check manually (by visually checking the path)
  • or move whatever is called by require* or include* to its own variable, echo it, copy it, and try accessing it from a terminal:

    $path = "/path/to/file";
    
    echo "Path : $path";
    
    require "$path";
    

    Then, in a terminal:

    cat <file path pasted>
    


2. Check that the file path is correct regarding relative vs absolute path considerations

  • if it is starting by a forward slash "/" then it is not referring to the root of your website's folder (the document root), but to the root of your server.
    • for example, your website's directory might be /users/tony/htdocs
  • if it is not starting by a forward slash then it is either relying on the include path (see below) or the path is relative. If it is relative, then PHP will calculate relatively to the path of the current working directory.
    • thus, not relative to the path of your web site's root, or to the file where you are typing
    • for that reason, always use absolute file paths

Best practices :

In order to make your script robust in case you move things around, while still generating an absolute path at runtime, you have 2 options :

  1. use require __DIR__ . "/relative/path/from/current/file". The __DIR__ magic constant returns the directory of the current file.
  2. define a SITE_ROOT constant yourself :

    • at the root of your web site's directory, create a file, e.g. config.php
    • in config.php, write

      define('SITE_ROOT', __DIR__);
      
    • in every file where you want to reference the site root folder, include config.php, and then use the SITE_ROOT constant wherever you like :

      require_once __DIR__."/../config.php";
      ...
      require_once SITE_ROOT."/other/file.php";
      

These 2 practices also make your application more portable because it does not rely on ini settings like the include path.


3. Check your include path

Another way to include files, neither relatively nor purely absolutely, is to rely on the include path. This is often the case for libraries or frameworks such as the Zend framework.

Such an inclusion will look like this :

include "Zend/Mail/Protocol/Imap.php"

In that case, you will want to make sure that the folder where "Zend" is, is part of the include path.

You can check the include path with :

echo get_include_path();

You can add a folder to it with :

set_include_path(get_include_path().":"."/path/to/new/folder");


4. Check that your server has access to that file

It might be that all together, the user running the server process (Apache or PHP) simply doesn't have permission to read from or write to that file.

To check under what user the server is running you can use posix_getpwuid :

$user = posix_getpwuid(posix_geteuid());

var_dump($user);

To find out the permissions on the file, type the following command in the terminal:

ls -l <path/to/file>

and look at permission symbolic notation


5. Check PHP settings

If none of the above worked, then the issue is probably that some PHP settings forbid it to access that file.

Three settings could be relevant :

  1. open_basedir
    • If this is set PHP won't be able to access any file outside of the specified directory (not even through a symbolic link).
    • However, the default behavior is for it not to be set in which case there is no restriction
    • This can be checked by either calling phpinfo() or by using ini_get("open_basedir")
    • You can change the setting either by editing your php.ini file or your httpd.conf file
  2. safe mode
    • if this is turned on restrictions might apply. However, this has been removed in PHP 5.4. If you are still on a version that supports safe mode upgrade to a PHP version that is still being supported.
  3. allow_url_fopen and allow_url_include
    • this applies only to including or opening files through a network process such as http:// not when trying to include files on the local file system
    • this can be checked with ini_get("allow_url_include") and set with ini_set("allow_url_include", "1")


Corner cases

If none of the above enabled to diagnose the problem, here are some special situations that could happen :


1. The inclusion of library relying on the include path

It can happen that you include a library, for example, the Zend framework, using a relative or absolute path. For example :

require "/usr/share/php/libzend-framework-php/Zend/Mail/Protocol/Imap.php"

But then you still get the same kind of error.

This could happen because the file that you have (successfully) included, has itself an include statement for another file, and that second include statement assumes that you have added the path of that library to the include path.

For example, the Zend framework file mentioned before could have the following include :

include "Zend/Mail/Protocol/Exception.php" 

which is neither an inclusion by relative path, nor by absolute path. It is assuming that the Zend framework directory has been added to the include path.

In such a case, the only practical solution is to add the directory to your include path.


2. SELinux

If you are running Security-Enhanced Linux, then it might be the reason for the problem, by denying access to the file from the server.

To check whether SELinux is enabled on your system, run the sestatus command in a terminal. If the command does not exist, then SELinux is not on your system. If it does exist, then it should tell you whether it is enforced or not.

To check whether SELinux policies are the reason for the problem, you can try turning it off temporarily. However be CAREFUL, since this will disable protection entirely. Do not do this on your production server.

setenforce 0

If you no longer have the problem with SELinux turned off, then this is the root cause.

To solve it, you will have to configure SELinux accordingly.

The following context types will be necessary :

  • httpd_sys_content_t for files that you want your server to be able to read
  • httpd_sys_rw_content_t for files on which you want read and write access
  • httpd_log_t for log files
  • httpd_cache_t for the cache directory

For example, to assign the httpd_sys_content_t context type to your website root directory, run :

semanage fcontext -a -t httpd_sys_content_t "/path/to/root(/.*)?"
restorecon -Rv /path/to/root

If your file is in a home directory, you will also need to turn on the httpd_enable_homedirs boolean :

setsebool -P httpd_enable_homedirs 1

In any case, there could be a variety of reasons why SELinux would deny access to a file, depending on your policies. So you will need to enquire into that. Here is a tutorial specifically on configuring SELinux for a web server.


3. Symfony

If you are using Symfony, and experiencing this error when uploading to a server, then it can be that the app's cache hasn't been reset, either because app/cache has been uploaded, or that cache hasn't been cleared.

You can test and fix this by running the following console command:

cache:clear


4. Non ACSII characters inside Zip file

Apparently, this error can happen also upon calling zip->close() when some files inside the zip have non-ASCII characters in their filename, such as "é".

A potential solution is to wrap the file name in utf8_decode() before creating the target file.

Credits to Fran Cano for identifying and suggesting a solution to this issue

Android RatingBar change star colors

For just changing the color of Rating bar from xml:-

android:progressTint="@color/your_color"
android:backgroundTint="@color/your_color"
android:secondaryProgressTint="@color/your_color"

How to output (to a log) a multi-level array in a format that is human-readable?

I just wonder why nobody uses or recommends the way I prefer to debug an array:

error_log(json_encode($array));

Next to my browser I tail my server log in the console eg.

tail -f /var/log/apache2/error.log

Decimal values in SQL for dividing results

SELECT CAST (col1 as float) / col2 FROM tbl1

One cast should work. ("Less is more.")

From Books Online:

Returns the data type of the argument with the higher precedence. For more information about data type precedence, see Data Type Precedence (Transact-SQL).

If an integer dividend is divided by an integer divisor, the result is an integer that has any fractional part of the result truncated

Error: EACCES: permission denied

I have same issue with webpack server installation on globally, Use steps from this Url Solved my issue, my be work for you.

Steps mention above There: Back-up your computer before you start.

Make a directory for global installations:

1. mkdir ~/.npm-global

Configure npm to use the new directory path:

2.npm config set prefix '~/.npm-global'

Open or create a ~/.profile file and add this line:

3.export PATH=~/.npm-global/bin:$PATH

Back on the command line, update your system variables:

4.source ~/.profile

Test: Download a package globally without using sudo.

npm install -g jshint

Instead of steps 2-4, you can use the corresponding ENV variable (e.g. if you don't want to modify ~/.profile):

NPM_CONFIG_PREFIX=~/.npm-global

String contains - ignore case

You can use

org.apache.commons.lang3.StringUtils.containsIgnoreCase(CharSequence str,
                                     CharSequence searchStr);

Checks if CharSequence contains a search CharSequence irrespective of case, handling null. Case-insensitivity is defined as by String.equalsIgnoreCase(String).

A null CharSequence will return false.

This one will be better than regex as regex is always expensive in terms of performance.

For official doc, refer to : StringUtils.containsIgnoreCase

Update :

If you are among the ones who

  • don't want to use Apache commons library
  • don't want to go with the expensive regex/Pattern based solutions,
  • don't want to create additional string object by using toLowerCase,

you can implement your own custom containsIgnoreCase using java.lang.String.regionMatches

public boolean regionMatches(boolean ignoreCase,
                             int toffset,
                             String other,
                             int ooffset,
                             int len)

ignoreCase : if true, ignores case when comparing characters.

public static boolean containsIgnoreCase(String str, String searchStr)     {
    if(str == null || searchStr == null) return false;

    final int length = searchStr.length();
    if (length == 0)
        return true;

    for (int i = str.length() - length; i >= 0; i--) {
        if (str.regionMatches(true, i, searchStr, 0, length))
            return true;
    }
    return false;
}

Missing artifact com.oracle:ojdbc6:jar:11.2.0 in pom.xml

Due to Oracle license restriction, there are no public repositories that provide ojdbc jar.

You need to download it and install in your local repository. Get jar from Oracle and install it in your local maven repository using

mvn install:install-file -Dfile={path/to/your/ojdbc.jar} -DgroupId=com.oracle 
-DartifactId=ojdbc6 -Dversion=11.2.0 -Dpackaging=jar

If you are using ojdbc7, here is the link

Javascript add method to object

There are many ways to create re-usable objects like this in JavaScript. Mozilla have a nice introduction here:

The following will work in your example:

function Foo(){
    this.bar = function (){
        alert("Hello World!");
    }
}

myFoo = new Foo();
myFoo.bar(); // Hello World?????????????????????????????????

How to import Swagger APIs into Postman?

  • Click on the orange button ("choose files")
  • Browse to the Swagger doc (swagger.yaml)
  • After selecting the file, a new collection gets created in POSTMAN. It will contain folders based on your endpoints.

You can also get some sample swagger files online to verify this(if you have errors in your swagger doc).

__init__() got an unexpected keyword argument 'user'

Check your imports. There could be two classes with the same name. Either from your code or from a library you are using. Personally that was the issue.

Cloning an Object in Node.js

var obj2 = JSON.parse(JSON.stringify(obj1));

Converting pfx to pem using openssl

You can use the OpenSSL Command line tool. The following commands should do the trick

openssl pkcs12 -in client_ssl.pfx -out client_ssl.pem -clcerts

openssl pkcs12 -in client_ssl.pfx -out root.pem -cacerts

If you want your file to be password protected etc, then there are additional options.

You can read the entire documentation here.

month name to month number and vice versa in python

One more:

def month_converter(month):
    months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
    return months.index(month) + 1

check if directory exists and delete in one command unix

Why not just use rm -rf /some/dir? That will remove the directory if it's present, otherwise do nothing. Unlike rm -r /some/dir this flavor of the command won't crash if the folder doesn't exist.

How to convert Calendar to java.sql.Date in Java?

Use stmt.setDate(1, new java.sql.Date(cal.getTimeInMillis()))

How to detect shake event with android?

You can also take a look on library Seismic

public class Demo extends Activity implements ShakeDetector.Listener {
  @Override protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    SensorManager sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
    ShakeDetector sd = new ShakeDetector(this);
    sd.start(sensorManager);

    TextView tv = new TextView(this);
    tv.setGravity(CENTER);
    tv.setText("Shake me, bro!");
    setContentView(tv, new LayoutParams(MATCH_PARENT, MATCH_PARENT));
  }

  @Override public void hearShake() {
    Toast.makeText(this, "Don't shake me, bro!", Toast.LENGTH_SHORT).show();
  }
}

How do I discover memory usage of my application in Android?

Note that memory usage on modern operating systems like Linux is an extremely complicated and difficult to understand area. In fact the chances of you actually correctly interpreting whatever numbers you get is extremely low. (Pretty much every time I look at memory usage numbers with other engineers, there is always a long discussion about what they actually mean that only results in a vague conclusion.)

Note: we now have much more extensive documentation on Managing Your App's Memory that covers much of the material here and is more up-to-date with the state of Android.

First thing is to probably read the last part of this article which has some discussion of how memory is managed on Android:

Service API changes starting with Android 2.0

Now ActivityManager.getMemoryInfo() is our highest-level API for looking at overall memory usage. This is mostly there to help an application gauge how close the system is coming to having no more memory for background processes, thus needing to start killing needed processes like services. For pure Java applications, this should be of little use, since the Java heap limit is there in part to avoid one app from being able to stress the system to this point.

Going lower-level, you can use the Debug API to get raw kernel-level information about memory usage: android.os.Debug.MemoryInfo

Note starting with 2.0 there is also an API, ActivityManager.getProcessMemoryInfo, to get this information about another process: ActivityManager.getProcessMemoryInfo(int[])

This returns a low-level MemoryInfo structure with all of this data:

    /** The proportional set size for dalvik. */
    public int dalvikPss;
    /** The private dirty pages used by dalvik. */
    public int dalvikPrivateDirty;
    /** The shared dirty pages used by dalvik. */
    public int dalvikSharedDirty;

    /** The proportional set size for the native heap. */
    public int nativePss;
    /** The private dirty pages used by the native heap. */
    public int nativePrivateDirty;
    /** The shared dirty pages used by the native heap. */
    public int nativeSharedDirty;

    /** The proportional set size for everything else. */
    public int otherPss;
    /** The private dirty pages used by everything else. */
    public int otherPrivateDirty;
    /** The shared dirty pages used by everything else. */
    public int otherSharedDirty;

But as to what the difference is between Pss, PrivateDirty, and SharedDirty... well now the fun begins.

A lot of memory in Android (and Linux systems in general) is actually shared across multiple processes. So how much memory a processes uses is really not clear. Add on top of that paging out to disk (let alone swap which we don't use on Android) and it is even less clear.

Thus if you were to take all of the physical RAM actually mapped in to each process, and add up all of the processes, you would probably end up with a number much greater than the actual total RAM.

The Pss number is a metric the kernel computes that takes into account memory sharing -- basically each page of RAM in a process is scaled by a ratio of the number of other processes also using that page. This way you can (in theory) add up the pss across all processes to see the total RAM they are using, and compare pss between processes to get a rough idea of their relative weight.

The other interesting metric here is PrivateDirty, which is basically the amount of RAM inside the process that can not be paged to disk (it is not backed by the same data on disk), and is not shared with any other processes. Another way to look at this is the RAM that will become available to the system when that process goes away (and probably quickly subsumed into caches and other uses of it).

That is pretty much the SDK APIs for this. However there is more you can do as a developer with your device.

Using adb, there is a lot of information you can get about the memory use of a running system. A common one is the command adb shell dumpsys meminfo which will spit out a bunch of information about the memory use of each Java process, containing the above info as well as a variety of other things. You can also tack on the name or pid of a single process to see, for example adb shell dumpsys meminfo system give me the system process:

** MEMINFO in pid 890 [system] **
                    native   dalvik    other    total
            size:    10940     7047      N/A    17987
       allocated:     8943     5516      N/A    14459
            free:      336     1531      N/A     1867
           (Pss):     4585     9282    11916    25783
  (shared dirty):     2184     3596      916     6696
    (priv dirty):     4504     5956     7456    17916

 Objects
           Views:      149        ViewRoots:        4
     AppContexts:       13       Activities:        0
          Assets:        4    AssetManagers:        4
   Local Binders:      141    Proxy Binders:      158
Death Recipients:       49
 OpenSSL Sockets:        0

 SQL
            heap:      205          dbFiles:        0
       numPagers:        0   inactivePageKB:        0
    activePageKB:        0

The top section is the main one, where size is the total size in address space of a particular heap, allocated is the kb of actual allocations that heap thinks it has, free is the remaining kb free the heap has for additional allocations, and pss and priv dirty are the same as discussed before specific to pages associated with each of the heaps.

If you just want to look at memory usage across all processes, you can use the command adb shell procrank. Output of this on the same system looks like:

  PID      Vss      Rss      Pss      Uss  cmdline
  890   84456K   48668K   25850K   21284K  system_server
 1231   50748K   39088K   17587K   13792K  com.android.launcher2
  947   34488K   28528K   10834K    9308K  com.android.wallpaper
  987   26964K   26956K    8751K    7308K  com.google.process.gapps
  954   24300K   24296K    6249K    4824K  com.android.phone
  948   23020K   23016K    5864K    4748K  com.android.inputmethod.latin
  888   25728K   25724K    5774K    3668K  zygote
  977   24100K   24096K    5667K    4340K  android.process.acore
...
   59     336K     332K      99K      92K  /system/bin/installd
   60     396K     392K      93K      84K  /system/bin/keystore
   51     280K     276K      74K      68K  /system/bin/servicemanager
   54     256K     252K      69K      64K  /system/bin/debuggerd

Here the Vss and Rss columns are basically noise (these are the straight-forward address space and RAM usage of a process, where if you add up the RAM usage across processes you get an ridiculously large number).

Pss is as we've seen before, and Uss is Priv Dirty.

Interesting thing to note here: Pss and Uss are slightly (or more than slightly) different than what we saw in meminfo. Why is that? Well procrank uses a different kernel mechanism to collect its data than meminfo does, and they give slightly different results. Why is that? Honestly I haven't a clue. I believe procrank may be the more accurate one... but really, this just leave the point: "take any memory info you get with a grain of salt; often a very large grain."

Finally there is the command adb shell cat /proc/meminfo that gives a summary of the overall memory usage of the system. There is a lot of data here, only the first few numbers worth discussing (and the remaining ones understood by few people, and my questions of those few people about them often resulting in conflicting explanations):

MemTotal:         395144 kB
MemFree:          184936 kB
Buffers:             880 kB
Cached:            84104 kB
SwapCached:            0 kB

MemTotal is the total amount of memory available to the kernel and user space (often less than the actual physical RAM of the device, since some of that RAM is needed for the radio, DMA buffers, etc).

MemFree is the amount of RAM that is not being used at all. The number you see here is very high; typically on an Android system this would be only a few MB, since we try to use available memory to keep processes running

Cached is the RAM being used for filesystem caches and other such things. Typical systems will need to have 20MB or so for this to avoid getting into bad paging states; the Android out of memory killer is tuned for a particular system to make sure that background processes are killed before the cached RAM is consumed too much by them to result in such paging.

Best way to check for nullable bool in a condition expression (if ...)

Use extensions.

public static class NullableMixin {
    public static bool IsTrue(this System.Nullable<bool> val) {
        return val == true;
    }
    public static bool IsFalse(this System.Nullable<bool> val) {
        return val == false;
    }
    public static bool IsNull(this System.Nullable<bool> val) {
        return val == null;
    }
    public static bool IsNotNull(this System.Nullable<bool> val) {
        return val.HasValue;
    }
}


Nullable<bool> value = null;
if(value.IsTrue()) {
// do something with it
}

Keep only first n characters in a string?

var myString = "Hello, how are you?";
myString.slice(0,8);

angularjs directive call function specified in attribute and pass an argument to it

You can create a directive that executes a function call with params by using the attrName: "&" to reference the expression in the outer scope.

We want to replace the ng-click directive with ng-click-x:

<button ng-click-x="add(a,b)">Add</button>

If we had this scope:

$scope.a = 2;
$scope.b = 2;

$scope.add = function (a, b) {
  $scope.result = parseFloat(a) + parseFloat(b);
}

We could write our directive like so:

angular.module("ng-click-x", [])

.directive('ngClickX', [function () {

  return {

    scope: {

      // Reference the outer scope
      fn: "&ngClickX",

    },

    restrict: "A",

    link: function(scope, elem) {

      function callFn () {
        scope.$apply(scope.fn());
      }

      elem[0].addEventListener('click', callFn);
    }
  };
}]);

Here is a live demo: http://plnkr.co/edit/4QOGLD?p=info

How to determine whether a given Linux is 32 bit or 64 bit?

Simple script to get 64 bit or 32 bit

        if $(getconf LONG_BIT | grep '64'); then
           echo "64 bit system"
        else
            echo "32 bit system"
        fi

Dynamically Add Images React Webpack

Using url-loader, described here (SurviveJS - Loading Images), you can then use in your code :

import LogoImg from 'YOUR_PATH/logo.png';

and

<img src={LogoImg}/>

Edit: a precision, images are inlined in the js archive with this technique. It can be worthy for small images, but use the technique wisely.

What does the clearfix class do in css?

When an element, such as a div is floated, its parent container no longer considers its height, i.e.

<div id="main">
  <div id="child" style="float:left;height:40px;"> Hi</div>
</div>

The parent container will not be be 40 pixels tall by default. This causes a lot of weird little quirks if you're using these containers to structure layout.

So the clearfix class that various frameworks use fixes this problem by making the parent container "acknowledge" the contained elements.

Day to day, I normally just use frameworks such as 960gs, Twitter Bootstrap for laying out and not bothering with the exact mechanics.

Can read more here

http://www.webtoolkit.info/css-clearfix.html

Hide text using css

If the point is simply to make the text inside the element invisible, set the color attribute to have 0 opacity using a rgba value such as color:rgba(0,0,0,0); clean and simple.

Best way to do a PHP switch with multiple values per case?

If anyone else was ever to maintain your code, they would almost certainly do a double take on version 2 -- that's extremely non-standard.

I would stick with version 1. I'm of the school of though that case statements without a statement block of their own should have an explicit // fall through comment next to them to indicate it is indeed your intent to fall through, thereby removing any ambiguity of whether you were going to handle the cases differently and forgot or something.

jQuery - setting the selected value of a select control via its text description

Try

[...mySelect.options].forEach(o=> o.selected = o.text == 'Text C' )

_x000D_
_x000D_
[...mySelect.options].forEach(o=> o.selected = o.text == 'Text C' );
_x000D_
<select id="mySelect">
  <option value="A">Text A</option>
  <option value="B">Text B</option>
  <option value="C">Text C</option>
</select>
_x000D_
_x000D_
_x000D_