Programs & Examples On #Draggable

An element capable of being dragged.

How can I make a jQuery UI 'draggable()' div draggable for touchscreen?

Caution: This answer was written in 2010 and technology moves fast. For a more recent solution, see @ctrl-alt-dileep's answer below.


Depending on your needs, you may wish to try the jQuery touch plugin; you can try an example here. It works fine to drag on my iPhone, whereas jQuery UI Draggable doesn't.

Alternatively, you can try this plugin, though that might require you to actually write your own draggable function.

As a sidenote: Believe it or not, we're hearing increasing buzz about how touch devices such as the iPad and iPhone is causing problems both for websites using :hover/onmouseover functions and draggable content.

If you're interested in the underlying solution for this, it's to use three new JavaScript events; ontouchstart, ontouchmove and ontouchend. Apple actually has written an article about their use, which you can find here. A simplified example can be found here. These events are used in both of the plugins I linked to.

jQuery UI - Draggable is not a function?

I had this junk at the bottom of my _layout mvc page that I found via chromes debugger (network section) loading jquery 1.10.2 after the jquery / jqueryui sections at the top of the same file. When I removed all that .sortable and .draggable started working.

@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
@RenderSection("scripts", required: false)

jquery draggable: how to limit the draggable area?

Use the "containment" option:

jQuery UI API - Draggable Widget - containment

The documentation says it only accepts the values: 'parent', 'document', 'window', [x1, y1, x2, y2] but I seem to remember it will accept a selector such as '#container' too.

Draggable div without jQuery UI

What I saw above is complicate.....

Here is some code can refer to.

$("#box").on({
                mousedown:function(e)
                {
                  dragging = true;
                  dragX = e.clientX - $(this).position().left;
                  //To calculate the distance between the cursor pointer and box 
                  dragY = e.clientY - $(this).position().top;
                },
                mouseup:function(){dragging = false;},
                  //If not set this on/off,the move will continue forever
                mousemove:function(e)
                {
                  if(dragging)
                  $(this).offset({top:e.clientY-dragY,left:e.clientX-dragX});

                }
            })

dragging,dragX,dragY may place as the global variable.

It's a simple show about this issue,but there is some bug about this method.

If it's your need now,here's the Example here.

make bootstrap twitter dialog modal draggable

You can use the code below if you dont want to use jQuery UI or any third party pluggin. It's only plain jQuery.

This answer works well with Bootstrap v3.x . For version 4.x see @User comment below

_x000D_
_x000D_
$(".modal").modal("show");_x000D_
_x000D_
$(".modal-header").on("mousedown", function(mousedownEvt) {_x000D_
    var $draggable = $(this);_x000D_
    var x = mousedownEvt.pageX - $draggable.offset().left,_x000D_
        y = mousedownEvt.pageY - $draggable.offset().top;_x000D_
    $("body").on("mousemove.draggable", function(mousemoveEvt) {_x000D_
        $draggable.closest(".modal-dialog").offset({_x000D_
            "left": mousemoveEvt.pageX - x,_x000D_
            "top": mousemoveEvt.pageY - y_x000D_
        });_x000D_
    });_x000D_
    $("body").one("mouseup", function() {_x000D_
        $("body").off("mousemove.draggable");_x000D_
    });_x000D_
    $draggable.closest(".modal").one("bs.modal.hide", function() {_x000D_
        $("body").off("mousemove.draggable");_x000D_
    });_x000D_
});
_x000D_
.modal-header {_x000D_
    cursor: move;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<div class="modal fade" tabindex="-1" role="dialog">_x000D_
  <div class="modal-dialog" role="document">_x000D_
    <div class="modal-content">_x000D_
      <div class="modal-header">_x000D_
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>_x000D_
        <h4 class="modal-title">Modal title</h4>_x000D_
      </div>_x000D_
      <div class="modal-body">_x000D_
        <p>One fine body&hellip;</p>_x000D_
      </div>_x000D_
      <div class="modal-footer">_x000D_
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>_x000D_
        <button type="button" class="btn btn-primary">Save changes</button>_x000D_
      </div>_x000D_
    </div><!-- /.modal-content -->_x000D_
  </div><!-- /.modal-dialog -->_x000D_
</div>
_x000D_
_x000D_
_x000D_

Preventing an image from being draggable or selectable without using JS

I've been forgetting to share my solution, I couldn't find a way to do this without using JS. There are some corner cases where @Jeffery A Wooden's suggested CSS just wont cover.

This is what I apply to all of my UI containers, no need to apply to each element since it recuses on all the child elements.

CSS:

.unselectable {
    /* For Opera and <= IE9, we need to add unselectable="on" attribute onto each element */
    /* Check this site for more details: http://help.dottoro.com/lhwdpnva.php */
    -moz-user-select: none; /* These user-select properties are inheritable, used to prevent text selection */
    -webkit-user-select: none;
    -ms-user-select: none; /* From IE10 only */
    user-select: none; /* Not valid CSS yet, as of July 2012 */

    -webkit-user-drag: none; /* Prevents dragging of images/divs etc */
    user-drag: none;
}

JS:

var makeUnselectable = function( $target ) {
    $target
        .addClass( 'unselectable' ) // All these attributes are inheritable
        .attr( 'unselectable', 'on' ) // For IE9 - This property is not inherited, needs to be placed onto everything
        .attr( 'draggable', 'false' ) // For moz and webkit, although Firefox 16 ignores this when -moz-user-select: none; is set, it's like these properties are mutually exclusive, seems to be a bug.
        .on( 'dragstart', function() { return false; } );  // Needed since Firefox 16 seems to ingore the 'draggable' attribute we just applied above when '-moz-user-select: none' is applied to the CSS 

    $target // Apply non-inheritable properties to the child elements
        .find( '*' )
        .attr( 'draggable', 'false' )
        .attr( 'unselectable', 'on' ); 
};

This was way more complicated than it needed to be.

Eclipse error "ADB server didn't ACK, failed to start daemon"

If you are using a sync application for the device, it could also be because there are other apps using the same 5037 port. Shut down all services running on port 5037 and try starting ADB.

To check if any application is using port 5037, use this:

netstat -a -n -o |findstr "5037"

Get the PID of the application.

Use Process Explorer to find the Process and exit it.

Now use adb start-server or adb get-state to start/check the ADB server status.

I faced the issue when I used the Snappea / Wandoujia Sync application.

Print content of JavaScript object?

You can give your objects their own toString methods in their prototypes.

How to get named excel sheets while exporting from SSRS

To export to different sheets and use custom names, as of SQL Server 2008 R2 this can be done using a combination of grouping, page breaks and the PageName property of the group.

Alternatively, if it's just the single sheet that you'd like to give a specific name, try the InitialPageName property on the report.

For a more detailed explanation, have a look here: http://blog.hoegaerden.be/2011/03/23/where-the-sheets-have-a-name-ssrs-excel-export/

Adjust plot title (main) position

Try this:

par(adj = 0)
plot(1, 1, main = "Title")

or equivalent:

plot(1, 1, main = "Title", adj = 0)

adj = 0 produces left-justified text, 0.5 (the default) centered text and 1 right-justified text. Any value in [0, 1] is allowed.

However, the issue is that this will also change the position of the label of the x-axis and y-axis.

IF...THEN...ELSE using XML

I don't think you can design the if-then-else construct without taking the design for other constructs into account. I think it's a good principle that each expression should be an element, and its subexpressions should be child elements. There are then questions about whether the name of an element should reflect the type of expression it is, or its role relative to the parent. Or you can do both:

<if>
  <condition>
    <equals>
      <number>2</number>
      <number>3</number>
    <equals>
  <condition>
  <then>
    <string>Mary</string>
  </then>
  <else>
    <concat>
      <string>John</string>
      <string>Smith</string>
    </concat>
  </else>
</if>

But you can sometimes get away with a design that omits the role-names (condition, then else) and relies on positional significance of elements relative to their parent. It depends a bit on how much you want to keep it concise.

How would you make two <div>s overlap?

Using CSS, you set the logo div to position absolute, and set the z-order to be above the second div.

#logo
{
    position: absolute:
    z-index: 2000;
    left: 100px;
    width: 100px;
    height: 50px;
}

javascript - replace dash (hyphen) with a space

I think the problem you are facing is almost this: -

str = str.replace("-", ' ');

You need to re-assign the result of the replacement to str, to see the reflected change.

From MSDN Javascript reference: -

The result of the replace method is a copy of stringObj after the specified replacements have been made.

To replace all the -, you would need to use /g modifier with a regex parameter: -

str = str.replace(/-/g, ' ');

Pointers in Python?

>> id(1)
1923344848  # identity of the location in memory where 1 is stored
>> id(1)
1923344848  # always the same
>> a = 1
>> b = a  # or equivalently b = 1, because 1 is immutable
>> id(a)
1923344848
>> id(b)  # equal to id(a)
1923344848

As you can see a and b are just two different names that reference to the same immutable object (int) 1. If later you write a = 2, you reassign the name a to a different object (int) 2, but the b continues referencing to 1:

>> id(2)
1923344880
>> a = 2
>> id(a)
1923344880  # equal to id(2)
>> b
1           # b hasn't changed
>> id(b)
1923344848  # equal to id(1)

What would happen if you had a mutable object instead, such as a list [1]?

>> id([1])
328817608
>> id([1])
328664968  # different from the previous id, because each time a new list is created
>> a = [1]
>> id(a)
328817800
>> id(a)
328817800 # now same as before
>> b = a
>> id(b)
328817800  # same as id(a)

Again, we are referencing to the same object (list) [1] by two different names a and b. However now we can mutate this list while it remains the same object, and a, b will both continue referencing to it

>> a[0] = 2
>> a
[2]
>> b
[2]
>> id(a)
328817800  # same as before
>> id(b)
328817800  # same as before

How to get the name of the current Windows user in JavaScript

I think is not possible to do that. It would be a huge security risk if a browser access to that kind of personal information

How to get the integer value of day of week

int day = (int)DateTime.Now.DayOfWeek;

First day of the week: Sunday (with a value of zero)

iPhone 6 and 6 Plus Media Queries

For iPhone 5,

@media screen and (device-aspect-ratio: 40/71)

for iPhone 6,7,8

@media only screen and (min-device-width: 375px) and (max-device-width: 667px) and (orientation : portrait)

for iPhone 6+,7+,8+

@media screen and (-webkit-device-pixel-ratio: 3) and (min-device-width: 414px)

Working fine for me as of now.

Twitter bootstrap scrollable modal

Your modal is being hidden in firefox, and that is because of the negative margin declaration you have inside your general stylesheet:

.modal {
    margin-top: -45%; /* remove this */
    max-height: 90%;
    overflow-y: auto;
}

Remove the negative margin and everything works just fine.

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

In HTML, elements containing nothing but normal whitespace characters are considered empty. A paragraph that contains just a normal space character will have zero height. A non-breaking space is a special kind of whitespace character that isn't considered to be insignificant, so it can be used as content for a non-empty paragraph.

Even if you consider CSS margins on paragraphs, since an "empty" paragraph has zero height, its vertical margins will collapse. This causes it to have no height and no margins, making it appear as if it were never there at all.

Where in an Eclipse workspace is the list of projects stored?

In Linux after deleting

<workspace>\.metadata\.plugins\org.eclipse.core.resources\.projects\

Does not worked.

After that i have done File->Refresh

Then it cleared all old project listed from eclipse.

csv.Error: iterator should return strings, not bytes

I had this error when running an old python script developped with Python 2.6.4

When updating to 3.6.2, I had to remove all 'rb' parameters from open calls in order to fix this csv reading error.

How can I reverse a NSArray in Objective-C?

Or the Scala-way:

-(NSArray *)reverse
{
    if ( self.count < 2 )
        return self;
    else
        return [[self.tail reverse] concat:[NSArray arrayWithObject:self.head]];
}

-(id)head
{
    return self.firstObject;
}

-(NSArray *)tail
{
    if ( self.count > 1 )
        return [self subarrayWithRange:NSMakeRange(1, self.count - 1)];
    else
        return @[];
}

When do you use the "this" keyword?

1 - Common Java setter idiom:

 public void setFoo(int foo) {
     this.foo = foo;
 }

2 - When calling a function with this object as a parameter

notifier.addListener(this);

Get querystring from URL using jQuery

To retrieve the entire querystring from the current URL, beginning with the ? character, you can use

location.search

https://developer.mozilla.org/en-US/docs/DOM/window.location

Example:

// URL = https://example.com?a=a%20a&b=b123
console.log(location.search); // Prints "?a=a%20a&b=b123" 

In regards to retrieving specific querystring parameters, while although classes like URLSearchParams and URL exist, they aren't supported by Internet Explorer at this time, and should probably be avoided. Instead, you can try something like this:

/**
 * Accepts either a URL or querystring and returns an object associating 
 * each querystring parameter to its value. 
 *
 * Returns an empty object if no querystring parameters found.
 */
function getUrlParams(urlOrQueryString) {
  if ((i = urlOrQueryString.indexOf('?')) >= 0) {
    const queryString = urlOrQueryString.substring(i+1);
    if (queryString) {
      return _mapUrlParams(queryString);
    } 
  }

  return {};
}

/**
 * Helper function for `getUrlParams()`
 * Builds the querystring parameter to value object map.
 *
 * @param queryString {string} - The full querystring, without the leading '?'.
 */
function _mapUrlParams(queryString) {
  return queryString    
    .split('&') 
    .map(function(keyValueString) { return keyValueString.split('=') })
    .reduce(function(urlParams, [key, value]) {
      if (Number.isInteger(parseInt(value)) && parseInt(value) == value) {
        urlParams[key] = parseInt(value);
      } else {
        urlParams[key] = decodeURI(value);
      }
      return urlParams;
    }, {});
}

You can use the above like so:

// Using location.search
let urlParams = getUrlParams(location.search); // Assume location.search = "?a=1&b=2b2"
console.log(urlParams); // Prints { "a": 1, "b": "2b2" }

// Using a URL string
const url = 'https://example.com?a=A%20A&b=1';
urlParams = getUrlParams(url);
console.log(urlParams); // Prints { "a": "A A", "b": 1 }

// To check if a parameter exists, simply do:
if (urlParams.hasOwnProperty('parameterName') { 
  console.log(urlParams.parameterName);
}

Get each line from textarea

You could use PHP constant:

$array = explode(PHP_EOL, $text);

additional notes:
1. For me this is the easiest and the safest way because it is cross platform compatible (Windows/Linux etc.)
2. It is better to use PHP CONSTANT whenever you can for faster execution

How do I reformat HTML code using Sublime Text 2?

you can set shortcut key F12 easy!!!

{ "keys": ["f12"], "command": "reindent" , "args": { "single_line": false } }

see detail here.

Returning a C string from a function

Return string from function

#include <stdio.h>

const char* greet() {
  return "Hello";
}

int main(void) {
  printf("%s", greet());
}

Adding multiple class using ng-class

For the ternary operator notation:

<div ng-class="expression1? 'class1 class2' : 'class3 class4'">

C error: undefined reference to function, but it IS defined

How are you doing the compiling and linking? You'll need to specify both files, something like:

gcc testpoint.c point.c

...so that it knows to link the functions from both together. With the code as it's written right now, however, you'll then run into the opposite problem: multiple definitions of main. You'll need/want to eliminate one (undoubtedly the one in point.c).

In a larger program, you typically compile and link separately to avoid re-compiling anything that hasn't changed. You normally specify what needs to be done via a makefile, and use make to do the work. In this case you'd have something like this:

OBJS=testpoint.o point.o

testpoint.exe: $(OBJS)
    gcc $(OJBS)

The first is just a macro for the names of the object files. You get it expanded with $(OBJS). The second is a rule to tell make 1) that the executable depends on the object files, and 2) telling it how to create the executable when/if it's out of date compared to an object file.

Most versions of make (including the one in MinGW I'm pretty sure) have a built-in "implicit rule" to tell them how to create an object file from a C source file. It normally looks roughly like this:

.c.o:
    $(CC) -c $(CFLAGS) $<

This assumes the name of the C compiler is in a macro named CC (implicitly defined like CC=gcc) and allows you to specify any flags you care about in a macro named CFLAGS (e.g., CFLAGS=-O3 to turn on optimization) and $< is a special macro that expands to the name of the source file.

You typically store this in a file named Makefile, and to build your program, you just type make at the command line. It implicitly looks for a file named Makefile, and runs whatever rules it contains.

The good point of this is that make automatically looks at the timestamps on the files, so it will only re-compile the files that have changed since the last time you compiled them (i.e., files where the ".c" file has a more recent time-stamp than the matching ".o" file).

Also note that 1) there are lots of variations in how to use make when it comes to large projects, and 2) there are also lots of alternatives to make. I've only hit on the bare minimum of high points here.

Regular expression to match numbers with or without commas and decimals in text

Taking a certain liberty with the requirements, you're looking for

\d+([\d,]?\d)*(\.\d+)?

But notice this will match e.g. 11,11,1

Is there a JavaScript function that can pad a string to get to a determined length?

One liner if you want something compact:

_x000D_
_x000D_
String.prototype.pad = function(len, chr){_x000D_
        return((((new Array(len)).fill(chr)).join("") +this).substring(this.length));_x000D_
}
_x000D_
_x000D_
_x000D_

How to test that a registered variable is not empty?

- name: set pkg copy dir name
  set_fact:
    PKG_DIR: >-
      {% if ansible_os_family == "RedHat" %}centos/*.rpm
      {%- elif ansible_distribution == "Ubuntu" %}ubuntu/*.deb
      {%- elif ansible_distribution == "Kylin Linux Advanced Server" %}kylin/*.deb
      {%- else %}{%- endif %}

jQuery append text inside of an existing paragraph tag

Try this...

$('p').append('<span id="add_here">new-dynamic-text</span>');

OR if there is an existing span, do this.

$('p').children('span').text('new-dynamic-text');

DEMO

Do HttpClient and HttpClientHandler have to be disposed between requests?

I think one should use singleton pattern to avoid having to create instances of the HttpClient and closing it all the time. If you are using .Net 4.0 you could use a sample code as below. for more information on singleton pattern check here.

class HttpClientSingletonWrapper : HttpClient
{
    private static readonly Lazy<HttpClientSingletonWrapper> Lazy= new Lazy<HttpClientSingletonWrapper>(()=>new HttpClientSingletonWrapper()); 

    public static HttpClientSingletonWrapper Instance {get { return Lazy.Value; }}

    private HttpClientSingletonWrapper()
    {
    }
}

Use the code as below.

var client = HttpClientSingletonWrapper.Instance;

HTML5 Video Autoplay not working correctly

_x000D_
_x000D_
html {_x000D_
  padding: 20px 0;_x000D_
  background-color: #efefef;_x000D_
}_x000D_
_x000D_
body {_x000D_
  width: 400px;_x000D_
  padding: 40px;_x000D_
  margin: 0 auto;_x000D_
  background: #fff;_x000D_
  box-shadow: 1px 1px 5px rgba(0, 0, 0, 0.5);_x000D_
}_x000D_
_x000D_
video {_x000D_
  width: 400px;_x000D_
  display: block;_x000D_
}
_x000D_
<video onloadeddata="this.play();this.muted=false;" poster="https://durian.blender.org/wp-content/themes/durian/images/void.png" playsinline loop muted controls>_x000D_
    <source src="http://grochtdreis.de/fuer-jsfiddle/video/sintel_trailer-480.mp4" type="video/mp4" />_x000D_
    Your browser does not support the video tag or the file format of this video._x000D_
</video>
_x000D_
_x000D_
_x000D_

Babel command not found

I had the same issue. Deleted the nodemodules folder and opened command prompt as administrator and then ran npm install.

All packages installed fine.

Lining up labels with radio buttons in bootstrap

If you add the 'radio inline' class to the control label in the solution provided by user1938475 it should line up correctly with the other labels. Or if you're only using 'radio' like your 2nd example just include the 'radio' class.

<label class="radio control-label">Some label</label>

OR for 'radio inline'

<label class="radio-inline control-label">Some label</label>

What is the difference between Hibernate and Spring Data JPA

If you prefer simplicity and more control on SQL queries then I would suggest going with Spring Data/ Spring JDBC.

Its good amount of learning curve in JPA and sometimes difficult to debug issues. On the other hand, while you have full control over SQL, it becomes much easier to optimize query and improve performance. You can easily share your SQL with DBA or someone who has a better understanding of Database.

How to exit from the application and show the home screen?

100% works fine. this is code for Exit your app onClick (Method)

    Button exit = (Button)findViewById(R.id.exitbutton);

    exit.setOnClickListener(new View.OnClickListener() {

        @Override

        public void onClick(View view) {

            finish();
            android.os.Process.killProcess(android.os.Process.myPid());
            System.exit(1);
            Toast.makeText(getApplicationContext(), "Closed Completely and Safely", Toast.LENGTH_LONG).show();

        }
    });

What is the difference between $routeProvider and $stateProvider?

Angular's own ng-Router takes URLs into consideration while routing, UI-Router takes states in addition to URLs.

States are bound to named, nested and parallel views, allowing you to powerfully manage your application's interface.

While in ng-router, you have to be very careful about URLs when providing links via <a href=""> tag, in UI-Router you have to only keep state in mind. You provide links like <a ui-sref="">. Note that even if you use <a href=""> in UI-Router, just like you would do in ng-router, it will still work.

So, even if you decide to change your URL some day, your state will remain same and you need to change URL only at .config.

While ngRouter can be used to make simple apps, UI-Router makes development much easier for complex apps. Here its wiki.

How do I manually create a file with a . (dot) prefix in Windows? For example, .htaccess

If you use Git and have Git Bash installed you can open a Git Bash at the directory (via Right Click in the white space in Explorer > Git Bash Here) and do:

touch .htaccess

running a command as a super user from a python script

I tried all the solutions, but did not work. Wanted to run long running tasks with Celery but for these I needed to run sudo chown command with subprocess.call().

This is what worked for me:

To add safe environment variables, in command line, type:

export MY_SUDO_PASS="user_password_here"

To test if it's working type:

echo $MY_SUDO_PASS
 > user_password_here

To run it at system startup add it to the end of this file:

nano ~/.bashrc  

#.bashrc
...
existing_content:

  elif [ -f /etc/bash_completion ]; then
    . /etc/bash_completion
  fi
fi
...

export MY_SUDO_PASS="user_password_here"

You can add all your environment variables passwords, usernames, host, etc here later.

If your variables are ready you can run:

To update:

echo $MY_SUDO_PASS | sudo -S apt-get update

Or to install Midnight Commander

echo $MY_SUDO_PASS | sudo -S apt-get install mc

To start Midnight Commander with sudo

echo $MY_SUDO_PASS | sudo -S mc

Or from python shell (or Django/Celery), to change directory ownership recursively:

python
>> import subprocess
>> subprocess.call('echo $MY_SUDO_PASS | sudo -S chown -R username_here /home/username_here/folder_to_change_ownership_recursivley', shell=True)

Hope it helps.

Why is Github asking for username/password when following the instructions on screen and pushing a new repo?

I had this same issue and wondered why it didn't happen with a bitbucket repo that was cloned with https. Looking into it a bit I found that the config for the BB repo had a URL that included my username. So I manually edited the config for my GH repo like so and voila, no more username prompt. I'm on Windows.

Edit your_repo_dir/.git/config (remember: .git folder is hidden)

Change:

https://github.com/WEMP/project-slideshow.git

to:

https://*username*@github.com/WEMP/project-slideshow.git

Save the file. Do a git pull to test it.

The proper way to do this is probably by using git bash commands to edit the setting, but editing the file directly didn't seem to be a problem.

How do I auto-submit an upload form when a file is selected?

HTML

<form id="xtarget" action="upload.php">
<input type="file" id="xfilename">
</form>

JAVASCRIPT PURE

<script type="text/javascript">
window.onload = function() {
    document.getElementById("xfilename").onchange = function() {
        document.getElementById("xtarget").submit();
    }
};
</script>

HTML button onclick event

<body>
"button" value="Add Students" onclick="window.location.href='Students.html';"> 
<input type="button" value="Add Courses" onclick="window.location.href='Courses.html';"> 
<input type="button" value="Student Payments" onclick="window.location.href='Payments.html';">
</body>

Cassandra cqlsh - connection refused

cqlsh --cqlversion="3.4.0" Connected to Test Cluster at 127.0.0.1:9042. [cqlsh 5.0.1 | Cassandra 3.0.9 | CQL spec 3.4.0 | Native protocol v4]

try the above command. It works for me.

How to find the cumulative sum of numbers in a list?

Somewhat hacky, but seems to work:

def cumulative_sum(l):
  y = [0]
  def inc(n):
    y[0] += n
    return y[0]
  return [inc(x) for x in l]

I did think that the inner function would be able to modify the y declared in the outer lexical scope, but that didn't work, so we play some nasty hacks with structure modification instead. It is probably more elegant to use a generator.

How to convert object to Dictionary<TKey, TValue> in C#?

this should work:

for numbers, strings, date, etc.:

    public static void MyMethod(object obj)
    {
        if (typeof(IDictionary).IsAssignableFrom(obj.GetType()))
        {
            IDictionary idict = (IDictionary)obj;

            Dictionary<string, string> newDict = new Dictionary<string, string>();
            foreach (object key in idict.Keys)
            {
                newDict.Add(key.ToString(), idict[key].ToString());
            }
        }
        else
        {
            // My object is not a dictionary
        }
    }

if your dictionary also contains some other objects:

    public static void MyMethod(object obj)
    {
        if (typeof(IDictionary).IsAssignableFrom(obj.GetType()))
        {
            IDictionary idict = (IDictionary)obj;
            Dictionary<string, string> newDict = new Dictionary<string, string>();

            foreach (object key in idict.Keys)
            {
                newDict.Add(objToString(key), objToString(idict[key]));
            }
        }
        else
        {
            // My object is not a dictionary
        }
    }

    private static string objToString(object obj)
    {
        string str = "";
        if (obj.GetType().FullName == "System.String")
        {
            str = (string)obj;
        }
        else if (obj.GetType().FullName == "test.Testclass")
        {
            TestClass c = (TestClass)obj;
            str = c.Info;
        }
        return str;
    }

How can I add a column that doesn't allow nulls in a Postgresql database?

Specifying a default value would also work, assuming a default value is appropriate.

Set the text in a span

You need to fix your selector. Although CSS syntax requires multiple classes to be space separated, selector syntax would require them to be directly concatenated, and dot prefixed:

$(".ui-icon.ui-icon-circle-triangle-w").text(...);

or better:

$(".ui-datepicker-prev > span").text(...);

How to merge specific files from Git branches

Are all the modifications to file.py in branch2 in their own commits, separate from modifications to other files? If so, you can simply cherry-pick the changes over:

git checkout branch1
git cherry-pick <commit-with-changes-to-file.py>

Otherwise, merge does not operate over individual paths...you might as well just create a git diff patch of file.py changes from branch2 and git apply them to branch1:

git checkout branch2
git diff <base-commit-before-changes-to-file.py> -- file.py > my.patch
git checkout branch1
git apply my.patch

Chrome dev tools fails to show response even the content returned has header Content-Type:text/html; charset=UTF-8

I think this only happens when you have 'Preserve log' checked and you are trying to view the response data of a previous request after you have navigated away.

For example, I viewed the Response to loading this Stack Overflow question. You can see it.

Response Data

The second time, I reloaded this page but didn't look at the Headers or Response. I navigated to a different website. Now when I look at the response, it shows 'Failed to load response data'.

No Response Data

This is a known issue, that's been around for a while, and debated a lot. However, there is a workaround, in which you pause on onunload, so you can view the response before it navigates away, and thereby doesn't lose the data upon navigating away.

window.onunload = function() { debugger; }

Android: Remove all the previous activities from the back stack

The solution proposed here worked for me:

Java

Intent i = new Intent(OldActivity.this, NewActivity.class);
// set the new task and clear flags
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(i);

Kotlin

val i = Intent(this, NewActivity::class.java)
// set the new task and clear flags
i.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
startActivity(i)

However, it requires API level >= 11.

Performing user authentication in Java EE / JSF using j_security_check

After searching the Web and trying many different ways, here's what I'd suggest for Java EE 6 authentication:

Set up the security realm:

In my case, I had the users in the database. So I followed this blog post to create a JDBC Realm that could authenticate users based on username and MD5-hashed passwords in my database table:

http://blog.gamatam.com/2009/11/jdbc-realm-setup-with-glassfish-v3.html

Note: the post talks about a user and a group table in the database. I had a User class with a UserType enum attribute mapped via javax.persistence annotations to the database. I configured the realm with the same table for users and groups, using the userType column as the group column and it worked fine.

Use form authentication:

Still following the above blog post, configure your web.xml and sun-web.xml, but instead of using BASIC authentication, use FORM (actually, it doesn't matter which one you use, but I ended up using FORM). Use the standard HTML , not the JSF .

Then use BalusC's tip above on lazy initializing the user information from the database. He suggested doing it in a managed bean getting the principal from the faces context. I used, instead, a stateful session bean to store session information for each user, so I injected the session context:

 @Resource
 private SessionContext sessionContext;

With the principal, I can check the username and, using the EJB Entity Manager, get the User information from the database and store in my SessionInformation EJB.

Logout:

I also looked around for the best way to logout. The best one that I've found is using a Servlet:

 @WebServlet(name = "LogoutServlet", urlPatterns = {"/logout"})
 public class LogoutServlet extends HttpServlet {
  @Override
  protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
   HttpSession session = request.getSession(false);

   // Destroys the session for this user.
   if (session != null)
        session.invalidate();

   // Redirects back to the initial page.
   response.sendRedirect(request.getContextPath());
  }
 }

Although my answer is really late considering the date of the question, I hope this helps other people that end up here from Google, just like I did.

Ciao,

Vítor Souza

CORS error :Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response

This is an API issue, you won't get this error if using Postman/Fielder to send HTTP requests to API. In case of browsers, for security purpose, they always send OPTIONS request/preflight to API before sending the actual requests (GET/POST/PUT/DELETE). Therefore, in case, the request method is OPTION, not only you need to add "Authorization" into "Access-Control-Allow-Headers", but you need to add "OPTIONS" into "Access-Control-allow-methods" as well. This was how I fixed:

if (context.Request.Method == "OPTIONS")
        {
            context.Response.Headers.Add("Access-Control-Allow-Origin", new[] { (string)context.Request.Headers["Origin"] });
            context.Response.Headers.Add("Access-Control-Allow-Headers", new[] { "Origin, X-Requested-With, Content-Type, Accept, Authorization" });
            context.Response.Headers.Add("Access-Control-Allow-Methods", new[] { "GET, POST, PUT, DELETE, OPTIONS" });
            context.Response.Headers.Add("Access-Control-Allow-Credentials", new[] { "true" });

        }

CSS: Truncate table cells, but fit as much as possible

Check if "nowrap" solve the issue to an extent. Note: nowrap is not supported in HTML5

<table border="1" style="width: 100%; white-space: nowrap; table-layout: fixed;">
<tr>
    <td style="overflow: hidden; text-overflow: ellipsis;" nowrap >This cells has more content  </td>
    <td style="overflow: hidden; text-overflow: ellipsis;" nowrap >Less content here has more content</td>
</tr>

Eclipse plugin for generating a class diagram

Try Amateras. It is a very good plugin for generating UML diagrams including class diagram.

Today's Date in Perl in MM/DD/YYYY format

You can use Time::Piece, which shouldn't need installing as it is a core module and has been distributed with Perl 5 since version 10.

use Time::Piece;

my $date = localtime->strftime('%m/%d/%Y');
print $date;

output

06/13/2012


Update

You may prefer to use the dmy method, which takes a single parameter which is the separator to be used between the fields of the result, and avoids having to specify a full date/time format

my $date = localtime->dmy('/');

This produces an identical result to that of my original solution

How to debug Lock wait timeout exceeded on MySQL?

Extrapolating from Rolando's answer above, it is these that are blocking your query:

---TRANSACTION 0 620783788, not started, process no 29956, OS thread id 1196472640
MySQL thread id 5341773, query id 189708353 10.64.89.143 viget

If you need to execute your query and can not wait for the others to run, kill them off using the MySQL thread id:

kill 5341773 <replace with your thread id>

(from within mysql, not the shell, obviously)

You have to find the thread IDs from the:

show engine innodb status\G

command, and figure out which one is the one that is blocking the database.

ExecutorService that interrupts tasks after a timeout

How about using the ExecutorService.shutDownNow() method as described in http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ExecutorService.html? It seems to be the simplest solution.

Store a closure as a variable in Swift

I've provide an example not sure if this is what you're after.

var completionHandler: (_ value: Float) -> ()

func printFloat(value: Float) {
    print(value)
}

completionHandler = printFloat

completionHandler(5)

It simply prints 5 using the completionHandler variable declared.

When do Java generics require <? extends T> instead of <T> and is there any downside of switching?

One way for me to understand wildcards is to think that the wildcard isn't specifying the type of the possible objects that given generic reference can "have", but the type of other generic references that it is is compatible with (this may sound confusing...) As such, the first answer is very misleading in it's wording.

In other words, List<? extends Serializable> means you can assign that reference to other Lists where the type is some unknown type which is or a subclass of Serializable. DO NOT think of it in terms of A SINGLE LIST being able to hold subclasses of Serializable (because that is incorrect semantics and leads to a misunderstanding of Generics).

How to store arrays in MySQL?

The proper way to do this is to use multiple tables and JOIN them in your queries.

For example:

CREATE TABLE person (
`id` INT NOT NULL PRIMARY KEY,
`name` VARCHAR(50)
);

CREATE TABLE fruits (
`fruit_name` VARCHAR(20) NOT NULL PRIMARY KEY,
`color` VARCHAR(20),
`price` INT
);

CREATE TABLE person_fruit (
`person_id` INT NOT NULL,
`fruit_name` VARCHAR(20) NOT NULL,
PRIMARY KEY(`person_id`, `fruit_name`)
);

The person_fruit table contains one row for each fruit a person is associated with and effectively links the person and fruits tables together, I.E.

1 | "banana"
1 | "apple"
1 | "orange"
2 | "straberry"
2 | "banana"
2 | "apple"

When you want to retrieve a person and all of their fruit you can do something like this:

SELECT p.*, f.*
FROM person p
INNER JOIN person_fruit pf
ON pf.person_id = p.id
INNER JOIN fruits f
ON f.fruit_name = pf.fruit_name

Launch an event when checking a checkbox in Angular2

You can use ngModel like

<input type="checkbox" [ngModel]="checkboxValue" (ngModelChange)="addProp($event)" data-md-icheck/>

To update the checkbox state by updating the property checkboxValue in your code and when the checkbox is changed by the user addProp() is called.

How to get the current URL within a Django template?

Both {{ request.path }} and {{ request.get_full_path }} return the current URL but not absolute URL, for example:

your_website.com/wallpapers/new_wallpaper

Both will return /new_wallpaper/ (notice the leading and trailing slashes)

So you'll have to do something like

{% if request.path == '/new_wallpaper/' %}
    <button>show this button only if url is new_wallpaper</button>
{% endif %}

However, you can get the absolute URL using (thanks to the answer above)

{{ request.build_absolute_uri }}

NOTE: you don't have to include request in settings.py, it's already there.

Gradle: Could not determine java version from '11.0.2'

As distributionUrl is still pointing to older version, upgrade wrapper using:

gradle wrapper --gradle-version 5.1.1

Note: Use gradle and not gradlew

How can I represent 'Authorization: Bearer <token>' in a Swagger Spec (swagger.json)

My Hackie way to solve this was by modifying the swagger.go file in the echo-swagger package in my case:

At the bottom of the file update the window.onload function to include a requestInterceptor which correctly formats the token.

window.onload = function() {
  // Build a system
  const ui = SwaggerUIBundle({
  url: "{{.URL}}",
  dom_id: '#swagger-ui',
  validatorUrl: null,
  presets: [
    SwaggerUIBundle.presets.apis,
    SwaggerUIStandalonePreset
  ],
  plugins: [
    SwaggerUIBundle.plugins.DownloadUrl
  ,
  layout: "StandaloneLayout",
  requestInterceptor: (req) => {
    req.headers.Authorization = "Bearer " + req.headers.Authorization
  return req
  }
})

window.ui = ui

}

Batch file to copy files from one folder to another folder

xcopy.exe is definitely your friend here. It's built into Windows, so its cost is nothing.

Just xcopy /s c:\source d:\target

You'd probably want to tweak a few things; some of the options we also add include these:

  • /s/e - recursive copy, including copying empty directories.
  • /v - add this to verify the copy against the original. slower, but for the paranoid.
  • /h - copy system and hidden files.
  • /k - copy read-only attributes along with files. otherwise, all files become read-write.
  • /x - if you care about permissions, you might want /o or /x.
  • /y - don't prompt before overwriting existing files.
  • /z - if you think the copy might fail and you want to restart it, use this. It places a marker on each file as it copies, so you can rerun the xcopy command to pick up from where it left off.

If you think the xcopy might fail partway through (like when you are copying over a flaky network connection), or that you have to stop it and want to continue it later, you can use xcopy /s/z c:\source d:\target.

Hope this helps.

How to mkdir only if a directory does not already exist?

The old tried and true

mkdir /tmp/qq >/dev/null 2>&1

will do what you want with none of the race conditions many of the other solutions have.

Sometimes the simplest (and ugliest) solutions are the best.

how to check if a file is a directory or regular file in python?

os.path.isfile("bob.txt") # Does bob.txt exist?  Is it a file, or a directory?
os.path.isdir("bob")

How to zoom div content using jquery?

Used zoom-master/jquery.zoom.js. The zoom for the image worked perfectly. Here is a link to the page. http://www.jacklmoore.com/zoom/

 <script>
    $(document).ready(function(){
        $('#ex1').zoom();

    });
</script>

PHP check file extension

$file = $_FILES["file"] ["tmp_name"]; 
$check_ext = strtolower(pathinfo($file,PATHINFO_EXTENSION));
if ($check_ext == "fileext") {
    //code
}
else { 
    //code
}

How to combine two strings together in PHP?

$result = implode(' ', array($data1, $data2));

is more generic.

C pointer to array/array of pointers disambiguation

I guess the second declaration is confusing to many. Here's an easy way to understand it.

Lets have an array of integers, i.e. int B[8].

Let's also have a variable A which points to B. Now, value at A is B, i.e. (*A) == B. Hence A points to an array of integers. In your question, arr is similar to A.

Similarly, in int* (*C) [8], C is a pointer to an array of pointers to integer.

How to sort an array of objects by multiple fields?

for a non-generic, simple solution to your exact problem:

homes.sort(
   function(a, b) {          
      if (a.city === b.city) {
         // Price is only important when cities are the same
         return b.price - a.price;
      }
      return a.city > b.city ? 1 : -1;
   });

List and kill at jobs on UNIX

You should be able to find your command with a ps variant like:

ps -ef
ps -fubob # if your job's user ID is bob.

Then, once located, it should be a simple matter to use kill to kill the process (permissions permitting).

If you're talking about getting rid of jobs in the at queue (that aren't running yet), you can use atq to list them and atrm to get rid of them.

How do I fix the indentation of selected lines in Visual Studio

To fix the indentation and formatting in all files of your solution:

  1. Install the Format All Files extension => close VS, execute the .vsix file and reopen VS;
  2. Menu Tools > Options... > Text Editor > All Languages > Tabs:
    1. Click on Smart (for resolving conflicts);
    2. Type the Tab Size and Indent Size you want (e.g. 2);
    3. Click on Insert Spaces if you want to replace tabs by spaces;
  3. In the Solution Explorer (Ctrl+Alt+L) right click in any file and choose from the menu Format All Files (near the bottom).

This will recursively open and save all files in your solution, setting the indentation you defined above.

You might want to check other programming languages tabs (Options...) for Code Style > Formatting as well.

From Now() to Current_timestamp in Postgresql

Here is an example ...

select * from tablename where to_char(added_time, 'YYYY-MM-DD')  = to_char( now(), 'YYYY-MM-DD' )

added_time is a column name which I converted to char for match

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

I got this error when trying to modify directly after running Query. Turns out, after making a view from that exact same query, I was able to modify the values.

Recyclerview inside ScrollView not scrolling smoothly

I only needed to use this:

mMyRecyclerView.setNestedScrollingEnabled(false);

in my onCreateView() method.

Thanks a lot!

How do you generate dynamic (parameterized) unit tests in Python?

Besides using setattr, we can use load_tests with Python 3.2 and later. Please refer to blog post blog.livreuro.com/en/coding/python/how-to-generate-discoverable-unit-tests-in-python-dynamically/

class Test(unittest.TestCase):
    pass

def _test(self, file_name):
    open(file_name, 'r') as f:
        self.assertEqual('test result',f.read())

def _generate_test(file_name):
    def test(self):
        _test(self, file_name)
    return test

def _generate_tests():
    for file in files:
        file_name = os.path.splitext(os.path.basename(file))[0]
        setattr(Test, 'test_%s' % file_name, _generate_test(file))

test_cases = (Test,)

def load_tests(loader, tests, pattern):
    _generate_tests()
    suite = TestSuite()
    for test_class in test_cases:
        tests = loader.loadTestsFromTestCase(test_class)
        suite.addTests(tests)
    return suite

if __name__ == '__main__':
    _generate_tests()
    unittest.main()

date() method, "A non well formed numeric value encountered" does not want to format a date passed in $_POST

From the documentation for strtotime():

Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed.

In your date string, you have 12-16-2013. 16 isn't a valid month, and hence strtotime() returns false.

Since you can't use DateTime class, you could manually replace the - with / using str_replace() to convert the date string into a format that strtotime() understands:

$date = '2-16-2013';
echo date('Y-m-d', strtotime(str_replace('-','/', $date))); // => 2013-02-16

Comparing Dates in Oracle SQL

31-DEC-95 isn't a string, nor is 20-JUN-94. They're numbers with some extra stuff added on the end. This should be '31-DEC-95' or '20-JUN-94' - note the single quote, '. This will enable you to do a string comparison.

However, you're not doing a string comparison; you're doing a date comparison. You should transform your string into a date. Either by using the built-in TO_DATE() function, or a date literal.

TO_DATE()

select employee_id
  from employee
 where employee_date_hired > to_date('31-DEC-95','DD-MON-YY')

This method has a few unnecessary pitfalls

  • As a_horse_with_no_name noted in the comments, DEC, doesn't necessarily mean December. It depends on your NLS_DATE_LANGUAGE and NLS_DATE_FORMAT settings. To ensure that your comparison with work in any locale you can use the datetime format model MM instead
  • The year '95 is inexact. You know you mean 1995, but what if it was '50, is that 1950 or 2050? It's always best to be explicit
select employee_id
  from employee
 where employee_date_hired > to_date('31-12-1995','DD-MM-YYYY')

Date literals

A date literal is part of the ANSI standard, which means you don't have to use an Oracle specific function. When using a literal you must specify your date in the format YYYY-MM-DD and you cannot include a time element.

select employee_id
  from employee
 where employee_date_hired > date '1995-12-31'

Remember that the Oracle date datatype includes a time elemement, so the date without a time portion is equivalent to 1995-12-31 00:00:00.

If you want to include a time portion then you'd have to use a timestamp literal, which takes the format YYYY-MM-DD HH24:MI:SS[.FF0-9]

select employee_id
  from employee
 where employee_date_hired > timestamp '1995-12-31 12:31:02'

Further information

NLS_DATE_LANGUAGE is derived from NLS_LANGUAGE and NLS_DATE_FORMAT is derived from NLS_TERRITORY. These are set when you initially created the database but they can be altered by changing your inialization parameters file - only if really required - or at the session level by using the ALTER SESSION syntax. For instance:

alter session set nls_date_format = 'DD.MM.YYYY HH24:MI:SS';

This means:

  • DD numeric day of the month, 1 - 31
  • MM numeric month of the year, 01 - 12 ( January is 01 )
  • YYYY 4 digit year - in my opinion this is always better than a 2 digit year YY as there is no confusion with what century you're referring to.
  • HH24 hour of the day, 0 - 23
  • MI minute of the hour, 0 - 59
  • SS second of the minute, 0-59

You can find out your current language and date language settings by querying V$NLS_PARAMETERSs and the full gamut of valid values by querying V$NLS_VALID_VALUES.

Further reading


Incidentally, if you want the count(*) you need to group by employee_id

select employee_id, count(*)
  from employee
 where employee_date_hired > date '1995-12-31'
 group by employee_id

This gives you the count per employee_id.

How to use LINQ to select object with minimum or maximum property value

People.Aggregate((curMin, x) => (curMin == null || (x.DateOfBirth ?? DateTime.MaxValue) <
    curMin.DateOfBirth ? x : curMin))

Setting default values to null fields when mapping with Jackson

There is no annotation to set default value.
You can set default value only on java class level:

public class JavaObject 
{
    public String notNullMember;

    public String optionalMember = "Value";
}

How do I pass an object from one activity to another on Android?

When you are creating an object of intent, you can take advantage of following two methods for passing objects between two activities.

putParcelable

putSerializable

You can have your class implement either Parcelable or Serializable. Then you can pass around your custom classes across activities. I have found this very useful.

Here is a small snippet of code I am using

CustomListing currentListing = new CustomListing();
Intent i = new Intent();
Bundle b = new Bundle();
b.putParcelable(Constants.CUSTOM_LISTING, currentListing);
i.putExtras(b);
i.setClass(this, SearchDetailsActivity.class);
startActivity(i);

And in newly started activity code will be something like this...

Bundle b = this.getIntent().getExtras();
if (b != null)
    mCurrentListing = b.getParcelable(Constants.CUSTOM_LISTING);

Text inset for UITextField?

Swift 5 version of Christopher's answer with extra usage sample

import UIKit

private class InsetTextField: UITextField {
    var insets: UIEdgeInsets

    init(insets: UIEdgeInsets) {
        self.insets = insets
        super.init(frame: .zero)
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("not intended for use from a NIB")
    }

    // placeholder position
    override func textRect(forBounds bounds: CGRect) -> CGRect {
         return super.textRect(forBounds: bounds.inset(by: insets))
    }
 
    // text position
    override func editingRect(forBounds bounds: CGRect) -> CGRect {
         return super.editingRect(forBounds: bounds.inset(by: insets))
    }
}

extension UITextField {

    class func textFieldWithInsets(insets: UIEdgeInsets) -> UITextField {
        return InsetTextField(insets: insets)
    }

}

Usage: -

class ViewController: UIViewController {

  private let passwordTextField: UITextField = {

        let textField = UITextField.textFieldWithInsets(insets: UIEdgeInsets(top: 10, left: 15, bottom: 10, right: 15))
     // ---
   
        return textField
    }()

}

Difference between spring @Controller and @RestController annotation

@RestController was provided since Spring 4.0.1. These controllers indicate that here @RequestMapping methods assume @ResponseBody semantics by default.

In earlier versions the similar functionality could be achieved by using below:

  1. @RequestMapping coupled with @ResponseBody like @RequestMapping(value = "/abc", method = RequestMethod.GET, produces ="application/xml") public @ResponseBody MyBean fetch(){ return new MyBean("hi") }

  2. <mvc:annotation-driven/> may be used as one of the ways for using JSON with Jackson or xml.

  3. MyBean can be defined like

@XmlRootElement(name = "MyBean") @XmlType(propOrder = {"field2", "field1"}) public class MyBean{ field1 field2 .. //getter, setter }

  1. @ResponseBody is treated as the view here among MVC and it is dispatched directly instead being dispatched from Dispatcher Servlet and the respective converters convert the response in the related format like text/html, application/xml, application/json .

However, the Restcontroller is already coupled with ResponseBody and the respective converters. Secondly, here, since instead of converting the responsebody, it is automatically converted to http response.

How to kill a child process after a given timeout in Bash?

Here's an attempt which tries to avoid killing a process after it has already exited, which reduces the chance of killing another process with the same process ID (although it's probably impossible to avoid this kind of error completely).

run_with_timeout ()
{
  t=$1
  shift

  echo "running \"$*\" with timeout $t"

  (
  # first, run process in background
  (exec sh -c "$*") &
  pid=$!
  echo $pid

  # the timeout shell
  (sleep $t ; echo timeout) &
  waiter=$!
  echo $waiter

  # finally, allow process to end naturally
  wait $pid
  echo $?
  ) \
  | (read pid
     read waiter

     if test $waiter != timeout ; then
       read status
     else
       status=timeout
     fi

     # if we timed out, kill the process
     if test $status = timeout ; then
       kill $pid
       exit 99
     else
       # if the program exited normally, kill the waiting shell
       kill $waiter
       exit $status
     fi
  )
}

Use like run_with_timeout 3 sleep 10000, which runs sleep 10000 but ends it after 3 seconds.

This is like other answers which use a background timeout process to kill the child process after a delay. I think this is almost the same as Dan's extended answer (https://stackoverflow.com/a/5161274/1351983), except the timeout shell will not be killed if it has already ended.

After this program has ended, there will still be a few lingering "sleep" processes running, but they should be harmless.

This may be a better solution than my other answer because it does not use the non-portable shell feature read -t and does not use pgrep.

check android application is in foreground or not?

I've found a simple soluition for this by creating a base activity class , u must extend all your activity classes from this :

public class BaseActivity extends ActionBarActivity {

@Override
protected void onResume() {
    ApplicationStateChecker.view_resumed(this);
    super.onResume();
}

@Override
protected void onStop() {
    ApplicationStateChecker.view_stopped(this);
    super.onStop();

}

@Override
protected void onPause() {
    ApplicationStateChecker.view_paused(this);
    super.onPause();

}

}

ApplicationStateChecker class :

public class ApplicationStateChecker {

private  static final String _pause_string = "paused";
private  static final String _resume_string = "resumed";

private static String _view_lastState;
private static boolean _from_background = true;

public static void view_paused(Activity activity){
    _view_lastState = _pause_string;
}

public static void view_stopped(Activity activity){

    if (  _view_lastState.equals(_pause_string) ){
        //if stop called and last event was pause then app is brought to background
        _from_background = true;
    }  //if

}

public static void view_resumed(Activity activity){

    if (  _from_background ) {
       //Do your stuff here , app is brought to foreground 

    }  //if

    _from_background = false;
    _view_lastState = _resume_string;
}

eslint: error Parsing error: The keyword 'const' is reserved

I used .eslintrc.js and I have added following code.

module.exports = {
    "parserOptions": {
        "ecmaVersion": 6
    }
};

Remove stubborn underline from link

Here is an example for the asp.net webforms LinkButton control:

 <asp:LinkButton ID="lbmmr1" runat="server" ForeColor="Blue" />

Code behind:

 lbmmr1.Attributes.Add("style", "text-decoration: none;")

Significance of ios_base::sync_with_stdio(false); cin.tie(NULL);

The two calls have different meanings that have nothing to do with performance; the fact that it speeds up the execution time is (or might be) just a side effect. You should understand what each of them does and not blindly include them in every program because they look like an optimization.

ios_base::sync_with_stdio(false);

This disables the synchronization between the C and C++ standard streams. By default, all standard streams are synchronized, which in practice allows you to mix C- and C++-style I/O and get sensible and expected results. If you disable the synchronization, then C++ streams are allowed to have their own independent buffers, which makes mixing C- and C++-style I/O an adventure.

Also keep in mind that synchronized C++ streams are thread-safe (output from different threads may interleave, but you get no data races).

cin.tie(NULL);

This unties cin from cout. Tied streams ensure that one stream is flushed automatically before each I/O operation on the other stream.

By default cin is tied to cout to ensure a sensible user interaction. For example:

std::cout << "Enter name:";
std::cin >> name;

If cin and cout are tied, you can expect the output to be flushed (i.e., visible on the console) before the program prompts input from the user. If you untie the streams, the program might block waiting for the user to enter their name but the "Enter name" message is not yet visible (because cout is buffered by default, output is flushed/displayed on the console only on demand or when the buffer is full).

So if you untie cin from cout, you must make sure to flush cout manually every time you want to display something before expecting input on cin.

In conclusion, know what each of them does, understand the consequences, and then decide if you really want or need the possible side effect of speed improvement.

How to get just the responsive grid from Bootstrap 3?

It's been a while since this question was asked, but maybe now you can forego Bootstrap altogether and use CSS Grid! (it's simpler, neater, more flexible and faster). See this cool article: Stop using Bootstrap — create a practical CSS Grid template for your component based UI

How to concatenate string variables in Bash

The simplest way with quotation marks:

B=Bar
b=bar
var="$B""$b""a"
echo "Hello ""$var"

Force sidebar height 100% using CSS (with a sticky bottom image)?

Until CSS's flexbox becomes more mainstream, you can always just absolutely position the sidebar, sticking it zero pixels away from the top and bottom, then set a margin on your main container to compensate.

JSFiddle

http://jsfiddle.net/QDCGv/

HTML

<section class="sidebar">I'm a sidebar.</section>

<section class="main">I'm the main section.</section>

CSS

section.sidebar {
  width: 250px;
  position: absolute;
  top: 0;
  bottom: 0;
  background-color: green;
}

section.main { margin-left: 250px; }

Note: This is an über simple way to do this but you'll find bottom does not mean "bottom of page," but "bottom of window." The sidebar will probably abrubtly end if your main content scrolls down.

How to convert an Stream into a byte[] in C#?

Quick and dirty technique:

    static byte[] StreamToByteArray(Stream inputStream)
    {
        if (!inputStream.CanRead)
        {
            throw new ArgumentException(); 
        }

        // This is optional
        if (inputStream.CanSeek)
        {
            inputStream.Seek(0, SeekOrigin.Begin);
        }

        byte[] output = new byte[inputStream.Length];
        int bytesRead = inputStream.Read(output, 0, output.Length);
        Debug.Assert(bytesRead == output.Length, "Bytes read from stream matches stream length");
        return output;
    }

Test:

    static void Main(string[] args)
    {
        byte[] data;
        string path = @"C:\Windows\System32\notepad.exe";
        using (FileStream fs = File.Open(path, FileMode.Open, FileAccess.Read))
        {
            data = StreamToByteArray(fs);
        }

        Debug.Assert(data.Length > 0);
        Debug.Assert(new FileInfo(path).Length == data.Length); 
    }

I would ask, why do you want to read a stream into a byte[], if you are wishing to copy the contents of a stream, may I suggest using MemoryStream and writing your input stream into a memory stream.

Value does not fall within the expected range

I had from a totaly different reason the same notice "Value does not fall within the expected range" from the Visual studio 2008 while trying to use the: Tools -> Windows Embedded Silverlight Tools -> Update Silverlight For Windows Embedded Project.

After spending many ohurs I found out that the problem was that there wasn't a resource file and the update tool looks for the .RC file

Therefor the solution is to add to the resource folder a .RC file and than it works perfectly. I hope it will help someone out there

Github: error cloning my private repository

If anybody else is facing this issue in Git for Windows and do not have curl-ca-bundle.crt anywhere on your system even after reinstalling, this is the process I followed:

  1. Download the latest version of curl here: curl download mirror
  2. Extract and navigate to curl-**.**.*/lib in the command line
  3. Run ./mk-ca-bundle.prl
  4. Copy ca-bundle.crt to your git path and update the config as listed in other answers

Shout out to this gist for helping me get the installation done.

javascript, is there an isObject function like isArray?

use the following

It will return a true or false

theObject instanceof Object

what is the difference between json and xml

They are two formats of representation of information. While JSON was designed to be more compact, XML was design to be more readable.

How can I insert new line/carriage returns into an element.textContent?

I know this question posted long time ago.

I had similar problem few days ago, passing value from web service in json format and place it in table cell contentText.

Because value is passed in format, for example, "text row1\r\ntext row2" and so on.

For new line in textContent You have to use \r\n and, finally, I had to use css white-space: pre-line; (Text will wrap when necessary, and on line breaks) and everything goes fine.

Or, You can use only white-space: pre; and then text will wrap only on line breaks (in this case \r\n).

So, there is example how to solve it with wrapping text only on line breaks :

_x000D_
_x000D_
var h1 = document.createElement("h1");_x000D_
_x000D_
//setting this css style solving problem with new line in textContent_x000D_
h1.setAttribute('style', 'white-space: pre;');_x000D_
_x000D_
//add \r\n in text everywhere You want for line-break (new line)_x000D_
h1.textContent = "This is a very long string and I would like to insert a carriage return \r\n...";_x000D_
h1.textContent += "moreover, I would like to insert another carriage return \r\n...";_x000D_
h1.textContent += "so this text will display in a new line";_x000D_
_x000D_
document.body.appendChild(h1);
_x000D_
_x000D_
_x000D_

Show how many characters remaining in a HTML text box using JavaScript

You can bind key press event with your input box and returning false if characters are more than 160 will solve the problem jsfiddle.

JavaScript:

$('textarea').keypress(function(){

    if(this.value.length > 160){
        return false;
    }

    $("#remainingC").html("Remaining characters : " + (160 - this.value.length));
});?

HTML

<textarea></textarea>?
<span id='remainingC'></span>

Aren't promises just callbacks?

In addition to the awesome answers above, 2 more points may be added:

1. Semantic difference:

Promises may be already resolved upon creation. This means they guarantee conditions rather than events. If they are resolved already, the resolved function passed to it is still called.

Conversely, callbacks handle events. So, if the event you are interested in has happened before the callback has been registered, the callback is not called.

2. Inversion of control

Callbacks involve inversion of control. When you register a callback function with any API, the Javascript runtime stores the callback function and calls it from the event loop once it is ready to be run.

Refer The Javascript Event loop for an explanation.

With Promises, control resides with the calling program. The .then() method may be called at any time if we store the promise object.

Centering floating divs within another div

In my case, I could not get the answer by @Sampson to work for me, at best I got a single column centered on the page. In the process however, I learned how the float actually works and created this solution. At it's core the fix is very simple but hard to find as evident by this thread which has had more than 146k views at the time of this post without mention.

All that is needed is to total the amount of screen space width that the desired layout will occupy then make the parent the same width and apply margin:auto. That's it!

The elements in the layout will dictate the width and height of the "outer" div. Take each "myFloat" or element's width or height + its borders + its margins and its paddings and add them all together. Then add the other elements together in the same fashion. This will give you the parent width. They can all be somewhat different sizes and you can do this with fewer or more elements.

Ex.(each element has 2 sides so border, margin and padding get multiplied x2)

So an element that has a width of 10px, border 2px, margin 6px, padding 3px would look like this: 10 + 4 + 12 + 6 = 32

Then add all of your element's totaled widths together.

Element 1 = 32
Element 2 = 24
Element 3 = 32
Element 4 = 24

In this example the width for the "outer" div would be 112.

_x000D_
_x000D_
.outer {_x000D_
  /* floats + margins + borders = 270 */_x000D_
  max-width: 270px;_x000D_
  margin: auto;_x000D_
  height: 80px;_x000D_
  border: 1px;_x000D_
  border-style: solid;_x000D_
}_x000D_
_x000D_
.myFloat {_x000D_
    /* 3 floats x 50px = 150px */_x000D_
    width: 50px;_x000D_
    /* 6 margins x 10px = 60 */_x000D_
    margin: 10px;_x000D_
    /* 6 borders x 10px = 60 */_x000D_
    border: 10px solid #6B6B6B;_x000D_
    float: left;_x000D_
    text-align: center;_x000D_
    height: 40px;_x000D_
}
_x000D_
<div class="outer">_x000D_
  <div class="myFloat">Float 1</div>_x000D_
  <div class="myFloat">Float 2</div>_x000D_
  <div class="myFloat">Float 3</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How do I obtain a Query Execution Plan in SQL Server?

Here's one important thing to know in addition to everything said before.

Query plans are often too complex to be represented by the built-in XML column type which has a limitation of 127 levels of nested elements. That is one of the reasons why sys.dm_exec_query_plan may return NULL or even throw an error in earlier MS SQL versions, so generally it's safer to use sys.dm_exec_text_query_plan instead. The latter also has a useful bonus feature of selecting a plan for a particular statement rather than the whole batch. Here's how you use it to view plans for currently running statements:

SELECT p.query_plan
FROM sys.dm_exec_requests AS r
OUTER APPLY sys.dm_exec_text_query_plan(
                r.plan_handle,
                r.statement_start_offset,
                r.statement_end_offset) AS p

The text column in the resulting table is however not very handy compared to an XML column. To be able to click on the result to be opened in a separate tab as a diagram, without having to save its contents to a file, you can use a little trick (remember you cannot just use CAST(... AS XML)), although this will only work for a single row:

SELECT Tag = 1, Parent = NULL, [ShowPlanXML!1!!XMLTEXT] = query_plan
FROM sys.dm_exec_text_query_plan(
                -- set these variables or copy values
                -- from the results of the above query
                @plan_handle,
                @statement_start_offset,
                @statement_end_offset)
FOR XML EXPLICIT

Gulp command not found after install

If you are on Mac run use root privilege

sudo npm install gulp-cli --global

To check if it's installed run

gulp -v

CLI version: 2.2.0 (The output)

Local version: Unknown

How to display the first few characters of a string in Python?

Since there is a delimiter, you should use that instead of worrying about how long the md5 is.

>>> s = "416d76b8811b0ddae2fdad8f4721ddbe|d4f656ee006e248f2f3a8a93a8aec5868788b927|12a5f648928f8e0b5376d2cc07de8e4cbf9f7ccbadb97d898373f85f0a75c47f"
>>> md5sum, delim, rest = s.partition('|')
>>> md5sum
'416d76b8811b0ddae2fdad8f4721ddbe'

Alternatively

>>> md5sum, sha1sum, sha5sum = s.split('|')
>>> md5sum
'416d76b8811b0ddae2fdad8f4721ddbe'
>>> sha1sum
'd4f656ee006e248f2f3a8a93a8aec5868788b927'
>>> sha5sum
'12a5f648928f8e0b5376d2cc07de8e4cbf9f7ccbadb97d898373f85f0a75c47f'

split python source code into multiple files?

Python has importing and namespacing, which are good. In Python you can import into the current namespace, like:

>>> from test import disp
>>> disp('World!')

Or with a namespace:

>>> import test
>>> test.disp('World!')

How to modify existing XML file with XmlDocument and XmlNode in C#

You need to do something like this:

// instantiate XmlDocument and load XML from file
XmlDocument doc = new XmlDocument();
doc.Load(@"D:\test.xml");

// get a list of nodes - in this case, I'm selecting all <AID> nodes under
// the <GroupAIDs> node - change to suit your needs
XmlNodeList aNodes = doc.SelectNodes("/Equipment/DataCollections/GroupAIDs/AID");

// loop through all AID nodes
foreach (XmlNode aNode in aNodes)
{
   // grab the "id" attribute
   XmlAttribute idAttribute = aNode.Attributes["id"];

   // check if that attribute even exists...
   if (idAttribute != null)
   {
      // if yes - read its current value
      string currentValue = idAttribute.Value;

      // here, you can now decide what to do - for demo purposes,
      // I just set the ID value to a fixed value if it was empty before
      if (string.IsNullOrEmpty(currentValue))
      {
         idAttribute.Value = "515";
      }
   }
}

// save the XmlDocument back to disk
doc.Save(@"D:\test2.xml");

Any way to Invoke a private method?

you can do this using ReflectionTestUtils of Spring (org.springframework.test.util.ReflectionTestUtils)

ReflectionTestUtils.invokeMethod(instantiatedObject,"methodName",argument);

Example : if you have a class with a private method square(int x)

Calculator calculator = new Calculator();
ReflectionTestUtils.invokeMethod(calculator,"square",10);

z-index not working with fixed positioning

When elements are positioned outside the normal flow, they can overlap other elements.

according to Overlapping Elements section on http://web.archive.org/web/20130501103219/http://w3schools.com/css/css_positioning.asp

How do you list all triggers in a MySQL database?

For showing a particular trigger in a particular schema you can try the following:

select * from information_schema.triggers where 
information_schema.triggers.trigger_name like '%trigger_name%' and 
information_schema.triggers.trigger_schema like '%data_base_name%'

How to temporarily exit Vim and go back

Assuming terminal Vim on a flavor of *nix:

To suspend your running Vim

Ctrl + Z

will suspend the process and get back to your shell

fg

will resume (bring to foreground) your suspended Vim.

To start a new shell

Start a subshell using:

:sh

(as configured by)

:set shell?

or

:!bash

followed by:

Ctrl+D (or exit, but why type so much?)

to kill the shell and return to Vim.

Best way to run scheduled tasks

Additionally, if your application uses SQL SERVER you can use the SQL Agent to schedule your tasks. This is where we commonly put re-occurring code that is data driven (email reminders, scheduled maintenance, purges, etc...). A great feature that is built in with the SQL Agent is failure notification options, which can alert you if a critical task fails.

Can not find the tag library descriptor for "http://java.sun.com/jsp/jstl/core"

in your pom.xml just add

    <!-- jstl -->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
    </dependency> 

and try run

mvn eclipse:eclipse -Dwtpversion=2.0

will solve the problem

How to prevent column break within an element?

A possible workaround for Firefox is to set the CSS property "display" of the element you don't want to have a break inside to "table". I don't know if it works for the LI tag (you'll probably lose the list -item-style), but it works for the P tag.

Removing a non empty directory programmatically in C or C++

You can use opendir and readdir to read directory entries and unlink to delete them.

No log4j2 configuration file found. Using default configuration: logging only errors to the console

I have solve this problem by configuring the build path. Here are the steps that I followed: In eclipse.

  1. create a folder and save the logj4 file in it.
  2. Write click in the folder created and go to Build path.
  3. Click on Add folder
  4. Choose the folder created.
  5. Click ok and Apply and close.

Now you should be able to run

what does Error "Thread 1:EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)" mean?

If someone else have got a similar error message, you probably built the app with optimisations(production) flag on and that's why the error message is not that communicative. Another possibility that you have got the error under development (from i386 I know you were using simulator). If that is the case, change the build environment to development and try to reproduce the situation to get a more specific error message.

Can an AWS Lambda function call another

I was looking at cutting out SNS until I saw this in the Lambda client docs (Java version):

Client for accessing AWS Lambda. All service calls made using this client are blocking, and will not return until the service call completes.

So SNS has an obvious advantage: it's asynchronous. Your lambda won't wait for the subsequent lambda to complete.

How to add row of data to Jtable from values received from jtextfield and comboboxes

you can use this code as template please customize it as per your requirement.

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

list.add(textField.getText());
list.add(comboBox.getSelectedItem());

model.addRow(list.toArray());

table.setModel(model);

here DefaultTableModel is used to add rows in JTable, you can get more info here.

mongodb how to get max value from collections

what about using aggregate framework:

db.collection.aggregate({ $group : { _id: null, max: { $max : "$age" }}});

regex string replace

Just change + to -:

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

You can read it as:

  1. [^ ]: match NOT from the set
  2. [^a-z0-9-]: match if not a-z, 0-9 or -
  3. / /g: do global match

More information:

Remove a prefix from a string

regex solution (The best way is the solution by @Elazar this is just for fun)

import re
def remove_prefix(text, prefix):
    return re.sub(r'^{0}'.format(re.escape(prefix)), '', text)

>>> print remove_prefix('template.extensions', 'template.')
extensions

104, 'Connection reset by peer' socket error, or When does closing a socket result in a RST rather than FIN?

I had the same issue however with doing an upload of a very large file using a python-requests client posting to a nginx+uwsgi backend.

What ended up being the cause was the the backend had a cap on the max file size for uploads lower than what the client was trying to send.

The error never showed up in our uwsgi logs since this limit was actually one imposed by nginx.

Upping the limit in nginx removed the error.

map function for objects (instead of arrays)

Define a function mapEntries.

mapEntries takes a callback function that is called on each entry in the object with the parameters value, key and object. It should return the a new value.

mapEntries should return a new object with the new values returned from the callback.

Object.defineProperty(Object.prototype, 'mapEntries', {
  enumerable: false,
  value: function (mapEntriesCallback) {
    return Object.fromEntries(
      Object.entries(this).map(
        ([key, value]) => [key, mapEntriesCallback(value, key, this)]
      )
    )
  }
})


// Usage example:

var object = {a: 1, b: 2, c: 3}
var newObject = object.mapEntries(value => value * value)
console.log(newObject)
//> {a: 1, b: 4, c: 9}

Edit: A previous version didn't specify that this is not an enumerable property

Get all non-unique values (i.e.: duplicate/more than one occurrence) in an array

Find non-unique values from 3 arrays (or more):

ES2015

_x000D_
_x000D_
//                              
var arr =  [1,2,2,3,3,4,5,6,2,3,7,8,5,22],
    arr2 = [1,2,511,12,50],
    arr3 = [22,0],
    merged,
    nonUnique;

// Combine all the arrays to a single one
merged = arr.concat(arr2, arr3)

// create a new (dirty) Array with only the non-unique items
nonUnique = merged.filter((item,i) => merged.includes(item, i+1))

// Cleanup - remove duplicate & empty items items 
nonUnique = [...new Set(nonUnique)]

console.log(nonUnique)
_x000D_
_x000D_
_x000D_


PRE-ES2015:

In the below example I chose to superimpose a unique method on top of the Array prototype, allowing access from everywhere and has more "declarative" syntax. I do not recommend this approach on large projects, since it might very well collide with another method with the same custom name.

_x000D_
_x000D_
Array.prototype.unique = function () {
    var arr = this.sort(), i=arr.length; // input must be sorted for this to work
    while(i--)
      arr[i] === arr[i-1] && arr.splice(i,1) // remove duplicate item
    return arr
}

Array.prototype.nonunique = function () {
    var arr = this.sort(), i=arr.length, res = []; // input must be sorted for this to work
    while(i--)
      arr[i] === arr[i-1] && (res.indexOf(arr[i]) == -1) && res.push(arr[i]) 
    return res
}

//                             
var arr =  [1,2,2,3,3,4,5,6,2,3,7,8,5,22],
    arr2 = [1,2,511,12,50],
    arr3 = [22,0],
    // merge all arrays & call custom Array Prototype - "unique"
    unique = arr.concat(arr2, arr3).unique(),
    nonunique = arr.concat(arr2, arr3).nonunique()

console.log(unique)     // [1,12,2,22,3,4,5,50,511,6,7,8]
console.log(nonunique)  // [1,12,2,22,3,4,5,50,511,6,7,8]
_x000D_
_x000D_
_x000D_

grep for special characters in Unix

A related note

To grep for carriage return, namely the \r character, or 0x0d, we can do this:

grep -F $'\r' application.log

Alternatively, use printf, or echo, for POSIX compatibility

grep -F "$(printf '\r')" application.log

And we can use hexdump, or less to see the result:

$ printf "a\rb" | grep -F $'\r' | hexdump -c
0000000   a  \r   b  \n

Regarding the use of $'\r' and other supported characters, see Bash Manual > ANSI-C Quoting:

Words of the form $'string' are treated specially. The word expands to string, with backslash-escaped characters replaced as specified by the ANSI C standard

How to hide .php extension in .htaccess

1) Are you sure mod_rewrite module is enabled? Check phpinfo()

2) Your above rule assumes the URL starts with "folder". Is this correct? Did you acutally want to have folder in the URL? This would match a URL like:

/folder/thing -> /folder/thing.php

If you actually want

/thing -> /folder/thing.php

You need to drop the folder from the match expression.

I usually use this to route request to page without php (but yours should work which leads me to think that mod_rewrite may not be enabled):

RewriteRule ^([^/\.]+)/?$ $1.php  [L,QSA]

3) Assuming you are declaring your rules in an .htaccess file, does your installation allow for setting Options (AllowOverride) overrides in .htaccess files? Some shared hosts do not.

When the server finds an .htaccess file (as specified by AccessFileName) it needs to know which directives declared in that file can override earlier access information.

Delete empty lines using sed

sed '/^$/d' should be fine, are you expecting to modify the file in place? If so you should use the -i flag.

Maybe those lines are not empty, so if that's the case, look at this question Remove empty lines from txtfiles, remove spaces from start and end of line I believe that's what you're trying to achieve.

Day Name from Date in JS

Take a look at this :

var event = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));

var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };

console.log(event.toLocaleDateString('de-DE', options));
// expected output: Donnerstag, 20. Dezember 2012

console.log(event.toLocaleDateString('ar-EG', options));
// expected output: ??????? ?? ??????? ????

console.log(event.toLocaleDateString('ko-KR', options));
// expected output: 2012? 12? 20? ???

Source : Mozilla Doc

change values in array when doing foreach

Here's a similar answer using using a => style function:

var data = [1,2,3,4];
data.forEach( (item, i, self) => self[i] = item + 10 );

gives the result:

[11,12,13,14]

The self parameter isn't strictly necessary with the arrow style function, so

data.forEach( (item,i) => data[i] = item + 10);

also works.

access denied for user @ 'localhost' to database ''

You are most likely not using the correct credentials for the MySQL server. You also need to ensure the user you are connecting as has the correct privileges to view databases/tables, and that you can connect from your current location in network topographic terms (localhost).

Android: Reverse geocoding - getFromLocation

The following code snippet is doing it for me (lat and lng are doubles declared above this bit):

Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> addresses = geocoder.getFromLocation(lat, lng, 1);

Java Runtime.getRuntime(): getting output from executing a command line program

If use are already have Apache commons-io available on the classpath, you may use:

Process p = new ProcessBuilder("cat", "/etc/something").start();
String stderr = IOUtils.toString(p.getErrorStream(), Charset.defaultCharset());
String stdout = IOUtils.toString(p.getInputStream(), Charset.defaultCharset());

How can one run multiple versions of PHP 5.x on a development LAMP server?

Rasmus Lerdorf, who created PHP, is maintaining an active Vagrant solution that seems to solve your needs. It allows for quickly switching between PHP versions, currently supporting more than 20 different versions. It comes out of the box with an nginx server, but can easily be switched to apache2 with a preconfigured setting. It also supports MySQL out of the box.

This way you will have access to all versions of PHP, deployable on two of the main web servers, in a nice vagrant box, maintained by the big man behind PHP.

For more information I would like to refer to the talk given by mr. Lerdorf at https://youtu.be/6XnysJAyThs?t=2864

The github repository containing the Vagrant solution is found at https://github.com/rlerdorf/php7dev

How to set the text color of TextView in code?

if you want to give color code directly then use

textView.setTextColor(Color.parseColor("#ffffff"));

or if you want to give color code from colors folder then use

textView.setTextColor(R.color.white);

How to check if a file is a valid image file?

Additionally to the PIL image check you can also add file name extension check like this:

filename.lower().endswith(('.png', '.jpg', '.jpeg', '.tiff', '.bmp', '.gif'))

Note that this only checks if the file name has a valid image extension, it does not actually open the image to see if it's a valid image, that's why you need to use additionally PIL or one of the libraries suggested in the other answers.

'numpy.ndarray' object is not callable error

The error TypeError: 'numpy.ndarray' object is not callable means that you tried to call a numpy array as a function. We can reproduce the error like so in the repl:

In [16]: import numpy as np

In [17]: np.array([1,2,3])()
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/home/user/<ipython-input-17-1abf8f3c8162> in <module>()
----> 1 np.array([1,2,3])()

TypeError: 'numpy.ndarray' object is not callable

If we are to assume that the error is indeed coming from the snippet of code that you posted (something that you should check,) then you must have reassigned either pd.rolling_mean or pd.rolling_std to a numpy array earlier in your code.

What I mean is something like this:

In [1]: import numpy as np

In [2]: import pandas as pd

In [3]: pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Works
Out[3]: array([ nan,  nan,  nan])

In [4]: pd.rolling_mean = np.array([1,2,3])

In [5]: pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Doesn't work anymore...
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/home/user/<ipython-input-5-f528129299b9> in <module>()
----> 1 pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Doesn't work anymore...

TypeError: 'numpy.ndarray' object is not callable

So, basically you need to search the rest of your codebase for pd.rolling_mean = ... and/or pd.rolling_std = ... to see where you may have overwritten them.


Also, if you'd like, you can put in reload(pd) just before your snippet, which should make it run by restoring the value of pd to what you originally imported it as, but I still highly recommend that you try to find where you may have reassigned the given functions.

Visual Studio keyboard shortcut to display IntelliSense

The most efficient one is Ctrl + ..

It helps to automate insertions of using directives. It works if the focus is on a new identifier, e.g. class name.

Is it possible in Java to access private fields via reflection

Yes, it absolutely is - assuming you've got the appropriate security permissions. Use Field.setAccessible(true) first if you're accessing it from a different class.

import java.lang.reflect.*;

class Other
{
    private String str;
    public void setStr(String value)
    {
        str = value;
    }
}

class Test
{
    public static void main(String[] args)
        // Just for the ease of a throwaway test. Don't
        // do this normally!
        throws Exception
    {
        Other t = new Other();
        t.setStr("hi");
        Field field = Other.class.getDeclaredField("str");
        field.setAccessible(true);
        Object value = field.get(t);
        System.out.println(value);
    }
}

And no, you shouldn't normally do this... it's subverting the intentions of the original author of the class. For example, there may well be validation applied in any situation where the field can normally be set, or other fields may be changed at the same time. You're effectively violating the intended level of encapsulation.

Can I pass column name as input parameter in SQL stored Procedure

Try using dynamic SQL:

create procedure sp_First @columnname varchar 
AS 
begin 
    declare @sql nvarchar(4000);
    set @sql='select ['+@columnname+'] from Table_1';
    exec sp_executesql @sql
end 
go

exec sp_First 'sname'
go

Find the max of two or more columns with pandas

You can get the maximum like this:

>>> import pandas as pd
>>> df = pd.DataFrame({"A": [1,2,3], "B": [-2, 8, 1]})
>>> df
   A  B
0  1 -2
1  2  8
2  3  1
>>> df[["A", "B"]]
   A  B
0  1 -2
1  2  8
2  3  1
>>> df[["A", "B"]].max(axis=1)
0    1
1    8
2    3

and so:

>>> df["C"] = df[["A", "B"]].max(axis=1)
>>> df
   A  B  C
0  1 -2  1
1  2  8  8
2  3  1  3

If you know that "A" and "B" are the only columns, you could even get away with

>>> df["C"] = df.max(axis=1)

And you could use .apply(max, axis=1) too, I guess.

Where to find htdocs in XAMPP Mac

For me it was in

/Users/your username/.bitnami/stackman/machines/xampp

I am using Mac Os Mojave 10.14.5

How to access html form input from asp.net code behind

Simplest way IMO is to include an ID and runat server tag on all your elements.

<div id="MYDIV" runat="server" />

Since it sounds like these are dynamically inserted controls, you might appreciate FindControl().

How to set env variable in Jupyter notebook

You can also set the variables in your kernel.json file:

My solution is useful if you need the same environment variables every time you start a jupyter kernel, especially if you have multiple sets of environment variables for different tasks.

To create a new ipython kernel with your environment variables, do the following:

  • Read the documentation at https://jupyter-client.readthedocs.io/en/stable/kernels.html#kernel-specs
  • Run jupyter kernelspec list to see a list with installed kernels and where the files are stored.
  • Copy the directory that contains the kernel.json (e.g. named python2) to a new directory (e.g. python2_myENV).
  • Change the display_name in the new kernel.json file.
  • Add a env dictionary defining the environment variables.

Your kernel json could look like this (I did not modify anything from the installed kernel.json except display_name and env):

{
 "display_name": "Python 2 with environment",
 "language": "python",
 "argv": [
  "/usr/bin/python2",
  "-m",
  "ipykernel_launcher",
  "-f",
  "{connection_file}"
 ],
 "env": {"LD_LIBRARY_PATH":""}
}

Use cases and advantages of this approach

  • In my use-case, I wanted to set the variable LD_LIBRARY_PATH which effects how compiled modules (e.g. written in C) are loaded. Setting this variable using %set_env did not work.
  • I can have multiple python kernels with different environments.
  • To change the environment, I only have to switch/ restart the kernel, but I do not have to restart the jupyter instance (useful, if I do not want to loose the variables in another notebook). See -however - https://github.com/jupyter/notebook/issues/2647

Running a command as Administrator using PowerShell?

You can create a batch file (*.bat) that runs your powershell script with administrative privileges when double-clicked. In this way, you do not need to change anything in your powershell script.To do this, create a batch file with the same name and location of your powershell script and then put the following content in it:

@echo off

set scriptFileName=%~n0
set scriptFolderPath=%~dp0
set powershellScriptFileName=%scriptFileName%.ps1

powershell -Command "Start-Process powershell \"-ExecutionPolicy Bypass -NoProfile -NoExit -Command `\"cd \`\"%scriptFolderPath%\`\"; & \`\".\%powershellScriptFileName%\`\"`\"\" -Verb RunAs"

That's it!

Here is the explanation:

Assuming your powershell script is in the path C:\Temp\ScriptTest.ps1, your batch file must have the path C:\Temp\ScriptTest.bat. When someone execute this batch file, the following steps will occur:

  1. The cmd will execute the command

    powershell -Command "Start-Process powershell \"-ExecutionPolicy Bypass -NoProfile -NoExit -Command `\"cd \`\"C:\Temp\`\"; & \`\".\ScriptTest.ps1\`\"`\"\" -Verb RunAs"
    
  2. A new powershell session will open and the following command will be executed:

    Start-Process powershell "-ExecutionPolicy Bypass -NoProfile -NoExit -Command `"cd \`"C:\Temp\`"; & \`".\ScriptTest.ps1\`"`"" -Verb RunAs
    
  3. Another new powershell session with administrative privileges will open in the system32 folder and the following arguments will be passed to it:

    -ExecutionPolicy Bypass -NoProfile -NoExit -Command "cd \"C:\Temp\"; & \".\ScriptTest.ps1\""
    
  4. The following command will be executed with administrative privileges:

    cd "C:\Temp"; & ".\ScriptTest.ps1"
    

    Once the script path and name arguments are double quoted, they can contain space or single quotation mark characters (').

  5. The current folder will change from system32 to C:\Temp and the script ScriptTest.ps1 will be executed. Once the parameter -NoExit was passed, the window wont be closed, even if your powershell script throws some exception.

Push Notifications in Android Platform

You can use Xtify (http://developer.xtify.com) - they have a push notifications webservice that works with their SDK. it's free and so far, it's worked really well for me.

Encoding Error in Panda read_csv

Try calling read_csv with encoding='latin1', encoding='iso-8859-1' or encoding='cp1252' (these are some of the various encodings found on Windows).

Get the list of stored procedures created and / or modified on a particular date?

For SQL Server 2012:

SELECT name, modify_date, create_date, type
FROM sys.procedures
WHERE name like '%XXX%' 
ORDER BY modify_date desc

How do I check if I'm running on Windows in Python?

Python os module

Specifically for Python 3.6/3.7:

os.name: The name of the operating system dependent module imported. The following names have currently been registered: 'posix', 'nt', 'java'.

In your case, you want to check for 'nt' as os.name output:

import os

if os.name == 'nt':
     ...

There is also a note on os.name:

See also sys.platform has a finer granularity. os.uname() gives system-dependent version information.

The platform module provides detailed checks for the system’s identity.

Alternative to deprecated getCellType

The accepted answer shows the reason for the deprecation but misses to name the alternative:

CellType    getCellTypeEnum()

where the CellType is the enum decribing the type of the cell.

The plan is to rename getCellTypeEnum() back to getCellType() in POI 4.0.

jQuery Mobile Page refresh mechanism

This answer did the trick for me http://view.jquerymobile.com/master/demos/faq/injected-content-is-not-enhanced.php.

In the context of a multi-pages template, I modify the content of a <div id="foo">...</div> in a Javascript 'pagebeforeshow' handler and trigger a refresh at the end of the script:

$(document).bind("pagebeforeshow", function(event,pdata) {
  var parsedUrl = $.mobile.path.parseUrl( location.href );
  switch ( parsedUrl.hash ) {
    case "#p_02":
      ... some modifications of the content of the <div> here ...
      $("#foo").trigger("create");
    break;
  }
});

What is the use of the JavaScript 'bind' method?

  • function.prototype.bind() accepts an Object.

  • It binds the calling function to the passed Object and the returns the same.

  • When an object is bound to a function, it means you will be able to access the values of that object from within the function using 'this' keyword.

It can also be said as,

function.prototype.bind() is used to provide/change the context of a function.

_x000D_
_x000D_
let powerOfNumber = function(number) {
  let product = 1;
    for(let i=1; i<= this.power; i++) {
      product*=number;
  }
  return product;
}


let powerOfTwo = powerOfNumber.bind({power:2});
alert(powerOfTwo(2));

let powerOfThree = powerOfNumber.bind({power:3});
alert(powerOfThree(2));

let powerOfFour = powerOfNumber.bind({power:4});
alert(powerOfFour(2));
_x000D_
_x000D_
_x000D_

Let us try to understand this.

    let powerOfNumber = function(number) {
      let product = 1;
      for (let i = 1; i <= this.power; i++) {
        product *= number;
      }
      return product;
    }

Here, in this function, this corresponds to the object bound to the function powerOfNumber. Currently we don't have any function that is bound to this function.

Let us create a function powerOfTwo which will find the second power of a number using the above function.

  let powerOfTwo = powerOfNumber.bind({power:2});
  alert(powerOfTwo(2));

Here the object {power : 2} is passed to powerOfNumber function using bind.

The bind function binds this object to the powerOfNumber() and returns the below function to powerOfTwo. Now, powerOfTwo looks like,

    let powerOfNumber = function(number) {
      let product = 1;
        for(let i=1; i<=2; i++) {
          product*=number;
      }
      return product;
    }

Hence, powerOfTwo will find the second power.

Feel free to check this out.

bind() function in Javascript

Proper use of the IDisposable interface

I won't repeat the usual stuff about Using or freeing un-managed resources, that has all been covered. But I would like to point out what seems a common misconception.
Given the following code

Public Class LargeStuff
  Implements IDisposable
  Private _Large as string()

  'Some strange code that means _Large now contains several million long strings.

  Public Sub Dispose() Implements IDisposable.Dispose
    _Large=Nothing
  End Sub

I realise that the Disposable implementation does not follow current guidelines, but hopefully you all get the idea.
Now, when Dispose is called, how much memory gets freed?

Answer: None.
Calling Dispose can release unmanaged resources, it CANNOT reclaim managed memory, only the GC can do that. Thats not to say that the above isn't a good idea, following the above pattern is still a good idea in fact. Once Dispose has been run, there is nothing stopping the GC re-claiming the memory that was being used by _Large, even though the instance of LargeStuff may still be in scope. The strings in _Large may also be in gen 0 but the instance of LargeStuff might be gen 2, so again, memory would be re-claimed sooner.
There is no point in adding a finaliser to call the Dispose method shown above though. That will just DELAY the re-claiming of memory to allow the finaliser to run.

Python ValueError: too many values to unpack

for k, m in self.materials.items():

example:

miles_dict = {'Monday':1, 'Tuesday':2.3, 'Wednesday':3.5, 'Thursday':0.9}
for k, v in miles_dict.items():
    print("%s: %s" % (k, v))

How to import a JSON file in ECMAScript 6?

Adding to the other answers, in Node.js it is possible to use require to read JSON files even inside ES modules. I found this to be especially useful when reading files inside other packages, because it takes advantage of Node's own module resolution strategy to locate the file.

require in an ES module must be first created with createRequire.

Here is a complete example:

import { createRequire } from 'module';

const require = createRequire(import.meta.url);
const packageJson = require('typescript/package.json');
console.log(`You have TypeScript version ${packageJson.version} installed.`);

In a project with TypeScript installed, the code above will read and print the TypeScript version number from package.json.

What does java.lang.Thread.interrupt() do?

Thread.interrupt() sets the interrupted status/flag of the target thread. Then code running in that target thread MAY poll the interrupted status and handle it appropriately. Some methods that block such as Object.wait() may consume the interrupted status immediately and throw an appropriate exception (usually InterruptedException)

Interruption in Java is not pre-emptive. Put another way both threads have to cooperate in order to process the interrupt properly. If the target thread does not poll the interrupted status the interrupt is effectively ignored.

Polling occurs via the Thread.interrupted() method which returns the current thread's interrupted status AND clears that interrupt flag. Usually the thread might then do something such as throw InterruptedException.

EDIT (from Thilo comments): Some API methods have built in interrupt handling. Of the top of my head this includes.

  • Object.wait(), Thread.sleep(), and Thread.join()
  • Most java.util.concurrent structures
  • Java NIO (but not java.io) and it does NOT use InterruptedException, instead using ClosedByInterruptException.

EDIT (from @thomas-pornin's answer to exactly same question for completeness)

Thread interruption is a gentle way to nudge a thread. It is used to give threads a chance to exit cleanly, as opposed to Thread.stop() that is more like shooting the thread with an assault rifle.

How do I set ANDROID_SDK_HOME environment variable?

If you face the same error, here are the step by step instructions:

  1. Open control panel
  2. Then go to System
  3. Then go to Change Environment Variables of the User
  4. Then click create a new environment variables
  5. Create a new variable named ANDROID_SDK_HOME
  6. Set its value to your Android directory, like C:/users/<username>/.android

How to clear all inputs, selects and also hidden fields in a form using jQuery?

If you want to apply clear value to a specific number of fields, then assign id or class to them and apply empty value to them. like this:

$('.all_fields').val('');

where all_fields is class applied to desired input fields for applying empty values. It will protect other fields to be empty, that you don't want to change.

android - listview get item view by position

This is the Kotlin version of the function posted by VVB. I used it in the ListView Adapter to implement the "go to next row first EditText when Enter key is pressed on the last EditText of current row" feature in the getView().

In the ListViewAdapter class, fun getView(), add lastEditText.setOnKeyListner as below:

lastEditText.setOnKeyListener { v, keyCode, event ->
    var setOnKeyListener = false
    if (keyCode == KeyEvent.KEYCODE_ENTER && event.action == KeyEvent.ACTION_UP) {
        try {
            val nextRow = getViewByPosition(position + 1, parent as ListView) as LinearLayout
            val nextET = nextRow.findViewById(R.id.firstEditText) as EditText
            nextET.isFocusableInTouchMode = true
            nextET.requestFocus()
        } catch (e: Exception) {
            // do nothing
        }
        setOnKeyListener = true
    }
    setOnKeyListener
}

add the fun getViewByPosition() after fun getView() as below:

private fun getViewByPosition(pos: Int, listView: ListView): View? {
    val firstListItemPosition: Int = listView.firstVisiblePosition
    val lastListItemPosition: Int = firstListItemPosition + listView.childCount - 1
    return if (pos < firstListItemPosition || pos > lastListItemPosition) {
        listView.adapter.getView(pos, null, listView)
    } else {
        val childIndex = pos + listView.headerViewsCount - firstListItemPosition
        listView.getChildAt(childIndex)
    }
}

How to check which version of Keras is installed?

You can write:

python
import keras
keras.__version__

How to query data out of the box using Spring data JPA by both Sort and Pageable?

Spring Pageable has a Sort included. So if your request has the values it will return a sorted pageable.

request: domain.com/endpoint?sort=[FIELDTOSORTBY]&[FIELDTOSORTBY].dir=[ASC|DESC]&page=0&size=20

That should return a sorted pageable by field provided in the provided order.

Adjust width and height of iframe to fit with content in it

I am using this code to autoadjust height of all iframes (with class autoHeight) when they loads on page. Tested and it works in IE, FF, Chrome, Safari and Opera.

function doIframe() {
    var $iframes = $("iframe.autoHeight"); 
    $iframes.each(function() {
        var iframe = this;
        $(iframe).load(function() {
            setHeight(iframe);
        });
    });
}

function setHeight(e) {
  e.height = e.contentWindow.document.body.scrollHeight + 35;
}

$(window).load(function() {
    doIframe();
});

Can (domain name) subdomains have an underscore "_" in it?

Most answers given here are false. It is perfectly legal to have an underscore in a domain name. Let me quote the standard, RFC 2181, section 11, "Name syntax":

The DNS itself places only one restriction on the particular labels that can be used to identify resource records. That one restriction relates to the length of the label and the full name. [...] Implementations of the DNS protocols must not place any restrictions on the labels that can be used. In particular, DNS servers must not refuse to serve a zone because it contains labels that might not be acceptable to some DNS client programs.

See also the original DNS specification, RFC 1034, section 3.5 "Preferred name syntax" but read it carefully.

Domains with underscores are very common in the wild. Check _jabber._tcp.gmail.com or _sip._udp.apnic.net.

Other RFC mentioned here deal with different things. The original question was for domain names. If the question is for host names (or for URLs, which include a host name), then this is different, the relevant standard is RFC 1123, section 2.1 "Host Names and Numbers" which limits host names to letters-digits-hyphen.

No more data to read from socket error

Try two things:

  1. Set in $ORACLE_HOME/network/admin/tnsnames.ora on the oracle server server=dedicated to server=shared to allow more than one connection at a time. Restart oracle.
  2. If you are using Java this might help you: In java/jdk1.6.0_31/jre/lib/security/Java.security change securerandom.source=file:/dev/urandom to securerandom.source=file:///dev/urandom

Is it possible to add an array or object to SharedPreferences on Android

To write,

SharedPreferences prefs = PreferenceManager
        .getDefaultSharedPreferences(this);
JSONArray jsonArray = new JSONArray();
jsonArray.put(1);
jsonArray.put(2);
Editor editor = prefs.edit();
editor.putString("key", jsonArray.toString());
System.out.println(jsonArray.toString());
editor.commit();

To Read,

try {
    JSONArray jsonArray2 = new JSONArray(prefs.getString("key", "[]"));
    for (int i = 0; i < jsonArray2.length(); i++) {
         Log.d("your JSON Array", jsonArray2.getInt(i)+"");
    }
} catch (Exception e) {
    e.printStackTrace();
}

Other way to do same:

//Retrieve the values
Gson gson = new Gson();
String jsonText = Prefs.getString("key", null);
String[] text = gson.fromJson(jsonText, String[].class);  //EDIT: gso to gson


//Set the values
Gson gson = new Gson();
List<String> textList = new ArrayList<String>(data);
String jsonText = gson.toJson(textList);
prefsEditor.putString("key", jsonText);
prefsEditor.apply();

Using GSON in Java:

public void saveArrayList(ArrayList<String> list, String key){
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
    SharedPreferences.Editor editor = prefs.edit();
    Gson gson = new Gson();
    String json = gson.toJson(list);
    editor.putString(key, json);
    editor.apply();    

}

public ArrayList<String> getArrayList(String key){
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
    Gson gson = new Gson();
    String json = prefs.getString(key, null);
    Type type = new TypeToken<ArrayList<String>>() {}.getType();
    return gson.fromJson(json, type);
}

Using GSON in Kotlin

fun saveArrayList(list: java.util.ArrayList<String?>?, key: String?) {
    val prefs: SharedPreferences = PreferenceManager.getDefaultSharedPreferences(activity)
    val editor: Editor = prefs.edit()
    val gson = Gson()
    val json: String = gson.toJson(list)
    editor.putString(key, json)
    editor.apply()
}

fun getArrayList(key: String?): java.util.ArrayList<String?>? {
    val prefs: SharedPreferences = PreferenceManager.getDefaultSharedPreferences(activity)
    val gson = Gson()
    val json: String = prefs.getString(key, null)
    val type: Type = object : TypeToken<java.util.ArrayList<String?>?>() {}.getType()
    return gson.fromJson(json, type)
}

How to check if all list items have the same value and return it, or return an “otherValue” if they don’t?

public int GetResult(List<int> list){
int first = list.First();
return list.All(x => x == first) ? first : SOME_OTHER_VALUE;
}

How to emulate GPS location in the Android Emulator?

First go in DDMS section in your eclipse Than open emulator Control .... Go To Manual Section set lat and long and then press Send Button

How to find the serial port number on Mac OS X?

mac os x don't use com numbers. you have to use something like 'ser:devicename' , 9600

Read response headers from API response - Angular 5 + TypeScript

Have you exposed the X-Token from server side using access-control-expose-headers? because not all headers are allowed to be accessed from the client side, you need to expose them from the server side

Also in your frontend, you can use new HTTP module to get a full response using {observe: 'response'} like

http
  .get<any>('url', {observe: 'response'})
  .subscribe(resp => {
    console.log(resp.headers.get('X-Token'));
  });

How to select the comparison of two columns as one column in Oracle

I stopped using DECODE several years ago because it is non-portable. Also, it is less flexible and less readable than a CASE/WHEN.

However, there is one neat "trick" you can do with decode because of how it deals with NULL. In decode, NULL is equal to NULL. That can be exploited to tell whether two columns are different as below.

select a, b, decode(a, b, 'true', 'false') as same
  from t;

     A       B  SAME
------  ------  -----
     1       1  true
     1       0  false
     1          false
  null    null  true  

How to get the number of columns from a JDBC ResultSet?

You can get columns number from ResultSetMetaData:

Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(query);
ResultSetMetaData rsmd = rs.getMetaData();

int columnsNumber = rsmd.getColumnCount();

How do I insert non breaking space character &nbsp; in a JSF page?

Not necessary to give 160 . 141 will also work. For the value field provide value="&#141" .

Moving matplotlib legend outside of the axis makes it cutoff by the figure box

Here is another, very manual solution. You can define the size of the axis and paddings are considered accordingly (including legend and tickmarks). Hope it is of use to somebody.

Example (axes size are the same!):

enter image description here

Code:

#==================================================
# Plot table

colmap = [(0,0,1) #blue
         ,(1,0,0) #red
         ,(0,1,0) #green
         ,(1,1,0) #yellow
         ,(1,0,1) #magenta
         ,(1,0.5,0.5) #pink
         ,(0.5,0.5,0.5) #gray
         ,(0.5,0,0) #brown
         ,(1,0.5,0) #orange
         ]


import matplotlib.pyplot as plt
import numpy as np

import collections
df = collections.OrderedDict()
df['labels']        = ['GWP100a\n[kgCO2eq]\n\nasedf\nasdf\nadfs','human\n[pts]','ressource\n[pts]'] 
df['all-petroleum long name'] = [3,5,2]
df['all-electric']  = [5.5, 1, 3]
df['HEV']           = [3.5, 2, 1]
df['PHEV']          = [3.5, 2, 1]

numLabels = len(df.values()[0])
numItems = len(df)-1
posX = np.arange(numLabels)+1
width = 1.0/(numItems+1)

fig = plt.figure(figsize=(2,2))
ax = fig.add_subplot(111)
for iiItem in range(1,numItems+1):
  ax.bar(posX+(iiItem-1)*width, df.values()[iiItem], width, color=colmap[iiItem-1], label=df.keys()[iiItem])
ax.set(xticks=posX+width*(0.5*numItems), xticklabels=df['labels'])

#--------------------------------------------------
# Change padding and margins, insert legend

fig.tight_layout() #tight margins
leg = ax.legend(loc='upper left', bbox_to_anchor=(1.02, 1), borderaxespad=0)
plt.draw() #to know size of legend

padLeft   = ax.get_position().x0 * fig.get_size_inches()[0]
padBottom = ax.get_position().y0 * fig.get_size_inches()[1]
padTop    = ( 1 - ax.get_position().y0 - ax.get_position().height ) * fig.get_size_inches()[1]
padRight  = ( 1 - ax.get_position().x0 - ax.get_position().width ) * fig.get_size_inches()[0]
dpi       = fig.get_dpi()
padLegend = ax.get_legend().get_frame().get_width() / dpi 

widthAx = 3 #inches
heightAx = 3 #inches
widthTot = widthAx+padLeft+padRight+padLegend
heightTot = heightAx+padTop+padBottom

# resize ipython window (optional)
posScreenX = 1366/2-10 #pixel
posScreenY = 0 #pixel
canvasPadding = 6 #pixel
canvasBottom = 40 #pixel
ipythonWindowSize = '{0}x{1}+{2}+{3}'.format(int(round(widthTot*dpi))+2*canvasPadding
                                            ,int(round(heightTot*dpi))+2*canvasPadding+canvasBottom
                                            ,posScreenX,posScreenY)
fig.canvas._tkcanvas.master.geometry(ipythonWindowSize) 
plt.draw() #to resize ipython window. Has to be done BEFORE figure resizing!

# set figure size and ax position
fig.set_size_inches(widthTot,heightTot)
ax.set_position([padLeft/widthTot, padBottom/heightTot, widthAx/widthTot, heightAx/heightTot])
plt.draw()
plt.show()
#--------------------------------------------------
#==================================================

Why do I need to configure the SQL dialect of a data source?

Short answer

"The irony of JDBC is that, although the programming interfaces are portable, the SQL language is not. Despite the many attempts to standardize it, it is still rare to write SQL of any complexity that will run unchanged on two major database platforms. Even where the SQL dialects are similar, each database performs differently depending on the structure of the query, necessitating vendor-specific tuning in most cases."

..stolen from Pro JPA 2 Mastering the Java Persistence API, chapter 1, page 9

So, we might think of JDBC as the ultimate specification that abstracts away everything related to databases, but it isn't.

A quote from the JDBC specification, chapter 4.4, page 20:

The driver layer may mask differences between standard SQL:2003 syntax and the native dialect supported by the data source.

May is no guarantee that the driver will, and therefore we should provide the dialect in order to have a working application. In a best-case scenario, the application will work but might not run as effectively as it could if the persistence provider knew which dialect to use. In the case of Hibernate he will refuse to deploy your application unless you feed him the dialect.

What about JPQL then?

The JDBC specification does not mention the word JPQL. JDBC is a standardized way of database access. Go read this JavaDoc and you will find that once the application can access the database, what must be fed into the JDBC compliant driver is vanilla = undecorated SQL.

It is worth noting that JPQL is a query language, not a data definition language (DDL). So even if we could feed the JDBC driver with JPQL, that would be of no use for the persistence provider during the phase of parsing the persistence.xml file and setting up tables.

Closer look at the property

For your reference, here is an example for Hibernate and EclipseLink on how to specify a Java DB dialect in the persistence.xml file:

<property name="hibernate.dialect" value="org.hibernate.dialect.DerbyTenSevenDialect"/>
<property name="eclipselink.target-database" value="JavaDB"/>

Is the property mandatory?

In theory, the property has not been standardized and the JPA 2.1 specification says not a word about SQL dialects. So we're out of luck and must turn to vendor specific empirical studies and documentation thereof.

Hibernate refuse to accept a deployment archive that hasn't specified the property rendering the archive undeployable. Hibernate documentation says:

Always set the hibernate.dialect property to the correct org.hibernate.dialect.Dialect subclass for your database.

So that is pretty clear. Do note that the dialects listed in the documentation are specifically targeting one or the other vendor. There is no "generic" dialect or anything like that. Given then that the property is an absolute requirement for a successful deployment, you would expect that the documentation of the WildFly application server which bundles Hibernate should say something, but it doesn't.

EclipseLink on the other hand is a bit more forgiving. If you don't provide the property, the deployment deploys (without warning too). EclipseLink documentation says:

Use the eclipselink.target-database property to specify the database to use, controlling custom operations and SQL generation for the specified database.

The talk is about "custom operations and SQL generation", meaning it is bit vague if you ask me. But one thing is clear: They don't say that the property is mandatory. Also note that one of the available values is "Database" which represent "a generic database" target. Hmm, what "dialect" would that be? SQL 2.0?? But then again, the property is called "target-database" and not "dialect" so maybe "Database" translates to no SQL at all lol. Moving on to the GlassFish server which bundles EclipseLink. Documentation (page "6-3") says:

You can specify the optional eclipselink.target-database property to guarantee that the database type is correct.

So GlassFish argues that the property is "optional" and the value added is a "guarantee" that I am actually using Java DB - in case I didn't know.

Conclusion

Copy-paste whatever you can find on google and pray to God.

Copy folder recursively, excluding some folders

Use rsync:

rsync -av --exclude='path1/to/exclude' --exclude='path2/to/exclude' source destination

Note that using source and source/ are different. A trailing slash means to copy the contents of the folder source into destination. Without the trailing slash, it means copy the folder source into destination.

Alternatively, if you have lots of directories (or files) to exclude, you can use --exclude-from=FILE, where FILE is the name of a file containing files or directories to exclude.

--exclude may also contain wildcards, such as --exclude=*/.svn*

Declaring and using MySQL varchar variables

If you are using phpmyadmin to add new routine then don't forget to wrap your code between BEGIN and ENDenter image description here

What is your single most favorite command-line trick using Bash?

You changed to a new directory and want to move a file from the new directory to the old one. In one move: mv file $OLDPWD

Android: How do I get string from resources using its name?

Best Approach

App.getRes().getString(R.string.some_id)

Will work Everywhere (Utils, Models also).

I have read all the answers, all answers can make your work done.

  • You can use getString(R.string.some_string_id) in both Activity or Fragment.
  • You can use Context.getString(R.string.some_string_id) where you don't have direct access to getString() method. Like Dialog.

Problem

When you don't have Context access, like a method in your Util class.

Assume below method without Context.

public void someMethod(){
    ...
    // can't use getResource() or getString() without Context.
}

Now you will pass Context as a parameter in this method and use getString().

public void someMethod(Context context){
    ...
    context.getString(R.string.some_id);
}

What i do is

public void someMethod(){
    ...
    App.getAppResources().getString(R.string.some_id)
}

What? It is very simple to use anywhere in your app!

So here is a solution by which you can access resources from anywhere like Util class .

import android.app.Application;
import android.content.res.Resources;

public class App extends Application {
    private static Resources resources;

    @Override
    public void onCreate() {
        super.onCreate();

        resources = getResources();
    }

    public static Resources getAppResources() {
        return resources;
    }

}

Add name field to your manifest.xml <application tag.

<application
        android:name=".App"
        ...
        >
        ...
    </application>

Now you are good to go. Use App.getAppResources().getString(R.string.some_id) anywhere in app.

Android overlay a view ontop of everything?

I have just made a solution for it. I made a library for this to do that in a reusable way that's why you don't need to recode in your XML. Here is documentation on how to use it in Java and Kotlin. First, initialize it from an activity from where you want to show the overlay-

AppWaterMarkBuilder.doConfigure()
                .setAppCompatActivity(MainActivity.this)
                .setWatermarkProperty(R.layout.layout_water_mark)
                .showWatermarkAfterConfig();

Then you can hide and show it from anywhere in your app -

  /* For hiding the watermark*/
  AppWaterMarkBuilder.hideWatermark() 

  /* For showing the watermark*/
  AppWaterMarkBuilder.showWatermark() 

Gif preview -

preview

How to enable Auto Logon User Authentication for Google Chrome

If you add your site to "Local Intranet" in

Chrome > Options > Under the Hood > Change Proxy Settings > Security (tab) > Local Intranet/Sites > Advanced.

Add you site URL here and it will work.

Update for New Version of Chrome

Chrome > Settings > Advanced > System > Open Proxy Settings > Security (tab) > Local Intranet > Sites (button) > Advanced.

How to set "style=display:none;" using jQuery's attr method?

Based on the comment we are removing one property from style attribute.

Here this was not affect, but when more property are used within the style it helpful.

$('#msform').css('display', '')

After this we use

$("#msform").show();

What does 'const static' mean in C and C++?

This ia s global constant visible/accessible only in the compilation module (.cpp file). BTW using static for this purpose is deprecated. Better use an anonymous namespace and an enum:

namespace
{
  enum
  {
     foo = 42
  };
}

onCreateOptionsMenu inside Fragments

I tried the @Alexander Farber and @Sino Raj answers. Both answers are nice, but I couldn't use the onCreateOptionsMenu inside my fragment, until I discover what was missing:

Add setSupportActionBar(toolbar) in my Activity, like this:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.id.activity_main);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
}

I hope this answer can be helpful for someone with the same problem.

Entity Framework - Generating Classes

I found very nice solution. Microsoft released a beta version of Entity Framework Power Tools: Entity Framework Power Tools Beta 2

There you can generate POCO classes, derived DbContext and Code First mapping for an existing database in some clicks. It is very nice!

After installation some context menu options would be added to your Visual Studio.

Right-click on a C# project. Choose Entity Framework-> Reverse Engineer Code First (Generates POCO classes, derived DbContext and Code First mapping for an existing database):

Visual Studio Context Menu

Then choose your database and click OK. That's all! It is very easy.

How to force a WPF binding to refresh?

You can use binding expressions:

private void ComboBox_Loaded(object sender, RoutedEventArgs e)
{
    ((ComboBox)sender).GetBindingExpression(ComboBox.ItemsSourceProperty)
                      .UpdateTarget();
}

But as Blindmeis noted you can also fire change notifications, further if your collection implements INotifyCollectionChanged (for example implemented in the ObservableCollection<T>) it will synchronize so you do not need to do any of this.

How to replace special characters in a string?

I am using this.

s = s.replaceAll("\\W", ""); 

It replace all special characters from string.

Here

\w : A word character, short for [a-zA-Z_0-9]

\W : A non-word character

How to find EOF through fscanf?

fscanf - "On success, the function returns the number of items successfully read. This count can match the expected number of readings or be less -even zero- in the case of a matching failure. In the case of an input failure before any data could be successfully read, EOF is returned."

So, instead of doing nothing with the return value like you are right now, you can check to see if it is == EOF.

You should check for EOF when you call fscanf, not check the array slot for EOF.

Calling a Function defined inside another function in Javascript

Again, not a direct answer to the question, but was led here by a web search. Ended up exposing the inner function without using return, etc. by simply assigning it to a global variable.

var fname;

function outer() {
    function inner() {
        console.log("hi");
    }
    fname = inner;
}

Now just

fname();

How can I specify the required Node.js version in package.json?

.nvmrc

If you are using NVM like this, which you likely should, then you can indicate the nodejs version required for given project in a git-tracked .nvmrc file:

echo v10.15.1 > .nvmrc

This does not take effect automatically on cd, which is sane: the user must then do a:

nvm use

and now that version of node will be used for the current shell.

You can list the versions of node that you have with:

nvm list

.nvmrc is documented at: https://github.com/creationix/nvm/tree/02997b0753f66c9790c6016ed022ed2072c22603#nvmrc

How to automatically select that node version on cd was asked at: Automatically switch to correct version of Node based on project

Tested with NVM 0.33.11.

C function that counts lines in file

I don't see anything immediately obvious as to what would cause a segmentation fault. My only suspicion is that your code expects to get a filename as a parameter when you run it, but if you don't pass it, it will attempt to reference one, anyway.

Accessing argv[1] when it doesn't exist would cause a segmentation fault. It's generally good practice to check the number of arguments before trying to reference them. You can do this by using the following function prototype for main(), and checking that argc is greater than 1 (simply, it will indicate the number entries in argv).

int main(int argc, char** argv)

The best way to figure out what causes a segfault in general is to use a debugger. If you're in Visual Studio, put a breakpoint at the top of your main function and then choose Run with debugging instead of "Run without debugging" when you start the program. It will stop execution at the top, and let you step line-by-line until you see a problem.

If you're in Linux, you can just grab the core file (it will have "core" in the name) and load that with gdb (GNU Debugger). It can give you a stack dump which will point you straight to the line that caused the segmentation fault to occur.

EDIT: I see you changed your question and code. So this answer probably isn't useful anymore, but I'll leave it as it's good advice anyway, and see if I can address the modified question, shortly).

Define constant variables in C++ header

You generally shouldn't use e.g. const int in a header file, if it's included in several source files. That is because then the variables will be defined once per source file (translation units technically speaking) because global const variables are implicitly static, taking up more memory than required.

You should instead have a special source file, Constants.cpp that actually defines the variables, and then have the variables declared as extern in the header file.

Something like this header file:

// Protect against multiple inclusions in the same source file
#ifndef CONSTANTS_H
#define CONSTANTS_H

extern const int CONSTANT_1;

#endif

And this in a source file:

const int CONSTANT_1 = 123;

Running a Python script from PHP

Inspired by Alejandro Quiroz:

<?php 

$command = escapeshellcmd('python test.py');
$output = shell_exec($command);
echo $output;

?>

Need to add Python, and don't need the path.

Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled

In my case i have included jdbc api dependencies in the project so the "Hello World" not printed. After removing the below dependency it works like a charm.

       <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>

How to define a variable in a Dockerfile?

If the variable is re-used within the same RUN instruction, one could simply set a shell variable. I really like how they approached this with the official Ruby Dockerfile.

Exception: Unexpected end of ZLIB input stream

You have to call close() on the GZIPOutputStream before you attempt to read it. The final bytes of the file will only be written when the file is actually closed. (This is irrespective of any explicit buffering in the output stack. The stream only knows to compress and write the last bytes when you tell it to close. A flush() probably won't help ... though calling finish() instead of close() should work. Look at the javadocs.)

Here's the correct code (in Java);

package test;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class GZipTest {

    public static void main(String[] args) throws
                FileNotFoundException, IOException {
        String name = "/tmp/test";
        GZIPOutputStream gz = new GZIPOutputStream(new FileOutputStream(name));
        gz.write(10);
        gz.close();       // Remove this to reproduce the reported bug
        System.out.println(new GZIPInputStream(new FileInputStream(name)).read());
    }
}

(I've not implemented resource management or exception handling / reporting properly as they are not relevant to the purpose of this code. Don't treat this as an example of "good code".)

SQL recursive query on self referencing table (Oracle)

Use:

    SELECT t1.id, 
           t1.parent_id, 
           t1.name,
           t2.name AS parent_name,
           t2.id AS parent_id
      FROM tbl t1
 LEFT JOIN tbl t2 ON t2.id = t1.parent_id
START WITH t1.id = 1 
CONNECT BY PRIOR t1.id = t1.parent_id

Automatically create an Enum based on values in a database lookup table?

I'm doing this exact thing, but you need to do some kind of code generation for this to work.

In my solution, I added a project "EnumeratedTypes". This is a console application which gets all of the values from the database and constructs the enums from them. Then it saves all of the enums to an assembly.

The enum generation code is like this:

// Get the current application domain for the current thread
AppDomain currentDomain = AppDomain.CurrentDomain;

// Create a dynamic assembly in the current application domain,
// and allow it to be executed and saved to disk.
AssemblyName name = new AssemblyName("MyEnums");
AssemblyBuilder assemblyBuilder = currentDomain.DefineDynamicAssembly(name,
                                      AssemblyBuilderAccess.RunAndSave);

// Define a dynamic module in "MyEnums" assembly.
// For a single-module assembly, the module has the same name as the assembly.
ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule(name.Name,
                                  name.Name + ".dll");

// Define a public enumeration with the name "MyEnum" and an underlying type of Integer.
EnumBuilder myEnum = moduleBuilder.DefineEnum("EnumeratedTypes.MyEnum",
                         TypeAttributes.Public, typeof(int));

// Get data from database
MyDataAdapter someAdapter = new MyDataAdapter();
MyDataSet.MyDataTable myData = myDataAdapter.GetMyData();

foreach (MyDataSet.MyDataRow row in myData.Rows)
{
    myEnum.DefineLiteral(row.Name, row.Key);
}

// Create the enum
myEnum.CreateType();

// Finally, save the assembly
assemblyBuilder.Save(name.Name + ".dll");

My other projects in the solution reference this generated assembly. As a result, I can then use the dynamic enums in code, complete with intellisense.

Then, I added a post-build event so that after this "EnumeratedTypes" project is built, it runs itself and generates the "MyEnums.dll" file.

By the way, it helps to change the build order of your project so that "EnumeratedTypes" is built first. Otherwise, once you start using your dynamically generated .dll, you won't be able to do a build if the .dll ever gets deleted. (Chicken and egg kind of problem -- your other projects in the solution need this .dll to build properly, and you can't create the .dll until you build your solution...)

I got most of the above code from this msdn article.

Hope this helps!

Querying DynamoDB by date

Updated Answer There is no convenient way to do this using Dynamo DB Queries with predictable throughput. One (sub optimal) option is to use a GSI with an artificial HashKey & CreatedAt. Then query by HashKey alone and mention ScanIndexForward to order the results. If you can come up with a natural HashKey (say the category of the item etc) then this method is a winner. On the other hand, if you keep the same HashKey for all items, then it will affect the throughput mostly when when your data set grows beyond 10GB (one partition)

Original Answer: You can do this now in DynamoDB by using GSI. Make the "CreatedAt" field as a GSI and issue queries like (GT some_date). Store the date as a number (msecs since epoch) for this kind of queries.

Details are available here: Global Secondary Indexes - Amazon DynamoDB : http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GSI.html#GSI.Using

This is a very powerful feature. Be aware that the query is limited to (EQ | LE | LT | GE | GT | BEGINS_WITH | BETWEEN) Condition - Amazon DynamoDB : http://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_Condition.html

Difference between SET autocommit=1 and START TRANSACTION in mysql (Have I missed something?)

In InnoDB you have START TRANSACTION;, which in this engine is the officialy recommended way to do transactions, instead of SET AUTOCOMMIT = 0; (don't use SET AUTOCOMMIT = 0; for transactions in InnoDB unless it is for optimizing read only transactions). Commit with COMMIT;.

You might want to use SET AUTOCOMMIT = 0; in InnoDB for testing purposes, and not precisely for transactions.

In MyISAM you do not have START TRANSACTION;. In this engine, use SET AUTOCOMMIT = 0; for transactions. Commit with COMMIT; or SET AUTOCOMMIT = 1; (Difference explained in MyISAM example commentary below). You can do transactions this way in InnoDB too.

Source: http://dev.mysql.com/doc/refman/5.6/en/glossary.html#glos_autocommit

Examples of general use transactions:

/* InnoDB */
START TRANSACTION;

INSERT INTO table_name (table_field) VALUES ('foo');
INSERT INTO table_name (table_field) VALUES ('bar');

COMMIT; /* SET AUTOCOMMIT = 1 might not set AUTOCOMMIT to its previous state */

/* MyISAM */
SET AUTOCOMMIT = 0;

INSERT INTO table_name (table_field) VALUES ('foo');
INSERT INTO table_name (table_field) VALUES ('bar');

SET AUTOCOMMIT = 1; /* COMMIT statement instead would not restore AUTOCOMMIT to 1 */

Loop Through Each HTML Table Column and Get the Data using jQuery

try this

    $("#mprDetailDataTable tr:gt(0)").each(function () {
        var this_row = $(this);
        var productId = $.trim(this_row.find('td:eq(0)').html());//td:eq(0) means first td of this row
        var product = $.trim(this_row.find('td:eq(1)').html())
        var Quantity = $.trim(this_row.find('td:eq(2)').html())
    });

Increment counter with loop

The varStatus references to LoopTagStatus which has a getIndex() method.

So:

<c:forEach var="tableEntity" items='${requestScope.tables}' varStatus="outer">
   <c:forEach var="rowEntity" items='${tableEntity.rows}' varStatus="inner">            
        <c:out value="${(outer.index * fn:length(tableEntity.rows)) + inner.index}" />
    </c:forEach>
</c:forEach>

See also: