Programs & Examples On #Bcdedit

BCDEdit is a command-line tool for managing BCD stores. It can be used for a variety of purposes, including creating new stores, modifying existing stores, adding boot menu options, and so on.

How to set adaptive learning rate for GradientDescentOptimizer?

Gradient descent algorithm uses the constant learning rate which you can provide in during the initialization. You can pass various learning rates in a way showed by Mrry.

But instead of it you can also use more advanced optimizers which have faster convergence rate and adapts to the situation.

Here is a brief explanation based on my understanding:

  • momentum helps SGD to navigate along the relevant directions and softens the oscillations in the irrelevant. It simply adds a fraction of the direction of the previous step to a current step. This achieves amplification of speed in the correct dirrection and softens oscillation in wrong directions. This fraction is usually in the (0, 1) range. It also makes sense to use adaptive momentum. In the beginning of learning a big momentum will only hinder your progress, so it makse sense to use something like 0.01 and once all the high gradients disappeared you can use a bigger momentom. There is one problem with momentum: when we are very close to the goal, our momentum in most of the cases is very high and it does not know that it should slow down. This can cause it to miss or oscillate around the minima
  • nesterov accelerated gradient overcomes this problem by starting to slow down early. In momentum we first compute gradient and then make a jump in that direction amplified by whatever momentum we had previously. NAG does the same thing but in another order: at first we make a big jump based on our stored information, and then we calculate the gradient and make a small correction. This seemingly irrelevant change gives significant practical speedups.
  • AdaGrad or adaptive gradient allows the learning rate to adapt based on parameters. It performs larger updates for infrequent parameters and smaller updates for frequent one. Because of this it is well suited for sparse data (NLP or image recognition). Another advantage is that it basically illiminates the need to tune the learning rate. Each parameter has its own learning rate and due to the peculiarities of the algorithm the learning rate is monotonically decreasing. This causes the biggest problem: at some point of time the learning rate is so small that the system stops learning
  • AdaDelta resolves the problem of monotonically decreasing learning rate in AdaGrad. In AdaGrad the learning rate was calculated approximately as one divided by the sum of square roots. At each stage you add another square root to the sum, which causes denominator to constantly decrease. In AdaDelta instead of summing all past square roots it uses sliding window which allows the sum to decrease. RMSprop is very similar to AdaDelta
  • Adam or adaptive momentum is an algorithm similar to AdaDelta. But in addition to storing learning rates for each of the parameters it also stores momentum changes for each of them separately

    A few visualizations: enter image description here enter image description here

Get pixel color from canvas, on mousemove

@Wayne Burkett's answer is good. If you wanted to also extract the alpha value to get an rgba color, we could do this:

var r = p[0], g = p[1], b = p[2], a = p[3] / 255;
var rgba = "rgb(" + r + "," + g + "," + b + "," + a + ")";

I divided the alpha value by 255 because the ImageData object stores it as an integer between 0 - 255, but most applications (for example, CanvasRenderingContext2D.fillRect()) require colors to be in valid CSS format, where the alpha value is between 0 and 1.

(Also remember that if you extract a transparent color and then draw it back onto the canvas, it will overlay whatever color is there previously. So if you drew the color rgba(0,0,0,0.1) over the same spot 10 times, it would be black.)

What is the HTML tabindex attribute?

In Simple words, tabindex is used to focus on elements. Syntax: tabindex="numeric_value" This numeric_value is the weight of element. Lower value will be accessed first.

Error "initializer element is not constant" when trying to initialize variable with const

This is a bit old, but I ran into a similar issue. You can do this if you use a pointer:

#include <stdio.h>
typedef struct foo_t  {
    int a; int b; int c;
} foo_t;
static const foo_t s_FooInit = { .a=1, .b=2, .c=3 };
// or a pointer
static const foo_t *const s_pFooInit = (&(const foo_t){ .a=2, .b=4, .c=6 });
int main (int argc, char **argv) {
    const foo_t *const f1 = &s_FooInit;
    const foo_t *const f2 = s_pFooInit;
    printf("Foo1 = %d, %d, %d\n", f1->a, f1->b, f1->c);
    printf("Foo2 = %d, %d, %d\n", f2->a, f2->b, f2->c);
    return 0;
}

DateTime.TryParse issue with dates of yyyy-dd-MM format

From DateTime on msdn:

Type: System.DateTime% When this method returns, contains the DateTime value equivalent to the date and time contained in s, if the conversion succeeded, or MinValue if the conversion failed. The conversion fails if the s parameter is null, is an empty string (""), or does not contain a valid string representation of a date and time. This parameter is passed uninitialized.

Use parseexact with the format string "yyyy-dd-MM hh:mm tt" instead.

Binding ng-model inside ng-repeat loop in AngularJS

<h4>Order List</h4>
<ul>
    <li ng-repeat="val in filter_option.order">
        <span>
            <input title="{{filter_option.order_name[$index]}}" type="radio" ng-model="filter_param.order_option" ng-value="'{{val}}'" />
            &nbsp;{{filter_option.order_name[$index]}}
        </span>
        <select title="" ng-model="filter_param[val]">
            <option value="asc">Asc</option>
            <option value="desc">Desc</option>
        </select>
    </li>
</ul>

libc++abi.dylib: terminating with uncaught exception of type NSException (lldb)

I had this same error when I had a typo for one of the views while building constraints using the visual formatter. I hope that helps someone... or me again one day.

Use of Java's Collections.singletonList()?

singletonList can hold instance of any object. Object state can be modify.

List<Character> list = new ArrayList<Character>();
list.add('X');
list.add('Y');
System.out.println("Initial list: "+ list);
List<List<Character>> list2 = Collections.singletonList(list);
list.add('Z');
System.out.println(list);
System.out.println(list2);

We can not define unmodifiableList like above.

#ifdef in C#

#if DEBUG
bool bypassCheck=TRUE_OR_FALSE;//i will decide depending on what i am debugging
#else
bool bypassCheck = false; //NEVER bypass it
#endif

Make sure you have the checkbox to define DEBUG checked in your build properties.

What does functools.wraps do?

In short, functools.wraps is just a regular function. Let's consider this official example. With the help of the source code, we can see more details about the implementation and the running steps as follows:

  1. wraps(f) returns an object, say O1. It is an object of the class Partial
  2. The next step is @O1... which is the decorator notation in python. It means

wrapper=O1.__call__(wrapper)

Checking the implementation of __call__, we see that after this step, (the left hand side )wrapper becomes the object resulted by self.func(*self.args, *args, **newkeywords) Checking the creation of O1 in __new__, we know self.func is the function update_wrapper. It uses the parameter *args, the right hand side wrapper, as its 1st parameter. Checking the last step of update_wrapper, one can see the right hand side wrapper is returned, with some of attributes modified as needed.

cartesian product in pandas

You could start by taking the Cartesian product of df1.col1 and df2.col3, then merge back to df1 to get col2.

Here's a general Cartesian product function which takes a dictionary of lists:

def cartesian_product(d):
    index = pd.MultiIndex.from_product(d.values(), names=d.keys())
    return pd.DataFrame(index=index).reset_index()

Apply as:

res = cartesian_product({'col1': df1.col1, 'col3': df2.col3})
pd.merge(res, df1, on='col1')
#  col1 col3 col2
# 0   1    5    3
# 1   1    6    3
# 2   2    5    4
# 3   2    6    4

Best way to unselect a <select> in jQuery?

Simplest Method

$('select').val('')

I simply used this on the select itself and it did the trick.

I'm on jQuery 1.7.1.

Html/PHP - Form - Input as array

HTML: Use names as

<input name="levels[level][]">
<input name="levels[build_time][]">

PHP:

$array = filter_input_array(INPUT_POST);
$newArray = array();
foreach (array_keys($array) as $fieldKey) {
    foreach ($array[$fieldKey] as $key=>$value) {
        $newArray[$key][$fieldKey] = $value;
    }
}  

$newArray will hold data as you want

Array ( 
  [0] => Array ( [level] => 1 [build_time] => 123 ) 
  [1] => Array ( [level] => 2 [build_time] => 456 )
)

Express.js - app.listen vs server.listen

The second form (creating an HTTP server yourself, instead of having Express create one for you) is useful if you want to reuse the HTTP server, for example to run socket.io within the same HTTP server instance:

var express = require('express');
var app     = express();
var server  = require('http').createServer(app);
var io      = require('socket.io').listen(server);
...
server.listen(1234);

However, app.listen() also returns the HTTP server instance, so with a bit of rewriting you can achieve something similar without creating an HTTP server yourself:

var express   = require('express');
var app       = express();

// app.use/routes/etc...

var server    = app.listen(3033);
var io        = require('socket.io').listen(server);

io.sockets.on('connection', function (socket) {
  ...
});

Moving uncommitted changes to a new branch

Just create a new branch:

git checkout -b newBranch

And if you do git status you'll see that the state of the code hasn't changed and you can commit it to the new branch.

Flatten an irregular list of lists

Iterative solution with Python 3

This solution may work with all objects except str and bytes.

from collections import Iterable
from collections import Iterator


def flat_iter(obj):
    stack = [obj]
    while stack:
        element = stack.pop()
        if element and isinstance(element, Iterator):
            stack.append(element)
            try:
                stack.append(next(element))
            except StopIteration:
                stack.pop()
        elif isinstance(element, Iterable) and not isinstance(element, (str, bytes)):
            stack.append(iter(element))
        else:
            yield element


tree_list = [[(1,2,3),(4,5,6, (7,8, 'next element is 5')), (5,6), [[[3,4,5],'foo1'],'foo2'],'foo3']]

not_iterable = 10

it1 = flat_iter(tree_list)
it2 = flat_iter(not_iterable)

print(list(it1))
print(list(it2))

[1, 2, 3, 4, 5, 6, 7, 8, 'next element is 5', 5, 6, 3, 4, 5, 'foo1', 'foo2', 'foo3']

[10]

How to list imported modules?

Find the intersection of sys.modules with globals:

import sys
modulenames = set(sys.modules) & set(globals())
allmodules = [sys.modules[name] for name in modulenames]

ASP.NET MVC Razor render without encoding

As well as the already mentioned @Html.Raw(string) approach, if you output an MvcHtmlString it will not be encoded. This can be useful when adding your own extensions to the HtmlHelper, or when returning a value from your view model that you know may contain html.

For example, if your view model was:

public class SampleViewModel
{
  public string SampleString { get; set; }
  public MvcHtmlString SampleHtmlString { get; set; }
}

For Core 1.0+ (and MVC 5+) use HtmlString

public class SampleViewModel
{
  public string SampleString { get; set; }
  public HtmlString SampleHtmlString { get; set; }
}

then

<!-- this will be encoded -->
<div>@Model.SampleString</div>
<!-- this will not be encoded -->
<div>@Html.Raw(Model.SampleString)</div>
<!-- this will not be encoded either -->
<div>@Model.SampleHtmlString</div>

What is the purpose of shuffling and sorting phase in the reducer in Map Reduce Programming?

Well, In Mapreduce there are two important phrases called Mapper and reducer both are too important, but Reducer is mandatory. In some programs reducers are optional. Now come to your question. Shuffling and sorting are two important operations in Mapreduce. First Hadoop framework takes structured/unstructured data and separate the data into Key, Value.

Now Mapper program separate and arrange the data into keys and values to be processed. Generate Key 2 and value 2 values. This values should process and re arrange in proper order to get desired solution. Now this shuffle and sorting done in your local system (Framework take care it) and process in local system after process framework cleanup the data in local system. Ok

Here we use combiner and partition also to optimize this shuffle and sort process. After proper arrangement, those key values passes to Reducer to get desired Client's output. Finally Reducer get desired output.

K1, V1 -> K2, V2 (we will write program Mapper), -> K2, V' (here shuffle and soft the data) -> K3, V3 Generate the output. K4,V4.

Please note all these steps are logical operation only, not change the original data.

Your question: What is the purpose of shuffling and sorting phase in the reducer in Map Reduce Programming?

Short answer: To process the data to get desired output. Shuffling is aggregate the data, reduce is get expected output.

How to update std::map after using the find method?

std::map::find returns an iterator to the found element (or to the end() if the element was not found). So long as the map is not const, you can modify the element pointed to by the iterator:

std::map<char, int> m;
m.insert(std::make_pair('c', 0));  // c is for cookie

std::map<char, int>::iterator it = m.find('c'); 
if (it != m.end())
    it->second = 42;

C# error: Use of unassigned local variable

The compiler only knows that the code is or isn't reachable if you use "return". Think of Environment.Exit() as a function that you call, and the compiler don't know that it will close the application.

Laravel form html with PUT method for PUT routes

<form action="{{url('/url_part_in_route').'/'.$parameter_of_update_function_of_resource_controller}}"  method="post">
@csrf
<input type="hidden" name="_method" value="PUT">    //   or @method('put')          
....    //  remained instructions                                                                              
<form>

How do I fix twitter-bootstrap on IE?

If you are within the intranet and the settings are set to compatibility mode, then proper doctypes and respond.js is not enough.

Please refer to this link for more info: Force IE8 or IE9 document mode to standards and see Ralph Bacon's answer.

It would be same as this:

<!DOCTYPE html>
<meta http-equiv="X-UA-Compatible" content="IE=edge">

How can I split a delimited string into an array in PHP?

Code:

$string = "9,[email protected],8";

$array  = explode(",", $string);

print_r($array);

$no = 1;
foreach ($array as $line) {
    echo $no . ". " . $line . PHP_EOL;
    $no++;
};

Online:

_x000D_
_x000D_
body, html, iframe { _x000D_
  width: 100% ;_x000D_
  height: 100% ;_x000D_
  overflow: hidden ;_x000D_
}
_x000D_
<iframe src="https://ideone.com/pGEAlb" ></iframe>
_x000D_
_x000D_
_x000D_

The ternary (conditional) operator in C

like dwn said, Performance was one of its benefits during the rise of complex processors, MSDN blog Non-classical processor behavior: How doing something can be faster than not doing it gives an example which clearly says the difference between ternary (conditional) operator and if/else statement.

give the following code:

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

int array[10000];

int countthem(int boundary)
{
 int count = 0;
 for (int i = 0; i < 10000; i++) {
  if (array[i] < boundary) count++;
 }
 return count;
}

int __cdecl wmain(int, wchar_t **)
{
 for (int i = 0; i < 10000; i++) array[i] = rand() % 10;

 for (int boundary = 0; boundary <= 10; boundary++) {
  LARGE_INTEGER liStart, liEnd;
  QueryPerformanceCounter(&liStart);

  int count = 0;
  for (int iterations = 0; iterations < 100; iterations++) {
   count += countthem(boundary);
  }

  QueryPerformanceCounter(&liEnd);
  printf("count=%7d, time = %I64d\n",
         count, liEnd.QuadPart - liStart.QuadPart);
 }
 return 0;
}

the cost for different boundary are much different and wierd (see the original material). while if change:

 if (array[i] < boundary) count++;

to

 count += (array[i] < boundary) ? 1 : 0;

The execution time is now independent of the boundary value, since:

the optimizer was able to remove the branch from the ternary expression.

but on my desktop intel i5 cpu/windows 10/vs2015, my test result is quite different with msdn blog.

when using debug mode, if/else cost:

count=      0, time = 6434
count= 100000, time = 7652
count= 200800, time = 10124
count= 300200, time = 12820
count= 403100, time = 15566
count= 497400, time = 16911
count= 602900, time = 15999
count= 700700, time = 12997
count= 797500, time = 11465
count= 902500, time = 7619
count=1000000, time = 6429

and ternary operator cost:

count=      0, time = 7045
count= 100000, time = 10194
count= 200800, time = 12080
count= 300200, time = 15007
count= 403100, time = 18519
count= 497400, time = 20957
count= 602900, time = 17851
count= 700700, time = 14593
count= 797500, time = 12390
count= 902500, time = 9283
count=1000000, time = 7020 

when using release mode, if/else cost:

count=      0, time = 7
count= 100000, time = 9
count= 200800, time = 9
count= 300200, time = 9
count= 403100, time = 9
count= 497400, time = 8
count= 602900, time = 7
count= 700700, time = 7
count= 797500, time = 10
count= 902500, time = 7
count=1000000, time = 7

and ternary operator cost:

count=      0, time = 16
count= 100000, time = 17
count= 200800, time = 18
count= 300200, time = 16
count= 403100, time = 22
count= 497400, time = 16
count= 602900, time = 16
count= 700700, time = 15
count= 797500, time = 15
count= 902500, time = 16
count=1000000, time = 16

the ternary operator is slower than if/else statement on my machine!

so according to different compiler optimization techniques, ternal operator and if/else may behaves much different.

using batch echo with special characters

You can escape shell metacharacters with ^:

echo ^<?xml version="1.0" encoding="utf-8" ?^> > myfile.xml

Note that since echo is a shell built-in it doesn't follow the usual conventions regarding quoting, so just quoting the argument will output the quotes instead of removing them.

char initial value in Java

Typically for local variables I initialize them as late as I can. It's rare that I need a "dummy" value. However, if you do, you can use any value you like - it won't make any difference, if you're sure you're going to assign a value before reading it.

If you want the char equivalent of 0, it's just Unicode 0, which can be written as

char c = '\0';

That's also the default value for an instance (or static) variable of type char.

jQuery Mobile: document ready vs. page events

jQuery Mobile 1.4 Update:

My original article was intended for old way of page handling, basically everything before jQuery Mobile 1.4. Old way of handling is now deprecated and it will stay active until (including) jQuery Mobile 1.5, so you can still use everything mentioned below, at least until next year and jQuery Mobile 1.6.

Old events, including pageinit don't exist any more, they are replaced with pagecontainer widget. Pageinit is erased completely and you can use pagecreate instead, that event stayed the same and its not going to be changed.

If you are interested in new way of page event handling take a look here, in any other case feel free to continue with this article. You should read this answer even if you are using jQuery Mobile 1.4 +, it goes beyond page events so you will probably find a lot of useful information.

Older content:

This article can also be found as a part of my blog HERE.

$(document).on('pageinit') vs $(document).ready()

The first thing you learn in jQuery is to call code inside the $(document).ready() function so everything will execute as soon as the DOM is loaded. However, in jQuery Mobile, Ajax is used to load the contents of each page into the DOM as you navigate. Because of this $(document).ready() will trigger before your first page is loaded and every code intended for page manipulation will be executed after a page refresh. This can be a very subtle bug. On some systems it may appear that it works fine, but on others it may cause erratic, difficult to repeat weirdness to occur.

Classic jQuery syntax:

$(document).ready(function() {

});

To solve this problem (and trust me this is a problem) jQuery Mobile developers created page events. In a nutshell page events are events triggered in a particular point of page execution. One of those page events is a pageinit event and we can use it like this:

$(document).on('pageinit', function() {

});

We can go even further and use a page id instead of document selector. Let's say we have jQuery Mobile page with an id index:

<div data-role="page" id="index">
    <div data-theme="a" data-role="header">
        <h3>
            First Page
        </h3>
        <a href="#second" class="ui-btn-right">Next</a>
    </div>

    <div data-role="content">
        <a href="#" data-role="button" id="test-button">Test button</a>
    </div>

    <div data-theme="a" data-role="footer" data-position="fixed">

    </div>
</div>

To execute code that will only available to the index page we could use this syntax:

$('#index').on('pageinit', function() {

});

Pageinit event will be executed every time page is about be be loaded and shown for the first time. It will not trigger again unless page is manually refreshed or Ajax page loading is turned off. In case you want code to execute every time you visit a page it is better to use pagebeforeshow event.

Here's a working example: http://jsfiddle.net/Gajotres/Q3Usv/ to demonstrate this problem.

Few more notes on this question. No matter if you are using 1 html multiple pages or multiple HTML files paradigm it is advised to separate all of your custom JavaScript page handling into a single separate JavaScript file. This will note make your code any better but you will have much better code overview, especially while creating a jQuery Mobile application.

There's also another special jQuery Mobile event and it is called mobileinit. When jQuery Mobile starts, it triggers a mobileinit event on the document object. To override default settings, bind them to mobileinit. One of a good examples of mobileinit usage is turning off Ajax page loading, or changing default Ajax loader behavior.

$(document).on("mobileinit", function(){
  //apply overrides here
});

Page events transition order

First all events can be found here: http://api.jquerymobile.com/category/events/

Lets say we have a page A and a page B, this is a unload/load order:

  1. page B - event pagebeforecreate

  2. page B - event pagecreate

  3. page B - event pageinit

  4. page A - event pagebeforehide

  5. page A - event pageremove

  6. page A - event pagehide

  7. page B - event pagebeforeshow

  8. page B - event pageshow

For better page events understanding read this:

  • pagebeforeload, pageload and pageloadfailed are fired when an external page is loaded
  • pagebeforechange, pagechange and pagechangefailed are page change events. These events are fired when a user is navigating between pages in the applications.
  • pagebeforeshow, pagebeforehide, pageshow and pagehide are page transition events. These events are fired before, during and after a transition and are named.
  • pagebeforecreate, pagecreate and pageinit are for page initialization.
  • pageremove can be fired and then handled when a page is removed from the DOM

Page loading jsFiddle example: http://jsfiddle.net/Gajotres/QGnft/

If AJAX is not enabled, some events may not fire.

Prevent page transition

If for some reason page transition needs to be prevented on some condition it can be done with this code:

$(document).on('pagebeforechange', function(e, data){
    var to = data.toPage,
        from = data.options.fromPage;

    if (typeof to  === 'string') {
        var u = $.mobile.path.parseUrl(to);
        to = u.hash || '#' + u.pathname.substring(1);
        if (from) from = '#' + from.attr('id');

        if (from === '#index' && to === '#second') {
            alert('Can not transition from #index to #second!');
            e.preventDefault();
            e.stopPropagation();

            // remove active status on a button, if transition was triggered with a button
            $.mobile.activePage.find('.ui-btn-active').removeClass('ui-btn-active ui-focus ui-btn');;
        }
    }
});

This example will work in any case because it will trigger at a begging of every page transition and what is most important it will prevent page change before page transition can occur.

Here's a working example:

Prevent multiple event binding/triggering

jQuery Mobile works in a different way than classic web applications. Depending on how you managed to bind your events each time you visit some page it will bind events over and over. This is not an error, it is simply how jQuery Mobile handles its pages. For example, take a look at this code snippet:

$(document).on('pagebeforeshow','#index' ,function(e,data){
    $(document).on('click', '#test-button',function(e) {
        alert('Button click');
    });
});

Working jsFiddle example: http://jsfiddle.net/Gajotres/CCfL4/

Each time you visit page #index click event will is going to be bound to button #test-button. Test it by moving from page 1 to page 2 and back several times. There are few ways to prevent this problem:

Solution 1

Best solution would be to use pageinit to bind events. If you take a look at an official documentation you will find out that pageinit will trigger ONLY once, just like document ready, so there's no way events will be bound again. This is best solution because you don't have processing overhead like when removing events with off method.

Working jsFiddle example: http://jsfiddle.net/Gajotres/AAFH8/

This working solution is made on a basis of a previous problematic example.

Solution 2

Remove event before you bind it:

$(document).on('pagebeforeshow', '#index', function(){
    $(document).off('click', '#test-button').on('click', '#test-button',function(e) {
        alert('Button click');
    });
});

Working jsFiddle example: http://jsfiddle.net/Gajotres/K8YmG/

Solution 3

Use a jQuery Filter selector, like this:

$('#carousel div:Event(!click)').each(function(){
    //If click is not bind to #carousel div do something
});

Because event filter is not a part of official jQuery framework it can be found here: http://www.codenothing.com/archives/2009/event-filter/

In a nutshell, if speed is your main concern then Solution 2 is much better than Solution 1.

Solution 4

A new one, probably an easiest of them all.

$(document).on('pagebeforeshow', '#index', function(){
    $(document).on('click', '#test-button',function(e) {
        if(e.handled !== true) // This will prevent event triggering more than once
        {
            alert('Clicked');
            e.handled = true;
        }
    });
});

Working jsFiddle example: http://jsfiddle.net/Gajotres/Yerv9/

Tnx to the sholsinger for this solution: http://sholsinger.com/archive/2011/08/prevent-jquery-live-handlers-from-firing-multiple-times/

pageChange event quirks - triggering twice

Sometimes pagechange event can trigger twice and it does not have anything to do with the problem mentioned before.

The reason the pagebeforechange event occurs twice is due to the recursive call in changePage when toPage is not a jQuery enhanced DOM object. This recursion is dangerous, as the developer is allowed to change the toPage within the event. If the developer consistently sets toPage to a string, within the pagebeforechange event handler, regardless of whether or not it was an object an infinite recursive loop will result. The pageload event passes the new page as the page property of the data object (This should be added to the documentation, it's not listed currently). The pageload event could therefore be used to access the loaded page.

In few words this is happening because you are sending additional parameters through pageChange.

Example:

<a data-role="button" data-icon="arrow-r" data-iconpos="right" href="#care-plan-view?id=9e273f31-2672-47fd-9baa-6c35f093a800&amp;name=Sat"><h3>Sat</h3></a>

To fix this problem use any page event listed in Page events transition order.

Page Change Times

As mentioned, when you change from one jQuery Mobile page to another, typically either through clicking on a link to another jQuery Mobile page that already exists in the DOM, or by manually calling $.mobile.changePage, several events and subsequent actions occur. At a high level the following actions occur:

  • A page change process is begun
  • A new page is loaded
  • The content for that page is “enhanced” (styled)
  • A transition (slide/pop/etc) from the existing page to the new page occurs

This is a average page transition benchmark:

Page load and processing: 3 ms

Page enhance: 45 ms

Transition: 604 ms

Total time: 670 ms

*These values are in milliseconds.

So as you can see a transition event is eating almost 90% of execution time.

Data/Parameters manipulation between page transitions

It is possible to send a parameter/s from one page to another during page transition. It can be done in few ways.

Reference: https://stackoverflow.com/a/13932240/1848600

Solution 1:

You can pass values with changePage:

$.mobile.changePage('page2.html', { dataUrl : "page2.html?paremeter=123", data : { 'paremeter' : '123' }, reloadPage : true, changeHash : true });

And read them like this:

$(document).on('pagebeforeshow', "#index", function (event, data) {
    var parameters = $(this).data("url").split("?")[1];;
    parameter = parameters.replace("parameter=","");
    alert(parameter);
});

Example:

index.html

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
  <html>_x000D_
    <head>_x000D_
    <meta charset="utf-8" />_x000D_
    <meta name="viewport" content="widdiv=device-widdiv, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />_x000D_
    <meta name="apple-mobile-web-app-capable" content="yes" />_x000D_
    <meta name="apple-mobile-web-app-status-bar-style" content="black" />_x000D_
    <title>_x000D_
    </title>_x000D_
    <link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />_x000D_
    <script src="http://www.dragan-gaic.info/js/jquery-1.8.2.min.js">_x000D_
    </script>_x000D_
    <script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>_x000D_
    <script>_x000D_
        $(document).on('pagebeforeshow', "#index",function () {_x000D_
            $(document).on('click', "#changePage",function () {_x000D_
                $.mobile.changePage('second.html', { dataUrl : "second.html?paremeter=123", data : { 'paremeter' : '123' }, reloadPage : false, changeHash : true });_x000D_
            });_x000D_
        });_x000D_
_x000D_
        $(document).on('pagebeforeshow', "#second",function () {_x000D_
            var parameters = $(this).data("url").split("?")[1];;_x000D_
            parameter = parameters.replace("parameter=","");_x000D_
            alert(parameter);_x000D_
        });_x000D_
    </script>_x000D_
   </head>_x000D_
   <body>_x000D_
    <!-- Home -->_x000D_
    <div data-role="page" id="index">_x000D_
        <div data-role="header">_x000D_
            <h3>_x000D_
                First Page_x000D_
            </h3>_x000D_
        </div>_x000D_
        <div data-role="content">_x000D_
          <a data-role="button" id="changePage">Test</a>_x000D_
        </div> <!--content-->_x000D_
    </div><!--page-->_x000D_
_x000D_
  </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

second.html

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
  <html>_x000D_
    <head>_x000D_
    <meta charset="utf-8" />_x000D_
    <meta name="viewport" content="widdiv=device-widdiv, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />_x000D_
    <meta name="apple-mobile-web-app-capable" content="yes" />_x000D_
    <meta name="apple-mobile-web-app-status-bar-style" content="black" />_x000D_
    <title>_x000D_
    </title>_x000D_
    <link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />_x000D_
    <script src="http://www.dragan-gaic.info/js/jquery-1.8.2.min.js">_x000D_
    </script>_x000D_
    <script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>_x000D_
   </head>_x000D_
   <body>_x000D_
    <!-- Home -->_x000D_
    <div data-role="page" id="second">_x000D_
        <div data-role="header">_x000D_
            <h3>_x000D_
                Second Page_x000D_
            </h3>_x000D_
        </div>_x000D_
        <div data-role="content">_x000D_
_x000D_
        </div> <!--content-->_x000D_
    </div><!--page-->_x000D_
_x000D_
  </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Solution 2:

Or you can create a persistent JavaScript object for a storage purpose. As long Ajax is used for page loading (and page is not reloaded in any way) that object will stay active.

var storeObject = {
    firstname : '',
    lastname : ''
}

Example: http://jsfiddle.net/Gajotres/9KKbx/

Solution 3:

You can also access data from the previous page like this:

$(document).on('pagebeforeshow', '#index',function (e, data) {
    alert(data.prevPage.attr('id'));
});

prevPage object holds a complete previous page.

Solution 4:

As a last solution we have a nifty HTML implementation of localStorage. It only works with HTML5 browsers (including Android and iOS browsers) but all stored data is persistent through page refresh.

if(typeof(Storage)!=="undefined") {
    localStorage.firstname="Dragan";
    localStorage.lastname="Gaic";
}

Example: http://jsfiddle.net/Gajotres/J9NTr/

Probably best solution but it will fail in some versions of iOS 5.X. It is a well know error.

Don’t Use .live() / .bind() / .delegate()

I forgot to mention (and tnx andleer for reminding me) use on/off for event binding/unbinding, live/die and bind/unbind are deprecated.

The .live() method of jQuery was seen as a godsend when it was introduced to the API in version 1.3. In a typical jQuery app there can be a lot of DOM manipulation and it can become very tedious to hook and unhook as elements come and go. The .live() method made it possible to hook an event for the life of the app based on its selector. Great right? Wrong, the .live() method is extremely slow. The .live() method actually hooks its events to the document object, which means that the event must bubble up from the element that generated the event until it reaches the document. This can be amazingly time consuming.

It is now deprecated. The folks on the jQuery team no longer recommend its use and neither do I. Even though it can be tedious to hook and unhook events, your code will be much faster without the .live() method than with it.

Instead of .live() you should use .on(). .on() is about 2-3x faster than .live(). Take a look at this event binding benchmark: http://jsperf.com/jquery-live-vs-delegate-vs-on/34, everything will be clear from there.

Benchmarking:

There's an excellent script made for jQuery Mobile page events benchmarking. It can be found here: https://github.com/jquery/jquery-mobile/blob/master/tools/page-change-time.js. But before you do anything with it I advise you to remove its alert notification system (each “change page” is going to show you this data by halting the app) and change it to console.log function.

Basically this script will log all your page events and if you read this article carefully (page events descriptions) you will know how much time jQm spent of page enhancements, page transitions ....

Final notes

Always, and I mean always read official jQuery Mobile documentation. It will usually provide you with needed information, and unlike some other documentation this one is rather good, with enough explanations and code examples.

Changes:

  • 30.01.2013 - Added a new method of multiple event triggering prevention
  • 31.01.2013 - Added a better clarification for chapter Data/Parameters manipulation between page transitions
  • 03.02.2013 - Added new content/examples to the chapter Data/Parameters manipulation between page transitions
  • 22.05.2013 - Added a solution for page transition/change prevention and added links to the official page events API documentation
  • 18.05.2013 - Added another solution against multiple event binding

Rails where condition using NOT NIL

It's not a bug in ARel, it's a bug in your logic.

What you want here is:

Foo.includes(:bar).where(Bar.arel_table[:id].not_eq(nil))

Configure cron job to run every 15 minutes on Jenkins

It should be,

*/15 * * * *  your_command_or_whatever

How do you create a REST client for Java?

You could try Rapa. Let us know your feedback about the same. And feel free to log issues or expected features.

make script execution to unlimited

Your script could be stopping, not because of the PHP timeout but because of the timeout in the browser you're using to access the script (ie. Firefox, Chrome, etc). Unfortunately there's seldom an easy way to extend this timeout, and in most browsers you simply can't. An option you have here is to access the script over a terminal. For example, on Windows you would make sure the PHP executable is in your path variable and then I think you execute:

C:\path\to\script> php script.php

Or, if you're using the PHP CGI, I think it's:

C:\path\to\script> php-cgi script.php

Plus, you would also set ini_set('max_execution_time', 0); in your script as others have mentioned. When running a PHP script this way, I'm pretty sure you can use buffer flushing to echo out the script's progress to the terminal periodically if you wish. The biggest issue I think with this method is there's really no way of stopping the script once it's started, other than stopping the entire PHP process or service.

IN vs ANY operator in PostgreSQL

There are two obvious points, as well as the points in the other answer:

  • They are exactly equivalent when using sub queries:

    SELECT * FROM table
    WHERE column IN(subquery);
    
    SELECT * FROM table
    WHERE column = ANY(subquery);
    

On the other hand:

  • Only the IN operator allows a simple list:

    SELECT * FROM table
    WHERE column IN(… , … , …);
    

Presuming they are exactly the same has caught me out several times when forgetting that ANY doesn’t work with lists.

2 ways for "ClearContents" on VBA Excel, but 1 work fine. Why?

That is because you are not fully qualifying your cells object. Try this

With Worksheets("SheetName")
    .Range(.Cells(1, 1), .Cells(10, 2)).ClearContents
End With

Notice the DOT before Cells?

What are the file limits in Git (number and size)?

This message from Linus himself can help you with some other limits

[...] CVS, ie it really ends up being pretty much oriented to a "one file at a time" model.

Which is nice in that you can have a million files, and then only check out a few of them - you'll never even see the impact of the other 999,995 files.

Git fundamentally never really looks at less than the whole repo. Even if you limit things a bit (ie check out just a portion, or have the history go back just a bit), git ends up still always caring about the whole thing, and carrying the knowledge around.

So git scales really badly if you force it to look at everything as one huge repository. I don't think that part is really fixable, although we can probably improve on it.

And yes, then there's the "big file" issues. I really don't know what to do about huge files. We suck at them, I know.

See more in my other answer: the limit with Git is that each repository must represent a "coherent set of files", the "all system" in itself (you can not tag "part of a repository").
If your system is made of autonomous (but inter-dependent) parts, you must use submodules.

As illustrated by Talljoe's answer, the limit can be a system one (large number of files), but if you do understand the nature of Git (about data coherency represented by its SHA-1 keys), you will realize the true "limit" is a usage one: i.e, you should not try to store everything in a Git repository, unless you are prepared to always get or tag everything back. For some large projects, it would make no sense.


For a more in-depth look at git limits, see "git with large files"
(which mentions git-lfs: a solution to store large files outside the git repo. GitHub, April 2015)

The three issues that limits a git repo:

  • huge files (the xdelta for packfile is in memory only, which isn't good with large files)
  • huge number of files, which means, one file per blob, and slow git gc to generate one packfile at a time.
  • huge packfiles, with a packfile index inefficient to retrieve data from the (huge) packfile.

A more recent thread (Feb. 2015) illustrates the limiting factors for a Git repo:

Will a few simultaneous clones from the central server also slow down other concurrent operations for other users?

There are no locks in server when cloning, so in theory cloning does not affect other operations. Cloning can use lots of memory though (and a lot of cpu unless you turn on reachability bitmap feature, which you should).

Will 'git pull' be slow?

If we exclude the server side, the size of your tree is the main factor, but your 25k files should be fine (linux has 48k files).

'git push'?

This one is not affected by how deep your repo's history is, or how wide your tree is, so should be quick..

Ah the number of refs may affect both git-push and git-pull.
I think Stefan knows better than I in this area.

'git commit'? (It is listed as slow in reference 3.) 'git status'? (Slow again in reference 3 though I don't see it.)
(also git-add)

Again, the size of your tree. At your repo's size, I don't think you need to worry about it.

Some operations might not seem to be day-to-day but if they are called frequently by the web front-end to GitLab/Stash/GitHub etc then they can become bottlenecks. (e.g. 'git branch --contains' seems terribly adversely affected by large numbers of branches.)

git-blame could be slow when a file is modified a lot.

How to add minutes to my Date

This is incorrectly specified:

SimpleDateFormat df = new SimpleDateFormat("yyyy-mm-dd HH:mm");

You're using minutes instead of month (MM)

Display the current time and date in an Android application

To display the current date function:

Calendar c = Calendar.getInstance();

SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy");
String date = df.format(c.getTime());
Date.setText(date);

You must want to import

import java.text.SimpleDateFormat; import java.util.Calendar;

You must want to use

TextView Date;
Date = (TextView) findViewById(R.id.Date);

How to remove jar file from local maven repository which was added with install:install-file?

At least on the current maven version you need to add the switch -DreResolve=false if you intend to remove the dependencies from your local repo without re-downloading them.

mvn dependency:purge-local-repository -DreResolve=false

removes the dependencies without downloading them again.

Git commit with no commit message

I have the following config in my private project:

git config alias.auto 'commit -a -m "changes made from [device name]"'

That way, when I'm in a hurry I do

git auto
git push

And at least I know what device the commit was made from.

Re-ordering factor levels in data frame

Assuming your dataframe is mydf:

mydf$task <- factor(mydf$task, levels = c("up", "down", "left", "right", "front", "back"))

How to select a schema in postgres when using psql?

In PostgreSQL the system determines which table is meant by following a search path, which is a list of schemas to look in.

The first matching table in the search path is taken to be the one wanted, otherwise, if there is no match a error is raised, even if matching table names exist in other schemas in the database.

To show the current search path you can use the following command:

SHOW search_path;

And to put the new schema in the path, you could use:

SET search_path TO myschema;

Or if you want multiple schemas:

SET search_path TO myschema, public;

Reference: https://www.postgresql.org/docs/current/static/ddl-schemas.html

Where is the php.ini file on a Linux/CentOS PC?

You can find the path to php.ini in the output of phpinfo(). See under "Loaded Configuration File".

enter image description here

Including all the jars in a directory within the Java classpath

For me this works in windows .

java -cp "/lib/*;" sample

For linux

java -cp "/lib/*:" sample

I am using Java 6

How to use jQuery to select a dropdown option?

if your options have a value, you can do this:

$('select').val("the-value-of-the-option-you-want-to-select");

'select' would be the id of your select or a class selector. or if there is just one select, you can use the tag as it is in the example.

Drop all data in a pandas dataframe

My favorite way is:

df = df[0:0] 

How do you connect to multiple MySQL databases on a single webpage?

<?php
    // Sapan Mohanty
    // Skype:sapan.mohannty
    //***********************************
    $oldData = mysql_connect('localhost', 'DBUSER', 'DBPASS');
    echo mysql_error();
    $NewData = mysql_connect('localhost', 'DBUSER', 'DBPASS');
    echo mysql_error();
    mysql_select_db('OLDDBNAME', $oldData );
    mysql_select_db('NEWDBNAME', $NewData );
    $getAllTablesName    = "SELECT table_name FROM information_schema.tables WHERE table_type = 'base table'";
    $getAllTablesNameExe = mysql_query($getAllTablesName);
    //echo mysql_error();
    while ($dataTableName = mysql_fetch_object($getAllTablesNameExe)) {

        $oldDataCount       = mysql_query('select count(*) as noOfRecord from ' . $dataTableName->table_name, $oldData);
        $oldDataCountResult = mysql_fetch_object($oldDataCount);


        $newDataCount       = mysql_query('select count(*) as noOfRecord from ' . $dataTableName->table_name, $NewData);
        $newDataCountResult = mysql_fetch_object($newDataCount);

        if ( $oldDataCountResult->noOfRecord != $newDataCountResult->noOfRecord ) {
            echo "<br/><b>" . $dataTableName->table_name . "</b>";
            echo " | Old: " . $oldDataCountResult->noOfRecord;
            echo " | New: " . $newDataCountResult->noOfRecord;

            if ($oldDataCountResult->noOfRecord < $newDataCountResult->noOfRecord) {
                echo " | <font color='green'>*</font>";

            } else {
                echo " | <font color='red'>*</font>";
            }

            echo "<br/>----------------------------------------";

        }     

    }
    ?>

How do I find a default constraint using INFORMATION_SCHEMA?

I don't think it's in the INFORMATION_SCHEMA - you'll probably have to use sysobjects or related deprecated tables/views.

You would think there would be a type for this in INFORMATION_SCHEMA.TABLE_CONSTRAINTS, but I don't see one.

Differences in boolean operators: & vs && and | vs ||

I know there's a lot of answers here, but they all seem a bit confusing. So after doing some research from the Java oracle study guide, I've come up with three different scenarios of when to use && or &. The three scenarios are logical AND, bitwise AND, and boolean AND.

Logical AND: Logical AND (aka Conditional AND) uses the && operator. It's short-circuited meaning: if the left operand is false, then the right operand will not be evaluated.
Example:

int x = 0;
if (false && (1 == ++x) {
    System.out.println("Inside of if");
}
System.out.println(x); // "0"

In the above example the value printed to the console of x will be 0, because the first operand in the if statement is false, hence java has no need to compute (1 == ++x) therefore x will not be computed.

Bitwise AND: Bitwise AND uses the & operator. It's used to preform a bitwise operation on the value. It's much easier to see what's going on by looking at operation on binary numbers ex:

int a = 5;     //                    5 in binary is 0101
int b = 12;    //                   12 in binary is 1100
int c = a & b; // bitwise & preformed on a and b is 0100 which is 4

As you can see in the example, when the binary representations of the numbers 5 and 12 are lined up, then a bitwise AND preformed will only produce a binary number where the same digit in both numbers have a 1. Hence 0101 & 1100 == 0100. Which in decimal is 5 & 12 == 4.

Boolean AND: Now the boolean AND operator behaves similarly and differently to both the bitwise AND and logical AND. I like to think of it as preforming a bitwise AND between two boolean values (or bits), therefore it uses & operator. The boolean values can be the result of a logical expression too.

It returns either a true or false value, much like the logical AND, but unlike the logical AND it is not short-circuited. The reason being, is that for it to preform that bitwise AND, it must know the value of both left and right operands. Here's an ex:

int x = 0;
if (false & (1 == ++x) {
    System.out.println("Inside of if");
}
System.out.println(x); //"1"

Now when that if statement is ran, the expression (1 == ++x) will be executed, even though the left operand is false. Hence the value printed out for x will be 1 because it got incremented.

This also applies to Logical OR (||), bitwise OR (|), and boolean OR (|) Hope this clears up some confusion.

No connection could be made because the target machine actively refused it 127.0.0.1

There is a firewall blocking the connection or the process that is hosting the service is not listening on that port. Or it is listening on a different port.

TypeError: a bytes-like object is required, not 'str'

This code is probably good for Python 2. But in Python 3, this will cause an issue, something related to bit encoding. I was trying to make a simple TCP server and encountered the same problem. Encoding worked for me. Try this with sendto command.

clientSocket.sendto(message.encode(),(serverName, serverPort))

Similarly you would use .decode() to receive the data on the UDP server side, if you want to print it exactly as it was sent.

Declaring array of objects

const sample = [];
    list.forEach(element => {
      const item = {} as { name: string, description: string };
      item.name= element.name;
      item.description= element.description;
      sample.push(item);
    });
    return sample;

Anyone try this.. and suggest something.

Copy data from one existing row to another existing row in SQL?

Copy a value from one row to any other qualified rows within the same table (or different tables):

UPDATE `your_table` t1, `your_table` t2
SET t1.your_field = t2.your_field
WHERE t1.other_field = some_condition
AND t1.another_field = another_condition
AND t2.source_id = 'explicit_value'

Start off by aliasing the table into 2 unique references so the SQL server can tell them apart

Next, specify the field(s) to copy.

Last, specify the conditions governing the selection of the rows

Depending on the conditions you may copy from a single row to a series, or you may copy a series to a series. You may also specify different tables, and you can even use sub-selects or joins to allow using other tables to control the relationships.

Python TypeError: cannot convert the series to <class 'int'> when trying to do math on dataframe

What if you do this (as was suggested earlier):

new_time = dfs['XYF']['TimeUS'].astype(float)
new_time_F = new_time / 1000000

Python open() gives FileNotFoundError/IOError: Errno 2 No such file or directory

  • Make sure the file exists: use os.listdir() to see the list of files in the current working directory
  • Make sure you're in the directory you think you're in with os.getcwd() (if you launch your code from an IDE, you may well be in a different directory)
  • You can then either:
    • Call os.chdir(dir), dir being the folder where the file is located, then open the file with just its name like you were doing.
    • Specify an absolute path to the file in your open call.
  • Remember to use a raw string if your path uses backslashes, like so: dir = r'C:\Python32'
    • If you don't use raw-string, you have to escape every backslash: 'C:\\User\\Bob\\...'
    • Forward-slashes also work on Windows 'C:/Python32' and do not need to be escaped.

Let me clarify how Python finds files:

  • An absolute path is a path that starts with your computer's root directory, for example 'C:\Python\scripts..' if you're on Windows.
  • A relative path is a path that does not start with your computer's root directory, and is instead relative to something called the working directory. You can view Python's current working directory by calling os.getcwd().

If you try to do open('sortedLists.yaml'), Python will see that you are passing it a relative path, so it will search for the file inside the current working directory. Calling os.chdir will change the current working directory.

Example: Let's say file.txt is found in C:\Folder.

To open it, you can do:

os.chdir(r'C:\Folder')
open('file.txt') #relative path, looks inside the current working directory

or

open(r'C:\Folder\file.txt') #full path

Vendor code 17002 to connect to SQLDeveloper

I had the same Problem. I had start my Oracle TNS Listener, then it works normally again.

See LISTENER: TNS-12545 ... No such file or directory.

Automatically start forever (node) on system restart

This case is valid for Debian.

Add the following to /etc/rc.local

/usr/bin/sudo -u {{user}} /usr/local/bin/forever start {{app path}}

  • {{user}} replaces your username.
  • {{app path}} replaces your app path. For example, /var/www/test/app.js

Make a div into a link

why not? use <a href="bla"> <div></div> </a> works fine in HTML5

Change value in a cell based on value in another cell

by typing yes it wont charge taxes, by typing no it will charge taxes.

=IF(C39="Yes","0",IF(C39="no",PRODUCT(G36*0.0825)))

How to get a variable type in Typescript?

The other answers are right, but when you're dealing with interfaces you cannot use typeof or instanceof because interfaces don't get compiled to javascript.

Instead you can use a typecast + function check typeguard to check your variable:

interface Car {
    drive(): void;
    honkTheHorn(): void;
}

interface Bike {
    drive(): void;
    ringTheBell(): void;
}

function start(vehicle: Bike | Car ) {
    vehicle.drive();

    // typecast and check if the function exists
    if ((<Bike>vehicle).ringTheBell) {
        const bike = (<Bike>vehicle);
        bike.ringTheBell();
    } else {
        const car = (<Car>vehicle);
        car.honkTheHorn();
    }
}

And this is the compiled JavaScript in ES2017:

function start(vehicle) {
    vehicle.drive();
    if (vehicle.ringTheBell) {
        const bike = vehicle;
        bike.ringTheBell();
    }
    else {
        const car = vehicle;
        car.honkTheHorn();
    }
}

Already defined in .obj - no double inclusions

This is not a compiler error: the error is coming from the linker. After compilation, the linker will merge the object files resulting from the compilation of each of your translation units (.cpp files).

The linker finds out that you have the same symbol defined multiple times in different translation units, and complains about it (it is a violation of the One Definition Rule).

The reason is most certainly that main.cpp includes client.cpp, and both these files are individually processed by the compiler to produce two separate object files. Therefore, all the symbols defined in the client.cpp translation unit will be defined also in the main.cpp translation unit. This is one of the reasons why you do not usually #include .cpp files.

Put the definition of your class in a separate client.hpp file which does not contain also the definitions of the member functions of that class; then, let client.cpp and main.cpp include that file (I mean #include). Finally, leave in client.cpp the definitions of your class's member functions.

client.h

#ifndef SOCKET_CLIENT_CLASS
#define SOCKET_CLIENT_CLASS
#ifndef BOOST_ASIO_HPP
#include <boost/asio.hpp>
#endif

class SocketClient // Or whatever the name is...
{

// ...

    bool read(int, char*); // Or whatever the name is...

//  ...
};

#endif

client.cpp

#include "Client.h"

// ...

bool SocketClient::read(int, char*)
{
    // Implementation  goes here...
}

// ... (add the definitions for all other member functions)

main.h

#include <iostream>
#include <string>
#include <sstream>
#include <boost/asio.hpp>
#include <boost/thread/thread.hpp>
#include "client.h"
//              ^^ Notice this!

main.cpp

#include "main.h"

Trying to git pull with error: cannot open .git/FETCH_HEAD: Permission denied

Got that issue when .git folder is hidden and all files in it is hidden too. Make only .git folder hidden without recursive files update and it will work.

How to jQuery clone() and change id?

Update: As Roko C.Bulijan pointed out.. you need to use .insertAfter to insert it after the selected div. Also see updated code if you want it appended to the end instead of beginning when cloned multiple times. DEMO

Code:

   var cloneCount = 1;;
   $("button").click(function(){
      $('#id')
          .clone()
          .attr('id', 'id'+ cloneCount++)
          .insertAfter('[id^=id]:last') 
           //            ^-- Use '#id' if you want to insert the cloned 
           //                element in the beginning
          .text('Cloned ' + (cloneCount-1)); //<--For DEMO
   }); 

Try,

$("#id").clone().attr('id', 'id1').after("#id");

If you want a automatic counter, then see below,

   var cloneCount = 1;
   $("button").click(function(){
      $("#id").clone().attr('id', 'id'+ cloneCount++).insertAfter("#id");
   }); 

No Android SDK found - Android Studio

According to the Android Studio download page, the SDK comes bundled with Android Studio. It has its own copy when you install Android Studio.

ADT is a plugin for Eclipse. Try reading through that webpage to see if there is something that got missed when installing.

Here is the wording from the site, regarding ADT:

Similar to Eclipse with the ADT Plugin, Android Studio provides integrated Android developer tools for development and debugging.

Get the index of the object inside an array, matching a condition

One step using Array.reduce() - no jQuery

var items = [{id: 331}, {id: 220}, {id: 872}];

var searchIndexForId = 220;
var index = items.reduce(function(searchIndex, item, index){
  if(item.id === searchIndexForId) { 
    console.log('found!');
    searchIndex = index;
  }
  return searchIndex;
}, null);

will return null if index was not found.

Inserting a Python datetime.datetime object into MySQL

when iserting into t-sql

this fails:

select CONVERT(datetime,'2019-09-13 09:04:35.823312',21)

this works:

select CONVERT(datetime,'2019-09-13 09:04:35.823',21)

easy way:

regexp = re.compile(r'\.(\d{6})')
def to_splunk_iso(dt):
    """Converts the datetime object to Splunk isoformat string."""
    # 6-digits string.
    microseconds = regexp.search(dt).group(1)
    return regexp.sub('.%d' % round(float(microseconds) / 1000), dt)

exec failed because the name not a valid identifier?

As was in my case if your sql is generated by concatenating or uses converts then sql at execute need to be prefixed with letter N as below

e.g.

Exec N'Select bla..' 

the N defines string literal is unicode.

R for loop skip to next iteration ifelse

for(n in 1:5) {
  if(n==3) next # skip 3rd iteration and go to next iteration
  cat(n)
}

Get file version in PowerShell

Just another way to do it is to use the built-in file access technique:

(get-item .\filename.exe).VersionInfo | FL

You can also get any particular property off the VersionInfo, thus:

(get-item .\filename.exe).VersionInfo.FileVersion

This is quite close to the dir technique.

How to find list of possible words from a letter matrix [Boggle Solver]

Hilarious. I nearly posted the same question a few days ago due to the same damn game! I did not however because just searched google for boggle solver python and got all the answers I could want.

What's the Android ADB shell "dumpsys" tool and what are its benefits?

What's dumpsys and what are its benefit

dumpsys is an android tool that runs on the device and dumps interesting information about the status of system services.

Obvious benefits:

  1. Possibility to easily get system information in a simple string representation.
  2. Possibility to use dumped CPU, RAM, Battery, storage stats for a pretty charts, which will allow you to check how your application affects the overall device!

What information can we retrieve from dumpsys shell command and how we can use it

If you run dumpsys you would see a ton of system information. But you can use only separate parts of this big dump.

to see all of the "subcommands" of dumpsys do:

dumpsys | grep "DUMP OF SERVICE"

Output:

DUMP OF SERVICE SurfaceFlinger:
DUMP OF SERVICE accessibility:
DUMP OF SERVICE account:
DUMP OF SERVICE activity:
DUMP OF SERVICE alarm:
DUMP OF SERVICE appwidget:
DUMP OF SERVICE audio:
DUMP OF SERVICE backup:
DUMP OF SERVICE battery:
DUMP OF SERVICE batteryinfo:
DUMP OF SERVICE clipboard:
DUMP OF SERVICE connectivity:
DUMP OF SERVICE content:
DUMP OF SERVICE cpuinfo:
DUMP OF SERVICE device_policy:
DUMP OF SERVICE devicestoragemonitor:
DUMP OF SERVICE diskstats:
DUMP OF SERVICE dropbox:
DUMP OF SERVICE entropy:
DUMP OF SERVICE hardware:
DUMP OF SERVICE input_method:
DUMP OF SERVICE iphonesubinfo:
DUMP OF SERVICE isms:
DUMP OF SERVICE location:
DUMP OF SERVICE media.audio_flinger:
DUMP OF SERVICE media.audio_policy:
DUMP OF SERVICE media.player:
DUMP OF SERVICE meminfo:
DUMP OF SERVICE mount:
DUMP OF SERVICE netstat:
DUMP OF SERVICE network_management:
DUMP OF SERVICE notification:
DUMP OF SERVICE package:
DUMP OF SERVICE permission:
DUMP OF SERVICE phone:
DUMP OF SERVICE power:
DUMP OF SERVICE reboot:
DUMP OF SERVICE screenshot:
DUMP OF SERVICE search:
DUMP OF SERVICE sensor:
DUMP OF SERVICE simphonebook:
DUMP OF SERVICE statusbar:
DUMP OF SERVICE telephony.registry:
DUMP OF SERVICE throttle:
DUMP OF SERVICE usagestats:
DUMP OF SERVICE vibrator:
DUMP OF SERVICE wallpaper:
DUMP OF SERVICE wifi:
DUMP OF SERVICE window:

Some Dumping examples and output

1) Getting all possible battery statistic:

$~ adb shell dumpsys battery

You will get output:

Current Battery Service state:
AC powered: false
AC capacity: 500000
USB powered: true
status: 5
health: 2
present: true
level: 100
scale: 100
voltage:4201
temperature: 271 <---------- Battery temperature! %)
technology: Li-poly <---------- Battery technology! %)

2)Getting wifi informations

~$ adb shell dumpsys wifi

Output:

Wi-Fi is enabled
Stay-awake conditions: 3

Internal state:
interface tiwlan0 runState=Running
SSID: XXXXXXX BSSID: xx:xx:xx:xx:xx:xx, MAC: xx:xx:xx:xx:xx:xx, Supplicant state: COMPLETED, RSSI: -60, Link speed: 54, Net ID: 2, security: 0, idStr: null
ipaddr 192.168.1.xxx gateway 192.168.x.x netmask 255.255.255.0 dns1 192.168.x.x dns2 8.8.8.8 DHCP server 192.168.x.x lease 604800 seconds
haveIpAddress=true, obtainingIpAddress=false, scanModeActive=false
lastSignalLevel=2, explicitlyDisabled=false

Latest scan results:

Locks acquired: 28 full, 0 scan
Locks released: 28 full, 0 scan

Locks held:

3) Getting CPU info

~$ adb shell dumpsys cpuinfo

Output:

Load: 0.08 / 0.4 / 0.64
CPU usage from 42816ms to 34683ms ago:
system_server: 1% = 1% user + 0% kernel / faults: 16 minor
kdebuglog.sh: 0% = 0% user + 0% kernel / faults: 160 minor
tiwlan_wq: 0% = 0% user + 0% kernel
usb_mass_storag: 0% = 0% user + 0% kernel
pvr_workqueue: 0% = 0% user + 0% kernel
+sleep: 0% = 0% user + 0% kernel
+sleep: 0% = 0% user + 0% kernel
TOTAL: 6% = 1% user + 3% kernel + 0% irq

4)Getting memory usage informations

~$ adb shell dumpsys meminfo 'your apps package name'

Output:

** MEMINFO in pid 5527 [com.sec.android.widgetapp.weatherclock] **
                    native   dalvik    other    total
            size:     2868     5767      N/A     8635
       allocated:     2861     2891      N/A     5752
            free:        6     2876      N/A     2882
           (Pss):      532       80     2479     3091
  (shared dirty):      932     2004     6060     8996
    (priv dirty):      512       36     1872     2420

 Objects
           Views:        0        ViewRoots:        0
     AppContexts:        0       Activities:        0
          Assets:        3    AssetManagers:        3
   Local Binders:        2    Proxy Binders:        8
Death Recipients:        0
 OpenSSL Sockets:        0


 SQL
               heap:        0         MEMORY_USED:        0
 PAGECACHE_OVERFLOW:        0         MALLOC_SIZE:        0

If you want see the info for all processes, use ~$ adb shell dumpsys meminfo

enter image description here

dumpsys is ultimately flexible and useful tool!

If you want to use this tool do not forget to add permission into your android manifest automatically android.permission.DUMP

Try to test all commands to learn more about dumpsys. Happy dumping!

The type or namespace name 'Entity' does not exist in the namespace 'System.Data'

Make sure you have the EntityFramework Nuget package installed for your project.

From @TonyDing's answer:

Right-click on the Solution from the Visual Studio Solution Explorer click the Manage Nuget packages for solution and install the EntityFramework

Once it is installed, I still had the error, but then did a reinstall per @papergodzilla's comment:

Update-Package -reinstall

and it resolved my issue

Do this in the Package Manager Console (View > Other windows > Package Manager Console).
Now everything is good!

How to remove item from array by value?

You can use underscore.js. It really makes things simple.

For example, with this:

var result = _.without(['three','seven','eleven'], 'seven');

And result will be ['three','eleven'].

In your case the code that you will have to write is:

ary = _.without(ary, 'seven')

It reduces the code that you write.

How can I resize an image dynamically with CSS as the browser width/height changes?

Just use this code. What most are forgeting is to specify max-width as the max-width of the image

img {   
    height: auto;
    width: 100%;
    max-width: 300px;
}

Check this demonstration http://shorturl.at/nBKVY

How can I move HEAD back to a previous location? (Detached head) & Undo commits

First reset locally:

git reset 23b6772

To see if you're on the right position, verify with:

git status

You will see something like:

On branch master Your branch is behind 'origin/master' by 17 commits, and can be fast-forwarded.

Then rewrite history on your remote tracking branch to reflect the change:

git push --force-with-lease // a useful command @oktober mentions in comments

Using --force-with-lease instead of --force will raise an error if others have meanwhile committed to the remote branch, in which case you should fetch first. More info in this article.

Java ArrayList replace at specific index

public void setItem(List<Item> dataEntity, Item item) {
    int itemIndex = dataEntity.indexOf(item);
    if (itemIndex != -1) {
        dataEntity.set(itemIndex, item);
    }
}

Why do we have to override the equals() method in Java?

To answer your question, firstly I would strongly recommend looking at the Documentation.

Without overriding the equals() method, it will act like "==". When you use the "==" operator on objects, it simply checks to see if those pointers refer to the same object. Not if their members contain the same value.

We override to keep our code clean, and abstract the comparison logic from the If statement, into the object. This is considered good practice and takes advantage of Java's heavily Object Oriented Approach.

C++ delete vector, objects, free memory

Move semantics allows for a straightforward way to release memory, by simply applying the assignment (=) operator from an empty rvalue:

std::vector<uint32_t> vec(100, 0);
std::cout << vec.capacity(); // 100

vec = vector<uint32_t>();    // Same as "vector<uint32_t>().swap(vec)";    
std::cout << vec.capacity(); // 0

It is as much efficient as the "swap()"-based method described in other answers (indeed, both are conceptually doing the same thing). When it comes to readability, however, the assignment version makes a better job at expressing the programmer's intention while being more concise.

How to update UI from another thread running in another class

First you need to use Dispatcher.Invoke to change the UI from another thread and to do that from another class, you can use events.
Then you can register to that event(s) in the main class and Dispatch the changes to the UI and in the calculation class you throw the event when you want to notify the UI:

class MainWindow : Window
{
    private void startCalc()
    {
        //your code
        CalcClass calc = new CalcClass();
        calc.ProgressUpdate += (s, e) => {
            Dispatcher.Invoke((Action)delegate() { /* update UI */ });
        };
        Thread calcthread = new Thread(new ParameterizedThreadStart(calc.testMethod));
        calcthread.Start(input);
    }
}

class CalcClass
{
    public event EventHandler ProgressUpdate;

    public void testMethod(object input)
    {
        //part 1
        if(ProgressUpdate != null)
            ProgressUpdate(this, new YourEventArgs(status));
        //part 2
    }
}

UPDATE:
As it seems this is still an often visited question and answer I want to update this answer with how I would do it now (with .NET 4.5) - this is a little longer as I will show some different possibilities:

class MainWindow : Window
{
    Task calcTask = null;

    void buttonStartCalc_Clicked(object sender, EventArgs e) { StartCalc(); } // #1
    async void buttonDoCalc_Clicked(object sender, EventArgs e) // #2
    {
        await CalcAsync(); // #2
    }

    void StartCalc()
    {
        var calc = PrepareCalc();
        calcTask = Task.Run(() => calc.TestMethod(input)); // #3
    }
    Task CalcAsync()
    {
        var calc = PrepareCalc();
        return Task.Run(() => calc.TestMethod(input)); // #4
    }
    CalcClass PrepareCalc()
    {
        //your code
        var calc = new CalcClass();
        calc.ProgressUpdate += (s, e) => Dispatcher.Invoke((Action)delegate()
            {
                // update UI
            });
        return calc;
    }
}

class CalcClass
{
    public event EventHandler<EventArgs<YourStatus>> ProgressUpdate; // #5

    public TestMethod(InputValues input)
    {
        //part 1
        ProgressUpdate.Raise(this, status); // #6 - status is of type YourStatus
        //part 2
    }
}

static class EventExtensions
{
    public static void Raise<T>(this EventHandler<EventArgs<T>> theEvent,
                                object sender, T args)
    {
        if (theEvent != null)
            theEvent(sender, new EventArgs<T>(args));
    }
}

@1) How to start the "synchronous" calculations and run them in the background

@2) How to start it "asynchronous" and "await it": Here the calculation is executed and completed before the method returns, but because of the async/await the UI is not blocked (BTW: such event handlers are the only valid usages of async void as the event handler must return void - use async Task in all other cases)

@3) Instead of a new Thread we now use a Task. To later be able to check its (successfull) completion we save it in the global calcTask member. In the background this also starts a new thread and runs the action there, but it is much easier to handle and has some other benefits.

@4) Here we also start the action, but this time we return the task, so the "async event handler" can "await it". We could also create async Task CalcAsync() and then await Task.Run(() => calc.TestMethod(input)).ConfigureAwait(false); (FYI: the ConfigureAwait(false) is to avoid deadlocks, you should read up on this if you use async/await as it would be to much to explain here) which would result in the same workflow, but as the Task.Run is the only "awaitable operation" and is the last one we can simply return the task and save one context switch, which saves some execution time.

@5) Here I now use a "strongly typed generic event" so we can pass and receive our "status object" easily

@6) Here I use the extension defined below, which (aside from ease of use) solve the possible race condition in the old example. There it could have happened that the event got null after the if-check, but before the call if the event handler was removed in another thread at just that moment. This can't happen here, as the extensions gets a "copy" of the event delegate and in the same situation the handler is still registered inside the Raise method.

Is there anyway to exclude artifacts inherited from a parent POM?

You can group your dependencies within a different project with packaging pom as described by Sonatypes Best Practices:

<project>
    <modelVersion>4.0.0</modelVersion>
    <artifactId>base-dependencies</artifactId>
    <groupId>es.uniovi.innova</groupId>
    <version>1.0.0</version>
    <packaging>pom</packaging>
    <dependencies>
        <dependency>
            <groupId>javax.mail</groupId>
            <artifactId>mail</artifactId>
            <version>1.4</version>
        </dependency>
    </dependencies>
</project>

and reference them from your parent-pom (watch the dependency <type>pom</type>):

<project>
    <modelVersion>4.0.0</modelVersion>
    <artifactId>base</artifactId>
    <groupId>es.uniovi.innova</groupId>
    <version>1.0.0</version>
    <packaging>pom</packaging>
    <dependencies>
        <dependency>
            <artifactId>base-dependencies</artifactId>
            <groupId>es.uniovi.innova</groupId>
            <version>1.0.0</version>
            <type>pom</type>
        </dependency>
    </dependencies>
</project>

Your child-project inherits this parent-pom as before. But now, the mail dependency can be excluded in the child-project within the dependencyManagement block:

<project>
    <modelVersion>4.0.0</modelVersion>
    <groupId>test</groupId>
    <artifactId>jruby</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <parent>
        <artifactId>base</artifactId>
        <groupId>es.uniovi.innova</groupId>
        <version>1.0.0</version>
    </parent>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <artifactId>base-dependencies</artifactId>
                <groupId>es.uniovi.innova</groupId>
                <version>1.0.0</version>
                <exclusions>
                    <exclusion>
                        <groupId>javax.mail</groupId>
                        <artifactId>mail</artifactId>
                    </exclusion>
                </exclusions>
            </dependency>
        </dependencies>
    </dependencyManagement>
</project>

Command-line tool for finding out who is locking a file

Handle should do the trick.

Ever wondered which program has a particular file or directory open? Now you can find out. Handle is a utility that displays information about open handles for any process in the system. You can use it to see the programs that have a file open, or to see the object types and names of all the handles of a program.

converting string to long in python

Well, longs can't hold anything but integers.

One option is to use a float: float('234.89')

The other option is to truncate or round. Converting from a float to a long will truncate for you: long(float('234.89'))

>>> long(float('1.1'))
1L
>>> long(float('1.9'))
1L
>>> long(round(float('1.1')))
1L
>>> long(round(float('1.9')))
2L

How can I select rows with most recent timestamp for each key value?

You can join the table with itself (on sensor id), and add left.timestamp < right.timestamp as join condition. Then you pick the rows, where right.id is null. Voila, you got the latest entry per sensor.

http://sqlfiddle.com/#!9/45147/37

SELECT L.* FROM sensorTable L
LEFT JOIN sensorTable R ON
L.sensorID = R.sensorID AND
L.timestamp < R.timestamp
WHERE isnull (R.sensorID)

But please note, that this will be very resource intensive if you have a little amount of ids and many values! So, I wouldn't recommend this for some sort of Measuring-Stuff, where each Sensor collects a value every minute. However in a Use-Case, where you need to track "Revisions" of something that changes just "sometimes", it's easy going.

Validating with an XML schema in Python

The PyXB package at http://pyxb.sourceforge.net/ generates validating bindings for Python from XML schema documents. It handles almost every schema construct and supports multiple namespaces.

JavaFX Application Icon

What do you think about creating new package i.e image.icons in your src directory and moving there you .png images? Than you just need to write:

Image image = new Image("/image/icons/nameOfImage.png");
primaryStage.getIcons().add(image);

This solution works for me perfectly, but still I'm not sure if it's correct (beginner here).

How to remove multiple indexes from a list at the same time?

You need to do this in a loop, there is no built-in operation to remove a number of indexes at once.

Your example is actually a contiguous sequence of indexes, so you can do this:

del my_list[2:6]

which removes the slice starting at 2 and ending just before 6.

It isn't clear from your question whether in general you need to remove an arbitrary collection of indexes, or if it will always be a contiguous sequence.

If you have an arbitrary collection of indexes, then:

indexes = [2, 3, 5]
for index in sorted(indexes, reverse=True):
    del my_list[index]

Note that you need to delete them in reverse order so that you don't throw off the subsequent indexes.

Hibernate Criteria Restrictions AND / OR combination

For the new Criteria since version Hibernate 5.2:

CriteriaBuilder criteriaBuilder = getSession().getCriteriaBuilder();
CriteriaQuery<SomeClass> criteriaQuery = criteriaBuilder.createQuery(SomeClass.class);

Root<SomeClass> root = criteriaQuery.from(SomeClass.class);

Path<Object> expressionA = root.get("A");
Path<Object> expressionB = root.get("B");

Predicate predicateAEqualX = criteriaBuilder.equal(expressionA, "X");
Predicate predicateBInXY = expressionB.in("X",Y);
Predicate predicateLeft = criteriaBuilder.and(predicateAEqualX, predicateBInXY);

Predicate predicateAEqualY = criteriaBuilder.equal(expressionA, Y);
Predicate predicateBEqualZ = criteriaBuilder.equal(expressionB, "Z");
Predicate predicateRight = criteriaBuilder.and(predicateAEqualY, predicateBEqualZ);

Predicate predicateResult = criteriaBuilder.or(predicateLeft, predicateRight);

criteriaQuery
        .select(root)
        .where(predicateResult);

List<SomeClass> list = getSession()
        .createQuery(criteriaQuery)
        .getResultList();  

How to disable right-click context-menu in JavaScript

If your page really relies on the fact that people won't be able to see that menu, you should know that modern browsers (for example Firefox) let the user decide if he really wants to disable it or not. So you have no guarantee at all that the menu would be really disabled.

JavaFX Panel inside Panel auto resizing

If you are using Scene Builder, you will see at the right an accordion panel which normally has got three options ("Properties", "Layout" and "Code"). In the second one ("Layout"), you will see an option called "[parent layout] Constraints" (in your case "AnchorPane Constrainsts").

You should put "0" in the four sides of the element wich represents the parent layout.

Getting a random value from a JavaScript array

_x000D_
_x000D_
static generateMonth() { _x000D_
const theDate = ['January', 'February', 'March']; _x000D_
const randomNumber = Math.floor(Math.random()*3);_x000D_
return theDate[randomNumber];_x000D_
};
_x000D_
_x000D_
_x000D_

You set a constant variable to the array, you then have another constant that chooses randomly between the three objects in the array and then the function simply returns the results.

Constructor overload in TypeScript

You should had in mind that...

contructor()

constructor(a:any, b:any, c:any)

It's the same as new() or new("a","b","c")

Thus

constructor(a?:any, b?:any, c?:any)

is the same above and is more flexible...

new() or new("a") or new("a","b") or new("a","b","c")

Parse JSON String to JSON Object in C#.NET

Another choice besides JObject is System.Json.JsonValue for Weak-Typed JSON object.

It also has a JsonValue blob = JsonValue.Parse(json); you can use. The blob will most likely be of type JsonObject which is derived from JsonValue, but could be JsonArray. Check the blob.JsonType if you need to know.

And to answer you question, YES, you may replace json with the name of your actual variable that holds the JSON string. ;-D

There is a System.Json.dll you should add to your project References.

-Jesse

How do you remove columns from a data.frame?

Use read.table with colClasses instances of "NULL" to avoid creating them in the first place:

## example data and temp file
x <- data.frame(x = 1:10, y = rnorm(10), z = runif(10), a = letters[1:10], stringsAsFactors = FALSE)
tmp <- tempfile()
write.table(x, tmp, row.names = FALSE)


(y <- read.table(tmp, colClasses = c("numeric", rep("NULL", 2), "character"), header = TRUE))

x a
1   1 a
2   2 b
3   3 c
4   4 d
5   5 e
6   6 f
7   7 g
8   8 h
9   9 i
10 10 j

unlink(tmp)

Using XAMPP, how do I swap out PHP 5.3 for PHP 5.2?

Years later, but for what it's worth - This is simple to do.

  • Just RENAME the C:\xampp directory

  • Install the desired new version of XAMPP

  • Simply run the control panel script "xampp-control.exe" directly from within the xampp folder. (Ignore warnings about "must run from C:\xampp - those have nothing to do with multiple installations.)

To switch between these versions of XAMPP, just rename the xampp directories as necessary, and re-run.

(HTML) Download a PDF file instead of opening them in browser when clicked

I needed to do this for files created with dynamic names in a particular folder and served by IIS.

This worked for me:

  • In IIS, go that folder and double click HTTP Response Headers.
  • Add a new header with the following info:

    Name: content-disposition Value: attachment

(from: http://forums.iis.net/t/1175103.aspx?add+CustomHeaders+only+for+certain+file+types+)

How to remove foreign key constraint in sql server?

If you find yourself in a situation where the FK name of a table has been auto-generated and you aren't able to view what it exactly is (in the case of not having rights to a database for instance) you could try something like this:

DECLARE @table NVARCHAR(512), @sql NVARCHAR(MAX);
SELECT @table = N'dbo.Table';
SELECT @sql = 'ALTER TABLE ' + @table
    + ' DROP CONSTRAINT ' + NAME + ';'
    FROM sys.foreign_keys
    WHERE [type] = 'F'
    AND [parent_object_id] = OBJECT_ID(@table);
EXEC sp_executeSQL @sql;

Build up a stored proc which drops the constraint of the specified table without specifying the actual FK name. It drops the constraint where the object [type] is equal to F (Foreign Key constraint).

Note: if there are multiple FK's in the table it will drop them all. So this solution works best if the table you are targeting has just one FK.

Jquery sortable 'change' event element position

$( "#sortable" ).sortable({
    change: function(event, ui) {       
        var pos = ui.helper.index() < ui.placeholder.index() 
            ? { start: ui.helper.index(), end: ui.placeholder.index() }
            : { start: ui.placeholder.index(), end: ui.helper.index() }

        $(this)
            .children().removeClass( 'highlight' )
            .not( ui.helper ).slice( pos.start, pos.end ).addClass( 'highlight' );
    },
    stop: function(event, ui) {
        $(this).children().removeClass( 'highlight' );
    }
});

FIDDLE

An example of how it could be done inside change event without storing arbitrary data into element storage. Since the element where drag starts is ui.helper, and the element of current position is ui.placeholder, we can take the elements between those two indexes and highlight them. Also, we can use this inside handler since it refers to the element that the widget is attached. The example works with dragging in both directions.

android on Text Change Listener

Another solution that may help someone. There are 2 EditText which change instead of each other after editing. By default, it led to cyclicity.

use variable:

Boolean uahEdited = false;
Boolean usdEdited = false;

add TextWatcher

uahEdit = findViewById(R.id.uahEdit);
usdEdit = findViewById(R.id.usdEdit);

uahEdit.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            if (!usdEdited) {
                uahEdited = true;
            }
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            String tmp = uahEdit.getText().toString();

            if(!tmp.isEmpty() && uahEdited) {
                uah = Double.valueOf(tmp);
                usd = uah / 27;
                usdEdit.setText(String.valueOf(usd));
            } else if (tmp.isEmpty()) {
                usdEdit.getText().clear();
            }
        }

        @Override
        public void afterTextChanged(Editable s) {
            uahEdited = false;
        }
    });

usdEdit.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            if (!uahEdited) {
                usdEdited = true;
            }
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            String tmp = usdEdit.getText().toString();

            if (!tmp.isEmpty() && usdEdited) {
                usd = Double.valueOf(tmp);
                uah = usd * 27;
                uahEdit.setText(String.valueOf(uah));
            } else if (tmp.isEmpty()) {
                uahEdit.getText().clear();
            }
        }

        @Override
        public void afterTextChanged(Editable s) {
            usdEdited = false;
        }
    });

Don't criticize too much. I am a novice developer

How to center a subview of UIView

Objective-C

yourSubView.center = CGPointMake(yourView.frame.size.width  / 2, 
                                 yourView.frame.size.height / 2);

Swift

yourSubView.center = CGPoint(x: yourView.frame.size.width  / 2,
                             y: yourView.frame.size.height / 2)

How to merge two PDF files into one in Java?

If you want to combine two files where one overlays the other (example: document A is a template and document B has the text you want to put on the template), this works:

after creating "doc", you want to write your template (templateFile) on top of that -

   PDDocument watermarkDoc = PDDocument.load(getServletContext()
                .getRealPath(templateFile));
   Overlay overlay = new Overlay();

   overlay.overlay(watermarkDoc, doc);

How to convert nanoseconds to seconds using the TimeUnit enum?

You should write :

    long startTime = System.nanoTime();        
    long estimatedTime = System.nanoTime() - startTime;

Assigning the endTime in a variable might cause a few nanoseconds. In this approach you will get the exact elapsed time.

And then:

TimeUnit.SECONDS.convert(estimatedTime, TimeUnit.NANOSECONDS)

Are there dictionaries in php?

Associative array in PHP actually considered as a dictionary.

An array in PHP is actually an ordered map. A map is a type that associates values to keys. it can be treated as an array, list (vector), hash table (an implementation of a map), dictionary, collection, stack, queue, and probably more.

<?php
$array = array(
    "foo" => "bar",
    "bar" => "foo",
);

// Using the short array syntax
$array = [
    "foo" => "bar",
    "bar" => "foo",
];
?>

An array is different than a dictionary in that arrays have both an index and a key. Dictionaries only have keys and no index.

How can I get terminal output in python?

You can use Popen in subprocess as they suggest.

with os, which is not recomment, it's like below:

import os
a  = os.popen('pwd').readlines()

Turning a Comma Separated string into individual rows

As of Feb 2016 - see the TALLY Table Example - very likely to outperform my TVF below, from Feb 2014. Keeping original post below for posterity:


Too much repeated code for my liking in the above examples. And I dislike the performance of CTEs and XML. Also, an explicit Id so that consumers that are order specific can specify an ORDER BY clause.

CREATE FUNCTION dbo.Split
(
    @Line nvarchar(MAX),
    @SplitOn nvarchar(5) = ','
)
RETURNS @RtnValue table
(
    Id INT NOT NULL IDENTITY(1,1) PRIMARY KEY CLUSTERED,
    Data nvarchar(100) NOT NULL
)
AS
BEGIN
    IF @Line IS NULL RETURN

    DECLARE @split_on_len INT = LEN(@SplitOn)
    DECLARE @start_at INT = 1
    DECLARE @end_at INT
    DECLARE @data_len INT

    WHILE 1=1
    BEGIN
        SET @end_at = CHARINDEX(@SplitOn,@Line,@start_at)
        SET @data_len = CASE @end_at WHEN 0 THEN LEN(@Line) ELSE @end_at-@start_at END
        INSERT INTO @RtnValue (data) VALUES( SUBSTRING(@Line,@start_at,@data_len) );
        IF @end_at = 0 BREAK;
        SET @start_at = @end_at + @split_on_len
    END

    RETURN
END

How to use continue in jQuery each() loop?

We can break both a $(selector).each() loop and a $.each() loop at a particular iteration by making the callback function return false. Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration.

return false; // this is equivalent of 'break' for jQuery loop

return;       // this is equivalent of 'continue' for jQuery loop

Note that $(selector).each() and $.each() are different functions.

References:

Two Page Login with Spring Security 3.2.x

There should be three pages here:

  1. Initial login page with a form that asks for your username, but not your password.
  2. You didn't mention this one, but I'd check whether the client computer is recognized, and if not, then challenge the user with either a CAPTCHA or else a security question. Otherwise the phishing site can simply use the tendered username to query the real site for the security image, which defeats the purpose of having a security image. (A security question is probably better here since with a CAPTCHA the attacker could have humans sitting there answering the CAPTCHAs to get at the security images. Depends how paranoid you want to be.)
  3. A page after that that displays the security image and asks for the password.

I don't see this short, linear flow being sufficiently complex to warrant using Spring Web Flow.

I would just use straight Spring Web MVC for steps 1 and 2. I wouldn't use Spring Security for the initial login form, because Spring Security's login form expects a password and a login processing URL. Similarly, Spring Security doesn't provide special support for CAPTCHAs or security questions, so you can just use Spring Web MVC once again.

You can handle step 3 using Spring Security, since now you have a username and a password. The form login page should display the security image, and it should include the user-provided username as a hidden form field to make Spring Security happy when the user submits the login form. The only way to get to step 3 is to have a successful POST submission on step 1 (and 2 if applicable).

onClick function of an input type="button" not working

you could also try creating a button, this will work if you put it outside of the form;

<button onClick="moreFields(); return false;">Give me more fields!</button>

Find package name for Android apps to use Intent to launch Market app from web

You can search the app online in the Google Play Store. When found, check the url, for example, https://play.google.com/store/apps/details?id=lutey.FTPServer&hl=en

The id parameter corresponds to the package name of the application. In the case of the url in the example, the package name is lutey.FTPServer.

C# Validating input for textbox on winforms

With WinForms you can use the ErrorProvider in conjunction with the Validating event to handle the validation of user input. The Validating event provides the hook to perform the validation and ErrorProvider gives a nice consistent approach to providing the user with feedback on any error conditions.

http://msdn.microsoft.com/en-us/library/system.windows.forms.errorprovider.aspx

Connect different Windows User in SQL Server Management Studio (2005 or later)

While there's no way to connect to multiple servers as different users in a single instance of SSMS, what you're looking for is the following RUNAS syntax:

runas /netonly /user:domain\username program.exe

When you use the "/netonly" switch, you can log in using remote credentials on a domain that you're not currently a member of, even if there's no trust set up. It just tells runas that the credentials will be used for accessing remote resources - the application interacts with the local computer as the currently logged-in user, and interacts with remote computers as the user whose credentials you've given.

You'd still have to run multiple instances of SSMS, but at least you could connect as different windows users in each one.


For example: runas /netonly /user:domain\username ssms.exe

SQL query: Delete all records from the table except latest N?

DELETE  i1.*
FROM    items i1
LEFT JOIN
        (
        SELECT  id
        FROM    items ii
        ORDER BY
                id DESC
        LIMIT 20
        ) i2
ON      i1.id = i2.id
WHERE   i2.id IS NULL

How do I pick 2 random items from a Python set?

Use the random module: http://docs.python.org/library/random.html

import random
random.sample(set([1, 2, 3, 4, 5, 6]), 2)

This samples the two values without replacement (so the two values are different).

Get $_POST from multiple checkboxes

Edit To reflect what @Marc said in the comment below.

You can do a loop through all the posted values.

HTML:

<input type="checkbox" name="check_list[]" value="<?=$rowid?>" />
<input type="checkbox" name="check_list[]" value="<?=$rowid?>" />
<input type="checkbox" name="check_list[]" value="<?=$rowid?>" />

PHP:

foreach($_POST['check_list'] as $item){
  // query to delete where item = $item
}

Dynamic constant assignment

Ruby doesn't like that you are assigning the constant inside of a method because it risks re-assignment. Several SO answers before me give the alternative of assigning it outside of a method--but in the class, which is a better place to assign it.

Why use Gradle instead of Ant or Maven?

Gradle can be used for many purposes - it's a much better Swiss army knife than Ant - but it's specifically focused on multi-project builds.

First of all, Gradle is a dependency programming tool which also means it's a programming tool. With Gradle you can execute any random task in your setup and Gradle will make sure all declared dependecies are properly and timely executed. Your code can be spread across many directories in any kind of layout (tree, flat, scattered, ...).

Gradle has two distinct phases: evaluation and execution. Basically, during evaluation Gradle will look for and evaluate build scripts in the directories it is supposed to look. During execution Gradle will execute tasks which have been loaded during evaluation taking into account task inter-dependencies.

On top of these dependency programming features Gradle adds project and JAR dependency features by intergration with Apache Ivy. As you know Ivy is a much more powerful and much less opinionated dependency management tool than say Maven.

Gradle detects dependencies between projects and between projects and JARs. Gradle works with Maven repositories (download and upload) like the iBiblio one or your own repositories but also supports and other kind of repository infrastructure you might have.

In multi-project builds Gradle is both adaptable and adapts to the build's structure and architecture. You don't have to adapt your structure or architecture to your build tool as would be required with Maven.

Gradle tries very hard not to get in your way, an effort Maven almost never makes. Convention is good yet so is flexibility. Gradle gives you many more features than Maven does but most importantly in many cases Gradle will offer you a painless transition path away from Maven.

How to open local files in Swagger-UI

I had that issue and here is much simpler solution:

  • Make a dir (eg: swagger-ui) in your public dir (static path: no route is required) and copy dist from swagger-ui into that directory and open localhost/swagger-ui
  • You will see swagger-ui with default petstore example
  • Replace default petstore url in dist/index.html with your localhost/api-docs or to make it more generalized, replace with this:

    location.protocol+'//' + location.hostname+(location.port ? ':' + location.port: '') + "/api-docs";

  • Hit again localhost/swagger-ui

Voila! You local swagger implementation is ready

How to trigger HTML button when you press Enter in textbox?

This should do it, I am using jQuery you can write plain javascript.
Replace sendMessage() with your functionality.

$('#addLinks').keypress(function(e) {
    if (e.which == 13) {
        sendMessage();
        e.preventDefault();
    }
});

View stored procedure/function definition in MySQL

An alternative quick and hacky solution if you want to get an overview of all the produres there are, or run into the issue of only getting the procedure header shown by SHOW CREATE PROCEDURE:

mysqldump --user=<user> -p --no-data --routines <database>

It will export the table descriptions as well, but no data. Works well for sniffing around unknown or forgotten schemas... ;)

Subtract minute from DateTime in SQL Server 2005

SELECT DATEADD(minute, -15, '2000-01-01 08:30:00'); 

The second value (-15 in this case) must be numeric (i.e. not a string like '00:15'). If you need to subtract hours and minutes I would recommend splitting the string on the : to get the hours and minutes and subtracting using something like

SELECT DATEADD(minute, -60 * @h - @m, '2000-01-01 08:30:00'); 

where @h is the hour part of your string and @m is the minute part of your string

EDIT:

Here is a better way:

SELECT CAST('2000-01-01 08:30:00' as datetime) - CAST('00:15' AS datetime)

How to display image with JavaScript?

You could make use of the Javascript DOM API. In particular, look at the createElement() method.

You could create a re-usable function that will create an image like so...

function show_image(src, width, height, alt) {
    var img = document.createElement("img");
    img.src = src;
    img.width = width;
    img.height = height;
    img.alt = alt;

    // This next line will just add it to the <body> tag
    document.body.appendChild(img);
}

Then you could use it like this...

<button onclick=
    "show_image('http://google.com/images/logo.gif', 
                 276, 
                 110, 
                 'Google Logo');">Add Google Logo</button> 

See a working example on jsFiddle: http://jsfiddle.net/Bc6Et/

How to import or copy images to the "res" folder in Android Studio?

To import files from OS X Finder into Android Studio, just drag the relevant files to your resource folder.

  • Drag & Drop by default moves files to your project (not what you always want)
  • Pressing ? (Alt) while dragging copies files

Don't find a permanent config option for this, but this is the workaround I'm using

ggplot combining two plots from different data.frames

As Baptiste said, you need to specify the data argument at the geom level. Either

#df1 is the default dataset for all geoms
(plot1 <- ggplot(df1, aes(v, p)) + 
    geom_point() +
    geom_step(data = df2)
)

or

#No default; data explicitly specified for each geom
(plot2 <- ggplot(NULL, aes(v, p)) + 
      geom_point(data = df1) +
      geom_step(data = df2)
)

How to verify if $_GET exists?

You can use isset function:

if(isset($_GET['id'])) {
    // id index exists
}

You can create a handy function to return default value if index doesn't exist:

function Get($index, $defaultValue) {
    return isset($_GET[$index]) ? $_GET[$index] : $defaultValue;
}

// prints "invalid id" if $_GET['id'] is not set
echo Get('id', 'invalid id');

You can also try to validate it at the same time:

function GetInt($index, $defaultValue) {
    return isset($_GET[$index]) && ctype_digit($_GET[$index])
            ? (int)$_GET[$index] 
            : $defaultValue;
}

// prints 0 if $_GET['id'] is not set or is not numeric
echo GetInt('id', 0);

Lock screen orientation (Android)

inside the Android manifest file of your project, find the activity declaration of whose you want to fix the orientation and add the following piece of code ,

android:screenOrientation="landscape"

for landscape orientation and for portrait add the following code,

android:screenOrientation="portrait"

Upload file to FTP using C#

The following works for me:

public virtual void Send(string fileName, byte[] file)
{
    ByteArrayToFile(fileName, file);

    var request = (FtpWebRequest) WebRequest.Create(new Uri(ServerUrl + fileName));

    request.Method = WebRequestMethods.Ftp.UploadFile;
    request.UsePassive = false;
    request.Credentials = new NetworkCredential(UserName, Password);
    request.ContentLength = file.Length;

    var requestStream = request.GetRequestStream();
    requestStream.Write(file, 0, file.Length);
    requestStream.Close();

    var response = (FtpWebResponse) request.GetResponse();

    if (response != null)
        response.Close();
}

You can't read send the file parameter in your code as it is only the filename.

Use the following:

byte[] bytes = File.ReadAllBytes(dir + file);

To get the file so you can pass it to the Send method.

Send JSON data with jQuery

It gets serialized so that the URI can read the name value pairs in the POST request by default. You could try setting processData:false to your list of params. Not sure if that would help.

How can I use Bash syntax in Makefile targets?

From the GNU Make documentation,

5.3.1 Choosing the Shell
------------------------

The program used as the shell is taken from the variable `SHELL'.  If
this variable is not set in your makefile, the program `/bin/sh' is
used as the shell.

So put SHELL := /bin/bash at the top of your makefile, and you should be good to go.

BTW: You can also do this for one target, at least for GNU Make. Each target can have its own variable assignments, like this:

all: a b

a:
    @echo "a is $$0"

b: SHELL:=/bin/bash   # HERE: this is setting the shell for b only
b:
    @echo "b is $$0"

That'll print:

a is /bin/sh
b is /bin/bash

See "Target-specific Variable Values" in the documentation for more details. That line can go anywhere in the Makefile, it doesn't have to be immediately before the target.

Why does my 'git branch' have no master?

master is just the name of a branch, there's nothing magic about it except it's created by default when a new repository is created.

You can add it back with git checkout -b master.

PHP function overloading

In PHP 5.6 you can use the splat operator ... as the last parameter and do away with func_get_args() and func_num_args():

function example(...$args)
{
   count($args); // Equivalent to func_num_args()
}

example(1, 2);
example(1, 2, 3, 4, 5, 6, 7);

You can use it to unpack arguments as well:

$args[] = 1;
$args[] = 2;
$args[] = 3;
example(...$args);

Is equivalent to:

example(1, 2, 3);

Efficient way to remove ALL whitespace from String?

My solution is to use Split and Join and it is surprisingly fast, in fact the fastest of the top answers here.

str = string.Join("", str.Split(default(string[]), StringSplitOptions.RemoveEmptyEntries));

Timings for 10,000 loop on simple string with whitespace inc new lines and tabs

  • split/join = 60 milliseconds
  • linq chararray = 94 milliseconds
  • regex = 437 milliseconds

Improve this by wrapping it up in method to give it meaning, and also make it an extension method while we are at it ...

public static string RemoveWhitespace(this string str) {
    return string.Join("", str.Split(default(string[]), StringSplitOptions.RemoveEmptyEntries));
}

jQuery Array of all selected checkboxes (by class)

You can also add underscore.js to your project and will be able to do it in one line:

_.map($("input[name='category_ids[]']:checked"), function(el){return $(el).val()})

Auto height of div

make sure the content inside your div ended with clear:both style

switch() statement usage

Well, timing to the rescue again. It seems switch is generally faster than if statements. So that, and the fact that the code is shorter/neater with a switch statement leans in favor of switch:

# Simplified to only measure the overhead of switch vs if

test1 <- function(type) {
 switch(type,
        mean = 1,
        median = 2,
        trimmed = 3)
}

test2 <- function(type) {
 if (type == "mean") 1
 else if (type == "median") 2
 else if (type == "trimmed") 3
}

system.time( for(i in 1:1e6) test1('mean') ) # 0.89 secs
system.time( for(i in 1:1e6) test2('mean') ) # 1.13 secs
system.time( for(i in 1:1e6) test1('trimmed') ) # 0.89 secs
system.time( for(i in 1:1e6) test2('trimmed') ) # 2.28 secs

Update With Joshua's comment in mind, I tried other ways to benchmark. The microbenchmark seems the best. ...and it shows similar timings:

> library(microbenchmark)
> microbenchmark(test1('mean'), test2('mean'), times=1e6)
Unit: nanoseconds
           expr  min   lq median   uq      max
1 test1("mean")  709  771    864  951 16122411
2 test2("mean") 1007 1073   1147 1223  8012202

> microbenchmark(test1('trimmed'), test2('trimmed'), times=1e6)
Unit: nanoseconds
              expr  min   lq median   uq      max
1 test1("trimmed")  733  792    843  944 60440833
2 test2("trimmed") 2022 2133   2203 2309 60814430

Final Update Here's showing how versatile switch is:

switch(type, case1=1, case2=, case3=2.5, 99)

This maps case2 and case3 to 2.5 and the (unnamed) default to 99. For more information, try ?switch

Debugging the error "gcc: error: x86_64-linux-gnu-gcc: No such file or directory"

After a fair amount of work, I was able to get it to build on Ubuntu 12.04 x86 and Debian 7.4 x86_64. I wrote up a guide below. Can you please try following it to see if it resolves the issue?

If not please let me know where you get stuck.

Install Common Dependencies

sudo apt-get install build-essential autoconf libtool pkg-config python-opengl python-imaging python-pyrex python-pyside.qtopengl idle-python2.7 qt4-dev-tools qt4-designer libqtgui4 libqtcore4 libqt4-xml libqt4-test libqt4-script libqt4-network libqt4-dbus python-qt4 python-qt4-gl libgle3 python-dev

Install NumArray 1.5.2

wget http://goo.gl/6gL0q3 -O numarray-1.5.2.tgz
tar xfvz numarray-1.5.2.tgz
cd numarray-1.5.2
sudo python setup.py install

Install Numeric 23.8

wget http://goo.gl/PxaHFW -O numeric-23.8.tgz
tar xfvz numeric-23.8.tgz
cd Numeric-23.8
sudo python setup.py install

Install HDF5 1.6.5

wget ftp://ftp.hdfgroup.org/HDF5/releases/hdf5-1.6/hdf5-1.6.5.tar.gz
tar xfvz hdf5-1.6.5.tar.gz
cd hdf5-1.6.5
./configure --prefix=/usr/local
sudo make 
sudo make install

Install Nanoengineer

git clone https://github.com/kanzure/nanoengineer.git
cd nanoengineer
./bootstrap
./configure
make
sudo make install

Troubleshooting

On Debian Jessie, you will receive the error message that cant pants mentioned. There seems to be an issue in the automake scripts. x86_64-linux-gnu-gcc is inserted in CFLAGS and gcc will interpret that as a name of one of the source files. As a workaround, let's create an empty file with that name. Empty so that it won't change the program and that very name so that compiler picks it up. From the cloned nanoengineer directory, run this command to make gcc happy (it is a hack yes, but it does work) ...

touch sim/src/x86_64-linux-gnu-gcc

If you receive an error message when attemping to compile HDF5 along the lines of: "error: call to ‘__open_missing_mode’ declared with attribute error: open with O_CREAT in second argument needs 3 arguments", then modify the file perform/zip_perf.c, line 548 to look like the following and then rerun make...

output = open(filename, O_RDWR | O_CREAT, S_IRUSR|S_IWUSR);

If you receive an error message about Numeric/arrayobject.h not being found when building Nanoengineer, try running

export CPPFLAGS=-I/usr/local/include/python2.7
./configure
make
sudo make install

If you receive an error message similar to "TRACE_PREFIX undeclared", modify the file sim/src/simhelp.c lines 38 to 41 to look like this and re-run make:

#ifdef DISTUTILS
static char tracePrefix[] = "";
#else
static char tracePrefix[] = "";

If you receive an error message when trying to launch NanoEngineer-1 that mentions something similar to "cannot import name GL_ARRAY_BUFFER_ARB", modify the lines in the following files

/usr/local/bin/NanoEngineer1_0.9.2.app/program/graphics/drawing/setup_draw.py
/usr/local/bin/NanoEngineer1_0.9.2.app/program/graphics/drawing/GLPrimitiveBuffer.py
/usr/local/bin/NanoEngineer1_0.9.2.app/program/prototype/test_drawing.py

that look like this:

from OpenGL.GL import GL_ARRAY_BUFFER_ARB
from OpenGL.GL import GL_ELEMENT_ARRAY_BUFFER_ARB

to look like this:

from OpenGL.GL.ARB.vertex_buffer_object import GL_ARRAY_BUFFER_AR
from OpenGL.GL.ARB.vertex_buffer_object import GL_ELEMENT_ARRAY_BUFFER_ARB

I also found an additional troubleshooting text file that has been removed, but you can find it here

How to hide action bar before activity is created, and then show it again?

Just add this in your styles.xml

<item name="android:windowNoTitle">true</item>

Python: Removing spaces from list objects

replace() does not operate in-place, you need to assign its result to something. Also, for a more concise syntax, you could supplant your for loop with a one-liner: hello_no_spaces = map(lambda x: x.replace(' ', ''), hello)

Activity has leaked window that was originally added

This happened to me when i am using ProgressDialog in AsyncTask. Actually i am using hide() method in onPostExecute. Based on the answer of @Alex Volovoy i need to use dismiss() with ProgressDialog to remove it in onPostExecute and its done.

progressDialog.hide(); // Don't use it, it gives error

progressDialog.dismiss(); // Use it

How to fix "Your Ruby version is 2.3.0, but your Gemfile specified 2.2.5" while server starting

You better install Ruby 2.2.5 for compatibility. The Ruby version in your local machine is different from the one declared in Gemfile.

If you're using rvm:

rvm install 2.2.5
rvm use 2.2.5

else if you're using rbenv:

rbenv install 2.2.5
rbenv local 2.2.5

else if you can not change ruby version by rbenv, read here

Hashmap does not work with int, char

Generics only support object types, not primitives. Unlike C++ templates, generics don't involve code generatation and there is only one HashMap code regardless of the number of generic types of it you use.

Trove4J gets around this by pre-generating selected collections to use primitives and supports TCharIntHashMap which to can wrap to support the Map<Character, Integer> if you need to.

TCharIntHashMap: An open addressed Map implementation for char keys and int values.

When to use 'npm start' and when to use 'ng serve'?

npm start will run whatever you have defined for the start command of the scripts object in your package.json file.

So if it looks like this:

"scripts": {
  "start": "ng serve"
}

Then npm start will run ng serve.

Spark - SELECT WHERE or filtering?

According to spark documentation "where() is an alias for filter()"

filter(condition) Filters rows using the given condition. where() is an alias for filter().

Parameters: condition – a Column of types.BooleanType or a string of SQL expression.

>>> df.filter(df.age > 3).collect()
[Row(age=5, name=u'Bob')]
>>> df.where(df.age == 2).collect()
[Row(age=2, name=u'Alice')]

>>> df.filter("age > 3").collect()
[Row(age=5, name=u'Bob')]
>>> df.where("age = 2").collect()
[Row(age=2, name=u'Alice')]

SQL Server Configuration Manager not found

Go to this location C:\Windows\System32 and find SQLServerManager . Worked for me. Configuration manager was there but somehow wasn't showing up in search results.

Can I assume (bool)true == (int)1 for any C++ compiler?

I've found different compilers return different results on true. I've also found that one is almost always better off comparing a bool to a bool instead of an int. Those ints tend to change value over time as your program evolves and if you assume true as 1, you can get bitten by an unrelated change elsewhere in your code.

Convert a numpy.ndarray to string(or bytes) and convert it back to numpy.ndarray

Imagine you have a numpy array of text like in a messenger

 >>> stex[40]
 array(['Know the famous thing ...

and you want to get statistics from the corpus (text col=11) you first must get the values from dataframe (df5) and then join all records together in one single corpus:

 >>> stex = (df5.ix[0:,[11]]).values
 >>> a_str = ','.join(str(x) for x in stex)
 >>> a_str = a_str.split()
 >>> fd2 = nltk.FreqDist(a_str)
 >>> fd2.most_common(50)

Difference Between Schema / Database in MySQL

Microsoft SQL Server for instance, Schemas refer to a single user and is another level of a container in the order of indicating the server, database, schema, tables, and objects.

For example, when you are intending to update dbo.table_a and the syntax isn't full qualified such as UPDATE table.a the DBMS can't decide to use the intended table. Essentially by default the DBMS will utilize myuser.table_a

Best way to save a trained model in PyTorch?

I've found this page on their github repo, I'll just paste the content here.


Recommended approach for saving a model

There are two main approaches for serializing and restoring a model.

The first (recommended) saves and loads only the model parameters:

torch.save(the_model.state_dict(), PATH)

Then later:

the_model = TheModelClass(*args, **kwargs)
the_model.load_state_dict(torch.load(PATH))

The second saves and loads the entire model:

torch.save(the_model, PATH)

Then later:

the_model = torch.load(PATH)

However in this case, the serialized data is bound to the specific classes and the exact directory structure used, so it can break in various ways when used in other projects, or after some serious refactors.

How can I display a messagebox in ASP.NET?

The best solution is a minimal use of java directly in the visualstudio GUI

here it is: On a button go to the "OnClientClick" property (its not into events*) overthere type:

return confirm('are you sure?')

it will put a dialog with cancel ok buttons transparent over current page if cancel is pressed no postback will ocure. However if you want only ok button type:

alert ('i told you so')

The events like onclick work server side they execute your code, while OnClientClick runs in the browser side. the come most close to a basic dialog

How to list active / open connections in Oracle?

select s.sid as "Sid", s.serial# as "Serial#", nvl(s.username, ' ') as "Username", s.machine as "Machine", s.schemaname as "Schema name", s.logon_time as "Login time", s.program as "Program", s.osuser as "Os user", s.status as "Status", nvl(s.process, ' ') as "OS Process id"
from v$session s
where nvl(s.username, 'a') not like 'a' and status like 'ACTIVE'
order by 1,2

This query attempts to filter out all background processes.

How to convert unsigned long to string

Try using sprintf:

unsigned long x=1000000;
char buffer[21];
sprintf(buffer,"%lu", x);

Edit:

Notice that you have to allocate a buffer in advance, and have no idea how long the numbers will actually be when you do so. I'm assuming 32bit longs, which can produce numbers as big as 10 digits.

See Carl Smotricz's answer for a better explanation of the issues involved.

How to switch text case in visual studio code

Quoted from this post:

The question is about how to make CTRL+SHIFT+U work in Visual Studio Code. Here is how to do it. (Version 1.8.1 or above). You can also choose a different key combination.

File-> Preferences -> Keyboard Shortcuts.

An editor will appear with keybindings.json file. Place the following JSON in there and save.

[
 {
    "key": "ctrl+shift+u",
    "command": "editor.action.transformToUppercase",
    "when": "editorTextFocus"
 },
 {
    "key": "ctrl+shift+l",
    "command": "editor.action.transformToLowercase",
    "when": "editorTextFocus"
 }
]

Now CTRL+SHIFT+U will capitalise selected text, even if multi line. In the same way, CTRL+SHIFT+L will make selected text lowercase.

These commands are built into VS Code, and no extensions are required to make them work.

Mergesort with Python

Try this recursive version

def mergeList(l1,l2):
    l3=[]
    Tlen=len(l1)+len(l2)
    inf= float("inf")
    for i in range(Tlen):
        print   "l1= ",l1[0]," l2= ",l2[0]
        if l1[0]<=l2[0]:
            l3.append(l1[0])
            del l1[0]
            l1.append(inf)
        else:
            l3.append(l2[0])
            del l2[0]
            l2.append(inf)
    return l3

def main():
    l1=[2,10,7,6,8]
    print mergeSort(breaklist(l1))

def breaklist(rawlist):
    newlist=[]
    for atom in rawlist:
        print atom
        list_atom=[atom]
        newlist.append(list_atom)
    return newlist

def mergeSort(inputList):
    listlen=len(inputList)
    if listlen ==1:
        return inputList
    else:
        newlist=[]
        if listlen % 2==0:
            for i in range(listlen/2):
                newlist.append(mergeList(inputList[2*i],inputList[2*i+1]))
        else:
            for i in range((listlen+1)/2):
                if 2*i+1<listlen:
                    newlist.append(mergeList(inputList[2*i],inputList[2*i+1]))
                else:
                    newlist.append(inputList[2*i])
        return  mergeSort(newlist)

if __name__ == '__main__':
    main()

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

={10,}

matches = that is repeated 10 or more times.

How to pip or easy_install tkinter on Windows

If you are using virtualenv, it is fine to install tkinter using sudo apt-get install python-tk(python2), sudo apt-get install python3-tk(python3), and and it will work fine in the virtual environment

How to delete a localStorage item when the browser window/tab is closed?

Try using

$(window).unload(function(){
  localStorage.clear();
});

Hope this works for you

Correct use for angular-translate in controllers

EDIT: Please see the answer from PascalPrecht (the author of angular-translate) for a better solution.


The asynchronous nature of the loading causes the problem. You see, with {{ pageTitle | translate }}, Angular will watch the expression; when the localization data is loaded, the value of the expression changes and the screen is updated.

So, you can do that yourself:

.controller('FirstPageCtrl', ['$scope', '$filter', function ($scope, $filter) {
    $scope.$watch(
        function() { return $filter('translate')('HELLO_WORLD'); },
        function(newval) { $scope.pageTitle = newval; }
    );
});

However, this will run the watched expression on every digest cycle. This is suboptimal and may or may not cause a visible performance degradation. Anyway it is what Angular does, so it cant be that bad...

Get the cell value of a GridView row

I had the same problem as yours. I found that when i use the BoundField tag in GridView to show my data. The row.Cells[1].Text is working in:

GridViewRow row = dgCustomer.SelectedRow;
TextBox1.Text = "Cell Value" + row.Cells[1].Text + "";

But when i use TemplateField tag to show data like this:

 <asp:TemplateField HeaderText="??">
    <ItemTemplate>
    <asp:Label ID="Part_No" runat="server" Text='<%# Eval("Part_No")%>' ></asp:Label>
    </ItemTemplate>
    <HeaderStyle CssClass="bhead" />
    <ItemStyle CssClass="bbody" />
    </asp:TemplateField>

The row.Cells[1].Text just return null. I got stuck in this problem for a long time. I figur out recently and i want to share with someone who have the same problem my solution. Please feel free to edit this post and/or correct me.

My Solution:

Label lbCod = GridView1.Rows["AnyValidIndex"].Cells["AnyValidIndex"].Controls["AnyValidIndex"] as Label;

I use Controls attribute to find the Label control which i use to show data, and you can find yours. When you find it and convert to the correct type object than you can extract text and so on. Ex:

string showText = lbCod.Text;

Reference: reference

Detect the Enter key in a text input field

 $(document).ready(function () {
        $(".input1").keyup(function (e) {
            if (e.keyCode == 13) {
                // Do something
            }
        });
    });

Add data dynamically to an Array

There are quite a few ways to work with dynamic arrays in PHP. Initialise an array:

$array = array();

Add to an array:

$array[] = "item"; // for your $arr1 
$array[$key] = "item"; // for your $arr2
array_push($array, "item", "another item");

Remove from an array:

$item = array_pop($array);
$item = array_shift($array);
unset($array[$key]);

There are plenty more ways, these are just some examples.

The transaction log for database is full. To find out why space in the log cannot be reused, see the log_reuse_wait_desc column in sys.databases

As an aside, it is always a good practice (and possibly a solution for this type of issue) to delete a large number of rows by using batches:

WHILE EXISTS (SELECT 1 
              FROM   YourTable 
              WHERE  <yourCondition>) 
  DELETE TOP(10000) FROM YourTable 
  WHERE  <yourCondition>

Linux command for extracting war file?

You can use the unzip command.

Image height and width not working?

You must write

<img src="theSource" style="width:30px;height:30px;" />

Inline styling will always take precedence over CSS styling. The width and height attributes are being overridden by your stylesheet, so you need to switch to this format.

Post multipart request with Android SDK

For posterity, I didn't see okhttp mentioned. Related post.

Basically you build up the body using a MultipartBody.Builder, and then post this in a request.

Example in kotlin:

    val body = MultipartBody.Builder()
            .setType(MultipartBody.FORM)
            .addFormDataPart(
                "file", 
                file.getName(),
                RequestBody.create(MediaType.parse("image/png"), file)
            )
            .addFormDataPart("timestamp", Date().time.toString())
            .build()

    val request = Request.Builder()
            .url(url)
            .post(body)
            .build()

    httpClient.newCall(request).enqueue(object : okhttp3.Callback {
        override fun onFailure(call: Call?, e: IOException?) {
            ...
        }

        override fun onResponse(call: Call?, response: Response?) {
            ...
        }
    })

SQL Server : trigger how to read value for Insert, Update, Delete

Please note that inserted, deleted means the same thing as inserted CROSS JOIN deleted and gives every combination of every row. I doubt this is what you want.

Something like this may help get you started...

SELECT
  CASE WHEN inserted.primaryKey IS NULL THEN 'This is a delete'
       WHEN  deleted.primaryKey IS NULL THEN 'This is an insert'
                                        ELSE 'This is an update'
  END  as Action,
  *
FROM
  inserted
FULL OUTER JOIN
  deleted
    ON inserted.primaryKey = deleted.primaryKey


Depending on what you want to do, you then reference the table you are interested in with inserted.userID or deleted.userID, etc.


Finally, be aware that inserted and deleted are tables and can (and do) contain more than one record.

If you insert 10 records at once, the inserted table will contain ALL 10 records. The same applies to deletes and the deleted table. And both tables in the case of an update.


EDIT Examplee Trigger after OPs edit.

ALTER TRIGGER [dbo].[UpdateUserCreditsLeft] 
  ON  [dbo].[Order]
  AFTER INSERT,UPDATE,DELETE
AS 
BEGIN

  -- SET NOCOUNT ON added to prevent extra result sets from
  -- interfering with SELECT statements.
  SET NOCOUNT ON;

  UPDATE
    User
  SET
    CreditsLeft = CASE WHEN inserted.UserID IS NULL THEN <new value for a  DELETE>
                       WHEN  deleted.UserID IS NULL THEN <new value for an INSERT>
                                                    ELSE <new value for an UPDATE>
                  END
  FROM
    User
  INNER JOIN
    (
      inserted
    FULL OUTER JOIN
      deleted
        ON inserted.UserID = deleted.UserID  -- This assumes UserID is the PK on UpdateUserCreditsLeft
    )
      ON User.UserID = COALESCE(inserted.UserID, deleted.UserID)

END


If the PrimaryKey of UpdateUserCreditsLeft is something other than UserID, use that in the FULL OUTER JOIN instead.

Angular2 set value for formGroup

You can use form.get to get the specific control object and use setValue

this.form.get(<formControlName>).setValue(<newValue>);

Any tools to generate an XSD schema from an XML instance document?

the Microsoft XSD inference tool is a good, free solution. Many XML editing tools, such as XmlSpy (mentioned by @Garth Gilmour) or OxygenXML Editor also have that feature. They're rather expensive, though. BizTalk Server also has an XSD inferring tool as well.

edit: I just discovered the .net XmlSchemaInference class, so if you're using .net you should consider that

Select Multiple Fields from List in Linq

Given List<MyType1> internalUsers and List<MyType2> externalUsers, based on the shared key of an email address...


For C# 7.0+:

var matches = (
    from i in internalUsers
    join e in externalUsers
    on i.EmailAddress.ToUpperInvariant() equals e.Email.ToUpperInvariant()
    select (internalUser:i, externalUser:e)
).ToList();

Which gives you matches as a List<(MyType1, MyType2)>.

From there you can compare them if you wish:

var internal_in_external = matches.Select(m => m.internalUser).ToList();
var external_in_internal = matches.Select(m => m.externalUser).ToList();

var internal_notIn_external = internalUsers.Except(internal_in_external).ToList();
var external_notIn_internal = externalUsers.Except(external_in_internal).ToList();

internal_in_external and internal_notIn_external will be of type List<MyType1>.

external_in_internal and external_notIn_internal will be of type List<MyType2>


For versions of C# prior to 7.0:

var matches = (
    from i in internalUsers
    join e in externalUsers
    on i.EmailAddress.ToUpperInvariant() equals e.Email.ToUpperInvariant()
    select new Tuple<MyType1, MyType2>(i, e)
).ToList();

Which gives you matches as a List<Tuple<MyType1, MyType2>>.

From there you can compare them if you wish:

var internal_in_external = matches.Select(m => m.Item1).ToList();
var external_in_internal = matches.Select(m => m.Item2).ToList();

var internal_notIn_external = internalUsers.Except(internal_in_external).ToList();
var external_notIn_internal = externalUsers.Except(external_in_internal).ToList();

internal_in_external and internal_notIn_external will be of type List<MyType1>.

external_in_internal and external_notIn_internal will be of type List<MyType2>

How to resolve the "EVP_DecryptFInal_ex: bad decrypt" during file decryption

This message can also occur when you specify the incorrect decryption password (yeah, lame, but not quite obvious to realize this from the error message, huh?).

I was using the command line to decrypt the recent DataBase backup for my auxiliary tool and suddenly faced this issue.

Finally, after 10 mins of grief and plus reading through this question/answers I have remembered that the password is different and everything worked just fine with the correct password.

Recover sa password

The best way is to simply reset the password by connecting with a domain/local admin (so you may need help from your system administrators), but this only works if SQL Server was set up to allow local admins (these are now left off the default admin group during setup).

If you can't use this or other existing methods to recover / reset the SA password, some of which are explained here:

Then you could always backup your important databases, uninstall SQL Server, and install a fresh instance.

You can also search for less scrupulous ways to do it (e.g. there are password crackers that I am not enthusiastic about sharing).

As an aside, the login properties for sa would never say Windows Authentication. This is by design as this is a SQL Authentication account. This does not mean that Windows Authentication is disabled at the instance level (in fact it is not possible to do so), it just doesn't apply for a SQL auth account.

I wrote a tip on using PSExec to connect to an instance using the NT AUTHORITY\SYSTEM account (which works < SQL Server 2012), and a follow-up that shows how to hack the SqlWriter service (which can work on more modern versions):

And some other resources:

Java: parse int value from a char

String element = "el5";
int x = element.charAt(2) - 48;

Subtracting ascii value of '0' = 48 from char

A KeyValuePair in Java

Hashtable<String, Object>

It is better than java.util.Properties which is by fact an extension of Hashtable<Object, Object>.

How can I do SELECT UNIQUE with LINQ?

The Distinct() is going to mess up the ordering, so you'll have to the sorting after that.

var uniqueColors = 
               (from dbo in database.MainTable 
                 where dbo.Property == true 
                 select dbo.Color.Name).Distinct().OrderBy(name=>name);

phpmyadmin - count(): Parameter must be an array or an object that implements Countable

Replace Function:

function PMA_isRememberSortingOrder($analyzed_sql_results) {
return $GLOBALS['cfg']['RememberSorting']
    &&!(
        $analyzed_sql_results['is_count']
        || $analyzed_sql_results['is_export']
        || $analyzed_sql_results['is_func']
        || $analyzed_sql_results['is_analyse']
    )&&
    $analyzed_sql_results['select_from']&&
    (
        empty($analyzed_sql_results['select_expr'])||
        count($analyzed_sql_results['select_expr'])==1&&
        $analyzed_sql_results['select_expr'][0] == '*'
    )
    && count($analyzed_sql_results['select_tables']) == 1;
}

Center a popup window on screen?

Facebook use the following algorithm to position their login popup window:

function PopupCenter(url, title, w, h) {
  var userAgent = navigator.userAgent,
      mobile = function() {
        return /\b(iPhone|iP[ao]d)/.test(userAgent) ||
          /\b(iP[ao]d)/.test(userAgent) ||
          /Android/i.test(userAgent) ||
          /Mobile/i.test(userAgent);
      },
      screenX = typeof window.screenX != 'undefined' ? window.screenX : window.screenLeft,
      screenY = typeof window.screenY != 'undefined' ? window.screenY : window.screenTop,
      outerWidth = typeof window.outerWidth != 'undefined' ? window.outerWidth : document.documentElement.clientWidth,
      outerHeight = typeof window.outerHeight != 'undefined' ? window.outerHeight : document.documentElement.clientHeight - 22,
      targetWidth = mobile() ? null : w,
      targetHeight = mobile() ? null : h,
      V = screenX < 0 ? window.screen.width + screenX : screenX,
      left = parseInt(V + (outerWidth - targetWidth) / 2, 10),
      right = parseInt(screenY + (outerHeight - targetHeight) / 2.5, 10),
      features = [];
  if (targetWidth !== null) {
    features.push('width=' + targetWidth);
  }
  if (targetHeight !== null) {
    features.push('height=' + targetHeight);
  }
  features.push('left=' + left);
  features.push('top=' + right);
  features.push('scrollbars=1');

  var newWindow = window.open(url, title, features.join(','));

  if (window.focus) {
    newWindow.focus();
  }

  return newWindow;
}

When and how should I use a ThreadLocal variable?

There is very good example in book Java Concurrency in Practice. Where author (Joshua Bloch) explains how Thread confinement is one of the simplest ways to achieve thread safety and ThreadLocal is more formal means of maintaining thread confinement. In the end he also explain how people can abuse it by using it as global variables.

I have copied the text from the mentioned book but code 3.10 is missing as it is not much important to understand where ThreadLocal should be use.

Thread-local variables are often used to prevent sharing in designs based on mutable Singletons or global variables. For example, a single-threaded application might maintain a global database connection that is initialized at startup to avoid having to pass a Connection to every method. Since JDBC connections may not be thread-safe, a multithreaded application that uses a global connection without additional coordination is not thread-safe either. By using a ThreadLocal to store the JDBC connection, as in ConnectionHolder in Listing 3.10, each thread will have its own connection.

ThreadLocal is widely used in implementing application frameworks. For example, J2EE containers associate a transaction context with an executing thread for the duration of an EJB call. This is easily implemented using a static Thread-Local holding the transaction context: when framework code needs to determine what transaction is currently running, it fetches the transaction context from this ThreadLocal. This is convenient in that it reduces the need to pass execution context information into every method, but couples any code that uses this mechanism to the framework.

It is easy to abuse ThreadLocal by treating its thread confinement property as a license to use global variables or as a means of creating “hidden” method arguments. Like global variables, thread-local variables can detract from reusability and introduce hidden couplings among classes, and should therefore be used with care.

youtube: link to display HD video by default

Nick Vogt at H3XED posted this syntax: https://www.youtube.com/v/VIDEOID?version=3&vq=hd1080

Take this link and replace the expression "VIDEOID" with the (shortened/shared) ID of the video.

Exapmple for ID: i3jNECZ3ybk looks like this: ... /v/i3jNECZ3ybk?version=3&vq=hd1080

What you get as a result is the standalone 1080p video but not in the Tube environment.

Best practice to validate null and empty collection in Java

We'll check a Collection object is empty, null or not. these all methods which are given below, are present in org.apache.commons.collections4.CollectionUtils package.

Check on List or set type of collection Objects.

CollectionUtils.isEmpty(listObject);
CollectionUtils.isNotEmpty(listObject);

Check on Map type of Objects.

MapUtils.isEmpty(mapObject);
MapUtils.isNotEmpty(mapObject);

The return type of all methods is boolean.

RESTful call in Java

Indeed, this is "very complicated in Java":

From: https://jersey.java.net/documentation/latest/client.html

Client client = ClientBuilder.newClient();
WebTarget target = client.target("http://foo").path("bar");
Invocation.Builder invocationBuilder = target.request(MediaType.TEXT_PLAIN_TYPE);
Response response = invocationBuilder.get();

Creating Duplicate Table From Existing Table

Use this query to create the new table with the values from existing table

CREATE TABLE New_Table_name AS SELECT * FROM Existing_table_Name; 

Now you can get all the values from existing table into newly created table.

Find number of decimal places in decimal value regardless of culture

you can use the InvariantCulture

string priceSameInAllCultures = price.ToString(System.Globalization.CultureInfo.InvariantCulture);

another possibility would be to do something like that:

private int GetDecimals(decimal d, int i = 0)
{
    decimal multiplied = (decimal)((double)d * Math.Pow(10, i));
    if (Math.Round(multiplied) == multiplied)
        return i;
    return GetDecimals(d, i+1);
}

Byte Array in Python

Dietrich's answer is probably just the thing you need for what you describe, sending bytes, but a closer analogue to the code you've provided for example would be using the bytearray type.

>>> key = bytearray([0x13, 0x00, 0x00, 0x00, 0x08, 0x00])
>>> bytes(key)
b'\x13\x00\x00\x00\x08\x00'
>>> 

JavaScript to scroll long page to DIV

Correct me if I'm wrong but I'm reading the question again and again and still think that Angus McCoteup was asking how to set an element to be position: fixed.

Angus McCoteup, check out http://www.cssplay.co.uk/layouts/fixed.html - if you want your DIV to behave like a menu there, have a look at a CSS there

How To: Execute command line in C#, get STD OUT results

You will need to use ProcessStartInfo with RedirectStandardOutput enabled - then you can read the output stream. You might find it easier to use ">" to redirect the output to a file (via the OS), and then simply read the file.

[edit: like what Ray did: +1]

Why is null an object and what's the difference between null and undefined?

What is the difference between null and undefined??

A property when it has no definition, is undefined. null is an object. Its type is object. null is a special value meaning "no value. undefined is not an object, it's type is undefined.

You can declare a variable, set it to null, and the behavior is identical except that you'll see "null" printed out versus "undefined". You can even compare a variable that is undefined to null or vice versa, and the condition will be true:

 undefined == null
 null == undefined

Refer to JavaScript Difference between null and undefined for more detail.

and with your new edit yes

if (object == null)  does mean the same  if(!object)

when testing if object is false, they both only meet the condition when testing if false, but not when true

Check here: Javascript gotcha

Nested Recycler view height doesn't wrap its content

Yes the workaround shown in all answer is correct , that is we need to customize the linear layout manager to calculate the height of its child items dynamically at run time. But all answers not working as expected .Please the below answer for custom layout manger with all orientation support.

public class MyLinearLayoutManager extends android.support.v7.widget.LinearLayoutManager {

private static boolean canMakeInsetsDirty = true;
private static Field insetsDirtyField = null;

private static final int CHILD_WIDTH = 0;
private static final int CHILD_HEIGHT = 1;
private static final int DEFAULT_CHILD_SIZE = 100;

private final int[] childDimensions = new int[2];
private final RecyclerView view;

private int childSize = DEFAULT_CHILD_SIZE;
private boolean hasChildSize;
private int overScrollMode = ViewCompat.OVER_SCROLL_ALWAYS;
private final Rect tmpRect = new Rect();

@SuppressWarnings("UnusedDeclaration")
public MyLinearLayoutManager(Context context) {
    super(context);
    this.view = null;
}

@SuppressWarnings("UnusedDeclaration")
public MyLinearLayoutManager(Context context, int orientation, boolean reverseLayout) {
    super(context, orientation, reverseLayout);
    this.view = null;
}

@SuppressWarnings("UnusedDeclaration")
public MyLinearLayoutManager(RecyclerView view) {
    super(view.getContext());
    this.view = view;
    this.overScrollMode = ViewCompat.getOverScrollMode(view);
}

@SuppressWarnings("UnusedDeclaration")
public MyLinearLayoutManager(RecyclerView view, int orientation, boolean reverseLayout) {
    super(view.getContext(), orientation, reverseLayout);
    this.view = view;
    this.overScrollMode = ViewCompat.getOverScrollMode(view);
}

public void setOverScrollMode(int overScrollMode) {
    if (overScrollMode < ViewCompat.OVER_SCROLL_ALWAYS || overScrollMode > ViewCompat.OVER_SCROLL_NEVER)
        throw new IllegalArgumentException("Unknown overscroll mode: " + overScrollMode);
    if (this.view == null) throw new IllegalStateException("view == null");
    this.overScrollMode = overScrollMode;
    ViewCompat.setOverScrollMode(view, overScrollMode);
}

public static int makeUnspecifiedSpec() {
    return View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
}

@Override
public void onMeasure(RecyclerView.Recycler recycler, RecyclerView.State state, int widthSpec, int heightSpec) {
    final int widthMode = View.MeasureSpec.getMode(widthSpec);
    final int heightMode = View.MeasureSpec.getMode(heightSpec);

    final int widthSize = View.MeasureSpec.getSize(widthSpec);
    final int heightSize = View.MeasureSpec.getSize(heightSpec);

    final boolean hasWidthSize = widthMode != View.MeasureSpec.UNSPECIFIED;
    final boolean hasHeightSize = heightMode != View.MeasureSpec.UNSPECIFIED;

    final boolean exactWidth = widthMode == View.MeasureSpec.EXACTLY;
    final boolean exactHeight = heightMode == View.MeasureSpec.EXACTLY;

    final int unspecified = makeUnspecifiedSpec();

    if (exactWidth && exactHeight) {
        // in case of exact calculations for both dimensions let's use default "onMeasure" implementation
        super.onMeasure(recycler, state, widthSpec, heightSpec);
        return;
    }

    final boolean vertical = getOrientation() == VERTICAL;

    initChildDimensions(widthSize, heightSize, vertical);

    int width = 0;
    int height = 0;

    // it's possible to get scrap views in recycler which are bound to old (invalid) adapter entities. This
    // happens because their invalidation happens after "onMeasure" method. As a workaround let's clear the
    // recycler now (it should not cause any performance issues while scrolling as "onMeasure" is never
    // called whiles scrolling)
    recycler.clear();

    final int stateItemCount = state.getItemCount();
    final int adapterItemCount = getItemCount();
    // adapter always contains actual data while state might contain old data (f.e. data before the animation is
    // done). As we want to measure the view with actual data we must use data from the adapter and not from  the
    // state
    for (int i = 0; i < adapterItemCount; i++) {
        if (vertical) {
            if (!hasChildSize) {
                if (i < stateItemCount) {
                    // we should not exceed state count, otherwise we'll get IndexOutOfBoundsException. For such items
                    // we will use previously calculated dimensions
                    measureChild(recycler, i, widthSize, unspecified, childDimensions);
                } else {
                    logMeasureWarning(i);
                }
            }
            height += childDimensions[CHILD_HEIGHT];
            if (i == 0) {
                width = childDimensions[CHILD_WIDTH];
            }
            if (hasHeightSize && height >= heightSize) {
                break;
            }
        } else {
            if (!hasChildSize) {
                if (i < stateItemCount) {
                    // we should not exceed state count, otherwise we'll get IndexOutOfBoundsException. For such items
                    // we will use previously calculated dimensions
                    measureChild(recycler, i, unspecified, heightSize, childDimensions);
                } else {
                    logMeasureWarning(i);
                }
            }
            width += childDimensions[CHILD_WIDTH];
            if (i == 0) {
                height = childDimensions[CHILD_HEIGHT];
            }
            if (hasWidthSize && width >= widthSize) {
                break;
            }
        }
    }

    if (exactWidth) {
        width = widthSize;
    } else {
        width += getPaddingLeft() + getPaddingRight();
        if (hasWidthSize) {
            width = Math.min(width, widthSize);
        }
    }

    if (exactHeight) {
        height = heightSize;
    } else {
        height += getPaddingTop() + getPaddingBottom();
        if (hasHeightSize) {
            height = Math.min(height, heightSize);
        }
    }

    setMeasuredDimension(width, height);

    if (view != null && overScrollMode == ViewCompat.OVER_SCROLL_IF_CONTENT_SCROLLS) {
        final boolean fit = (vertical && (!hasHeightSize || height < heightSize))
                || (!vertical && (!hasWidthSize || width < widthSize));

        ViewCompat.setOverScrollMode(view, fit ? ViewCompat.OVER_SCROLL_NEVER : ViewCompat.OVER_SCROLL_ALWAYS);
    }
}

private void logMeasureWarning(int child) {
    if (BuildConfig.DEBUG) {
        Log.w("MyLinearLayoutManager", "Can't measure child #" + child + ", previously used dimensions will be reused." +
                "To remove this message either use #setChildSize() method or don't run RecyclerView animations");
    }
}

private void initChildDimensions(int width, int height, boolean vertical) {
    if (childDimensions[CHILD_WIDTH] != 0 || childDimensions[CHILD_HEIGHT] != 0) {
        // already initialized, skipping
        return;
    }
    if (vertical) {
        childDimensions[CHILD_WIDTH] = width;
        childDimensions[CHILD_HEIGHT] = childSize;
    } else {
        childDimensions[CHILD_WIDTH] = childSize;
        childDimensions[CHILD_HEIGHT] = height;
    }
}

@Override
public void setOrientation(int orientation) {
    // might be called before the constructor of this class is called
    //noinspection ConstantConditions
    if (childDimensions != null) {
        if (getOrientation() != orientation) {
            childDimensions[CHILD_WIDTH] = 0;
            childDimensions[CHILD_HEIGHT] = 0;
        }
    }
    super.setOrientation(orientation);
}

public void clearChildSize() {
    hasChildSize = false;
    setChildSize(DEFAULT_CHILD_SIZE);
}

public void setChildSize(int childSize) {
    hasChildSize = true;
    if (this.childSize != childSize) {
        this.childSize = childSize;
        requestLayout();
    }
}

private void measureChild(RecyclerView.Recycler recycler, int position, int widthSize, int heightSize, int[] dimensions) {
    final View child;
    try {
        child = recycler.getViewForPosition(position);
    } catch (IndexOutOfBoundsException e) {
        if (BuildConfig.DEBUG) {
            Log.w("MyLinearLayoutManager", "MyLinearLayoutManager doesn't work well with animations. Consider switching them off", e);
        }
        return;
    }

    final RecyclerView.LayoutParams p = (RecyclerView.LayoutParams) child.getLayoutParams();

    final int hPadding = getPaddingLeft() + getPaddingRight();
    final int vPadding = getPaddingTop() + getPaddingBottom();

    final int hMargin = p.leftMargin + p.rightMargin;
    final int vMargin = p.topMargin + p.bottomMargin;

    // we must make insets dirty in order calculateItemDecorationsForChild to work
    makeInsetsDirty(p);
    // this method should be called before any getXxxDecorationXxx() methods
    calculateItemDecorationsForChild(child, tmpRect);

    final int hDecoration = getRightDecorationWidth(child) + getLeftDecorationWidth(child);
    final int vDecoration = getTopDecorationHeight(child) + getBottomDecorationHeight(child);

    final int childWidthSpec = getChildMeasureSpec(widthSize, hPadding + hMargin + hDecoration, p.width, canScrollHorizontally());
    final int childHeightSpec = getChildMeasureSpec(heightSize, vPadding + vMargin + vDecoration, p.height, canScrollVertically());

    child.measure(childWidthSpec, childHeightSpec);

    dimensions[CHILD_WIDTH] = getDecoratedMeasuredWidth(child) + p.leftMargin + p.rightMargin;
    dimensions[CHILD_HEIGHT] = getDecoratedMeasuredHeight(child) + p.bottomMargin + p.topMargin;

    // as view is recycled let's not keep old measured values
    makeInsetsDirty(p);
    recycler.recycleView(child);
}

private static void makeInsetsDirty(RecyclerView.LayoutParams p) {
    if (!canMakeInsetsDirty) {
        return;
    }
    try {
        if (insetsDirtyField == null) {
            insetsDirtyField = RecyclerView.LayoutParams.class.getDeclaredField("mInsetsDirty");
            insetsDirtyField.setAccessible(true);
        }
        insetsDirtyField.set(p, true);
    } catch (NoSuchFieldException e) {
        onMakeInsertDirtyFailed();
    } catch (IllegalAccessException e) {
        onMakeInsertDirtyFailed();
    }
}

private static void onMakeInsertDirtyFailed() {
    canMakeInsetsDirty = false;
    if (BuildConfig.DEBUG) {
        Log.w("MyLinearLayoutManager", "Can't make LayoutParams insets dirty, decorations measurements might be incorrect");
    }
}
}

Equivalent VB keyword for 'break'

In case you're inside a Sub of Function and you want to exit it, you can use :

Exit Sub

or

Exit Function 

Use jQuery to change a second select list based on the first select list option

_x000D_
_x000D_
$("#select1").change(function() {_x000D_
  if ($(this).data('options') === undefined) {_x000D_
    /*Taking an array of all options-2 and kind of embedding it on the select1*/_x000D_
    $(this).data('options', $('#select2 option').clone());_x000D_
  }_x000D_
  var id = $(this).val();_x000D_
  var options = $(this).data('options').filter('[value=' + id + ']');_x000D_
  $('#select2').html(options);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>_x000D_
<select name="select1" id="select1">_x000D_
  <option value="1">Fruit</option>_x000D_
  <option value="2">Animal</option>_x000D_
  <option value="3">Bird</option>_x000D_
  <option value="4">Car</option>_x000D_
</select>_x000D_
_x000D_
_x000D_
<select name="select2" id="select2">_x000D_
  <option value="1">Banana</option>_x000D_
  <option value="1">Apple</option>_x000D_
  <option value="1">Orange</option>_x000D_
  <option value="2">Wolf</option>_x000D_
  <option value="2">Fox</option>_x000D_
  <option value="2">Bear</option>_x000D_
  <option value="3">Eagle</option>_x000D_
  <option value="3">Hawk</option>_x000D_
  <option value="4">BWM<option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

Using jQuery data() to store data

I guess hiding elements doesn't work cross-browser(2012), I have'nt tested it myself.

Changing variable names with Python for loops

It looks like you want to use a list instead:

group=[]
for i in range(3):
     group[i]=self.getGroup(selected, header+i)

make a header full screen (width) css

Just set the header width to be 100vw to make it full screen width and set the header height to be 100vh to make it full screen height

jQuery keypress() event not firing?

With jQuery, I've done it this way:

function checkKey(e){
     switch (e.keyCode) {
        case 40:
            alert('down');
            break;
        case 38:
            alert('up');
            break;
        case 37:
            alert('left');
            break;
        case 39:
            alert('right');
            break;
        default:
            alert('???');  
            }      
}

if ($.browser.mozilla) {
    $(document).keypress (checkKey);
} else {
    $(document).keydown (checkKey);
}

Also, try these plugins, which looks like they do all that work for you:

http://www.openjs.com/scripts/events/keyboard_shortcuts

http://www.webappers.com/2008/07/31/bind-a-hot-key-combination-with-jquery-hotkeys/

Converting integer to digit list

By looping it can be done the following way :)

num1= int(input('Enter the number'))
sum1 = num1 #making a alt int to store the value of the orginal so it wont be affected
y = [] #making a list 
while True:
    if(sum1==0):#checking if the number is not zero so it can break if it is
        break
    d = sum1%10 #last number of your integer is saved in d
    sum1 = int(sum1/10) #integer is now with out the last number ie.4320/10 become 432
    y.append(d) # appending the last number in the first place

y.reverse()#as last is in first , reversing the number to orginal form
print(y)

Answer becomes

Enter the number2342
[2, 3, 4, 2]

Rendering an array.map() in React

let durationBody = duration.map((item, i) => {
      return (
        <option key={i} value={item}>
          {item}
        </option>
      );
    });

Font scaling based on width of container

100% is relative to the base font size, which, if you haven't set it, would be the browser's user-agent default.

To get the effect you're after, I would use a piece of JavaScript code to adjust the base font size relative to the window dimensions.

CSS: stretching background image to 100% width and height of screen?

You need to set the height of html to 100%

body {
    background-image:url("../images/myImage.jpg");
    background-repeat: no-repeat;
    background-size: 100% 100%;
}
html {
    height: 100%
}

http://jsfiddle.net/8XUjP/

How can I print out C++ map values?

for(map<string, pair<string,string> >::const_iterator it = myMap.begin();
    it != myMap.end(); ++it)
{
    std::cout << it->first << " " << it->second.first << " " << it->second.second << "\n";
}

In C++11, you don't need to spell out map<string, pair<string,string> >::const_iterator. You can use auto

for(auto it = myMap.cbegin(); it != myMap.cend(); ++it)
{
    std::cout << it->first << " " << it->second.first << " " << it->second.second << "\n";
}

Note the use of cbegin() and cend() functions.

Easier still, you can use the range-based for loop:

for(auto elem : myMap)
{
   std::cout << elem.first << " " << elem.second.first << " " << elem.second.second << "\n";
}

Creating a data frame from two vectors using cbind

Vectors and matrices can only be of a single type and cbind and rbind on vectors will give matrices. In these cases, the numeric values will be promoted to character values since that type will hold all the values.

(Note that in your rbind example, the promotion happens within the c call:

> c(10, "[]", "[[1,2]]")
[1] "10"      "[]"      "[[1,2]]"

If you want a rectangular structure where the columns can be different types, you want a data.frame. Any of the following should get you what you want:

> x = data.frame(v1=c(10, 20), v2=c("[]", "[]"), v3=c("[[1,2]]","[[1,3]]"))
> x
  v1 v2      v3
1 10 [] [[1,2]]
2 20 [] [[1,3]]
> str(x)
'data.frame':   2 obs. of  3 variables:
 $ v1: num  10 20
 $ v2: Factor w/ 1 level "[]": 1 1
 $ v3: Factor w/ 2 levels "[[1,2]]","[[1,3]]": 1 2

or (using specifically the data.frame version of cbind)

> x = cbind.data.frame(c(10, 20), c("[]", "[]"), c("[[1,2]]","[[1,3]]"))
> x
  c(10, 20) c("[]", "[]") c("[[1,2]]", "[[1,3]]")
1        10            []                 [[1,2]]
2        20            []                 [[1,3]]
> str(x)
'data.frame':   2 obs. of  3 variables:
 $ c(10, 20)              : num  10 20
 $ c("[]", "[]")          : Factor w/ 1 level "[]": 1 1
 $ c("[[1,2]]", "[[1,3]]"): Factor w/ 2 levels "[[1,2]]","[[1,3]]": 1 2

or (using cbind, but making the first a data.frame so that it combines as data.frames do):

> x = cbind(data.frame(c(10, 20)), c("[]", "[]"), c("[[1,2]]","[[1,3]]"))
> x
  c.10..20. c("[]", "[]") c("[[1,2]]", "[[1,3]]")
1        10            []                 [[1,2]]
2        20            []                 [[1,3]]
> str(x)
'data.frame':   2 obs. of  3 variables:
 $ c.10..20.              : num  10 20
 $ c("[]", "[]")          : Factor w/ 1 level "[]": 1 1
 $ c("[[1,2]]", "[[1,3]]"): Factor w/ 2 levels "[[1,2]]","[[1,3]]": 1 2

Simpler way to create dictionary of separate variables?

As unwind said, this isn't really something you do in Python - variables are actually name mappings to objects.

However, here's one way to try and do it:

 >>> a = 1
 >>> for k, v in list(locals().iteritems()):
         if v is a:
             a_as_str = k
 >>> a_as_str
 a
 >>> type(a_as_str)
 'str'

How to "inverse match" with regex?

What language are you using? The capabilities and syntax of the regex implementation matter for this.

You could use look-ahead. Using python as an example

import re

not_andrea = re.compile('(?!Andrea)\w{6}', re.IGNORECASE)

To break that down:

(?!Andrea) means 'match if the next 6 characters are not "Andrea"'; if so then

\w means a "word character" - alphanumeric characters. This is equivalent to the class [a-zA-Z0-9_]

\w{6} means exactly 6 word characters.

re.IGNORECASE means that you will exclude "Andrea", "andrea", "ANDREA" ...

Another way is to use your program logic - use all lines not matching Andrea and put them through a second regex to check for 6 characters. Or first check for at least 6 word characters, and then check that it does not match Andrea.

What .NET collection provides the fastest search

If you're using .Net 3.5, you can make cleaner code using:

foreach (Record item in LookupCollection.Intersect(LargeCollection))
{
  //dostuff
}

I don't have .Net 3.5 here and so this is untested. It relies on an extension method. Not that LookupCollection.Intersect(LargeCollection) is probably not the same as LargeCollection.Intersect(LookupCollection) ... the latter is probably much slower.

This assumes LookupCollection is a HashSet