Programs & Examples On #Envjs

EnvJS is a simulated JavaScript browser

How can I replace newline or \r\n with <br/>?

Try this:

echo str_replace(array('\r\n', '\n\r', '\n', '\r'), '<br>', $description);

How can I remove an entry in global configuration with git config?

Try this from the command line to change the git config details.

git config --global --replace-all user.name "Your New Name"

git config --global --replace-all user.email "Your new email"

How to get screen dimensions as pixels in Android

If you want the display dimensions in pixels you can use getSize:

Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;

If you're not in an Activity you can get the default Display via WINDOW_SERVICE:

WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();

If you are in a fragment and want to acomplish this just use Activity.WindowManager (in Xamarin.Android) or getActivity().getWindowManager() (in java).

Before getSize was introduced (in API level 13), you could use the getWidth and getHeight methods that are now deprecated:

Display display = getWindowManager().getDefaultDisplay(); 
int width = display.getWidth();  // deprecated
int height = display.getHeight();  // deprecated

For the use case you're describing however, a margin/padding in the layout seems more appropriate.

Another way is: DisplayMetrics

A structure describing general information about a display, such as its size, density, and font scaling. To access the DisplayMetrics members, initialize an object like this:

DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);

We can use widthPixels to get information for:

"The absolute width of the display in pixels."

Example:

Log.d("ApplicationTagName", "Display width in px is " + metrics.widthPixels);

Api level 30 update

final WindowMetrics metrics = windowManager.getCurrentWindowMetrics();
 // Gets all excluding insets
 final WindowInsets windowInsets = metrics.getWindowInsets();
 Insets insets = windowInsets.getInsetsIgnoreVisibility(WindowInsets.Type.navigationBars()
         | WindowInsets.Type.displayCutout());

 int insetsWidth = insets.right + insets.left;
 int insetsHeight = insets.top + insets.bottom;

 // Legacy size that Display#getSize reports
 final Rect bounds = metrics.getBounds();
 final Size legacySize = new Size(bounds.width() - insetsWidth,
         bounds.height() - insetsHeight);

Install msi with msiexec in a Specific Directory

Use APPLICATIONFOLDER="path" for latest msiexec

Case-insensitive search in Rails model

Another approach that no one has mentioned is to add case insensitive finders into ActiveRecord::Base. Details can be found here. The advantage of this approach is that you don't have to modify every model, and you don't have to add the lower() clause to all your case insensitive queries, you just use a different finder method instead.

Error converting data types when importing from Excel to SQL Server 2008

SSIS doesn't implicitly convert data types, so you need to do it explicitly. The Excel connection manager can only handle a few data types and it tries to make a best guess based on the first few rows of the file. This is fully documented in the SSIS documentation.

You have several options:

  • Change your destination data type to float
  • Load to a 'staging' table with data type float using the Import Wizard and then INSERT into the real destination table using CAST or CONVERT to convert the data
  • Create an SSIS package and use the Data Conversion transformation to convert the data

You might also want to note the comments in the Import Wizard documentation about data type mappings.

Change icon on click (toggle)

$("#togglebutton").click(function () {
  $(".fa-arrow-circle-left").toggleClass("fa-arrow-circle-right");
}

I have a button with the id "togglebutton" and an icon from FontAwesome . This can be a way to toggle it . from left arrow to right arrow icon

Iterate over the lines of a string

Here are three possibilities:

foo = """
this is 
a multi-line string.
"""

def f1(foo=foo): return iter(foo.splitlines())

def f2(foo=foo):
    retval = ''
    for char in foo:
        retval += char if not char == '\n' else ''
        if char == '\n':
            yield retval
            retval = ''
    if retval:
        yield retval

def f3(foo=foo):
    prevnl = -1
    while True:
      nextnl = foo.find('\n', prevnl + 1)
      if nextnl < 0: break
      yield foo[prevnl + 1:nextnl]
      prevnl = nextnl

if __name__ == '__main__':
  for f in f1, f2, f3:
    print list(f())

Running this as the main script confirms the three functions are equivalent. With timeit (and a * 100 for foo to get substantial strings for more precise measurement):

$ python -mtimeit -s'import asp' 'list(asp.f3())'
1000 loops, best of 3: 370 usec per loop
$ python -mtimeit -s'import asp' 'list(asp.f2())'
1000 loops, best of 3: 1.36 msec per loop
$ python -mtimeit -s'import asp' 'list(asp.f1())'
10000 loops, best of 3: 61.5 usec per loop

Note we need the list() call to ensure the iterators are traversed, not just built.

IOW, the naive implementation is so much faster it isn't even funny: 6 times faster than my attempt with find calls, which in turn is 4 times faster than a lower-level approach.

Lessons to retain: measurement is always a good thing (but must be accurate); string methods like splitlines are implemented in very fast ways; putting strings together by programming at a very low level (esp. by loops of += of very small pieces) can be quite slow.

Edit: added @Jacob's proposal, slightly modified to give the same results as the others (trailing blanks on a line are kept), i.e.:

from cStringIO import StringIO

def f4(foo=foo):
    stri = StringIO(foo)
    while True:
        nl = stri.readline()
        if nl != '':
            yield nl.strip('\n')
        else:
            raise StopIteration

Measuring gives:

$ python -mtimeit -s'import asp' 'list(asp.f4())'
1000 loops, best of 3: 406 usec per loop

not quite as good as the .find based approach -- still, worth keeping in mind because it might be less prone to small off-by-one bugs (any loop where you see occurrences of +1 and -1, like my f3 above, should automatically trigger off-by-one suspicions -- and so should many loops which lack such tweaks and should have them -- though I believe my code is also right since I was able to check its output with other functions').

But the split-based approach still rules.

An aside: possibly better style for f4 would be:

from cStringIO import StringIO

def f4(foo=foo):
    stri = StringIO(foo)
    while True:
        nl = stri.readline()
        if nl == '': break
        yield nl.strip('\n')

at least, it's a bit less verbose. The need to strip trailing \ns unfortunately prohibits the clearer and faster replacement of the while loop with return iter(stri) (the iter part whereof is redundant in modern versions of Python, I believe since 2.3 or 2.4, but it's also innocuous). Maybe worth trying, also:

    return itertools.imap(lambda s: s.strip('\n'), stri)

or variations thereof -- but I'm stopping here since it's pretty much a theoretical exercise wrt the strip based, simplest and fastest, one.

Can I use jQuery to check whether at least one checkbox is checked?

_x000D_
_x000D_
$('#fm_submit').submit(function(e){_x000D_
    e.preventDefault();_x000D_
    var ck_box = $('input[type="checkbox"]:checked').length;_x000D_
    _x000D_
    // return in firefox or chrome console _x000D_
    // the number of checkbox checked_x000D_
    console.log(ck_box); _x000D_
_x000D_
    if(ck_box > 0){_x000D_
      alert(ck_box);_x000D_
    } _x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<form name = "frmTest[]" id="fm_submit">_x000D_
  <input type="checkbox" value="true" checked="true" >_x000D_
  <input type="checkbox" value="true" checked="true" >_x000D_
  <input type="checkbox" >_x000D_
  <input type="checkbox" >_x000D_
  <input type="submit" id="fm_submit" name="fm_submit" value="Submit">_x000D_
</form>_x000D_
<div class="container"></div>
_x000D_
_x000D_
_x000D_

Generating a Random Number between 1 and 10 Java

The standard way to do this is as follows:

Provide:

  • min Minimum value
  • max Maximum value

and get in return a Integer between min and max, inclusive.

Random rand = new Random();

// nextInt as provided by Random is exclusive of the top value so you need to add 1 

int randomNum = rand.nextInt((max - min) + 1) + min;

See the relevant JavaDoc.

As explained by Aurund, Random objects created within a short time of each other will tend to produce similar output, so it would be a good idea to keep the created Random object as a field, rather than in a method.

Import pandas dataframe column as string not int

Just want to reiterate this will work in pandas >= 0.9.1:

In [2]: read_csv('sample.csv', dtype={'ID': object})
Out[2]: 
                           ID
0  00013007854817840016671868
1  00013007854817840016749251
2  00013007854817840016754630
3  00013007854817840016781876
4  00013007854817840017028824
5  00013007854817840017963235
6  00013007854817840018860166

I'm creating an issue about detecting integer overflows also.

EDIT: See resolution here: https://github.com/pydata/pandas/issues/2247

Update as it helps others:

To have all columns as str, one can do this (from the comment):

pd.read_csv('sample.csv', dtype = str)

To have most or selective columns as str, one can do this:

# lst of column names which needs to be string
lst_str_cols = ['prefix', 'serial']
# use dictionary comprehension to make dict of dtypes
dict_dtypes = {x : 'str'  for x in lst_str_cols}
# use dict on dtypes
pd.read_csv('sample.csv', dtype=dict_dtypes)

How to format a string as a telephone number in C#

As far as I know you can't do this with string.Format ... you would have to handle this yourself. You could just strip out all non-numeric characters and then do something like:

string.Format("({0}) {1}-{2}",
     phoneNumber.Substring(0, 3),
     phoneNumber.Substring(3, 3),
     phoneNumber.Substring(6));

This assumes the data has been entered correctly, which you could use regular expressions to validate.

CardView background color always white

You can do it either in XML or programmatically:

In XML:

card_view:cardBackgroundColor="@android:color/red"

Programmatically:

cardView.setCardBackgroundColor(Color.RED);

How to find the index of an element in an array in Java?

For primitive arrays

Starting with Java 8, the general purpose solution for a primitive array arr, and a value to search val, is:

public static int indexOf(char[] arr, char val) {
    return IntStream.range(0, arr.length).filter(i -> arr[i] == val).findFirst().orElse(-1);
}

This code creates a stream over the indexes of the array with IntStream.range, filters the indexes to keep only those where the array's element at that index is equal to the value searched and finally keeps the first one matched with findFirst. findFirst returns an OptionalInt, as it is possible that no matching indexes were found. So we invoke orElse(-1) to either return the value found or -1 if none were found.

Overloads can be added for int[], long[], etc. The body of the method will remain the same.

For Object arrays

For object arrays, like String[], we could use the same idea and have the filtering step using the equals method, or Objects.equals to consider two null elements equal, instead of ==.

But we can do it in a simpler manner with:

public static <T> int indexOf(T[] arr, T val) {
    return Arrays.asList(arr).indexOf(val);
}

This creates a list wrapper for the input array using Arrays.asList and searches the index of the element with indexOf.

This solution does not work for primitive arrays, as shown here: a primitive array like int[] is not an Object[] but an Object; as such, invoking asList on it creates a list of a single element, which is the given array, not a list of the elements of the array.

Show ImageView programmatically

//LinearLayOut Setup
LinearLayout linearLayout= new LinearLayout(this);
linearLayout.setOrientation(LinearLayout.VERTICAL);

linearLayout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT));

//ImageView Setup
ImageView imageView = new ImageView(this);

//setting image resource
imageView.setImageResource(R.drawable.play);

//setting image position
imageView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, 
LayoutParams.WRAP_CONTENT));

//adding view to layout
linearLayout.addView(imageView);
//make visible to program
setContentView(linearLayout);

Unix ls command: show full path when using options

Try this, works for me: ls -d /a/b/c/*

How to subtract date/time in JavaScript?

You can use getTime() method to convert the Date to the number of milliseconds since January 1, 1970. Then you can easy do any arithmetic operations with the dates. Of course you can convert the number back to the Date with setTime(). See here an example.

Building a fat jar using maven

An alternative is to use the maven shade plugin to build an uber-jar.

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-shade-plugin</artifactId>
    <version> Your Version Here </version>
    <configuration>
            <!-- put your configurations here -->
    </configuration>
    <executions>
            <execution>
                    <phase>package</phase>
                    <goals>
                            <goal>shade</goal>
                    </goals>
            </execution>
    </executions>
</plugin>

Using unset vs. setting a variable to empty

Based on the comments above, here is a simple test:

isunset() { [[ "${!1}" != 'x' ]] && [[ "${!1-x}" == 'x' ]] && echo 1; }
isset()   { [ -z "$(isunset "$1")" ] && echo 1; }

Example:

$ unset foo; [[ $(isunset foo) ]] && echo "It's unset" || echo "It's set"
It's unset
$ foo=     ; [[ $(isunset foo) ]] && echo "It's unset" || echo "It's set"
It's set
$ foo=bar  ; [[ $(isunset foo) ]] && echo "It's unset" || echo "It's set"
It's set

Getting Lat/Lng from Google marker

_x000D_
_x000D_
var map = new google.maps.Map(document.getElementById('map_canvas'), {_x000D_
  zoom: 10,_x000D_
  center: new google.maps.LatLng(13.103, 80.274),_x000D_
  mapTypeId: google.maps.MapTypeId.ROADMAP_x000D_
});_x000D_
_x000D_
var myMarker = new google.maps.Marker({_x000D_
  position: new google.maps.LatLng(18.103, 80.274),_x000D_
  draggable: true_x000D_
});_x000D_
_x000D_
google.maps.event.addListener(myMarker, 'dragend', function(evt) {_x000D_
  document.getElementById('current').innerHTML = '<p>Marker dropped: Current Lat: ' + evt.latLng.lat().toFixed(3) + ' Current Lng: ' + evt.latLng.lng().toFixed(3) + '</p>';_x000D_
});_x000D_
google.maps.event.addListener(myMarker, 'dragstart', function(evt) {_x000D_
  document.getElementById('current').innerHTML = '<p>Currently dragging marker...</p>';_x000D_
});_x000D_
map.setCenter(myMarker.position);_x000D_
myMarker.setMap(map);_x000D_
_x000D_
function getLocation() {_x000D_
  if (navigator.geolocation) {_x000D_
    navigator.geolocation.getCurrentPosition(showPosition);_x000D_
  } else {_x000D_
    x.innerHTML = "Geolocation is not supported by this browser.";_x000D_
  }_x000D_
}_x000D_
_x000D_
function showPosition(position) {_x000D_
  document.getElementById('current').innerHTML = '<p>Marker dropped: Current Lat: ' + position.coords.latitude + ' Current Lng: ' + position.coords.longitude + '</p>';_x000D_
  var myMarker = new google.maps.Marker({_x000D_
    position: new google.maps.LatLng(position.coords.latitude, position.coords.longitude),_x000D_
    draggable: true_x000D_
  });_x000D_
  google.maps.event.addListener(myMarker, 'dragend', function(evt) {_x000D_
    document.getElementById('current').innerHTML = '<p>Marker dropped: Current Lat: ' + evt.latLng.lat().toFixed(3) + ' Current Lng: ' + evt.latLng.lng().toFixed(3) + '</p>';_x000D_
  });_x000D_
  google.maps.event.addListener(myMarker, 'dragstart', function(evt) {_x000D_
    document.getElementById('current').innerHTML = '<p>Currently dragging marker...</p>';_x000D_
  });_x000D_
  map.setCenter(myMarker.position);_x000D_
  myMarker.setMap(map);_x000D_
}_x000D_
getLocation();
_x000D_
#map_canvas {_x000D_
  width: 980px;_x000D_
  height: 500px;_x000D_
}_x000D_
_x000D_
#current {_x000D_
  padding-top: 25px;_x000D_
}
_x000D_
<script src="http://maps.google.com/maps/api/js?sensor=false&.js"></script>_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
_x000D_
<head>_x000D_
_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <section>_x000D_
    <div id='map_canvas'></div>_x000D_
    <div id="current">_x000D_
      <p>Marker dropped: Current Lat:18.103 Current Lng:80.274</p>_x000D_
    </div>_x000D_
  </section>_x000D_
_x000D_
_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

Resize image in PHP

You need to use either PHP's ImageMagick or GD functions to work with images.

With GD, for example, it's as simple as...

function resize_image($file, $w, $h, $crop=FALSE) {
    list($width, $height) = getimagesize($file);
    $r = $width / $height;
    if ($crop) {
        if ($width > $height) {
            $width = ceil($width-($width*abs($r-$w/$h)));
        } else {
            $height = ceil($height-($height*abs($r-$w/$h)));
        }
        $newwidth = $w;
        $newheight = $h;
    } else {
        if ($w/$h > $r) {
            $newwidth = $h*$r;
            $newheight = $h;
        } else {
            $newheight = $w/$r;
            $newwidth = $w;
        }
    }
    $src = imagecreatefromjpeg($file);
    $dst = imagecreatetruecolor($newwidth, $newheight);
    imagecopyresampled($dst, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);

    return $dst;
}

And you could call this function, like so...

$img = resize_image(‘/path/to/some/image.jpg’, 200, 200);

From personal experience, GD's image resampling does dramatically reduce file size too, especially when resampling raw digital camera images.

How to set gradle home while importing existing project in Android studio

In Windows

..\AndroidStudio2.0Beta6\android-studio\gradle\gradle-2.10

What is tail call optimization?

GCC C minimal runnable example with x86 disassembly analysis

Let's see how GCC can automatically do tail call optimizations for us by looking at the generated assembly.

This will serve as an extremely concrete example of what was mentioned in other answers such as https://stackoverflow.com/a/9814654/895245 that the optimization can convert recursive function calls to a loop.

This in turn saves memory and improves performance, since memory accesses are often the main thing that makes programs slow nowadays.

As an input, we give GCC a non-optimized naive stack based factorial:

tail_call.c

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

unsigned factorial(unsigned n) {
    if (n == 1) {
        return 1;
    }
    return n * factorial(n - 1);
}

int main(int argc, char **argv) {
    int input;
    if (argc > 1) {
        input = strtoul(argv[1], NULL, 0);
    } else {
        input = 5;
    }
    printf("%u\n", factorial(input));
    return EXIT_SUCCESS;
}

GitHub upstream.

Compile and disassemble:

gcc -O1 -foptimize-sibling-calls -ggdb3 -std=c99 -Wall -Wextra -Wpedantic \
  -o tail_call.out tail_call.c
objdump -d tail_call.out

where -foptimize-sibling-calls is the name of generalization of tail calls according to man gcc:

   -foptimize-sibling-calls
       Optimize sibling and tail recursive calls.

       Enabled at levels -O2, -O3, -Os.

as mentioned at: How do I check if gcc is performing tail-recursion optimization?

I choose -O1 because:

  • the optimization is not done with -O0. I suspect that this is because there are required intermediate transformations missing.
  • -O3 produces ungodly efficient code that would not be very educative, although it is also tail call optimized.

Disassembly with -fno-optimize-sibling-calls:

0000000000001145 <factorial>:
    1145:       89 f8                   mov    %edi,%eax
    1147:       83 ff 01                cmp    $0x1,%edi
    114a:       74 10                   je     115c <factorial+0x17>
    114c:       53                      push   %rbx
    114d:       89 fb                   mov    %edi,%ebx
    114f:       8d 7f ff                lea    -0x1(%rdi),%edi
    1152:       e8 ee ff ff ff          callq  1145 <factorial>
    1157:       0f af c3                imul   %ebx,%eax
    115a:       5b                      pop    %rbx
    115b:       c3                      retq
    115c:       c3                      retq

With -foptimize-sibling-calls:

0000000000001145 <factorial>:
    1145:       b8 01 00 00 00          mov    $0x1,%eax
    114a:       83 ff 01                cmp    $0x1,%edi
    114d:       74 0e                   je     115d <factorial+0x18>
    114f:       8d 57 ff                lea    -0x1(%rdi),%edx
    1152:       0f af c7                imul   %edi,%eax
    1155:       89 d7                   mov    %edx,%edi
    1157:       83 fa 01                cmp    $0x1,%edx
    115a:       75 f3                   jne    114f <factorial+0xa>
    115c:       c3                      retq
    115d:       89 f8                   mov    %edi,%eax
    115f:       c3                      retq

The key difference between the two is that:

  • the -fno-optimize-sibling-calls uses callq, which is the typical non-optimized function call.

    This instruction pushes the return address to the stack, therefore increasing it.

    Furthermore, this version also does push %rbx, which pushes %rbx to the stack.

    GCC does this because it stores edi, which is the first function argument (n) into ebx, then calls factorial.

    GCC needs to do this because it is preparing for another call to factorial, which will use the new edi == n-1.

    It chooses ebx because this register is callee-saved: What registers are preserved through a linux x86-64 function call so the subcall to factorial won't change it and lose n.

  • the -foptimize-sibling-calls does not use any instructions that push to the stack: it only does goto jumps within factorial with the instructions je and jne.

    Therefore, this version is equivalent to a while loop, without any function calls. Stack usage is constant.

Tested in Ubuntu 18.10, GCC 8.2.

jQuery text() and newlines

Try this:

$(someElem).html('this<br> has<br> newlines);

In a Git repository, how to properly rename a directory?

Basic rename (or move):

git mv <old name> <new name>

Case sensitive rename—eg. from casesensitive to CaseSensitive—you must use a two step:

git mv casesensitive tmp
git mv tmp CaseSensitive

(More about case sensitivity in Git…)

…followed by commit and push would be the simplest way to rename a directory in a git repo.

Most efficient way to map function over numpy array

All above answers compares well, but if you need to use custom function for mapping, and you have numpy.ndarray, and you need to retain the shape of array.

I have compare just two, but it will retain the shape of ndarray. I have used the array with 1 million entries for comparison. Here I use square function, which is also inbuilt in numpy and has great performance boost, since there as was need of something, you can use function of your choice.

import numpy, time
def timeit():
    y = numpy.arange(1000000)
    now = time.time()
    numpy.array([x * x for x in y.reshape(-1)]).reshape(y.shape)        
    print(time.time() - now)
    now = time.time()
    numpy.fromiter((x * x for x in y.reshape(-1)), y.dtype).reshape(y.shape)
    print(time.time() - now)
    now = time.time()
    numpy.square(y)  
    print(time.time() - now)

Output

>>> timeit()
1.162431240081787    # list comprehension and then building numpy array
1.0775556564331055   # from numpy.fromiter
0.002948284149169922 # using inbuilt function

here you can clearly see numpy.fromiter works great considering to simple approach, and if inbuilt function is available please use that.

How to add Certificate Authority file in CentOS 7

copy your certificates inside

/etc/pki/ca-trust/source/anchors/

then run the following command

update-ca-trust

mysqldump with create database line

Here is how to do dump the database (with just the schema):

mysqldump -u root -p"passwd" --no-data --add-drop-database --databases my_db_name | sed 's#/[*]!40000 DROP DATABASE IF EXISTS my_db_name;#' >my_db_name.sql

If you also want the data, remove the --no-data option.

Difference between two dates in MySQL

select TO_CHAR(TRUNC(SYSDATE)+(to_date( '31-MAY-2012 12:25', 'DD-MON-YYYY HH24:MI') 
                             - to_date( '31-MAY-2012 10:37', 'DD-MON-YYYY HH24:MI')), 
        'HH24:MI:SS') from dual

-- result : 01:48:00

OK it's not quite what the OP asked, but it's what I wanted to do :-)

Get value of a string after last slash in JavaScript

As required in Question::

var string1= "foo/bar/test.html";
  if(string1.contains("/"))
  {
      var string_parts = string1.split("/");
    var result = string_parts[string_parts.length - 1];
    console.log(result);
  }  

and for question asked on url (asked for one occurence of '=' )::
[http://stackoverflow.com/questions/24156535/how-to-split-a-string-after-a-particular-character-in-jquery][1]

var string1= "Hello how are =you";
  if(string1.contains("="))
  {
      var string_parts = string1.split("=");
    var result = string_parts[string_parts.length - 1];
    console.log(result);
  }

unknown type name 'uint8_t', MinGW

To use uint8_t type alias, you have to include stdint.h standard header.

Remove Last Comma from a string

First, one should check if the last character is a comma. If it exists, remove it.

if (str.indexOf(',', this.length - ','.length) !== -1) {
    str = str.substring(0, str.length - 1);
}

NOTE str.indexOf(',', this.length - ','.length) can be simplified to str.indexOf(',', this.length - 1)

How to get image width and height in OpenCV?

Also for openCV in python you can do:

img = cv2.imread('myImage.jpg')
height, width, channels = img.shape 

scp or sftp copy multiple files with single command

NOTE: I apologize in advance for answering only a portion of the above question. However, I found these commands to be useful for my current unix needs.

Uploading specific files from a local machine to a remote machine:

~/Desktop/dump_files$ scp file1.txt file2.txt lab1.cpp etc.ext [email protected]:Folder1/DestinationFolderForFiles/

Uploading an entire directory from a local machine to a remote machine:

~$ scp -r Desktop/dump_files [email protected]:Folder1/DestinationFolderForFiles/

Downloading an entire directory from a remote machine to a local machine:

~/Desktop$ scp -r [email protected]:Public/web/ Desktop/

C# Set collection?

I use a wrapper around a Dictionary<T, object>, storing nulls in the values. This gives O(1) add, lookup and remove on the keys, and to all intents and purposes acts like a set.

How can I change the default width of a Twitter Bootstrap modal box?

Bootstrap 3: In order to maintain responsive features for small and extra small devices I did the following:

@media (min-width: 768px) {
.modal-dialog-wide
{ width: 750px;/* your width */ }
}

What is the difference between C++ and Visual C++?

C++ is a programming language and Visual C++ is an IDE for developing with languages such as C and C++.

VC++ contains tools for, amongst others, developing against the .net framework and the Windows API.

SQL Server Creating a temp table for this query

DECLARE #MyTempTable TABLE (SiteName varchar(50), BillingMonth varchar(10), Consumption float)

INSERT INTO #MyTempTable (SiteName, BillingMonth, Consumption)
SELECT  tblMEP_Sites.Name AS SiteName, convert(varchar(10),BillingMonth ,101) AS BillingMonth, SUM(Consumption) AS Consumption
FROM tblMEP_Projects.......  --your joining statements

Here, # - use this to create table inside tempdb
@ - use this to create table as variable.

Get a file name from a path

A possible solution:

string filename = "C:\\MyDirectory\\MyFile.bat";

// Remove directory if present.
// Do this before extension removal incase directory has a period character.
const size_t last_slash_idx = filename.find_last_of("\\/");
if (std::string::npos != last_slash_idx)
{
    filename.erase(0, last_slash_idx + 1);
}

// Remove extension if present.
const size_t period_idx = filename.rfind('.');
if (std::string::npos != period_idx)
{
    filename.erase(period_idx);
}

Detect Route Change with react-router

This is an old question and I don't quite understand the business need of listening for route changes to push a route change; seems roundabout.

BUT if you ended up here because all you wanted was to update the 'page_path' on a react-router route change for google analytics / global site tag / something similar, here's a hook you can now use. I wrote it based on the accepted answer:

useTracking.js

import { useEffect } from 'react'
import { useHistory } from 'react-router-dom'

export const useTracking = (trackingId) => {
  const { listen } = useHistory()

  useEffect(() => {
    const unlisten = listen((location) => {
      // if you pasted the google snippet on your index.html
      // you've declared this function in the global
      if (!window.gtag) return

      window.gtag('config', trackingId, { page_path: location.pathname })
    })

    // remember, hooks that add listeners
    // should have cleanup to remove them
    return unlisten
  }, [trackingId, listen])
}

You should use this hook once in your app, somewhere near the top but still inside a router. I have it on an App.js that looks like this:

App.js

import * as React from 'react'
import { BrowserRouter, Route, Switch } from 'react-router-dom'

import Home from './Home/Home'
import About from './About/About'
// this is the file above
import { useTracking } from './useTracking'

export const App = () => {
  useTracking('UA-USE-YOURS-HERE')

  return (
    <Switch>
      <Route path="/about">
        <About />
      </Route>
      <Route path="/">
        <Home />
      </Route>
    </Switch>
  )
}

// I find it handy to have a named export of the App
// and then the default export which wraps it with
// all the providers I need.
// Mostly for testing purposes, but in this case,
// it allows us to use the hook above,
// since you may only use it when inside a Router
export default () => (
  <BrowserRouter>
    <App />
  </BrowserRouter>
)

c# dictionary one key many values

You can create a very simplistic multi-dictionary, which automates to process of inserting values like this:

public class MultiDictionary<TKey, TValue> : Dictionary<TKey, List<TValue>>
{
    public void Add(TKey key, TValue value)
    {
        if (TryGetValue(key, out List<TValue> valueList)) {
            valueList.Add(value);
        } else {
            Add(key, new List<TValue> { value });
        }
    }
}

This creates an overloaded version of the Add method. The original one allows you to insert a list of items for a key, if no entry for this entry exists yet. This version allows you to insert a single item in any case.

iPhone App Development on Ubuntu

I found one interesting site which seems pretty detailed on how you could setup a ubuntu for iPhone development. But it's a little old from November 2008 for the SDK 2.0.

Ubuntu 8.10 for iPhone open toolchain SDK2.0

The instructions also include something about the Android SDK/Emulator which you can leave out.

Question mark and colon in JavaScript

hsb.s = max != 0 ? 255 * delta / max : 0;

? is a ternary operator. It works like an if in conjunction with the :

!= means not equals

So, the long form of this line would be

if (max != 0) { //if max is not zero
  hsb.s = 255 * delta / max;
} else {
  hsb.s = 0;
}

How do I format date and time on ssrs report?

I am using following in SSRS 2005

=Format(Globals!ExecutionTime,"MM-dd-yyyy" & " ") 
& CStr(Hour(Globals!ExecutionTime))  & ":"
& CStr(Minute(Globals!ExecutionTime))

Or

=Format(Globals!ExecutionTime,"MM-dd-yyyy" & " ") 
& Right("00" & CStr(Hour(Globals!ExecutionTime)), 2)
& ":"
& Right("00" & CStr(Minute(Globals!ExecutionTime)), 2)

Based on comment:

=Format(CDate(Globals!ExecutionTime), "MM-dd-yyyy hh:mm.ss") 

OR

=Format(CDate(Globals!ExecutionTime), "MM-dd-yyyy HH:mm.ss")

The type List is not generic; it cannot be parameterized with arguments [HTTPClient]

I got the same error, but when i did as below, it resolved the issue.
Instead of writing like this:

List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);

use the below one:

ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);

Using pointer to char array, values in that array can be accessed?

Your should create ptr as follows:

char *ptr;

You have created ptr as an array of pointers to chars. The above creates a single pointer to a char.

Edit: complete code should be:

char *ptr;
char arr[5] = {'a','b','c','d','e'};
ptr = arr;
printf("\nvalue:%c", *(ptr+0));

C# Sort and OrderBy comparison

you should calculate the complexity of algorithms used by the methods OrderBy and Sort. QuickSort has a complexity of n (log n) as i remember, where n is the length of the array.

i've searched for orderby's too, but i could not find any information even in msdn library. if you have not any same values and sorting related to only one property, i prefer to use Sort() method; if not than use OrderBy.

How to execute a stored procedure within C# program

No Dapper answer here. So I added one

using Dapper;
using System.Data.SqlClient;

using (var cn = new SqlConnection(@"Server=(local);DataBase=master;Integrated Security=SSPI"))
    cn.Execute("dbo.test", commandType: CommandType.StoredProcedure);

What is the correct way to create a single-instance WPF application?

Update 2017-01-25. After trying few things, I decided to go with VisualBasic.dll it is easier and works better (at least for me). I let my previous answer just as reference...

Just as reference, this is how I did without passing arguments (which I can't find any reason to do so... I mean a single app with arguments that as to be passed out from one instance to another one). If file association is required, then an app should (per users standard expectation) be instanciated for each doc. If you have to pass args to existing app, I think I would used vb dll.

Not passing args (just single instance app), I prefer not registering a new Window message and not override the message loop as defined in Matt Davis Solution. Although it's not a big deal to add a VisualBasic dll, but I prefer not add a new reference just to do single instance app. Also, I do prefer instanciate a new class with Main instead of calling Shutdown from App.Startup override to ensure to exit as soon as possible.

In hope that anybody will like it... or will inspire a little bit :-)

Project startup class should be set as 'SingleInstanceApp'.

public class SingleInstanceApp
{
    [STAThread]
    public static void Main(string[] args)
    {
        Mutex _mutexSingleInstance = new Mutex(true, "MonitorMeSingleInstance");

        if (_mutexSingleInstance.WaitOne(TimeSpan.Zero, true))
        {
            try
            {
                var app = new App();
                app.InitializeComponent();
                app.Run();

            }
            finally
            {
                _mutexSingleInstance.ReleaseMutex();
                _mutexSingleInstance.Close();
            }
        }
        else
        {
            MessageBox.Show("One instance is already running.");

            var processes = Process.GetProcessesByName(Assembly.GetEntryAssembly().GetName().Name);
            {
                if (processes.Length > 1)
                {
                    foreach (var process in processes)
                    {
                        if (process.Id != Process.GetCurrentProcess().Id)
                        {
                            WindowHelper.SetForegroundWindow(process.MainWindowHandle);
                        }
                    }
                }
            }
        }
    }
}

WindowHelper:

using System;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Interop;
using System.Windows.Threading;

namespace HQ.Util.Unmanaged
{
    public class WindowHelper
    {
        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool SetForegroundWindow(IntPtr hWnd);

How to debug a bash script?

sh -x script [arg1 ...]
bash -x script [arg1 ...]

These give you a trace of what is being executed. (See also 'Clarification' near the bottom of the answer.)

Sometimes, you need to control the debugging within the script. In that case, as Cheeto reminded me, you can use:

set -x

This turns debugging on. You can then turn it off again with:

set +x

(You can find out the current tracing state by analyzing $-, the current flags, for x.)

Also, shells generally provide options '-n' for 'no execution' and '-v' for 'verbose' mode; you can use these in combination to see whether the shell thinks it could execute your script — occasionally useful if you have an unbalanced quote somewhere.


There is contention that the '-x' option in Bash is different from other shells (see the comments). The Bash Manual says:

  • -x

    Print a trace of simple commands, for commands, case commands, select commands, and arithmetic for commands and their arguments or associated word lists after they are expanded and before they are executed. The value of the PS4 variable is expanded and the resultant value is printed before the command and its expanded arguments.

That much does not seem to indicate different behaviour at all. I don't see any other relevant references to '-x' in the manual. It does not describe differences in the startup sequence.

Clarification: On systems such as a typical Linux box, where '/bin/sh' is a symlink to '/bin/bash' (or wherever the Bash executable is found), the two command lines achieve the equivalent effect of running the script with execution trace on. On other systems (for example, Solaris, and some more modern variants of Linux), /bin/sh is not Bash, and the two command lines would give (slightly) different results. Most notably, '/bin/sh' would be confused by constructs in Bash that it does not recognize at all. (On Solaris, /bin/sh is a Bourne shell; on modern Linux, it is sometimes Dash — a smaller, more strictly POSIX-only shell.) When invoked by name like this, the 'shebang' line ('#!/bin/bash' vs '#!/bin/sh') at the start of the file has no effect on how the contents are interpreted.

The Bash manual has a section on Bash POSIX mode which, contrary to a long-standing but erroneous version of this answer (see also the comments below), does describe in extensive detail the difference between 'Bash invoked as sh' and 'Bash invoked as bash'.

When debugging a (Bash) shell script, it will be sensible and sane — necessary even — to use the shell named in the shebang line with the -x option. Otherwise, you may (will?) get different behaviour when debugging from when running the script.

Access denied for user 'homestead'@'localhost' (using password: YES)

after config db restart the:

 php artisan serve

If the serve is active before set db config.

Get resultset from oracle stored procedure

Hi I know this was asked a while ago but I've just figured this out and it might help someone else. Not sure if this is exactly what you're looking for but this is how I call a stored proc and view the output using SQL Developer.
In SQL Developer when viewing the proc, right click and choose 'Run' or select Ctrl+F11 to bring up the Run PL/SQL window. This creates a template with the input and output params which you need to modify. My proc returns a sys_refcursor. The tricky part for me was declaring a row type that is exactly equivalent to the select stmt / sys_refcursor being returned by the proc:

DECLARE
  P_CAE_SEC_ID_N NUMBER;
  P_FM_SEC_CODE_C VARCHAR2(200);
  P_PAGE_INDEX NUMBER;
  P_PAGE_SIZE NUMBER;
  v_Return sys_refcursor;
  type t_row is record (CAE_SEC_ID NUMBER,FM_SEC_CODE VARCHAR2(7),rownum number, v_total_count number);
  v_rec t_row;

BEGIN
  P_CAE_SEC_ID_N := NULL;
  P_FM_SEC_CODE_C := NULL;
  P_PAGE_INDEX := 0;
  P_PAGE_SIZE := 25;

  CAE_FOF_SECURITY_PKG.GET_LIST_FOF_SECURITY(
    P_CAE_SEC_ID_N => P_CAE_SEC_ID_N,
    P_FM_SEC_CODE_C => P_FM_SEC_CODE_C,
    P_PAGE_INDEX => P_PAGE_INDEX,
    P_PAGE_SIZE => P_PAGE_SIZE,
    P_FOF_SEC_REFCUR => v_Return
  );
  -- Modify the code to output the variable
  -- DBMS_OUTPUT.PUT_LINE('P_FOF_SEC_REFCUR = ');
  loop
    fetch v_Return into v_rec;
    exit when v_Return%notfound;
    DBMS_OUTPUT.PUT_LINE('sec_id = ' || v_rec.CAE_SEC_ID || 'sec code = ' ||v_rec.FM_SEC_CODE);
  end loop;

END;

C++ int to byte array

Int to byte and vice versa.

unsigned char bytes[4];
unsigned long n = 1024;

bytes[0] = (n >> 24) & 0xFF;
bytes[1] = (n >> 16) & 0xFF;
bytes[2] = (n >> 8) & 0xFF;
bytes[3] = n & 0xFF;

printf("%x %x %x %x\n", bytes[0], bytes[1], bytes[2], bytes[3]);


int num = 0;
for(int i = 0; i < 4; i++)
 {
 num <<= 8;
 num |= bytes[i];
 }


printf("number %d",num);

How to empty the message in a text area with jquery?

A comment to jarijira

Well I have had many issues with .html and .empty() methods for inputs o. If the id represents an input and not another type of html selector like

or use the .val() function to manipulate.

For example: this is the proper way to manipulate input values

<textarea class="form-control" id="someInput"></textarea>

$(document).ready(function () {
     var newVal='test'
     $('#someInput').val('') //clear input value
     $('#someInput').val(newVal) //override w/ the new value
     $('#someInput').val('test2) 
     newVal= $('#someInput').val(newVal) //get input value

}

For improper, but sometimes works For example: this is the proper way to manipulate input values

<textarea class="form-control" id="someInput"></textarea>

$(document).ready(function () {
     var newVal='test'
     $('#someInput').html('') //clear input value
     $('#someInput').empty() //clear html inside of the id
     $('#someInput').html(newVal) //override the html inside of text area w/ string could be '<div>test3</div>
     really overriding with a string manipulates the value, but this is not the best practice as you do not put things besides strings or values inside of an input. 
     newVal= $('#someInput').val(newVal) //get input value

}

An issue that I had was I was using the $getJson method and I was indeed able to use .html calls to manipulate my inputs. However, whenever I had an error or fail on the getJSON I could no longer change my inputs using the .clear and .html calls. I could still return the .val(). After some experimentation and research I discovered that you should only use the .val() function to make changes to input fields.

Convert char* to string C++

std::string str;
char* const s = "test";

str.assign(s);

string& assign (const char* s); => signature FYR

Reference/s here.

Using CMake to generate Visual Studio C++ project files

CMake is actually pretty good for this. The key part was everyone on the Windows side has to remember to run CMake before loading in the solution, and everyone on our Mac side would have to remember to run it before make.

The hardest part was as a Windows developer making sure your structural changes were in the cmakelist.txt file and not in the solution or project files as those changes would probably get lost and even if not lost would not get transferred over to the Mac side who also needed them, and the Mac guys would need to remember not to modify the make file for the same reasons.

It just requires a little thought and patience, but there will be mistakes at first. But if you are using continuous integration on both sides then these will get shook out early, and people will eventually get in the habit.

What does void* mean and how to use it?

C11 standard (n1570) §6.2.2.3 al1 p55 says :

A pointer to void may be converted to or from a pointer to any object type. A pointer to any object type may be converted to a pointer to void and back again; the result shall compare equal to the original pointer.

You can use this generic pointer to store a pointer to any object type, but you can't use usual arithmetic operations with it and you can't deference it.

Php header location redirect not working

Use the following code:

if(isset($_SERVER['HTTPS']) == 'on')
{

    $self = $_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
    ?>

     <script type='text/javascript'>
     window.location.href = 'http://<?php echo $self ?>';
     </script>"
     <?php

     exit();
}
?>

How to make a <div> appear in front of regular text/tables

z-index only works on absolute or relatively positioned elements. I would use an outer div set to position relative. Set the div on top to position absolute to remove it from the flow of the document.

_x000D_
_x000D_
.wrapper {position:relative;width:500px;}_x000D_
_x000D_
.front {_x000D_
  border:3px solid #c00;_x000D_
  background-color:#fff;_x000D_
  width:300px;_x000D_
  position:absolute;_x000D_
  z-index:10;_x000D_
  top:30px;_x000D_
  left:50px;_x000D_
 }_x000D_
  _x000D_
.behind {background-color:#ccc;}
_x000D_
<div class="wrapper">_x000D_
    <p class="front">Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.</p>_x000D_
    <div class="behind">_x000D_
        <p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.</p>_x000D_
        <table>_x000D_
            <thead>_x000D_
                <tr>_x000D_
                    <th>aaa</th>_x000D_
                    <th>bbb</th>_x000D_
                    <th>ccc</th>_x000D_
                    <th>ddd</th>_x000D_
                </tr>_x000D_
            </thead>_x000D_
            <tbody>_x000D_
                <tr>_x000D_
                    <td>111</td>_x000D_
                    <td>222</td>_x000D_
                    <td>333</td>_x000D_
                    <td>444</td>_x000D_
                </tr>_x000D_
            </tbody>_x000D_
        </table>_x000D_
        <p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.</p>_x000D_
    </div> _x000D_
</div> 
_x000D_
_x000D_
_x000D_

How to convert an integer to a character array using C

You may give a shot at using itoa. Another alternative is to use sprintf.

Could not load file or assembly 'System.Web.WebPages.Razor, Version=2.0.0.0

I downgraded via NuGet to MVC 4 and then upgraded again to 5.2.7 and it fixed this issue

Does JavaScript guarantee object property order?

From the JSON standard:

An object is an unordered collection of zero or more name/value pairs, where a name is a string and a value is a string, number, boolean, null, object, or array.

(emphasis mine).

So, no you can't guarantee the order.

Where is Maven's settings.xml located on Mac OS?

I installed mavaen using sdkman because of which the other proposed solution didn't work, as they are applicable if the installation is done via Homebrew or as a standalone binary.

for my solution I did "which mvn" in the terminal which returned: "/Users/samkaz/.sdkman/candidates/maven/current/bin/mvn"

Then after opening the path in a finder and looking around the above directory I found settings.xml in the below folder. "/Users/samkaz/.sdkman/candidates/maven/3.6.3/conf"

How to 'update' or 'overwrite' a python list

You may try this

alist[0] = 2014

but if you are not sure about the position of 123 then you may try like this:

for idx, item in enumerate(alist):
   if 123 in item:
       alist[idx] = 2014

What does T&& (double ampersand) mean in C++11?

It denotes an rvalue reference. Rvalue references will only bind to temporary objects, unless explicitly generated otherwise. They are used to make objects much more efficient under certain circumstances, and to provide a facility known as perfect forwarding, which greatly simplifies template code.

In C++03, you can't distinguish between a copy of a non-mutable lvalue and an rvalue.

std::string s;
std::string another(s);           // calls std::string(const std::string&);
std::string more(std::string(s)); // calls std::string(const std::string&);

In C++0x, this is not the case.

std::string s;
std::string another(s);           // calls std::string(const std::string&);
std::string more(std::string(s)); // calls std::string(std::string&&);

Consider the implementation behind these constructors. In the first case, the string has to perform a copy to retain value semantics, which involves a new heap allocation. However, in the second case, we know in advance that the object which was passed in to our constructor is immediately due for destruction, and it doesn't have to remain untouched. We can effectively just swap the internal pointers and not perform any copying at all in this scenario, which is substantially more efficient. Move semantics benefit any class which has expensive or prohibited copying of internally referenced resources. Consider the case of std::unique_ptr- now that our class can distinguish between temporaries and non-temporaries, we can make the move semantics work correctly so that the unique_ptr cannot be copied but can be moved, which means that std::unique_ptr can be legally stored in Standard containers, sorted, etc, whereas C++03's std::auto_ptr cannot.

Now we consider the other use of rvalue references- perfect forwarding. Consider the question of binding a reference to a reference.

std::string s;
std::string& ref = s;
(std::string&)& anotherref = ref; // usually expressed via template

Can't recall what C++03 says about this, but in C++0x, the resultant type when dealing with rvalue references is critical. An rvalue reference to a type T, where T is a reference type, becomes a reference of type T.

(std::string&)&& ref // ref is std::string&
(const std::string&)&& ref // ref is const std::string&
(std::string&&)&& ref // ref is std::string&&
(const std::string&&)&& ref // ref is const std::string&&

Consider the simplest template function- min and max. In C++03 you have to overload for all four combinations of const and non-const manually. In C++0x it's just one overload. Combined with variadic templates, this enables perfect forwarding.

template<typename A, typename B> auto min(A&& aref, B&& bref) {
    // for example, if you pass a const std::string& as first argument,
    // then A becomes const std::string& and by extension, aref becomes
    // const std::string&, completely maintaining it's type information.
    if (std::forward<A>(aref) < std::forward<B>(bref))
        return std::forward<A>(aref);
    else
        return std::forward<B>(bref);
}

I left off the return type deduction, because I can't recall how it's done offhand, but that min can accept any combination of lvalues, rvalues, const lvalues.

how to Call super constructor in Lombok

Lombok does not support that also indicated by making any @Value annotated class final (as you know by using @NonFinal).

The only workaround I found is to declare all members final yourself and use the @Data annotation instead. Those subclasses need to be annotated by @EqualsAndHashCode and need an explicit all args constructor as Lombok doesn't know how to create one using the all args one of the super class:

@Data
public class A {
    private final int x;
    private final int y;
}

@Data
@EqualsAndHashCode(callSuper = true)
public class B extends A {
    private final int z;

    public B(int x, int y, int z) {
        super(x, y);
        this.z = z;
    }
}

Especially the constructors of the subclasses make the solution a little untidy for superclasses with many members, sorry.

How do you install GLUT and OpenGL in Visual Studio 2012?

OpenGL is bundled with Visual Studio. You just need to install GLUT package (freeglut would be fine), which can be found in NuGet.

Open your solution, click TOOLS->NuGet Package Manager->Package Manager Console to open a NuGet console, type Install-Package freeglut.

--

For VS 2013, use nupengl.core package instead.

--

It's 2020 now. Use VCPKG.

Trying to read cell 1,1 in spreadsheet using Google Script API

You have to first obtain the Range object. Also, getCell() will not return the value of the cell but instead will return a Range object of the cell. So, use something on the lines of

function email() {

// Opens SS by its ID

var ss = SpreadsheetApp.openById("0AgJjDgtUl5KddE5rR01NSFcxYTRnUHBCQ0stTXNMenc");

// Get the name of this SS

var name = ss.getName();  // Not necessary 

// Read cell 1,1 * Line below does't work *

// var data = Range.getCell(0, 0);
var sheet = ss.getSheetByName('Sheet1'); // or whatever is the name of the sheet 
var range = sheet.getRange(1,1); 
var data = range.getValue();

}

The hierarchy is Spreadsheet --> Sheet --> Range --> Cell.

WP -- Get posts by category?

'category_name'=>'this cat' also works but isn't printed in the WP docs

Eclipse Build Path Nesting Errors

Got similar issue. Did following steps, issue resolved:

  1. Remove project in eclipse.
  2. Delete .Project file and . Settings folder.
  3. Import project as existing maven project again to eclipse.

How can I close a dropdown on click outside?

NOTE: For those wanting to use web workers and you need to avoid using document and nativeElement this will work.

I answered the same question here: https://stackoverflow.com/questions/47571144

Copy/Paste from the above link:

I had the same issue when I was making a drop-down menu and a confirmation dialog I wanted to dismiss them when clicking outside.

My final implementation works perfectly but requires some css3 animations and styling.

NOTE: i have not tested the below code, there may be some syntax problems that need to be ironed out, also the obvious adjustments for your own project!

What i did:

I made a separate fixed div with height 100%, width 100% and transform:scale(0), this is essentially the background, you can style it with background-color: rgba(0, 0, 0, 0.466); to make obvious the menu is open and the background is click-to-close. The menu gets a z-index higher than everything else, then the background div gets a z-index lower than the menu but also higher than everything else. Then the background has a click event that close the drop-down.

Here it is with your html code.

<div class="dropdownbackground" [ngClass]="{showbackground: qtydropdownOpened}" (click)="qtydropdownOpened = !qtydropdownOpened"><div>
<div class="zindex" [class.open]="qtydropdownOpened">
  <button (click)="qtydropdownOpened = !qtydropdownOpened" type="button" 
         data-toggle="dropdown" aria-haspopup="true" [attr.aria-expanded]="qtydropdownOpened ? 'true': 'false' ">
   {{selectedqty}}<span class="caret margin-left-1x "></span>
 </button>
  <div class="dropdown-wrp dropdown-menu">
  <ul class="default-dropdown">
      <li *ngFor="let quantity of quantities">
       <a (click)="qtydropdownOpened = !qtydropdownOpened;setQuantity(quantity)">{{quantity  }}</a>
       </li>
   </ul>
  </div>
 </div>

Here is the css3 which needs some simple animations.

/* make sure the menu/drop-down is in front of the background */
.zindex{
    z-index: 3;
}

/* make background fill the whole page but sit behind the drop-down, then
scale it to 0 so its essentially gone from the page */
.dropdownbackground{
    width: 100%;
    height: 100%;
    position: fixed;
    z-index: 2;
    transform: scale(0);
    opacity: 0;
    background-color: rgba(0, 0, 0, 0.466);
}

/* this is the class we add in the template when the drop down is opened
it has the animation rules set these how you like */
.showbackground{
    animation: showBackGround 0.4s 1 forwards; 

}

/* this animates the background to fill the page
if you don't want any thing visual you could use a transition instead */
@keyframes showBackGround {
    1%{
        transform: scale(1);
        opacity: 0;
    }
    100% {
        transform: scale(1);
        opacity: 1;
    }
}

If you aren't after anything visual you can just use a transition like this

.dropdownbackground{
    width: 100%;
    height: 100%;
    position: fixed;
    z-index: 2;
    transform: scale(0);
    opacity: 0;
    transition all 0.1s;
}

.dropdownbackground.showbackground{
     transform: scale(1);
}

How can I generate a list or array of sequential integers in Java?

This is the shortest I could find.

List version

public List<Integer> makeSequence(int begin, int end)
{
    List<Integer> ret = new ArrayList<Integer>(++end - begin);

    for (; begin < end; )
        ret.add(begin++);

    return ret;
}

Array Version

public int[] makeSequence(int begin, int end)
{
    if(end < begin)
        return null;

    int[] ret = new int[++end - begin];
    for (int i=0; begin < end; )
        ret[i++] = begin++;
    return ret;
}

javascript convert int to float

JavaScript only has a Number type that stores floating point values.

There is no int.

Edit:

If you want to format the number as a string with two digits after the decimal point use:

(4).toFixed(2)

Initialization of all elements of an array to one default value in C++?

1) When you use an initializer, for a struct or an array like that, the unspecified values are essentially default constructed. In the case of a primitive type like ints, that means they will be zeroed. Note that this applies recursively: you could have an array of structs containing arrays and if you specify just the first field of the first struct, then all the rest will be initialized with zeros and default constructors.

2) The compiler will probably generate initializer code that is at least as good as you could do by hand. I tend to prefer to let the compiler do the initialization for me, when possible.

Hadoop cluster setup - java.net.ConnectException: Connection refused

For me it was that I could not cluster my zookeeper.

hdfs haadmin -getServiceState 1
active

hdfs haadmin -getServiceState 2
active

My hadoop-hdfs-zkfc-[hostname].log showed:

2017-04-14 11:46:55,351 WARN org.apache.hadoop.ha.HealthMonitor: Transport-level exception trying to monitor health of NameNode at HOST/192.168.1.55:9000: java.net.ConnectException: Connection refused Call From HOST/192.168.1.55 to HOST:9000 failed on connection exception: java.net.ConnectException: Connection refused; For more details see: http://wiki.apache.org/hadoop/ConnectionRefused

solution:

hdfs-site.xml
  <property>
    <name>dfs.namenode.rpc-bind-host</name>
      <value>0.0.0.0</value>
  </property>

before

netstat -plunt

tcp        0      0 192.168.1.55:9000        0.0.0.0:*               LISTEN      13133/java

nmap localhost -p 9000

Starting Nmap 6.40 ( http://nmap.org ) at 2017-04-14 12:15 EDT
Nmap scan report for localhost (127.0.0.1)
Host is up (0.000047s latency).
Other addresses for localhost (not scanned): 127.0.0.1
PORT     STATE  SERVICE
9000/tcp closed cslistener

after

netstat -plunt
tcp        0      0 0.0.0.0:9000            0.0.0.0:*               LISTEN      14372/java

nmap localhost -p 9000

Starting Nmap 6.40 ( http://nmap.org ) at 2017-04-14 12:28 EDT
Nmap scan report for localhost (127.0.0.1)
Host is up (0.000039s latency).
Other addresses for localhost (not scanned): 127.0.0.1
PORT     STATE SERVICE
9000/tcp open  cslistener

PHP substring extraction. Get the string before the first '/' or the whole string

What about this :

substr($mystring.'/', 0, strpos($mystring, '/'))

Simply add a '/' to the end of mystring so you can be sure there is at least one ;)

How to read a list of files from a folder using PHP?

The simplest and most fun way (imo) is glob

foreach (glob("*.*") as $filename) {
    echo $filename."<br />";
}

But the standard way is to use the directory functions.

if (is_dir($dir)) {
    if ($dh = opendir($dir)) {
        while (($file = readdir($dh)) !== false) {
            echo "filename: .".$file."<br />";
        }
        closedir($dh);
    }
}

There are also the SPL DirectoryIterator methods. If you are interested

Session only cookies with Javascript

Yes, that is correct.

Not putting an expires part in will create a session cookie, whether it is created in JavaScript or on the server.

See https://stackoverflow.com/a/532660/1901857

jQuery callback on image load (even when the image is cached)

I had this problem with IE where the e.target.width would be undefined. The load event would fire but I couldn't get the dimensions of the image in IE (chrome + FF worked).

Turns out you need to look for e.currentTarget.naturalWidth & e.currentTarget.naturalHeight.

Once again, IE does things it's own (more complicated) way.

Collection was modified; enumeration operation may not execute

When a subscriber unsubscribes you are changing contents of the collection of Subscribers during enumeration.

There are several ways to fix this, one being changing the for loop to use an explicit .ToList():

public void NotifySubscribers(DataRecord sr)  
{
    foreach(Subscriber s in subscribers.Values.ToList())
    {
                                              ^^^^^^^^^  
        ...

Regex to check with starts with http://, https:// or ftp://

You need a whole input match here.

System.out.println(test.matches("^(http|https|ftp)://.*$")); 

Edit:(Based on @davidchambers's comment)

System.out.println(test.matches("^(https?|ftp)://.*$")); 

Invoking a static method using reflection

String methodName= "...";
String[] args = {};

Method[] methods = clazz.getMethods();
for (Method m : methods) {
    if (methodName.equals(m.getName())) {
        // for static methods we can use null as instance of class
        m.invoke(null, new Object[] {args});
        break;
    }
}

Mongoose query where value is not null

You should be able to do this like (as you're using the query api):

Entrant.where("pincode").ne(null)

... which will result in a mongo query resembling:

entrants.find({ pincode: { $ne: null } })

A few links that might help:

Purpose of returning by const value?

It makes sure that the returned object (which is an RValue at that point) can't be modified. This makes sure the user can't do thinks like this:

myFunc() = Object(...);

That would work nicely if myFunc returned by reference, but is almost certainly a bug when returned by value (and probably won't be caught by the compiler). Of course in C++11 with its rvalues this convention doesn't make as much sense as it did earlier, since a const object can't be moved from, so this can have pretty heavy effects on performance.

Shortcut to Apply a Formula to an Entire Column in Excel

If the formula already exists in a cell you can fill it down as follows:

  • Select the cell containing the formula and press CTRL+SHIFT+DOWN to select the rest of the column (CTRL+SHIFT+END to select up to the last row where there is data)
  • Fill down by pressing CTRL+D
  • Use CTRL+UP to return up

On Mac, use CMD instead of CTRL.

An alternative if the formula is in the first cell of a column:

  • Select the entire column by clicking the column header or selecting any cell in the column and pressing CTRL+SPACE
  • Fill down by pressing CTRL+D

How do I get column datatype in Oracle with PL-SQL with low privileges?

You can try this.

SELECT *
  FROM (SELECT column_name,
               data_type,
               data_type
               || CASE
                     WHEN data_precision IS NOT NULL
                          AND NVL (data_scale, 0) > 0
                     THEN
                        '(' || data_precision || ',' || data_scale || ')'
                     WHEN data_precision IS NOT NULL
                          AND NVL (data_scale, 0) = 0
                     THEN
                        '(' || data_precision || ')'
                     WHEN data_precision IS NULL AND data_scale IS NOT NULL
                     THEN
                        '(*,' || data_scale || ')'
                     WHEN char_length > 0
                     THEN
                        '(' || char_length
                        || CASE char_used
                              WHEN 'B' THEN ' Byte'
                              WHEN 'C' THEN ' Char'
                              ELSE NULL
                           END
                        || ')'
                  END
               || DECODE (nullable, 'N', ' NOT NULL')
                  DataTypeWithLength
          FROM user_tab_columns
         WHERE table_name = 'CONTRACT')
 WHERE DataTypeWithLength = 'CHAR(1 Byte)';

multiple plot in one figure in Python

Since I don't have a high enough reputation to comment I'll answer liang question on Feb 20 at 10:01 as an answer to the original question.

In order for the for the line labels to show you need to add plt.legend to your code. to build on the previous example above that also includes title, ylabel and xlabel:

import matplotlib.pyplot as plt

plt.plot(<X AXIS VALUES HERE>, <Y AXIS VALUES HERE>, 'line type', label='label here')
plt.plot(<X AXIS VALUES HERE>, <Y AXIS VALUES HERE>, 'line type', label='label here')
plt.title('title')
plt.ylabel('ylabel')
plt.xlabel('xlabel')
plt.legend()
plt.show()

How can I get the current date and time in UTC or GMT in Java?

If you want to avoid parsing the date and just want a timestamp in GMT, you could use:

final Date gmt = new Timestamp(System.currentTimeMillis()
            - Calendar.getInstance().getTimeZone()
                    .getOffset(System.currentTimeMillis()));

Change Circle color of radio button

There is an xml attribute for it:

android:buttonTint="yourcolor"

How can I concatenate a string within a loop in JSTL/JSP?

define a String variable using the JSP tags

<%!
String test = new String();
%>

then refer to that variable in your loop as

<c:forEach items="${myParams.items}" var="currentItem" varStatus="stat">
test+= whaterver_value
</c:forEach>

How can I echo a newline in a batch file?

This solution works(Tested):

type nul | more /e /p

This converts isolated line feeds to carriage return line feed combination.

What do \t and \b do?

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

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

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

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

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

LaTeX Optional Arguments

Example from the guide:

\newcommand{\example}[2][YYY]{Mandatory arg: #2;
                                 Optional arg: #1.}

This defines \example to be a command with two arguments, 
referred to as #1 and #2 in the {<definition>}--nothing new so far. 
But by adding a second optional argument to this \newcommand 
(the [YYY]) the first argument (#1) of the newly defined 
command \example is made optional with its default value being YYY.

Thus the usage of \example is either:

   \example{BBB}
which prints:
Mandatory arg: BBB; Optional arg: YYY.
or:
   \example[XXX]{AAA}
which prints:
Mandatory arg: AAA; Optional arg: XXX.

How do you stretch an image to fill a <div> while keeping the image's aspect-ratio?

This did the trick for me

div img {
    width: 100%;
    min-height: 500px;
    width: 100vw;
    height: 100vh;
    object-fit: cover;
}

Multi-select dropdown list in ASP.NET

jQuery Dropdown Check List can be used to transform a regular multiple select html element into a dropdown checkbox list, it works on client so can be used with any server side technology:

alt text
(source: googlecode.com)

SQL SERVER DATETIME FORMAT

In MS SQL Server you can do:

SET DATEFORMAT ymd

How to clear textarea on click?

You may try this code,

<textarea name="textarea" cols="70" rows="2" class="searchBox" id="textarea" onfocus="if(this.value == 'Please describe why') this.value='';" onblur="if(this.value == '') this.value='Please describe why';">Please describe why</textarea>

SSRS Query execution failed for dataset

BIGHAP: A SIMPLE WORK AROUND FOR THIS ISSUE.

I ran into the same problem when working with SharePoint lists as the DataSource, and read the blogs above which were very helpful. I had made changes in both the DataSource and Data object names and query fields in Visual Studio and the query worked in visual Studio. I was able to deploy the report to SharePoint but when I tried to open it I received the same error.

I guessed that the issue was that I needed to redeploy both the DataSource and the DataSet to SharePoint so that that changes in the rendering tools were all synced.

I redeployed the DataSource, DataSet and the Report to sharePoint and it worked. As one of the blogs stated, although visual studio allowed the changes I made in the dataset and datasource, if you have not set visual studio to automatically redeploy datasource and dataset when you deploy the report(which can be dangerous, because this can affect other reports which share these objects) this error can occur.

So, of course the fix is that in this case you have to redeploy datasource, dataset and Report to resolve the issue.

How to make remote REST call inside Node.js? any CURL?

To use latest Async/Await features

https://www.npmjs.com/package/request-promise-native

npm install --save request
npm install --save request-promise-native

//code

async function getData (){
    try{
          var rp = require ('request-promise-native');
          var options = {
          uri:'https://reqres.in/api/users/2',
          json:true
        };

        var response = await rp(options);
        return response;
    }catch(error){
        throw error;
    }        
}

try{
    console.log(getData());
}catch(error){
    console.log(error);
}

How to grant permission to users for a directory using command line in Windows?

I struggled with this for a while and only combining the answers in this thread worked for me (on Windows 10):
1. Open cmd or PowerShell and go to the folder with files
2. takeown /R /F .
3. icacls * /T /grant dan:F

Good luck!

How to use subprocess popen Python

In the recent Python version, subprocess has a big change. It offers a brand-new class Popen to handle os.popen1|2|3|4.

The new subprocess.Popen()

import subprocess
subprocess.Popen('ls -la', shell=True)

Its arguments:

subprocess.Popen(args, 
                bufsize=0, 
                executable=None, 
                stdin=None, stdout=None, stderr=None, 
                preexec_fn=None, close_fds=False, 
                shell=False, 
                cwd=None, env=None, 
                universal_newlines=False, 
                startupinfo=None, 
                creationflags=0)

Simply put, the new Popen includes all the features which were split into 4 separate old popen.

The old popen:

Method  Arguments
popen   stdout
popen2  stdin, stdout
popen3  stdin, stdout, stderr
popen4  stdin, stdout and stderr

You could get more information in Stack Abuse - Robert Robinson. Thank him for his devotion.

What’s the difference between "Array()" and "[]" while declaring a JavaScript array?

I've incurred in a weird behaviour using [].

We have Model "classes" with fields initialised to some value. E.g.:

require([
  "dojo/_base/declare",
  "dijit/_WidgetBase",
], function(declare, parser, ready, _WidgetBase){

   declare("MyWidget", [_WidgetBase], {
     field1: [],
     field2: "",
     function1: function(),
     function2: function()
   });    
});

I found that when the fields are initialised with [] then it would be shared by all Model objects. Making changes to one affects all others.

This doesn't happen initialising them with new Array(). Same for the initialisation of Objects ({} vs new Object())

TBH I am not sure if its a problem with the framework we were using (Dojo)

Get the selected option id with jQuery

$('#my_select option:selected').attr('id');

Bash script plugin for Eclipse?

There exists now a dedicated bash script plugin called "Bash editor". It's available at eclipse market place:

Bash editor log

You can find it at https://marketplace.eclipse.org/content/bash-editor or by marketplace client when searching for "bash".

The plugin does also provide a debugger. Inisde official Bash Editor YouTube playlist you can find some tutorials about usage etc.

PS: I am the author of the mentioned plugin.

Assert that a WebElement is not present using Selenium WebDriver with java

It looks like findElements() only returns quickly if it finds at least one element. Otherwise it waits for the implicit wait timeout, before returning zero elements - just like findElement().

To keep the speed of the test good, this example temporarily shortens the implicit wait, while waiting for the element to disappear:

static final int TIMEOUT = 10;

public void checkGone(String id) {
    FluentWait<WebDriver> wait = new WebDriverWait(driver, TIMEOUT)
            .ignoring(StaleElementReferenceException.class);

    driver.manage().timeouts().implicitlyWait(1, TimeUnit.SECONDS);
    try {
        wait.until(ExpectedConditions.numberOfElementsToBe(By.id(id), 0));
    } finally {
        resetTimeout();
    }
}

void resetTimeout() {
    driver.manage().timeouts().implicitlyWait(TIMEOUT, TimeUnit.SECONDS);
}

Still looking for a way to avoid the timeout completely though...

How do I conditionally apply CSS styles in AngularJS?

Another option when you need a simple css style of one or two properties:

View:

<tr ng-repeat="element in collection">
    [...amazing code...] 
    <td ng-style="{'background-color': getTrColor(element.myvar)}">
        {{ element.myvar }}
    </td>
    [...more amazing code...]
</tr>

Controller:

$scope.getTrColor = function (colorIndex) {
    switch(colorIndex){
        case 0: return 'red';
        case 1: return 'green';
        default: return 'yellow';
    }
};

Code formatting shortcuts in Android Studio for Operation Systems

Some times even I type Ctrl+Alt+L is not working in XML, so found this way to make it work.

Go to Settings --> Editor --> Code Style --> Select Default --> Ok.

For your reference see the screenshot:

enter image description here

Angular2 RC5: Can't bind to 'Property X' since it isn't a known property of 'Child Component'

I ran into the same error, when I just forgot to declare my custom component in my NgModule - check there, if the others solutions won't work for you.

jQuery selector first td of each row

try this selector -

$("tr").find("td:first")

Demo --> http://jsfiddle.net/66HbV/

Or

$("tr td:first-child")

Demo --> http://jsfiddle.net/66HbV/1/

</td>foobar</td> should be <td>foobar</td>

How to change date format from DD/MM/YYYY or MM/DD/YYYY to YYYY-MM-DD?

We can do something like this

DateTime date_temp_from = DateTime.Parse(from.Value); //from.value" is input by user (dd/MM/yyyy)
DateTime date_temp_to = DateTime.Parse(to.Value); //to.value" is input by user (dd/MM/yyyy)

string date_from = date_temp_from.ToString("yyyy/MM/dd HH:mm");
string date_to = date_temp_to.ToString("yyyy/MM/dd HH:mm");

Thank you

check if array is empty (vba excel)

Above methods didn´t work for me. This did:

  Dim arrayIsNothing As Boolean

    On Error Resume Next
    arrayIsNothing = IsNumeric(UBound(YOUR_ARRAY)) And False
    If Err.Number <> 0 Then arrayIsNothing = True
    Err.Clear
    On Error GoTo 0

    'Now you can test:
    if arrayIsNothing then ...

Python: How to get stdout after running os.system?

These answers didn't work for me. I had to use the following:

import subprocess
p = subprocess.Popen(["pwd"], stdout=subprocess.PIPE)
out = p.stdout.read()
print out

Or as a function (using shell=True was required for me on Python 2.6.7 and check_output was not added until 2.7, making it unusable here):

def system_call(command):
    p = subprocess.Popen([command], stdout=subprocess.PIPE, shell=True)
    return p.stdout.read()

CREATE FILE encountered operating system error 5(failed to retrieve text for this error. Reason: 15105)

In my case I have got the error when trying to create a databae on a new drive. To overcome the problem I created a new folder in that drive and set the user properties Security to full control on it(It may be sufficient to set Modify ). Conclusion: SET the Drive/Folder Properties Security for users to "Modify".

Split output of command by columns using Bash?

Similar to brianegge's awk solution, here is the Perl equivalent:

ps | egrep 11383 | perl -lane 'print $F[3]'

-a enables autosplit mode, which populates the @F array with the column data.
Use -F, if your data is comma-delimited, rather than space-delimited.

Field 3 is printed since Perl starts counting from 0 rather than 1

Virtual Serial Port for Linux

I can think of three options:

Implement RFC 2217

RFC 2217 covers a com port to TCP/IP standard that allows a client on one system to emulate a serial port to the local programs, while transparently sending and receiving data and control signals to a server on another system which actually has the serial port. Here's a high-level overview.

What you would do is find or implement a client com port driver that would implement the client side of the system on your PC - appearing to be a real serial port but in reality shuttling everything to a server. You might be able to get this driver for free from Digi, Lantronix, etc in support of their real standalone serial port servers.

You would then implement the server side of the connection locally in another program - allowing the client to connect and issuing the data and control commands as needed.

It's probably non trivial, but the RFC is out there, and you might be able to find an open source project that implements one or both sides of the connection.

Modify the linux serial port driver

Alternately, the serial port driver source for Linux is readily available. Take that, gut the hardware control pieces, and have that one driver run two /dev/ttySx ports, as a simple loopback. Then connect your real program to the ttyS2 and your simulator to the other ttySx.

Use two USB<-->Serial cables in a loopback

But the easiest thing to do right now? Spend $40 on two serial port USB devices, wire them together (null modem) and actually have two real serial ports - one for the program you're testing, one for your simulator.

-Adam

How to insert a newline in front of a pattern?

echo one,two,three | sed 's/,/\
/g'

How can I set NODE_ENV=production on Windows?

first in powershell type

$env:NODE_ENV="production"

then type

node fileName.js

It will work perfectly displaying all the outputs.

What is stability in sorting algorithms and why is it important?

If you assume what you are sorting are just numbers and only their values identify/distinguish them (e.g. elements with same value are identicle), then the stability-issue of sorting is meaningless.

However, objects with same priority in sorting may be distinct, and sometime their relative order is meaningful information. In this case, unstable sort generates problems.

For example, you have a list of data which contains the time cost [T] of all players to clean a maze with Level [L] in a game. Suppose we need to rank the players by how fast they clean the maze. However, an additional rule applies: players who clean the maze with higher-level always have a higher rank, no matter how long the time cost is.

Of course you might try to map the paired value [T,L] to a real number [R] with some algorithm which follows the rules and then rank all players with [R] value.

However, if stable sorting is feasible, then you may simply sort the entire list by [T] (Faster players first) and then by [L]. In this case, the relative order of players (by time cost) will not be changed after you grouped them by level of maze they cleaned.

PS: of course the approach to sort twice is not the best solution to the particular problem but to explain the question of poster it should be enough.

How to search in commit messages using command line?

git log --grep=<pattern>
    Limit the commits output to ones with log message that matches the 
    specified pattern (regular expression).

--git help log

Passing an array/list into a Python function

def sumlist(items=[]):
    sum = 0
    for i in items:
        sum += i

    return sum

t=sumlist([2,4,8,1])
print(t)

SQL query return data from multiple tables

You can use the concept of multiple queries in the FROM keyword. Let me show you one example:

SELECT DISTINCT e.id,e.name,d.name,lap.lappy LAPTOP_MAKE,c_loc.cnty COUNTY    
FROM  (
          SELECT c.id cnty,l.name
          FROM   county c, location l
          WHERE  c.id=l.county_id AND l.end_Date IS NOT NULL
      ) c_loc, emp e 
      INNER JOIN dept d ON e.deptno =d.id
      LEFT JOIN 
      ( 
         SELECT l.id lappy, c.name cmpy
         FROM   laptop l, company c
         WHERE l.make = c.name
      ) lap ON e.cmpy_id=lap.cmpy

You can use as many tables as you want to. Use outer joins and union where ever it's necessary, even inside table subqueries.

That's a very easy method to involve as many as tables and fields.

Codeigniter : calling a method of one controller from other

This is not supported behavior of the MVC System. If you want to execute an action of another controller you just redirect the user to the page you want (i.e. the controller function that consumes the url).

If you want common functionality, you should build a library to be used in the two different controllers.

I can only assume you want to build up your site a bit modular. (I.e. re-use the output of one controller method in other controller methods.) There's some plugins / extensions for CI that help you build like that. However, the simplest way is to use a library to build up common "controls" (i.e. load the model, render the view into a string). Then you can return that string and pass it along to the other controller's view.

You can load into a string by adding true at the end of the view call:

$string_view = $this->load->view('someview', array('data'=>'stuff'), true);

Python slice first and last element in list

What about this?

>>> first_element, last_element = some_list[0], some_list[-1]

How do I access store state in React Redux?

You need to use Store.getState() to get current state of your Store.

For more information about getState() watch this short video.

iPhone: Setting Navigation Bar Title

The view controller must be a child of some UINavigationController for the .title property to take effect. If the UINavigationBar is simply a view, you need to push a navigation item containing the title, or modify the last navigation item:

UINavigationItem* item = [[UINavigationItem alloc] initWithTitle:@"title text"];
...
[bar pushNavigationItem:item animated:YES];
[item release];

or

bar.topItem.title = @"title text";

How can I exclude one word with grep?

I understood the question as "How do I match a word but exclude another", for which one solution is two greps in series: First grep finding the wanted "word1", second grep excluding "word2":

grep "word1" | grep -v "word2"

In my case: I need to differentiate between "plot" and "#plot" which grep's "word" option won't do ("#" not being a alphanumerical).

Hope this helps.

Android Studio: Gradle - build fails -- Execution failed for task ':dexDebug'

The right answer is, that some of your jar files does not compile. You should go into your build.gradle file in your project, and look in your dependencies.

If you're just importing some jar files, you could try to remove them and add them one at a time. This will help you determine which one of them causes the error.

In my case, I did just that, and when I was importing the last one, the app compiled. So I think the real problem was that I was importing too many at once. But now it all works.

Excel formula to get ranking position

You could also use the RANK function

=RANK(C2,$C$2:$C$7,0)

It would return data like your example:

  | A       | B        | C
1 | name    | position | points
2 | person1 | 1        | 10
3 | person2 | 2        | 9
4 | person3 | 2        | 9
5 | person4 | 2        | 9
6 | person5 | 5        | 8
7 | person6 | 6        | 7

The 'Points' column needs to be sorted into descending order.

XSLT counting elements with a given value

Your xpath is just a little off:

count(//Property/long[text()=$parPropId])

Edit: Cerebrus quite rightly points out that the code in your OP (using the implicit value of a node) is absolutely fine for your purposes. In fact, since it's quite likely you want to work with the "Property" node rather than the "long" node, it's probably superior to ask for //Property[long=$parPropId] than the text() xpath, though you could make a case for the latter on readability grounds.

What can I say, I'm a bit tired today :)

How can VBA connect to MySQL database in Excel?

Ranjit's code caused the same error message as reported by Tin, but worked after updating Cn.open with the ODBC driver I'm running. Check the Drivers tab in the ODBC Data Source Administrator. Mine said "MySQL ODBC 5.3 Unicode Driver" so I updated accordingly.

git status (nothing to commit, working directory clean), however with changes commited

Small hint which other people didn't talk about: git doesn't record changes if you add empty folders in your project folder. That's it, I was adding empty folders with random names to check wether it was recording changes, it wasn't. But it started to do it as soon as I began adding files in them. Cheers.

Sending HTTP Post request with SOAP action using org.apache.http

It was giving 415 Http response Code as error,

So I added

httppost.addHeader("Content-Type", "text/xml; charset=utf-8");

Everything alright now, Http: 200

How to use string.substr() function?

Another interesting variant question can be:

How would you make "12345" as "12 23 34 45" without using another string?

Will following do?

    for(int i=0; i < a.size()-1; ++i)
    {
        //b = a.substr(i, 2);
        c = atoi((a.substr(i, 2)).c_str());
        cout << c << " ";
    }

How do I retrieve the number of columns in a Pandas data frame?

Surprised I haven't seen this yet, so without further ado, here is:

df.columns.size

How to make a div center align in HTML

it depends if your div is in position: absolute / fixed or relative / static

for position: absolute & fixed

<div style="position: absolute; /*or fixed*/;
width: 50%;
height: 300px;
left: 50%;
top:100px;
margin: 0 0 0 -25%">blblablbalba</div>

The trick here is to have a negative margin half the width of the object

for position: relative & static

<div style="position: relative; /*or static*/;
width: 50%;
height: 300px;
margin: 0 auto">blblablbalba</div>

for both techniques, it is imperative to set the width.

How to pass a file path which is in assets folder to File(String path)?

Unless you unpack them, assets remain inside the apk. Accordingly, there isn't a path you can feed into a File. The path you've given in your question will work with/in a WebView, but I think that's a special case for WebView.

You'll need to unpack the file or use it directly.

If you have a Context, you can use context.getAssets().open("myfoldername/myfilename"); to open an InputStream on the file. With the InputStream you can use it directly, or write it out somewhere (after which you can use it with File).

Python: Is there an equivalent of mid, right, and left from BASIC?

You can use this method also it will act like that

thadari=[1,2,3,4,5,6]

#Front Two(Left)
print(thadari[:2])
[1,2]

#Last Two(Right)# edited
print(thadari[-2:])
[5,6]

#mid
mid = len(thadari) //2

lefthalf = thadari[:mid]
[1,2,3]
righthalf = thadari[mid:]
[4,5,6]

Hope it will help

How to convert date to timestamp?

The below code will convert the current date into the timestamp.

var currentTimeStamp = Date.parse(new Date());
console.log(currentTimeStamp);

SQL: capitalize first letter only

Please check the query without using a function:

declare @T table(Insurance varchar(max))

insert into @T values ('wezembeek-oppem')
insert into @T values ('roeselare')
insert into @T values ('BRUGGE')
insert into @T values ('louvain-la-neuve')

select (
       select upper(T.N.value('.', 'char(1)'))+
                lower(stuff(T.N.value('.', 'varchar(max)'), 1, 1, ''))+(CASE WHEN RIGHT(T.N.value('.', 'varchar(max)'), 1)='-' THEN '' ELSE ' ' END)
       from X.InsXML.nodes('/N') as T(N)
       for xml path(''), type
       ).value('.', 'varchar(max)') as Insurance
from 
  (
  select cast('<N>'+replace(
            replace(
                Insurance, 
                ' ', '</N><N>'),
            '-', '-</N><N>')+'</N>' as xml) as InsXML
  from @T
  ) as X

How to avoid the need to specify the WSDL location in a CXF or JAX-WS generated webservice client?

@Martin Devillers solution works fine. For completeness, providing the steps below:

  1. Put your wsdl to resource directory like : src/main/resource
  2. In pom file, add both wsdlDirectory and wsdlLocation(don't miss / at the beginning of wsdlLocation), like below. While wsdlDirectory is used to generate code and wsdlLocation is used at runtime to create dynamic proxy.

    <wsdlDirectory>src/main/resources/mydir</wsdlDirectory>
    <wsdlLocation>/mydir/my.wsdl</wsdlLocation>
    
  3. Then in your java code(with no-arg constructor):

    MyPort myPort = new MyPortService().getMyPort();
    
  4. Here is the full code generation part in pom file, with fluent api in generated code.

    <plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>jaxws-maven-plugin</artifactId>
    <version>2.5</version>
    
    <dependencies>
        <dependency>
            <groupId>org.jvnet.jaxb2_commons</groupId>
            <artifactId>jaxb2-fluent-api</artifactId>
            <version>3.0</version>
        </dependency>
        <dependency>
            <groupId>com.sun.xml.ws</groupId>
            <artifactId>jaxws-tools</artifactId>
            <version>2.3.0</version>
        </dependency>
    </dependencies>
    
    <executions>
        <execution>
            <id>wsdl-to-java-generator</id>
            <goals>
                <goal>wsimport</goal>
            </goals>
            <configuration>
                <xjcArgs>
                    <xjcArg>-Xfluent-api</xjcArg>
                </xjcArgs>
                <keep>true</keep>
                <wsdlDirectory>src/main/resources/package</wsdlDirectory>
                <wsdlLocation>/package/my.wsdl</wsdlLocation>
                <sourceDestDir>${project.build.directory}/generated-sources/annotations/jaxb</sourceDestDir>
                <packageName>full.package.here</packageName>
            </configuration>
        </execution>
    </executions>
    

How to insert multiple rows from array using CodeIgniter framework?

Although it is too late to answer this question. Here are my answer on the same.

If you are using CodeIgniter then you can use inbuilt methods defined in query_builder class.

$this->db->insert_batch()

Generates an insert string based on the data you supply, and runs the query. You can either pass an array or an object to the function. Here is an example using an array:

$data = array(
    array(
            'title' => 'My title',
            'name' => 'My Name',
            'date' => 'My date'
    ),
    array(
            'title' => 'Another title',
            'name' => 'Another Name',
            'date' => 'Another date'
    )
);

$this->db->insert_batch('mytable', $data);
// Produces: INSERT INTO mytable (title, name, date) VALUES ('My title', 'My name', 'My date'),  ('Another title', 'Another name', 'Another date')

The first parameter will contain the table name, the second is an associative array of values.

You can find more details about query_builder here

How can I strip first X characters from string using sed?

pipe it through awk '{print substr($0,42)}' where 42 is one more than the number of characters to drop. For example:

$ echo abcde| awk '{print substr($0,2)}'
bcde
$

How does Task<int> become an int?

No requires converting the Task to int. Simply Use The Task Result.

int taskResult = AccessTheWebAndDouble().Result;

public async Task<int> AccessTheWebAndDouble()
{
    int task = AccessTheWeb();
    return task;
}

It will return the value if available otherwise it return 0.

Replace all 0 values to NA

You can replace 0 with NA only in numeric fields (i.e. excluding things like factors), but it works on a column-by-column basis:

col[col == 0 & is.numeric(col)] <- NA

With a function, you can apply this to your whole data frame:

changetoNA <- function(colnum,df) {
    col <- df[,colnum]
    if (is.numeric(col)) {  #edit: verifying column is numeric
        col[col == -1 & is.numeric(col)] <- NA
    }
    return(col)
}
df <- data.frame(sapply(1:5, changetoNA, df))

Although you could replace the 1:5 with the number of columns in your data frame, or with 1:ncol(df).

Group a list of objects by an attribute

You could do this:

Map<String, List<Student>> map = new HashMap<String, List<Student>>();
List<Student> studlist = new ArrayList<Student>();
studlist.add(new Student("1726", "John", "New York"));
map.put("New York", studlist);

the keys will be locations and the values list of students. So later you can get a group of students just by using:

studlist = map.get("New York");

How can I get a list of repositories 'apt-get' is checking?

It seems the closest is:

apt-cache policy

Refreshing page on click of a button

Works for every browser.

<button type="button" onClick="Refresh()">Close</button>

<script>
    function Refresh() {
        window.parent.location = window.parent.location.href;
    }
</script>

What is the __del__ method, How to call it?

The __del__ method, it will be called when the object is garbage collected. Note that it isn't necessarily guaranteed to be called though. The following code by itself won't necessarily do it:

del obj

The reason being that del just decrements the reference count by one. If something else has a reference to the object, __del__ won't get called.

There are a few caveats to using __del__ though. Generally, they usually just aren't very useful. It sounds to me more like you want to use a close method or maybe a with statement.

See the python documentation on __del__ methods.

One other thing to note: __del__ methods can inhibit garbage collection if overused. In particular, a circular reference that has more than one object with a __del__ method won't get garbage collected. This is because the garbage collector doesn't know which one to call first. See the documentation on the gc module for more info.

Property '...' has no initializer and is not definitely assigned in the constructor

Can't you just use a Definite Assignment Assertion? (See https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#definite-assignment-assertions)

i.e. declaring the property as makes!: any[]; The ! assures typescript that there definitely will be a value at runtime.

Sorry I haven't tried this in angular but it worked great for me when I was having the exact same problem in React.

How to add image in a TextView text?

Try this ..

    txtview.setCompoundDrawablesWithIntrinsicBounds(
                    R.drawable.image, 0, 0, 0);

Also see this.. http://developer.android.com/reference/android/widget/TextView.html

Try this in xml file

    <TextView
        android:id="@+id/txtStatus"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:drawableLeft="@drawable/image"
        android:drawablePadding="5dp"
        android:maxLines="1"
        android:text="@string/name"/>

How can I upgrade NumPy?

This works for me:

pip install numpy --upgrade

Connecting to SQL Server using windows authentication

I was facing the same issue and the reason was single backslah. I used double backslash in my "Data source" and it worked

connetionString = "Data Source=localhost\\SQLEXPRESS;Database=databasename;Integrated Security=SSPI";

intellij idea - Error: java: invalid source release 1.9

intellij-invalid-source

You've to set the JAVA SDK and appropriate language level in the project settings. Click to enlarge.

How to update one file in a zip archive

7zip (7za) can be used for adding/updating files/directories nicely:

Example: Replacing (regardless of file date) the MANIFEST.MF file in a JAR file. The /source/META-INF directory contains the MANIFEST.MF file that you want to put into the jar (zip):

7za a /tmp/file.jar /source/META-INF/

Only update (does not replace the target if the source is older)

7za u /tmp/file.jar /source/META-INF/

Cookie blocked/not saved in IFRAME in Internet Explorer

This is a great topic on the issue, however I found that one important detail (which was essential at least in my case) that was not posted here or anywhere else (I apologize if I just missed it) was that the P3P line must be passed in header of EVERY file sent from the 3rd party server, even files not setting or using the cookies such as Javascript files or images. Otherwise the cookies will be blocked. I have more on this in a post here: http://posheika.net/?p=110

Retrieving the text of the selected <option> in <select> element

You can use selectedIndex to retrieve the current selected option:

el = document.getElementById('elemId')
selectedText = el.options[el.selectedIndex].text

How to indent/format a selection of code in Visual Studio Code with Ctrl + Shift + F

  • you can also indent a whole section by selecting it and clicking TAB
  • and also indent backward using Shift+TAB

And of course for auto indentation and formatting, following the language you're using, you can see which good extensions do the good job, and which formatters to install or which parameters settings to enable or set for each language and its available tools. Just make sure to read well the documentation of the extension, to install and set all what it need.

Up to now the indentation problem bothers me with Python when copy pasting a block of code. If that's the case, here is how you solve that: Visual Studio Code indentation for Python

How do I check if a SQL Server text column is empty?

Use DATALENGTH method, for example:

SELECT length = DATALENGTH(myField)
FROM myTABLE

How to find the largest file in a directory and its subdirectories?

Quote from this link-

If you want to find and print the top 10 largest files names (not directories) in a particular directory and its sub directories

$ find . -printf '%s %p\n'|sort -nr|head

To restrict the search to the present directory use "-maxdepth 1" with find.

$ find . -maxdepth 1 -printf '%s %p\n'|sort -nr|head

And to print the top 10 largest "files and directories":

$ du -a . | sort -nr | head

** Use "head -n X" instead of the only "head" above to print the top X largest files (in all the above examples)

How to increase scrollback buffer size in tmux?

The history limit is a pane attribute that is fixed at the time of pane creation and cannot be changed for existing panes. The value is taken from the history-limit session option (the default value is 2000).

To create a pane with a different value you will need to set the appropriate history-limit option before creating the pane.

To establish a different default, you can put a line like the following in your .tmux.conf file:

set-option -g history-limit 3000

Note: Be careful setting a very large default value, it can easily consume lots of RAM if you create many panes.

For a new pane (or the initial pane in a new window) in an existing session, you can set that session’s history-limit. You might use a command like this (from a shell):

tmux set-option history-limit 5000 \; new-window

For (the initial pane of the initial window in) a new session you will need to set the “global” history-limit before creating the session:

tmux set-option -g history-limit 5000 \; new-session

Note: If you do not re-set the history-limit value, then the new value will be also used for other panes/windows/sessions created in the future; there is currently no direct way to create a single new pane/window/session with its own specific limit without (at least temporarily) changing history-limit (though show-option (especially in 1.7 and later) can help with retrieving the current value so that you restore it later).

Multiple markers Google Map API v3 from array of addresses and avoid OVER_QUERY_LIMIT while geocoding on pageLoad

Regardless of your situation, heres a working demo that creates markers on the map based on an array of addresses.

http://jsfiddle.net/P2QhE/

Javascript code embedded aswell:

$(document).ready(function () {
    var map;
    var elevator;
    var myOptions = {
        zoom: 1,
        center: new google.maps.LatLng(0, 0),
        mapTypeId: 'terrain'
    };
    map = new google.maps.Map($('#map_canvas')[0], myOptions);

    var addresses = ['Norway', 'Africa', 'Asia','North America','South America'];

    for (var x = 0; x < addresses.length; x++) {
        $.getJSON('http://maps.googleapis.com/maps/api/geocode/json?address='+addresses[x]+'&sensor=false', null, function (data) {
            var p = data.results[0].geometry.location
            var latlng = new google.maps.LatLng(p.lat, p.lng);
            new google.maps.Marker({
                position: latlng,
                map: map
            });

        });
    }

}); 

How do we change the URL of a working GitLab install?

Do not forget to clear the cache after updating the external_url param in /etc/gitlab/gitlab.rb, otherwise your existing project clone URLs will still be showing your old host name.

A simple 3 step process to change the hostname is as follows

  • update the external_url param in /etc/gitlab/gitlab.rb
  • sudo gitlab-ctl reconfigure
  • sudo gitlab-ctl restart
  • sudo gitlab-rake cache:clear

Ref:

https://forum.gitlab.com/t/clone-url-wont-change/21692/6

Timeout a command in bash without unnecessary delay

Kinda hacky, but it works. Doesn't work if you have other foreground processes (please help me fix this!)

sleep TIMEOUT & SPID=${!}; (YOUR COMMAND HERE; kill ${SPID}) & CPID=${!}; fg 1; kill ${CPID}

Actually, I think you can reverse it, meeting your 'bonus' criteria:

(YOUR COMMAND HERE & SPID=${!}; (sleep TIMEOUT; kill ${SPID}) & CPID=${!}; fg 1; kill ${CPID}) < asdf > fdsa

Passing parameter using onclick or a click binding with KnockoutJS

If you set up a click binding in Knockout the event is passed as the second parameter. You can use the event to obtain the element that the click occurred on and perform whatever action you want.

Here is a fiddle that demonstrates: http://jsfiddle.net/jearles/xSKyR/

Alternatively, you could create your own custom binding, which will receive the element it is bound to as the first parameter. On init you could attach your own click event handler to do any actions you wish.

http://knockoutjs.com/documentation/custom-bindings.html

HTML

<div>
    <button data-bind="click: clickMe">Click Me!</button>
</div>

Js

var ViewModel = function() {
    var self = this;
    self.clickMe = function(data,event) {

      var target = event.target || event.srcElement;

      if (target.nodeType == 3) // defeat Safari bug
        target = target.parentNode;

      target.parentNode.innerHTML = "something";
    }
}

ko.applyBindings(new ViewModel());

from list of integers, get number closest to a given value

def closest(list, Number):
    aux = []
    for valor in list:
        aux.append(abs(Number-valor))

    return aux.index(min(aux))

This code will give you the index of the closest number of Number in the list.

The solution given by KennyTM is the best overall, but in the cases you cannot use it (like brython), this function will do the work

PHP Create and Save a txt file to root directory

fopen() will open a resource in the same directory as the file executing the command. In other words, if you're just running the file ~/test.php, your script will create ~/myText.txt.

This can get a little confusing if you're using any URL rewriting (such as in an MVC framework) as it will likely create the new file in whatever the directory contains the root index.php file.

Also, you must have correct permissions set and may want to test before writing to the file. The following would help you debug:

$fp = fopen("myText.txt","wb");
if( $fp == false ){
    //do debugging or logging here
}else{
    fwrite($fp,$content);
    fclose($fp);
}

How do I get the path of the current executed file in Python?

See my answer to the question Importing modules from parent folder for related information, including why my answer doesn't use the unreliable __file__ variable. This simple solution should be cross-compatible with different operating systems as the modules os and inspect come as part of Python.

First, you need to import parts of the inspect and os modules.

from inspect import getsourcefile
from os.path import abspath

Next, use the following line anywhere else it's needed in your Python code:

abspath(getsourcefile(lambda:0))

How it works:

From the built-in module os (description below), the abspath tool is imported.

OS routines for Mac, NT, or Posix depending on what system we're on.

Then getsourcefile (description below) is imported from the built-in module inspect.

Get useful information from live Python objects.

  • abspath(path) returns the absolute/full version of a file path
  • getsourcefile(lambda:0) somehow gets the internal source file of the lambda function object, so returns '<pyshell#nn>' in the Python shell or returns the file path of the Python code currently being executed.

Using abspath on the result of getsourcefile(lambda:0) should make sure that the file path generated is the full file path of the Python file.
This explained solution was originally based on code from the answer at How do I get the path of the current executed file in Python?.

How to generate xsd from wsdl

Follow these steps :

  1. Create a project using the WSDL.
  2. Choose your interface and open in interface viewer.
  3. Navigate to the tab 'WSDL Content'.
  4. Use the last icon under the tab 'WSDL Content' : 'Export the entire WSDL and included/imported files to a local directory'.
  5. select the folder where you want the XSDs to be exported to.

Note: SOAPUI will remove all relative paths and will save all XSDs to the same folder. Refer the screenshot : enter image description here

'this' implicitly has type 'any' because it does not have a type annotation

For method decorator declaration with configuration "noImplicitAny": true, you can specify type of this variable explicitly depends on @tony19's answer

function logParameter(this:any, target: Object, propertyName: string) {
  //...
}

8080 port already taken issue when trying to redeploy project from Spring Tool Suite IDE

Goto Window->Preferences, search for Launching.

Select the "Terminate and Relaunch while launching" option.

Press Apply.

How are ssl certificates verified?

The client has a pre-seeded store of SSL certificate authorities' public keys. There must be a chain of trust from the certificate for the server up through intermediate authorities up to one of the so-called "root" certificates in order for the server to be trusted.

You can examine and/or alter the list of trusted authorities. Often you do this to add a certificate for a local authority that you know you trust - like the company you work for or the school you attend or what not.

The pre-seeded list can vary depending on which client you use. The big SSL certificate vendors insure that their root certs are in all the major browsers ($$$).

Monkey-in-the-middle attacks are "impossible" unless the attacker has the private key of a trusted root certificate. Since the corresponding certificates are widely deployed, the exposure of such a private key would have serious implications for the security of eCommerce generally. Because of that, those private keys are very, very closely guarded.

Remove Null Value from String array in java

If you want to avoid fencepost errors and avoid moving and deleting items in an array, here is a somewhat verbose solution that uses List:

import java.util.ArrayList;
import java.util.List;

public class RemoveNullValue {
  public static void main( String args[] ) {
    String[] firstArray = {"test1", "", "test2", "test4", "", null};

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

    for(String s : firstArray) {
       if(s != null && s.length() > 0) {
          list.add(s);
       }
    }

    firstArray = list.toArray(new String[list.size()]);
  }
}

Added null to show the difference between an empty String instance ("") and null.

Since this answer is around 4.5 years old, I'm adding a Java 8 example:

import java.util.Arrays;
import java.util.stream.Collectors;

public class RemoveNullValue {
    public static void main( String args[] ) {
        String[] firstArray = {"test1", "", "test2", "test4", "", null};

        firstArray = Arrays.stream(firstArray)
                     .filter(s -> (s != null && s.length() > 0))
                     .toArray(String[]::new);    

    }
}

JavaFX 2.1 TableView refresh items

You just need to clear the table and call the function that generates the filling of the table.

ButtonRefresh.setOnAction((event) -> {
            tacheTable.getItems().clear();
            PopulateTable();
        });

How can I get the current screen orientation?

if you want to override that onConfigurationChanged method and still want it to do the basic stuff then consider using super.onConfigyrationChanged() as the first statement in the overriden method.

Operand type clash: int is incompatible with date + The INSERT statement conflicted with the FOREIGN KEY constraint

Try wrapping your dates in single quotes, like this:

'15-6-2005'

It should be able to parse the date this way.

Edittext change border color with shape.xml

selector is used for applying multiple alternate drawables for different status of the view, so in this case, there is no need for selector

instead use shape

<?xml version="1.0" encoding="utf-8"?>
    <shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="#ffffff" />
    <stroke android:width="1dip" android:color="#ff9900" />
</shape>

How to change time in DateTime?

int year = 2012;
int month = 12;
int day = 24;
int hour = 0;
int min = 0;
int second = 23;
DateTime dt = new DateTime(year, month, day, hour, min, second);

Java String.split() Regex

You could also do something like:

String str = "a + b - c * d / e < f > g >= h <= i == j";
String[] arr = str.split("(?<=\\G(\\w+(?!\\w+)|==|<=|>=|\\+|/|\\*|-|(<|>)(?!=)))\\s*");

It handles white spaces and words of variable length and produces the array:

[a, +, b, -, c, *, d, /, e, <, f, >, g, >=, h, <=, i, ==, j]

What does the ^ (XOR) operator do?

Another application for XOR is in circuits. It is used to sum bits.

When you look at a truth table:

 x | y | x^y
---|---|-----
 0 | 0 |  0     // 0 plus 0 = 0 
 0 | 1 |  1     // 0 plus 1 = 1
 1 | 0 |  1     // 1 plus 0 = 1
 1 | 1 |  0     // 1 plus 1 = 0 ; binary math with 1 bit

You can notice that the result of XOR is x added with y, without keeping track of the carry bit, the carry bit is obtained from the AND between x and y.

x^y // is actually ~xy + ~yx
    // Which is the (negated x ANDed with y) OR ( negated y ANDed with x ).

How to solve error message: "Failed to map the path '/'."

This line (top of the stack trace) is telling you there is something wrong which the hosting configuration.

 System.Web.HttpRuntime.HostingInit(HostingEnvironmentFlags hostingFlags, PolicyLevel policyLevel, Exception appDomainCreationException) +336

How is your server set up? Have you checked the config files?

I'd search through them specifically for any settings or attributes which have the single value "/".

Force an Android activity to always use landscape mode

That's it!! Long waiting for this fix.

I've an old Android issue about double-start an activity that required (programmatically) landscape mode: setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE)

Now Android make Landscape mode on start.

time.sleep -- sleeps thread or process?

The thread will block, but the process is still alive.

In a single threaded application, this means everything is blocked while you sleep. In a multithreaded application, only the thread you explicitly 'sleep' will block and the other threads still run within the process.

pip is not able to install packages correctly: Permission denied error

Set up a virtualenv:

% curl -kLso /tmp/get-pip.py https://bootstrap.pypa.io/get-pip.py 
% sudo python /tmp/get-pip.py

These commands install pip into the global site-packages directory.

% sudo pip install virtualenv

and ditto for virtualenv:

% mkdir -p ~/.virtualenvs

I like my virtualenvs under one tree in my home directory called .virtualenvs

% virtualenv ~/.virtualenvs/lxmltest

Creates a virtualenv.

% . ~/.virtualenvs/lxmltest/bin/activate

Removes the need to specify the full path to pip/python in this virtualenv.

% pip install lxml

Alternatively execute ~/.virtualenvs/lxmltest/bin/pip install lxml if you chose not to follow the previous step. Note, I'm not sure how far along you are, so some of these steps can be safely skipped. Of course, if you mess something up, you can always rm -Rf ~/.virtualenvs/lxmltest and start again from a new virtualenv.

Assign output of os.system to a variable and prevent it from being displayed on the screen

Python 2.6 and 3 specifically say to avoid using PIPE for stdout and stderr.

The correct way is

import subprocess

# must create a file object to store the output. Here we are getting
# the ssid we are connected to
outfile = open('/tmp/ssid', 'w');
status = subprocess.Popen(["iwgetid"], bufsize=0, stdout=outfile)
outfile.close()

# now operate on the file

How change default SVN username and password to commit changes?

For Windows (7), the same folder is located at,

%APPDATA%\Subversion\auth

Type in the above in the Run(Win key + R) dialog box and hit Enter,

To check the existing username open the below file as a text file,

%APPDATA%\Subversion\auth\svn.simple\xxxxxxxxxx

How to convert a table to a data frame

I figured it out already:

as.data.frame.matrix(mytable) 

does what I need -- apparently, the table needs to somehow be converted to a matrix in order to be appropriately translated into a data frame. I found more details on this as.data.frame.matrix() function for contingency tables at the Computational Ecology blog.

How do I delete multiple rows with different IDs?

Disclaim: the following suggestion could be an overhead depending on the situation. The function is only tested with MSSQL 2008 R2 but seams be compatible to other versions

if you wane do this with many Id's you may could use a function which creates a temp table where you will be able to DELETE FROM the selection

how the query could look like:

-- not tested
-- @ids will contain a varchar with your ids e.g.'9 12 27 37'
DELETE FROM table WHERE id IN (SELECT i.number FROM iter_intlist_to_tbl(@ids))

here is the function:

ALTER FUNCTION iter_intlist_to_tbl (@list nvarchar(MAX))
   RETURNS @tbl TABLE (listpos int IDENTITY(1, 1) NOT NULL,
                       number  int NOT NULL) AS

   -- funktion gefunden auf http://www.sommarskog.se/arrays-in-sql-2005.html
   -- dient zum übergeben einer liste von elementen

BEGIN
    -- Deklaration der Variablen
    DECLARE @startpos int,
            @endpos   int,
            @textpos  int,
            @chunklen smallint,
            @str      nvarchar(4000),
            @tmpstr   nvarchar(4000),
            @leftover nvarchar(4000)

    -- Startwerte festlegen
   SET @textpos = 1
   SET @leftover = ''

   -- Loop 1
    WHILE @textpos <= datalength(@list) / 2
    BEGIN

        --
        SET @chunklen = 4000 - datalength(@leftover) / 2 --datalength() gibt die anzahl der bytes zurück (mit Leerzeichen)

        --
        SET @tmpstr = ltrim(@leftover + substring(@list, @textpos, @chunklen))--SUBSTRING ( @string ,start , length ) | ltrim(@string) abschneiden aller Leerzeichen am Begin des Strings

        --hochzählen der TestPosition
        SET @textpos = @textpos + @chunklen

        --start position 0 setzen
        SET @startpos = 0

        -- end position bekommt den charindex wo ein [LEERZEICHEN] gefunden wird
        SET @endpos = charindex(' ' COLLATE Slovenian_BIN2, @tmpstr)--charindex(searchChar,Wo,Startposition)

        -- Loop 2
        WHILE @endpos > 0
        BEGIN
            --str ist der string welcher zwischen den [LEERZEICHEN] steht
            SET @str = substring(@tmpstr, @startpos + 1, @endpos - @startpos - 1) 

            --wenn @str nicht leer ist wird er zu int Convertiert und @tbl unter der Spalte 'number' hinzugefügt
            IF @str <> ''
                INSERT @tbl (number) VALUES(convert(int, @str))-- convert(Ziel-Type,Value)

            -- start wird auf das letzte bekannte end gesetzt
            SET @startpos = @endpos

            -- end position bekommt den charindex wo ein [LEERZEICHEN] gefunden wird
            SET @endpos = charindex(' ' COLLATE Slovenian_BIN2, @tmpstr, @startpos + 1)
        END
        -- Loop 2

        -- dient dafür den letzten teil des strings zu selektieren
        SET @leftover = right(@tmpstr, datalength(@tmpstr) / 2 - @startpos)--right(@string,anzahl der Zeichen) bsp.: right("abcdef",3) => "def"
    END
    -- Loop 1

    --wenn @leftover nach dem entfernen aller [LEERZEICHEN] nicht leer ist wird er zu int Convertiert und @tbl unter der Spalte 'number' hinzugefügt
    IF ltrim(rtrim(@leftover)) <> ''
        INSERT @tbl (number) VALUES(convert(int, @leftover))

    RETURN
END


    -- ############################ WICHTIG ############################
    -- das is ein Beispiel wie man die Funktion benutzt
    --
    --CREATE    PROCEDURE get_product_names_iter 
    --      @ids varchar(50) AS
    --SELECT    P.ProductName, P.ProductID
    --FROM      Northwind.Products P
    --JOIN      iter_intlist_to_tbl(@ids) i ON P.ProductID = i.number
    --go
    --EXEC get_product_names_iter '9 12 27 37'
    --
    -- Funktion gefunden auf http://www.sommarskog.se/arrays-in-sql-2005.html
    -- dient zum übergeben einer Liste von Id's
    -- ############################ WICHTIG ############################

Android: why is there no maxHeight for a View?

There is no way to set maxHeight. But you can set the Height.

To do that you will need to discovery the height of each item of you scrollView. After that just set your scrollView height to numberOfItens * heightOfItem.

To discovery the height of an item do that:

View item = adapter.getView(0, null, scrollView);
item.measure(0, 0);
int heightOfItem = item.getMeasuredHeight();

To set the height do that:

// if the scrollView already has a layoutParams:
scrollView.getLayoutParams().height = heightOfItem * numberOfItens;
// or
// if the layoutParams is null, then create a new one.
scrollView.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, heightOfItem * numberOfItens));

Removing the first 3 characters from a string

Use the substring method of the String class :

String removeCurrency=amount.getText().toString().substring(3);

Angular 1.6.0: "Possibly unhandled rejection" error

The first option is simply to hide an error with disabling it by configuring errorOnUnhandledRejections in $qProvider configuration as suggested Cengkuru Michael

BUT this will only switch off logging. The error itself will remain

The better solution in this case will be - handling a rejection with .catch(fn) method:

resource.get().$promise
    .then(function (response) {})
    .catch(function (err) {});

LINKS:

How to get IP address of running docker container

Use --format option to get only the IP address instead whole container info:

sudo docker inspect --format '{{ .NetworkSettings.IPAddress }}' <CONTAINER ID>

Counting number of words in a file

So easy we can get the String from files by method: getText();

public class Main {

    static int countOfWords(String str) {
        if (str.equals("") || str == null) {
            return 0;
        }else{
            int numberWords = 0;
            for (char c : str.toCharArray()) {
                if (c == ' ') {
                    numberWords++;
                }
            }

            return ++numberWordss;
        }
    }
}

IntelliJ: Never use wildcard imports

It's obvious why you'd want to disable this: To force IntelliJ to include each and every import individually. It makes it easier for people to figure out exactly where classes you're using come from.

Click on the Settings "wrench" icon on the toolbar, open "Imports" under "Code Style", and check the "Use single class import" selection. You can also completely remove entries under "Packages to use import with *", or specify a threshold value that only uses the "*" when the individual classes from a package exceeds that threshold.

Update: in IDEA 13 "Use single class import" does not prevent wildcard imports. The solution is to go to Preferences (? + , on macOS / Ctrl + Alt + S on Windows and Linux) > Editor > Code Style > Java > Imports tab set Class count to use import with '*' and Names count to use static import with '*' to a higher value. Any value over 99 seems to work fine.

ASP.NET jQuery Ajax Calling Code-Behind Method

This hasn't solved my problem too, so I changed the parameters slightly.
This code worked for me:

var dataValue = "{ name: 'person', isGoing: 'true', returnAddress: 'returnEmail' }";

$.ajax({
    type: "POST",
    url: "Default.aspx/OnSubmit",
    data: dataValue,
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    error: function (XMLHttpRequest, textStatus, errorThrown) {
        alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
    },
    success: function (result) {
        alert("We returned: " + result.d);
    }
});

How to check size of a file using Bash?

alternative solution with awk and double parenthesis:

FILENAME=file.txt
SIZE=$(du -sb $FILENAME | awk '{ print $1 }')

if ((SIZE<90000)) ; then 
    echo "less"; 
else 
    echo "not less"; 
fi

Complete list of reasons why a css file might not be working

I don't know if some people are loading first RESET.CSS:

_x000D_
_x000D_
html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed, 
figure, figcaption, footer, header, hgroup, 
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
    margin: 0;
    padding: 0;
    border: 0;
    font-size: 100%;
    font: inherit;
    vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure, 
footer, header, hgroup, menu, nav, section {
    display: block;
}
body {
    line-height: 1;
}
ol, ul {
    list-style: none;
}
blockquote, q {
    quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
    content: '';
    content: none;
}
table {
    border-collapse: collapse;
    border-spacing: 0;
}

a {
    color: inherit;
    text-decoration: none;
}
_x000D_
_x000D_
_x000D_

Setting attribute disabled on a SPAN element does not prevent click events

The disabled attribute is not global and is only allowed on form controls. What you could do is set a custom data attribute (perhaps data-disabled) and check for that attribute when you handle the click event.

How to decompile a whole Jar file?

Insert the following into decompile.jar.sh

# Usage: decompile.jar.sh some.jar [-d]

# clean target folders
function clean_target {
  rm -rf $unjar $src $jad_log
}

# clean all debug stuff
function clean_stuff {
  rm -rf $unjar $jad_log
}

# the main function
function work {
  jar=$1
  unjar=`basename $jar.unjar`
  src=`basename $jar.src`
  jad_log=jad.log

  clean_target

  unzip -q $jar -d $unjar
  jad -d $src -ff -r -lnc -o -s java $unjar/**/*.class > $jad_log 2>&1

  if [ ! $debug ]; then
    clean_stuff
  fi

  if [ -d $src ] 
    then
      echo "$jar has been decompiled to $src"
    else
      echo "Got some problems check output or run in debug mode"
  fi
}

function usage {
  echo "This script extract and decompile JAR file"
  echo "Usage: $0 some.jar [-d]"
  echo "    where: some.jar is the target to decompile"
  echo "    use -d for debug mode"
}

# check params
if [ -n "$1" ]
  then
    if [ "$2" == "-d" ]; then
      debug=true
      set -x
    fi
    work $1
  else
    usage
fi
  • chmod +x decomplie.jar.sh //executable
  • ln -s ./decomplie.jar.s /usr/bin/dj

Ready to use, just type dj your.jar and you will get your.jar.src folder with sources. Use -d option for debug mode.