Programs & Examples On #Type theory

Finding the median of an unsorted array

You can use the Median of Medians algorithm to find median of an unsorted array in linear time.

How to find a user's home directory on linux or unix?

For UNIX-Like systems you might want to execute "echo ~username" using the shell (so use Runtime.exec() to run {"/bin/sh", "-c", "echo ~username"}).

iOS Safari – How to disable overscroll but allow scrollable divs to scroll normally?

Using Tyler Dodge's excellent answer kept lagging on my iPad, so I added some throttling code, now it's quite smooth. There is some minimal skipping sometimes while scrolling.

// Uses document because document will be topmost level in bubbling
$(document).on('touchmove',function(e){
  e.preventDefault();
});

var scrolling = false;

// Uses body because jquery on events are called off of the element they are
// added to, so bubbling would not work if we used document instead.
$('body').on('touchstart','.scrollable',function(e) {

    // Only execute the below code once at a time
    if (!scrolling) {
        scrolling = true;   
        if (e.currentTarget.scrollTop === 0) {
          e.currentTarget.scrollTop = 1;
        } else if (e.currentTarget.scrollHeight === e.currentTarget.scrollTop + e.currentTarget.offsetHeight) {
          e.currentTarget.scrollTop -= 1;
        }
        scrolling = false;
    }
});

// Prevents preventDefault from being called on document if it sees a scrollable div
$('body').on('touchmove','.scrollable',function(e) {
  e.stopPropagation();
});

Also, adding the following CSS fixes some rendering glitches (source):

.scrollable {
    overflow: auto;
    overflow-x: hidden;
    -webkit-overflow-scrolling: touch;
}
.scrollable * {
    -webkit-transform: translate3d(0,0,0);
}

How to properly express JPQL "join fetch" with "where" clause as JPA 2 CriteriaQuery?

I will show visually the problem, using the great example from James answer and adding the alternative solution.

When you do the follow query, without the FETCH:

Select e from Employee e 
join e.phones p 
where p.areaCode = '613'

You will have the follow results from Employee as you expected:

EmployeeId EmployeeName PhoneId PhoneAreaCode
1 James 5 613
1 James 6 416

But when you add the FETCH word on JOIN, this is what happens:

EmployeeId EmployeeName PhoneId PhoneAreaCode
1 James 5 613

The generated SQL is the same for the two queries, but the Hibernate removes on memory the 416 register when you use WHERE on the FETCH join.

So, to bring all phones and apply the WHERE correctly, you need to have two JOINs: one for the WHERE and another for the FETCH. Like:

Select e from Employee e 
join e.phones p 
join fetch e.phones      //no alias, to not commit the mistake
where p.areaCode = '613'

How to change button text in Swift Xcode 6?

swift 4 work as well as 3

libero.setTitle("---", for: .normal)

where libero is a uibutton

How to properly -filter multiple strings in a PowerShell copy script

Get-ChildItem $originalPath\* -Include @("*.gif", "*.jpg", "*.xls*", "*.doc*", "*.pdf*", "*.wav*", "*.ppt")

jQuery: Adding two attributes via the .attr(); method

the proper way is:

.attr({target:'nw', title:'Opens in a new window'})

In C#, why is String a reference type that behaves like a value type?

Strings aren't value types since they can be huge, and need to be stored on the heap. Value types are (in all implementations of the CLR as of yet) stored on the stack. Stack allocating strings would break all sorts of things: the stack is only 1MB for 32-bit and 4MB for 64-bit, you'd have to box each string, incurring a copy penalty, you couldn't intern strings, and memory usage would balloon, etc...

(Edit: Added clarification about value type storage being an implementation detail, which leads to this situation where we have a type with value sematics not inheriting from System.ValueType. Thanks Ben.)

Controlling execution order of unit tests in Visual Studio

I'll not address the order of tests, sorry. Others already did it. Also, if you know about "ordered tests" - well, this is MS VS's response to the problem. I know that those ordered-tests are no fun. But they thought it will be "it" and there's really nothing more in MSTest about that.

I write about one of your assumptions:

as there is no way to tear down the static class.

Unless your static class represents some process-wide external state external to your code (like ie. the state of an unmanaged native DLL library thats P/Invoked by the rest of your code), your assumption that there is no way is not true.

If your static class refers to this, then sorry, you are perfectly right, the rest of this anwer is irrelevant. Still, as you didn't say that, I assume your code is "managed".

Think and check the AppDomain thingy. Rarely it is needed, but this is exactly the case when you'd probably like to use them.

You can create a new AppDomain, and instantiate the test there, and run the test method there. Static data used by managed code will isolated there and upon completion, you will be able to unload the AppDomain and all the data, statics included, will evaporate. Then, next test would initialize another appdomain, and so on.

This will work unless you have external state that you must track. AppDomains only isolate the managed memory. Any native DLL will still be load per-process and their state will be shared by all AppDomains.

Also, creating/tearing down the appdomains will, well, slow down the tests. Also, you may have problems with assembly resolution in the child appdomain, but they are solvable with reasonable amount of reusable code.

Also, you may have small problems with passing test data to - and back from - the child AppDomain. Objects passed will either have to be serializable in some way, or be MarshalByRef or etc. Talking cross-domain is almost like IPC.

However, take care here, it will be 100% managed talking. If you take some extra care and add a little work to the AppDomain setup, you will be able to even pass delegates and run them in the target domain. Then, instead of making some hairy cross-domain setup, you can wrap your tests with to something like:

void testmethod()
{
    TestAppDomainHelper.Run( () =>
    {
        // your test code
    });
}

or even

[IsolatedAppDomain]
void testmethod()
{
    // your test code
}

if your test framework supports creating such wrappers/extensions. After some initial research and work, using them is almost trivial.

The default XML namespace of the project must be the MSBuild XML namespace

if the project is not a big ,

1- change the name of folder project

2- make a new project with the same project (before renaming)

3- add existing files from the old project to the new project (totally same , same folders , same names , ...)

4- open the the new project file (as xml ) and the old project

5- copy the new project file (xml content ) and paste it in the old project file

6- delete the old project

7- rename the old folder project to old name

Run JavaScript code on window close or page refresh?

Ok, I found a working solution for this, it consists of using the beforeunload event and then making the handler return null. This executes the wanted code without a confirmation box popping-up. It goes something like this:

window.onbeforeunload = closingCode;
function closingCode(){
   // do something...
   return null;
}

Using COALESCE to handle NULL values in PostgreSQL

If you're using 0 and an empty string '' and null to designate undefined you've got a data problem. Just update the columns and fix your schema.

UPDATE pt.incentive_channel
SET   pt.incentive_marketing = NULL
WHERE pt.incentive_marketing = '';

UPDATE pt.incentive_channel
SET   pt.incentive_advertising = NULL
WHERE pt.incentive_marketing = '';

UPDATE pt.incentive_channel
SET   pt.incentive_channel = NULL
WHERE pt.incentive_marketing = '';

This will make joining and selecting substantially easier moving forward.

Including an anchor tag in an ASP.NET MVC Html.ActionLink

My solution will work if you apply the ActionFilter to the Subcategory action method, as long as you always want to redirect the user to the same bookmark:

http://spikehd.blogspot.com/2012/01/mvc3-redirect-action-to-html-bookmark.html

It modifies the HTML buffer and outputs a small piece of javascript to instruct the browser to append the bookmark.

You could modify the javascript to manually scroll, instead of using a bookmark in the URL, of course!

Hope it helps :)

How to return an array from an AJAX call?

well, I know that I'm a bit too late, but I tried all of your solutions and with no success! So here is how I managed to do it. First of all, I'm working on an Asp.Net MVC project. The Only thing I changed was in my c# method getInvitation:

public ActionResult getInvitation (Guid s_ID)
{
    using (var db = new cRM_Verband_BWEntities())
    {
        var listSidsMit = (from data in db.TERMINEINLADUNGEN where data.RECID_KOMMUNIKATIONEN == s_ID select data.RECID_MITARBEITER.ToString()).ToArray();
        return Json(listSidsMit);
    }
}

SuccessFunction in JS :

function successFunction(result) {
    console.log(result);
}

I changed the Method Type from string[] to ActionResult and of course at the end I wrapped my array listSidsMit with the Json method.

Why does git revert complain about a missing -m option?

By default git revert refuses to revert a merge commit as what that actually means is ambiguous. I presume that your HEAD is in fact a merge commit.

If you want to revert the merge commit, you have to specify which parent of the merge you want to consider to be the main trunk, i.e. what you want to revert to.

Often this will be parent number one, for example if you were on master and did git merge unwanted and then decided to revert the merge of unwanted. The first parent would be your pre-merge master branch and the second parent would be the tip of unwanted.

In this case you could do:

git revert -m 1 HEAD

Disable back button in android

if you are using FragmentActivity. then do like this

first call This inside your Fragment.

public void callParentMethod(){
    getActivity().onBackPressed();
}

and then Call onBackPressed method in side your parent FragmentActivity class.

@Override
public void onBackPressed() {
  //super.onBackPressed();
  //create a dialog to ask yes no question whether or not the user wants to exit
  ...
}

How do I give PHP write access to a directory?

1st Figure out which user is owning httpd process using the following command

ps aux | grep httpd

you will get a several line response like this:

phpuser   17121  0.0  0.2 414060  7928 ?        SN   03:49   0:00 /usr/sbin/httpd

Here 1st column shows the user name. So now you know the user who is trying to write files, which is in this case phpuser You can now go ahead and set the permission for directory where your php script is trying to write something:

sudo chown phpuser:phpuser PhpCanWriteHere
sudo chmod 755 PhpCanWriteHere

Integer.valueOf() vs. Integer.parseInt()

Actually, valueOf uses parseInt internally. The difference is parseInt returns an int primitive while valueOf returns an Integer object. Consider from the Integer.class source:

public static int parseInt(String s) throws NumberFormatException {
    return parseInt(s, 10);
}

public static Integer valueOf(String s, int radix) throws NumberFormatException {
    return Integer.valueOf(parseInt(s, radix));
}

public static Integer valueOf(String s) throws NumberFormatException {
    return Integer.valueOf(parseInt(s, 10));
}

As for parsing with a comma, I'm not familiar with one. I would sanitize them.

int million = Integer.parseInt("1,000,000".replace(",", ""));

How to make a background 20% transparent on Android

There is an XML value alpha that takes double values.

Since API 11+ the range is from 0f to 1f (inclusive), 0f being transparent and 1f being opaque:

  • android:alpha="0.0" thats invisible

  • android:alpha="0.5" see-through

  • android:alpha="1.0" full visible

That's how it works.

#1273 – Unknown collation: ‘utf8mb4_unicode_520_ci’

I just opened the dump.sql file in Notepad++ and hit CTRL+H to find and replace the string "utf8mb4_0900_ai_ci" and replaced it with "utf8mb4_general_ci". Source link https://www.freakyjolly.com/resolved-when-i-faced-1273-unknown-collation-utf8mb4_0900_ai_ci-error/

Creating stored procedure and SQLite?

Yet, it is possible to fake it using a dedicated table, named for your fake-sp, with an AFTER INSERT trigger. The dedicated table rows contain the parameters for your fake sp, and if it needs to return results you can have a second (poss. temp) table (with name related to the fake-sp) to contain those results. It would require two queries: first to INSERT data into the fake-sp-trigger-table, and the second to SELECT from the fake-sp-results-table, which could be empty, or have a message-field if something went wrong.

How to join multiple lines of file names into one with custom delimiter?

You can use chomp to merge multiple line in single line:

perl -e 'while (<>) { if (/\$/ ) { chomp; } print ;}' bad0 >test

put line break condition in if statement.It can be special character or any delimiter.

How to get all Windows service names starting with a common word?

Save it as a .ps1 file and then execute

powershell -file "path\to your\start stop nation service command file.ps1"

Subversion stuck due to "previous operation has not finished"?

I have also stuck with the same issue I have tried blow:

1.Try kill the process related to svn i.e. TSVNCache.exe and TortoiseProc 2.Reverting the unversioned files and deletion of same, which I have in svn . 3.cleanup using command prompt "svn cleanup"

and finally when restarted the desktop it worked for me , So for restart of system worked for me

Go build: "Cannot find package" (even though GOPATH is set)

In the recent go versions from 1.14 onwards, we have to do go mod vendor before building or running, since by default go appends -mod=vendor to the go commands. So after doing go mod vendor, if we try to build, we won't face this issue.

Simple tool to 'accept theirs' or 'accept mine' on a whole file using git

Based on kynan's answer, here are the same aliases, modified so they can handle spaces and initial dashes in filenames:

accept-ours = "!f() { [ -z \"$@\" ] && set - '.'; git checkout --ours -- \"$@\"; git add -u -- \"$@\"; }; f"
accept-theirs = "!f() { [ -z \"$@\" ] && set - '.'; git checkout --theirs -- \"$@\"; git add -u -- \"$@\"; }; f"

Using Keras & Tensorflow with AMD GPU

I'm writing an OpenCL 1.2 backend for Tensorflow at https://github.com/hughperkins/tensorflow-cl

This fork of tensorflow for OpenCL has the following characteristics:

  • it targets any/all OpenCL 1.2 devices. It doesnt need OpenCL 2.0, doesnt need SPIR-V, or SPIR. Doesnt need Shared Virtual Memory. And so on ...
  • it's based on an underlying library called 'cuda-on-cl', https://github.com/hughperkins/cuda-on-cl
    • cuda-on-cl targets to be able to take any NVIDIA® CUDA™ soure-code, and compile it for OpenCL 1.2 devices. It's a very general goal, and a very general compiler
  • for now, the following functionalities are implemented:
  • it is developed on Ubuntu 16.04 (using Intel HD5500, and NVIDIA GPUs) and Mac Sierra (using Intel HD 530, and Radeon Pro 450)

This is not the only OpenCL fork of Tensorflow available. There is also a fork being developed by Codeplay https://www.codeplay.com , using Computecpp, https://www.codeplay.com/products/computesuite/computecpp Their fork has stronger requirements than my own, as far as I know, in terms of which specific GPU devices it works on. You would need to check the Platform Support Notes (at the bottom of hte computecpp page), to determine whether your device is supported. The codeplay fork is actually an official Google fork, which is here: https://github.com/benoitsteiner/tensorflow-opencl

How to see query history in SQL Server Management Studio

A slightly out-of-the-box method would be to script up a solution in AutoHotKey. I use this, and it's not perfect, but works and is free. Essentially, this script assigns a hotkey to CTRL+SHIFT+R which will copy the selected SQL in SSMS (CTRL+C), save off a datestamp SQL file, and then execute the highlighted query (F5). If you aren't used to AHK scripts, the leading semicolon is a comment.

;CTRL+SHIFT+R to run a query that is first saved off
^+r::
;Copy
Send, ^c
; Set variables
EnvGet, HomeDir, USERPROFILE
FormatTime, DateString,,yyyyMMdd
FormatTime, TimeString,,hhmmss
; Make a spot to save the clipboard
FileCreateDir %HomeDir%\Documents\sqlhist\%DateString%
FileAppend, %Clipboard%, %HomeDir%\Documents\sqlhist\%DateString%\%TimeString%.sql
; execute the query
Send, {f5}
Return

The biggest limitations are that this script won't work if you click "Execute" rather than use the keyboard shortcut, and this script won't save off the whole file - just the selected text. But, you could always modify the script to execute the query, and then select all (CTRL+A) before the copy/save.

Using a modern editor with "find in files" features will let you search your SQL history. You could even get fancy and scrape your files into a SQLite3 database to query your queries.

how to set "camera position" for 3d plots using python/matplotlib?

By "camera position," it sounds like you want to adjust the elevation and the azimuth angle that you use to view the 3D plot. You can set this with ax.view_init. I've used the below script to first create the plot, then I determined a good elevation, or elev, from which to view my plot. I then adjusted the azimuth angle, or azim, to vary the full 360deg around my plot, saving the figure at each instance (and noting which azimuth angle as I saved the plot). For a more complicated camera pan, you can adjust both the elevation and angle to achieve the desired effect.

    from mpl_toolkits.mplot3d import Axes3D
    ax = Axes3D(fig)
    ax.scatter(xx,yy,zz, marker='o', s=20, c="goldenrod", alpha=0.6)
    for ii in xrange(0,360,1):
        ax.view_init(elev=10., azim=ii)
        savefig("movie%d.png" % ii)

Passing $_POST values with cURL

$query_string = "";

if ($_POST) {
    $kv = array();
    foreach ($_POST as $key => $value) {
        $kv[] = stripslashes($key) . "=" . stripslashes($value);
    }
    $query_string = join("&", $kv);
}

if (!function_exists('curl_init')){
    die('Sorry cURL is not installed!');
}

$url = 'https://www.abcd.com/servlet/';

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, count($kv));
curl_setopt($ch, CURLOPT_POSTFIELDS, $query_string);

curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, FALSE);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);

$result = curl_exec($ch);

curl_close($ch);

Bootstrap 3 unable to display glyphicon properly

For me placing my fonts folder as per location specified in bootstrap.css solved the problem

Mostly its fonts folder should be in parent directory of bootstrap.css file .

I faced this problem , and researching many answers , if anyone still in 2015 faces this problem then its either a CSS problem , or location mismatch for files .

The bug has already been solved by bootstrap

"inappropriate ioctl for device"

"files" in *nix type systems are very much an abstract concept.

They can be areas on disk organized by a file system, but they could equally well be a network connection, a bit of shared memory, the buffer output from another process, a screen or a keyboard.

In order for perl to be really useful it mirrors this model very closely, and does not treat files by emulating a magnetic tape as many 4gls do.

So it tried an "IOCTL" operation 'open for write' on a file handle which does not allow write operations which is an inappropriate IOCTL operation for that device/file.

The easiest thing to do is stick an " or die 'Cannot open $myfile' statement at the end of you open and you can choose your own meaningful message.

Float a div right, without impacting on design

Try setting its position to absolute. That takes it out of the flow of the document.

jQuery .slideRight effect

If you're willing to include the jQuery UI library, in addition to jQuery itself, then you can simply use hide(), with additional arguments, as follows:

$(document).ready(
    function(){
        $('#slider').click(
            function(){
                $(this).hide('slide',{direction:'right'},1000);

            });
    });

JS Fiddle demo.


Without using jQuery UI, you could achieve your aim just using animate():

$(document).ready(
    function(){
        $('#slider').click(
            function(){
                $(this)
                    .animate(
                        {
                            'margin-left':'1000px'
                            // to move it towards the right and, probably, off-screen.
                        },1000,
                        function(){
                            $(this).slideUp('fast');
                            // once it's finished moving to the right, just 
                            // removes the the element from the display, you could use
                            // `remove()` instead, or whatever.
                        }
                        );

            });
    });

JS Fiddle demo

If you do choose to use jQuery UI, then I'd recommend linking to the Google-hosted code, at: https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.6/jquery-ui.min.js

How to assign the output of a command to a Makefile variable

Here's a bit more complicated example with piping and variable assignment inside recipe:

getpodname:
    # Getting pod name
    @eval $$(minikube docker-env) ;\
    $(eval PODNAME=$(shell sh -c "kubectl get pods | grep profile-posts-api | grep Running" | awk '{print $$1}'))
    echo $(PODNAME)

How to get the browser to navigate to URL in JavaScript

Try these:

  1. window.location.href = 'http://www.google.com';
  2. window.location.assign("http://www.w3schools.com");
  3. window.location = 'http://www.google.com';

For more see this link: other ways to reload the page with JavaScript

Get an object's class name at runtime

Solution using Decorators that survives minification/uglification

We use code generation to decorate our Entity classes with metadata like so:

@name('Customer')
export class Customer {
  public custId: string;
  public name: string;
}

Then consume with the following helper:

export const nameKey = Symbol('name');

/**
 * To perserve class name though mangling.
 * @example
 * @name('Customer')
 * class Customer {}
 * @param className
 */
export function name(className: string): ClassDecorator {
  return (Reflect as any).metadata(nameKey, className);
}

/**
 * @example
 * const type = Customer;
 * getName(type); // 'Customer'
 * @param type
 */
export function getName(type: Function): string {
  return (Reflect as any).getMetadata(nameKey, type);
}

/**
 * @example
 * const instance = new Customer();
 * getInstanceName(instance); // 'Customer'
 * @param instance
 */
export function getInstanceName(instance: Object): string {
  return (Reflect as any).getMetadata(nameKey, instance.constructor);
}

Extra info:

  • You may need to install reflect-metadata
  • reflect-metadata is pollyfill written by members ot TypeScript for the proposed ES7 Reflection API
  • The proposal for decorators in JS can be tracked here

How do I add a ToolTip to a control?

Just subscribe to the control's ToolTipTextNeeded event, and return e.TooltipText, much simpler.

How do I create my own URL protocol? (e.g. so://...)

This is different for each browser, in IE and windows you need to create what they call a pluggable protocol handler.

The basic steps are as follows:

  1. Implement the IInternetProtocol interface.
  2. Implement the IInternetProtocolRoot interface.
  3. Implement the IClassFactory interface.
  4. Optional. Implement the IInternetProtocolInfo interface. Support for the HTTP protocol is provided by the transaction handler.
  5. If IInternetProtocolInfo is implemented, provide support for PARSE_SECURITY_URL and PARSE_SECURITY_DOMAIN so the URL security zone manager can handle the security properly. Write the code for your protocol handler.
  6. Provide support for BINDF_NO_UI and BINDF_SILENTOPERATION.
  7. Add a subkey for your protocol handler in the registry under HKEY_CLASSES_ROOT\PROTOCOLS\Handler.
  8. Create a string value, CLSID, under the subkey and set the string to the CLSID of your protocol handler.

See About Asynchronous Pluggable Protocols on MSDN for more details on the windows side. There is also a sample in the windows SDK.

A quick google also showed this article on codeproject: http://www.codeproject.com/KB/IP/DataProtocol.aspx.

Finally, as a security guy I have to point out that this code needs to be battle hardened. It's at a high risk because to do it reliably you can't do it in managed code and have to do it in C++ (I suppose you could use VB6). You should consider whether you really need to do this and if you do, design it carefully and code it securely. An attacker can easily control the content that gets passed to you by simply including a link on a page. For example if you have a simple buffer overflow then nobody better do this: <a href="custom:foooo{insert long string for buffer overflow here}"> Click me for free porn</a>

Strongly consider using strsafe and the new secure CRT methods included in the VC8 and above compilers. See http://blogs.msdn.com/michael_howard/archive/2006/02/27/540123.aspx if you have no idea what I'm talking about.

Python element-wise tuple operations like sum

Sort of combined the first two answers, with a tweak to ironfroggy's code so that it returns a tuple:

import operator

class stuple(tuple):
    def __add__(self, other):
        return self.__class__(map(operator.add, self, other))
        # obviously leaving out checking lengths

>>> a = stuple([1,2,3])
>>> b = stuple([3,2,1])
>>> a + b
(4, 4, 4)

Note: using self.__class__ instead of stuple to ease subclassing.

How to delete items from a dictionary while iterating over it?

With python3, iterate on dic.keys() will raise the dictionary size error. You can use this alternative way:

Tested with python3, it works fine and the Error "dictionary changed size during iteration" is not raised:

my_dic = { 1:10, 2:20, 3:30 }
# Is important here to cast because ".keys()" method returns a dict_keys object.
key_list = list( my_dic.keys() )

# Iterate on the list:
for k in key_list:
    print(key_list)
    print(my_dic)
    del( my_dic[k] )


print( my_dic )
# {}

how to create a cookie and add to http response from inside my service layer?

A cookie is a object with key value pair to store information related to the customer. Main objective is to personalize the customer's experience.

An utility method can be created like

private Cookie createCookie(String cookieName, String cookieValue) {
    Cookie cookie = new Cookie(cookieName, cookieValue);
    cookie.setPath("/");
    cookie.setMaxAge(MAX_AGE_SECONDS);
    cookie.setHttpOnly(true);
    cookie.setSecure(true);
    return cookie;
}

If storing important information then we should alsways put setHttpOnly so that the cookie cannot be accessed/modified via javascript. setSecure is applicable if you are want cookies to be accessed only over https protocol.

using above utility method you can add cookies to response as

Cookie cookie = createCookie("name","value");
response.addCookie(cookie);

How to normalize a signal to zero mean and unit variance?

If you have the stats toolbox, then you can compute

Z = zscore(S);

Synchronous Requests in Node.js

Aredridels answer is relatively good (upvoted it), but I think it lacks the loop equivalent. This should help you:

Sync code equivalent:

while (condition) {
  var data = request(url);
  <math here>
}
return result;

Async code for serial execution:

function continueLoop() {
  if (!condition) return cb(result);
  request(url, function(err, res, body) {
    <math here>
    continueLoop()
  })
}
continueLoop()

"element.dispatchEvent is not a function" js error caught in firebug of FF3.0

After all the Jquery script tag's add

<script>jQuery.noConflict();</script>

to avoid the conflict between Prototype and Jquery.

How to import cv2 in python3?

The best way is to create a virtual env. first and then do pip install , everything will work fine

Adding POST parameters before submit

You can do a form.serializeArray(), then add name-value pairs before posting:

var form = $(this).closest('form');

form = form.serializeArray();

form = form.concat([
    {name: "customer_id", value: window.username},
    {name: "post_action", value: "Update Information"}
]);

$.post('/change-user-details', form, function(d) {
    if (d.error) {
        alert("There was a problem updating your user details")
    } 
});

Match two strings in one line with grep

You should have grep like this:

$ grep 'string1' file | grep 'string2'

Shortcuts in Objective-C to concatenate NSStrings

Try stringWithFormat:

NSString *myString = [NSString stringWithFormat:@"%@ %@ %@ %d", "The", "Answer", "Is", 42];

ASP.NET MVC Global Variables

public static class GlobalVariables
{
    // readonly variable
    public static string Foo
    {
        get
        {
            return "foo";
        }
    }

    // read-write variable
    public static string Bar
    {
        get
        {
            return HttpContext.Current.Application["Bar"] as string;
        }
        set
        {
            HttpContext.Current.Application["Bar"] = value;
        }
    }
}

Debugging iframes with Chrome developer tools

In my fairly complex scenario the accepted answer for how to do this in Chrome doesn't work for me. You may want to try the Firefox debugger instead (part of the Firefox developer tools), which shows all of the 'Sources', including those that are part of an iFrame

PHP form send email to multiple recipients

You can add your receipients to $email_to variable separating them with comma (,). Or you can add new fields to headers, namely CC: or BCC: and put your receipients there. BCC is most recommended

How to make nginx to listen to server_name:port

The server_namedocs directive is used to identify virtual hosts, they're not used to set the binding.

netstat tells you that nginx listens on 0.0.0.0:80 which means that it will accept connections from any IP.

If you want to change the IP nginx binds on, you have to change the listendocs rule.
So, if you want to set nginx to bind to localhost, you'd change that to:

listen 127.0.0.1:80;

In this way, requests that are not coming from localhost are discarded (they don't even hit nginx).

Writing an Excel file in EPPlus

It's best if you worked with DataSets and/or DataTables. Once you have that, ideally straight from your stored procedure with proper column names for headers, you can use the following method:

ws.Cells.LoadFromDataTable(<DATATABLE HERE>, true, OfficeOpenXml.Table.TableStyles.Light8);

.. which will produce a beautiful excelsheet with a nice table!

Now to serve your file, assuming you have an ExcelPackage object as in your code above called pck..

Response.Clear();

Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("Content-Disposition", "attachment;filename=" + sFilename);

Response.BinaryWrite(pck.GetAsByteArray());
Response.End();

CSS: Fix row height

HTML Table row heights will typically change proportionally to the table height, if the table height is larger than the height of your rows. Since the table is forcing the height of your rows, you can remove the table height to resolve the issue. If this is not acceptable, you can also give the rows explicit height, and add a third row that will auto size to the remaining table height.

Another option in CSS2 is the Max-Height Property, although it may lead to strange behavior in a table.http://www.w3schools.com/cssref/pr_dim_max-height.asp

.

How to check if a string is a valid JSON string in JavaScript without using Try/Catch

if(resp) {
    try {
        resp = $.parseJSON(resp);
        console.log(resp);
    } catch(e) {
        alert(e);
    }
}

hope this works for you too

How to make Toolbar transparent?

Just add android:background="@android:color/transparent" like below in your appbar layout

<android.support.design.widget.AppBarLayout
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:background="@android:color/transparent">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        app:popupTheme="@style/AppTheme.PopupOverlay" />

</android.support.design.widget.AppBarLayout>`

Create code first, many to many, with additional fields in association table

I'll just post the code to do this using the fluent API mapping.

public class User {
    public int UserID { get; set; }
    public string Username { get; set; }
    public string Password { get; set; }

    public ICollection<UserEmail> UserEmails { get; set; }
}

public class Email {
    public int EmailID { get; set; }
    public string Address { get; set; }

    public ICollection<UserEmail> UserEmails { get; set; }
}

public class UserEmail {
    public int UserID { get; set; }
    public int EmailID { get; set; }
    public bool IsPrimary { get; set; }
}

On your DbContext derived class you could do this:

public class MyContext : DbContext {
    protected override void OnModelCreating(DbModelBuilder builder) {
        // Primary keys
        builder.Entity<User>().HasKey(q => q.UserID);
        builder.Entity<Email>().HasKey(q => q.EmailID);
        builder.Entity<UserEmail>().HasKey(q => 
            new { 
                q.UserID, q.EmailID
            });

        // Relationships
        builder.Entity<UserEmail>()
            .HasRequired(t => t.Email)
            .WithMany(t => t.UserEmails)
            .HasForeignKey(t => t.EmailID)

        builder.Entity<UserEmail>()
            .HasRequired(t => t.User)
            .WithMany(t => t.UserEmails)
            .HasForeignKey(t => t.UserID)
    }
}

It has the same effect as the accepted answer, with a different approach, which is no better nor worse.

What is a Memory Heap?

A memory heap is a location in memory where memory may be allocated at random access.
Unlike the stack where memory is allocated and released in a very defined order, individual data elements allocated on the heap are typically released in ways which is asynchronous from one another. Any such data element is freed when the program explicitly releases the corresponding pointer, and this may result in a fragmented heap. In opposition only data at the top (or the bottom, depending on the way the stack works) may be released, resulting in data element being freed in the reverse order they were allocated.

How to get all columns' names for all the tables in MySQL?

The question was :

Is there a fast way of getting all COLUMN NAMES from all tables in MySQL, without having to list all the tables?

SQL to get all information for each column

select * from information_schema.columns
where table_schema = 'your_db'
order by table_name,ordinal_position

SQL to get all COLUMN NAMES

select COLUMN_NAME from information_schema.columns
where table_schema = 'your_db'
order by table_name,ordinal_position

SQL variable to hold list of integers

For SQL Server 2016+ and Azure SQL Database, the STRING_SPLIT function was added that would be a perfect solution for this problem. Here is the documentation: https://docs.microsoft.com/en-us/sql/t-sql/functions/string-split-transact-sql

Here is an example:

/*List of ids in a comma delimited string
  Note: the ') WAITFOR DELAY ''00:00:02''' is a way to verify that your script 
        doesn't allow for SQL injection*/
DECLARE @listOfIds VARCHAR(MAX) = '1,3,a,10.1,) WAITFOR DELAY ''00:00:02''';

--Make sure the temp table was dropped before trying to create it
IF OBJECT_ID('tempdb..#MyTable') IS NOT NULL DROP TABLE #MyTable;

--Create example reference table
CREATE TABLE #MyTable
([Id] INT NOT NULL);

--Populate the reference table
DECLARE @i INT = 1;
WHILE(@i <= 10)
BEGIN
    INSERT INTO #MyTable
    SELECT @i;

    SET @i = @i + 1;
END

/*Find all the values
  Note: I silently ignore the values that are not integers*/
SELECT t.[Id]
FROM #MyTable as t
    INNER JOIN 
        (SELECT value as [Id] 
        FROM STRING_SPLIT(@listOfIds, ',')
        WHERE ISNUMERIC(value) = 1 /*Make sure it is numeric*/
            AND ROUND(value,0) = value /*Make sure it is an integer*/) as ids
    ON t.[Id] = ids.[Id];

--Clean-up
DROP TABLE #MyTable;

The result of the query is 1,3

~Cheers

Error - Android resource linking failed (AAPT2 27.0.3 Daemon #0)

There should be some error in resource files. It mean is there may be miss typed value of attributes. Go through the resource files and correct these value and enjoy the work.

Unstage a deleted file in git

If it has been staged and committed, then the following will reset the file:

git reset COMMIT_HASH file_path
git checkout COMMIT_HASH file_path
git add file_path

This will work for a deletion that occurred several commits previous.

How do I start an activity from within a Fragment?

I done it, below code is working for me....

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.hello_world, container, false);

        Button newPage = (Button)v.findViewById(R.id.click);
        newPage.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), HomeActivity.class);
                startActivity(intent);
            }
        });
        return v;
    }

and Please make sure that your destination activity should be register in Manifest.xml file,

but in my case all tabs are not shown in HomeActivity, is any solution for that ?

How to Empty Caches and Clean All Targets Xcode 4 and later

Here's my shell script solution, which deletes derived data and cleans a project's cached assets, for Xcode 4, 5 and 6.

Sometimes, simply calling rm -rf on the Derived Data directory leaves a lingering file or two, but my script loops until all files are deleted.

Using CMake to generate Visual Studio C++ project files

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

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

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

Centering image and text in R Markdown for a PDF report

If you are centering the output of an R code chunk, e.g., a plot, then you can use the fig.align option in knitr.

```{r fig.align="center"}
plot(mtcars)
```

Count multiple columns with group by in one query

    SELECT SUM(Output.count),Output.attr 
FROM
(
    SELECT COUNT(column1  ) AS count,column1 AS attr FROM tab1 GROUP BY column1 
    UNION ALL
    SELECT COUNT(column2) AS count,column2 AS attr FROM tab1 GROUP BY column2
    UNION ALL
    SELECT COUNT(column3) AS count,column3 AS attr FROM tab1 GROUP BY column3) AS Output

    GROUP BY attr 

Make a nav bar stick

I would recommend to use Bootstrap. http://getbootstrap.com/. This approach is very straight-forward and light weight.

<div class="navbar navbar-inverse navbar-fixed-top">
   <div class="container">
      <div class="navbar-collapse collapse">
         <ul class="nav navbar-nav navbar-fixed-top">
            <li><a href="#home"> <br>BLINK</a></li>
                <li><a href="#news"><br>ADVERTISING WITH BLINK</a></li>
                <li><a href="#contact"><br>EDUCATING WITH BLINK</a></li>
                <li><a href="#about"><br>ABOUT US</a></li>
            </ul>
        </div>
    </div>
</div>

You need to include the Bootstrap into your project, which will include the necessary scripts and styles. Then just call the class 'navbar-fixed-top'. This will do the trick. See above example

Angular 2: How to access an HTTP response body?

The response data are in JSON string form. The app must parse that string into JavaScript objects by calling response.json().

  this.http.request('http://thecatapi.com/api/images/get?format=html&results_per_page=10').
  .map(res => res.json())
  .subscribe(data => {
    console.log(data);
  })

https://angular.io/docs/ts/latest/guide/server-communication.html#!#extract-data

Storing database records into array

<?php

// run query
$query = mysql_query("SELECT * FROM table");

// set array
$array = array();

// look through query
while($row = mysql_fetch_assoc($query)){

  // add each row returned into an array
  $array[] = $row;

  // OR just echo the data:
  echo $row['username']; // etc

}

// debug:
print_r($array); // show all array data
echo $array[0]['username']; // print the first rows username

Java FileReader encoding issue

For another as Latin languages for example Cyrillic you can use something like this:

FileReader fr = new FileReader("src/text.txt", StandardCharsets.UTF_8);

and be sure that your .txt file is saved with UTF-8 (but not as default ANSI) format. Cheers!

How to compare a local git branch with its remote branch?

If you want to see the difference as just the names of the files changed then use:

git diff --name-status <remote-branch> <local-branch>,

else this would show all differences between the two branches:

git diff <remote-branch> <local-branch>

Border around tr element doesn't show?

Add this to the stylesheet:

table {
  border-collapse: collapse;
}

JSFiddle.

The reason why it behaves this way is actually described pretty well in the specification:

There are two distinct models for setting borders on table cells in CSS. One is most suitable for so-called separated borders around individual cells, the other is suitable for borders that are continuous from one end of the table to the other.

... and later, for collapse setting:

In the collapsing border model, it is possible to specify borders that surround all or part of a cell, row, row group, column, and column group.

WordPress query single post by slug

How about?

<?php
   $queried_post = get_page_by_path('my_slug',OBJECT,'post');
?>

How to hash some string with sha256 in Java?

I think that the easiest solution is to use Apache Common Codec:

String sha256hex = org.apache.commons.codec.digest.DigestUtils.sha256Hex(stringText);   

Set session variable in laravel

in Laravel 5.4

use this method:

Session::put('variableName', $value);

Asp.net - Add blank item at top of dropdownlist

After your databind:

drpList.Items.Insert(0, new ListItem(String.Empty, String.Empty));
drpList.SelectedIndex = 0;

PHP function ssh2_connect is not working

Honestly, I'd recommend using phpseclib, a pure PHP SSH2 implementation. Example:

<?php
include('Net/SSH2.php');

$ssh = new Net_SSH2('www.domain.tld');
if (!$ssh->login('username', 'password')) {
    exit('Login Failed');
}

echo $ssh->exec('pwd');
echo $ssh->exec('ls -la');
?>

It's a ton more portable, easier to use and more feature packed too.

Storyboard - refer to ViewController in AppDelegate

If you use XCode 5 you should do it in a different way.

  • Select your UIViewController in UIStoryboard
  • Go to the Identity Inspector on the right top pane
  • Check the Use Storyboard ID checkbox
  • Write a unique id to the Storyboard ID field

Then write your code.

// Override point for customization after application launch.

if (<your implementation>) {
    UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@"Main" 
                                                             bundle: nil];
    YourViewController *yourController = (YourViewController *)[mainStoryboard 
      instantiateViewControllerWithIdentifier:@"YourViewControllerID"];
    self.window.rootViewController = yourController;
}

return YES;

Unique constraint violation during insert: why? (Oracle)

It looks like you are not providing a value for the primary key field DB_ID. If that is a primary key, you must provide a unique value for that column. The only way not to provide it would be to create a database trigger that, on insert, would provide a value, most likely derived from a sequence.

If this is a restoration from another database and there is a sequence on this new instance, it might be trying to reuse a value. If the old data had unique keys from 1 - 1000 and your current sequence is at 500, it would be generating values that already exist. If a sequence does exist for this table and it is trying to use it, you would need to reconcile the values in your table with the current value of the sequence.

You can use SEQUENCE_NAME.CURRVAL to see the current value of the sequence (if it exists of course)

Creating a triangle with for loops

private static void printStar(int x) {
    int i, j;
    for (int y = 0; y < x; y++) { // number of row of '*'

        for (i = y; i < x - 1; i++)
            // number of space each row
            System.out.print(' ');

        for (j = 0; j < y * 2 + 1; j++)
            // number of '*' each row
            System.out.print('*');

        System.out.println();
    }
}

Ionic 2: Cordova is not available. Make sure to include cordova.js or run in a device/simulator (running in emulator)

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { EmailComposer } from '@ionic-native/email-composer';

@Component({
  selector: 'page-about',
  templateUrl: 'about.html'
})
export class AboutPage {
  sendObj = {
    to: '',
    cc: '',
    bcc: '',
    attachments:'',
    subject:'',
    body:''
  }

  constructor(public navCtrl: NavController,private emailComposer: EmailComposer) {}

  sendEmail(){
  let email = {
    to: this.sendObj.to,
    cc: this.sendObj.cc,
    bcc: this.sendObj.bcc,
    attachments: [this.sendObj.attachments],
    subject: this.sendObj.subject,
    body: this.sendObj.body,
    isHtml: true
  }; 
  this.emailComposer.open(email);
  }  
 }

starts here html about

<ion-header>
  <ion-navbar>
    <ion-title>
      Send Invoice
    </ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
  <ion-item>
    <ion-label stacked>To</ion-label>
    <ion-input [(ngModel)]="sendObj.to"></ion-input>
  </ion-item>
  <ion-item>
    <ion-label stacked>CC</ion-label>
    <ion-input [(ngModel)]="sendObj.cc"></ion-input>
  </ion-item>
  <ion-item>
    <ion-label stacked>BCC</ion-label>
    <ion-input [(ngModel)]="sendObj.bcc"></ion-input>
  </ion-item>
  <ion-item>
    <ion-label stacked>Add pdf</ion-label>
    <ion-input [(ngModel)]="sendObj.attachments" type="file"></ion-input>
  </ion-item>
  <ion-item>
    <ion-label stacked>Subject</ion-label>
    <ion-input [(ngModel)]="sendObj.subject"></ion-input>
  </ion-item>
  <ion-item>
    <ion-label stacked>Text message</ion-label>
    <ion-input [(ngModel)]="sendObj.body"></ion-input>
  </ion-item>

  <button ion-button full (click)="sendEmail()">Send Email</button>

</ion-content>


other stuff here

import { NgModule, ErrorHandler } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular';
import { MyApp } from './app.component';

import { AboutPage } from '../pages/about/about';
import { ContactPage } from '../pages/contact/contact';
import { HomePage } from '../pages/home/home';
import { TabsPage } from '../pages/tabs/tabs';

import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';

import { File } from '@ionic-native/file';
import { FileOpener } from '@ionic-native/file-opener';
import { EmailComposer } from '@ionic-native/email-composer';

@NgModule({
  declarations: [
    MyApp,
    AboutPage,
    ContactPage,
    HomePage,
    TabsPage
  ],
  imports: [
    BrowserModule,
    IonicModule.forRoot(MyApp)
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    AboutPage,
    ContactPage,
    HomePage,
    TabsPage
  ],
  providers: [
    StatusBar,
    SplashScreen,
    EmailComposer,
    {provide: ErrorHandler, useClass: IonicErrorHandler},  
    File,
    FileOpener
  ]
})
export class AppModule {}

Angular JS Uncaught Error: [$injector:modulerr]

The problem was caused by missing inclusion of ngRoute module. Since version 1.1.6 it's a separate part:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0rc1/angular-route.min.js"></script>

var app = angular.module('myapp', ['ngRoute']);

This is getting reference from: AngularJS 1.2 $injector:modulerr David answer

How to inspect FormData?

ES6+ solutions:

To see the structure of form data:

console.log([...formData])

To see each key-value pair:

for (let [key, value] of formData.entries()) {
  console.log(`${key}: ${value}`);
}

How to show shadow around the linearlayout in Android?

For lollipop and above you can use elevation.

For older versions:

Here is a lazy hack from: http://odedhb.blogspot.com/2013/05/android-layout-shadow-without-9-patch.html

(toast_frame does not work on KitKat, shadow was removed from toasts)

just use:

android:background="@android:drawable/toast_frame"

or:

android:background="@android:drawable/dialog_frame"

as a background

examples:

<TextView
        android:layout_width="fill_parent"
        android:text="I am a simple textview with a shadow"
        android:layout_height="wrap_content"
        android:textSize="18sp"
        android:padding="16dp"
        android:textColor="#fff"
        android:background="@android:drawable/toast_frame"
        />

and with different bg color:

<LinearLayout
        android:layout_height="64dp"
        android:layout_width="fill_parent"
        android:gravity="center"
        android:background="@android:drawable/toast_frame"
        android:padding="4dp"
        >
    <Button
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:text="Button shadow"
            android:background="#33b5e5"
            android:textSize="24sp"
            android:textStyle="bold"
            android:textColor="#fff"
            android:layout_gravity="center|bottom"
            />

</LinearLayout>

How can I Insert data into SQL Server using VBNet

Imports System.Data

Imports System.Data.SqlClient

Public Class Form2

Dim myconnection As SqlConnection

Dim mycommand As SqlCommand

Dim dr As SqlDataReader

Dim dr1 As SqlDataReader

Dim ra As Integer


Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click


    myconnection = New SqlConnection("server=localhost;uid=root;pwd=;database=simple")

    'you need to provide password for sql server

    myconnection.Open()

    mycommand = New SqlCommand("insert into tbl_cus([name],[class],[phone],[address]) values ('" & TextBox1.Text & "','" & TextBox2.Text & "','" & TextBox3.Text & "','" & TextBox4.Text & "')", myconnection)

    mycommand.ExecuteNonQuery()

    MessageBox.Show("New Row Inserted" & ra)

    myconnection.Close()

End Sub

End Class

Is it possible to add an HTML link in the body of a MAILTO link

Here's what I put together. It works on the select mobile device I needed it for, but I'm not sure how universal the solution is

<a href="mailto:[email protected]?subject=Me&body=%3Chtml%20xmlns%3D%22http:%2F%2Fwww.w3.org%2F1999%2Fxhtml%22%3E%3C%2Fhead%3E%3Cbody%3EPlease%20%3Ca%20href%3D%22http:%2F%2Fwww.w3.org%22%3Eclick%3C%2Fa%3E%20me%3C%2Fbody%3E%3C%2Fhtml%3E">

Can anyone explain what JSONP is, in layman terms?

JSONP is a way of getting around the browser's same-origin policy. How? Like this:

enter image description here

The goal here is to make a request to otherdomain.com and alert the name in the response. Normally we'd make an AJAX request:

$.get('otherdomain.com', function (response) {
  var name = response.name;
  alert(name);
});

However, since the request is going out to a different domain, it won't work.

We can make the request using a <script> tag though. Both <script src="otherdomain.com"></script> and $.get('otherdomain.com') will result in the same request being made:

GET otherdomain.com

Q: But if we use the <script> tag, how could we access the response? We need to access it if we want to alert it.

A: Uh, we can't. But here's what we could do - define a function that uses the response, and then tell the server to respond with JavaScript that calls our function with the response as its argument.

Q: But what if the server won't do this for us, and is only willing to return JSON to us?

A: Then we won't be able to use it. JSONP requires the server to cooperate.

Q: Having to use a <script> tag is ugly.

A: Libraries like jQuery make it nicer. Ex:

$.ajax({
    url: "http://otherdomain.com",
    jsonp: "callback",
    dataType: "jsonp",
    success: function( response ) {
        console.log( response );
    }
});

It works by dynamically creating the <script> tag DOM element.

Q: <script> tags only make GET requests - what if we want to make a POST request?

A: Then JSONP won't work for us.

Q: That's ok, I just want to make a GET request. JSONP is awesome and I'm going to go use it - thanks!

A: Actually, it isn't that awesome. It's really just a hack. And it isn't the safest thing to use. Now that CORS is available, you should use it whenever possible.

How can I disable a tab inside a TabControl?

You can do it through the tabpages: tabPage1.Hide(), tabPage2.Show() etc.

Secure Web Services: REST over HTTPS vs SOAP + WS-Security. Which is better?

See the wiki article:

In point-to-point situations confidentiality and data integrity can also be enforced on Web services through the use of Transport Layer Security (TLS), for example, by sending messages over https.

WS-Security however addresses the wider problem of maintaining integrity and confidentiality of messages until after a message was sent from the originating node, providing so called end to end security.

That is:

  • HTTPS is a transport layer (point-to-point) security mechanism
  • WS-Security is an application layer (end-to-end) security mechanism.

Professional jQuery based Combobox control?

Unfortunately, the best thing I have seen is the jquery.combobox, but it doesn't really look like something I'd really want to use in my web applications. I think there are some usability issues with this control, but as a user I don't think I'd know to start typing for the dropdownlist to turn into a textbox.

I much prefer the Combo Dropdown Box, but it still has some features that I'd want and it's still in alpha. The only think I don't like about this other than its being alpha... is that once I type in the combobox, the original dropdownlist items disappear. However, maybe there is a setting for this... or maybe it could be added fairly easily.

Those are the only two options that I know of. Good luck in your search. I'd love to hear if you find one or if the second option works out for you.

how to convert String into Date time format in JAVA?

With SimpleDateFormat. And steps are -

  1. Create your date pattern string
  2. Create SimpleDateFormat Object
  3. And parse with it.
  4. It will return Date Object.

Convert PDF to clean SVG?

This topic is quite old, but here is a handy solution that I found:

http://www.cityinthesky.co.uk/opensource/pdf2svg/

It offers a tool, pdf2png, which once installed does exactly the job in command line. I've tested it with irreproachable results so far, including with bitmaps.

EDIT : My mistake, this tool also converts letters to paths, so it does not address the initial question. However it does a good job anyway, and can be useful to anyone who does not intend to modify the code in the svg file, so I'll leave the post.

Print newline in PHP in single quotes

The only escape sequence you can use in single quotes is for the single quote itself.

$foo = 'That\'s great';

The only way you could insert a new line into a string created with single quotes is to insert a literal newline

$bar = 'That\'s
cheating';

Updating version numbers of modules in a multi-module Maven project

I encourage you to read the Maven Book about multi-module (reactor) builds.

I meant in particular the following:

<parent>
    <artifactId>xyz-application</artifactId>
    <groupId>com.xyz</groupId>
    <version>2.50.0.g</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>com.xyz</groupId>
<artifactId>xyz-Library</artifactId>
<version>2.50.0.g</version>

should be changed into. Here take care about the not defined version only in parent part it is defined.

<modelVersion>4.0.0</modelVersion>

<parent>
    <artifactId>xyz-application</artifactId>
    <groupId>com.xyz</groupId>
    <version>2.50.0.g</version>
</parent>
<groupId>com.xyz</groupId>
<artifactId>xyz-Library</artifactId>

This is a better link.

How do I build an import library (.lib) AND a DLL in Visual C++?

you also should specify def name in the project settings here:

Configuration > Properties/Input/Advanced/Module > Definition File

Copying PostgreSQL database to another server

Accepted answer is correct, but if you want to avoid entering the password interactively, you can use this:

PGPASSWORD={{export_db_password}} pg_dump --create -h {{export_db_host}} -U {{export_db_user}} {{export_db_name}} | PGPASSWORD={{import_db_password}} psql -h {{import_db_host}} -U {{import_db_user}} {{import_db_name}}

Pure CSS animation visibility with delay

You can play with delay prop of animation, just set visibility:visible after a delay, demo:

_x000D_
_x000D_
@keyframes delayedShow {_x000D_
  to {_x000D_
    visibility: visible;_x000D_
  }_x000D_
}_x000D_
_x000D_
.delayedShow{_x000D_
  visibility: hidden;_x000D_
  animation: 0s linear 2.3s forwards delayedShow ;_x000D_
}
_x000D_
So, Where are you?_x000D_
_x000D_
<div class="delayedShow">_x000D_
  Hey, I'm here!_x000D_
</div>
_x000D_
_x000D_
_x000D_

Grouping into interval of 5 minutes within a time range

select 
CONCAT(CAST(CREATEDATE AS DATE),' ',datepart(hour,createdate),':',ROUNd(CAST((CAST((CAST(DATEPART(MINUTE,CREATEDATE) AS DECIMAL (18,4)))/5 AS INT)) AS DECIMAL (18,4))/12*60,2)) AS '5MINDATE'
,count(something)
from TABLE
group by CONCAT(CAST(CREATEDATE AS DATE),' ',datepart(hour,createdate),':',ROUNd(CAST((CAST((CAST(DATEPART(MINUTE,CREATEDATE) AS DECIMAL (18,4)))/5 AS INT)) AS DECIMAL (18,4))/12*60,2))

405 method not allowed Web API

This does not answer your specific question, but when I had the same problem I ended up here and I figured that more people might do the same.

The problem I had was that I had indeliberately declared my Get method as static. I missed this an entire forenoon, and it caused no warnings from attributes or similar.

Incorrect:

public class EchoController : ApiController
{
    public static string Get()
    {
        return string.Empty;
    }
}

Correct:

public class EchoController : ApiController
{
    public string Get()
    {
        return string.Empty;
    }
}

join list of lists in python

For one-level flatten, if you care about speed, this is faster than any of the previous answers under all conditions I tried. (That is, if you need the result as a list. If you only need to iterate through it on the fly then the chain example is probably better.) It works by pre-allocating a list of the final size and copying the parts in by slice (which is a lower-level block copy than any of the iterator methods):

def join(a):
    """Joins a sequence of sequences into a single sequence.  (One-level flattening.)
    E.g., join([(1,2,3), [4, 5], [6, (7, 8, 9), 10]]) = [1,2,3,4,5,6,(7,8,9),10]
    This is very efficient, especially when the subsequences are long.
    """
    n = sum([len(b) for b in a])
    l = [None]*n
    i = 0
    for b in a:
        j = i+len(b)
        l[i:j] = b
        i = j
    return l

Sorted times list with comments:

[(0.5391559600830078, 'flatten4b'), # join() above. 
(0.5400412082672119, 'flatten4c'), # Same, with sum(len(b) for b in a) 
(0.5419249534606934, 'flatten4a'), # Similar, using zip() 
(0.7351131439208984, 'flatten1b'), # list(itertools.chain.from_iterable(a)) 
(0.7472689151763916, 'flatten1'), # list(itertools.chain(*a)) 
(1.5468521118164062, 'flatten3'), # [i for j in a for i in j] 
(26.696547985076904, 'flatten2')] # sum(a, [])

What's the maximum value for an int in PHP?

It depends on your OS, but 2147483647 is the usual value, according to the manual.

concatenate variables

Note that if strings has spaces then quotation marks are needed at definition and must be chopped while concatenating:

rem The retail files set
set FILES_SET="(*.exe *.dll"

rem The debug extras files set
set DEBUG_EXTRA=" *.pdb"

rem Build the DEBUG set without any
set FILES_SET=%FILES_SET:~1,-1%%DEBUG_EXTRA:~1,-1%

rem Append the closing bracket
set FILES_SET=%FILES_SET%)

echo %FILES_SET%

Cheers...

Execute a SQL Stored Procedure and process the results

Dim sqlConnection1 As New SqlConnection("Your Connection String")
Dim cmd As New SqlCommand

cmd.CommandText = "StoredProcedureName"
cmd.CommandType = CommandType.StoredProcedure
cmd.Connection = sqlConnection1

sqlConnection1.Open()

Dim adapter As System.Data.SqlClient.SqlDataAdapter
Dim dsdetailwk As New DataSet

Try
   adapter = New System.Data.SqlClient.SqlDataAdapter
   adapter.SelectCommand = cmd
   adapter.Fill(dsdetailwk, "delivery")
   Catch Err As System.Exception
End Try

sqlConnection1.Close()

datagridview1.DataSource = dsdetailwk.Tables(0)

IntelliJ: Error:java: error: release version 5 not supported

I did everything above but had to do one more thing in IntelliJ:

Project Structure > Modules

I had to change every module's "language level"

How to draw rounded rectangle in Android UI?

You could just define a new xml background in the drawables folder

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="enter_your_desired_color_here" />
<corners android:radius="enter_your_desired_radius_the_corners" />
</shape>  

After this just include it in your TextView or EditText by defining it in the background.

<TextView
 android:id="@+id/textView"
 android:layout_width="0dp"
 android:layout_height="80dp"
 android:background="YOUR_FILE_HERE"
 Android:layout_weight="1"
 android:gravity="center"
 android:text="TEXT_HERE"
 android:textSize="40sp" />

Android: Clear Activity Stack

When you call startActivity on the last activity you could always use

Intent.FLAG_ACTIVITY_CLEAR_TOP

as a flag on that intent.

Read more about the flag here.

SQL Server Error : String or binary data would be truncated

You're trying to write more data than a specific column can store. Check the sizes of the data you're trying to insert against the sizes of each of the fields.

In this case transaction_status is a varchar(10) and you're trying to store 19 characters to it.

Is there a JavaScript strcmp()?

Javascript doesn't have it, as you point out.

A quick search came up with:

function strcmp ( str1, str2 ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Waldo Malqui Silva
    // +      input by: Steve Hilder
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    revised by: gorthaur
    // *     example 1: strcmp( 'waldo', 'owald' );
    // *     returns 1: 1
    // *     example 2: strcmp( 'owald', 'waldo' );
    // *     returns 2: -1

    return ( ( str1 == str2 ) ? 0 : ( ( str1 > str2 ) ? 1 : -1 ) );
}

from http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_strcmp/

Of course, you could just add localeCompare if needed:

if (typeof(String.prototype.localeCompare) === 'undefined') {
    String.prototype.localeCompare = function(str, locale, options) {
        return ((this == str) ? 0 : ((this > str) ? 1 : -1));
    };
}

And use str1.localeCompare(str2) everywhere, without having to worry wether the local browser has shipped with it. The only problem is that you would have to add support for locales and options if you care about that.

Getting session value in javascript

You can access your session variable like '<%= Session["VariableName"]%>'

the text in single quotes will give session value. 1)

<script>
var session ='<%= Session["VariableName"]%>'
</script>

2) you can take a hidden field and assign value at server;

hiddenfield.value= session["xyz"].tostring();

//and in script you access the hiddenfield  like

alert(document.getElementbyId("hiddenfield").value);

Get full path without filename from path that includes filename

Use GetParent() as shown, works nicely. Add error checking as you need.

var fn = openFileDialogSapTable.FileName;
var currentPath = Path.GetFullPath( fn );
currentPath = Directory.GetParent(currentPath).FullName;

List directory tree structure in python?

Here you can find code with output like this: https://stackoverflow.com/a/56622847/6671330

V .
|-> V folder1
|   |-> V folder2
|   |   |-> V folder3
|   |   |   |-> file3.txt
|   |   |-> file2.txt
|   |-> V folderX
|   |-> file1.txt
|-> 02-hw1_wdwwfm.py
|-> 06-t1-home1.py
|-> 06-t1-home2.py
|-> hw1.py

UnicodeDecodeError: 'ascii' codec can't decode byte 0xef in position 1

In my case, it was caused by my Unicode file being saved with a "BOM". To solve this, I cracked open the file using BBEdit and did a "Save as..." choosing for encoding "Unicode (UTF-8)" and not what it came with which was "Unicode (UTF-8, with BOM)"

I do not want to inherit the child opacity from the parent in CSS

My answer is not about static parent-child layout, its about animations.

I was doing an svg demo today, and i needed svg to be inside div (because svg is created with parent's div width and height, to animate the path around), and this parent div needed to be invisible during svg path animation (and then this div was supposed to animate opacity from 0 to 1, it's the most important part). And because parent div with opacity: 0 was hiding my svg, i came across this hack with visibility option (child with visibility: visible can be seen inside parent with visibility: hidden):

.main.invisible .test {
  visibility: hidden;
}
.main.opacity-zero .test {
  opacity: 0;
  transition: opacity 0s !important;
}
.test { // parent div
  transition: opacity 1s;
}
.test-svg { // child svg
  visibility: visible;
}

And then, in js, you removing .invisible class with timeout function, adding .opacity-zero class, trigger layout with something like whatever.style.top; and removing .opacity-zero class.

var $main = $(".main");
  setTimeout(function() {
    $main.addClass('opacity-zero').removeClass("invisible");
    $(".test-svg").hide();
    $main.css("top");
    $main.removeClass("opacity-zero");
  }, 3000);

Better to check this demo http://codepen.io/suez/pen/54bbb2f09e8d7680da1af2faa29a0aef?editors=011

What's onCreate(Bundle savedInstanceState)

As Dhruv Gairola answered, you can save the state of the application by using Bundle savedInstanceState. I am trying to give a very simple example that new learners like me can understand easily.

Suppose, you have a simple fragment with a TextView and a Button. Each time you clicked the button the text changes. Now, change the orientation of you device/emulator and notice that you lost the data (means the changed data after clicking you got) and fragment starts as the first time again. By using Bundle savedInstanceState we can get rid of this. If you take a look into the life cyle of the fragment.Fragment Lifecylce you will get that a method "onSaveInstanceState" is called when the fragment is about to destroyed.

So, we can save the state means the changed text value into that bundle like this

 int counter  = 0;
 @Override
 public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putInt("value",counter);
 }

After you make the orientation the "onCreate" method will be called right? so we can just do this

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

    if(savedInstanceState == null){
        //it is the first time the fragment is being called
        counter = 0;
    }else{
        //not the first time so we will check SavedInstanceState bundle
        counter = savedInstanceState.getInt("value",0); //here zero is the default value
    }
}

Now, you won't lose your value after the orientation. The modified value always will be displayed.

How to break out from foreach loop in javascript

Use a for loop instead of .forEach()

var myObj = [{"a": "1","b": null},{"a": "2","b": 5}]
var result = false

for(var call of myObj) {
    console.log(call)
    
    var a = call['a'], b = call['b']
     
    if(a == null || b == null) {
        result = false
        break
    }
}

opening a window form from another form programmatically

private void btnchangerate_Click(object sender, EventArgs e)
    {
        this.Hide();  //current form will hide
        Form1 fm = new Form1(); //another form will open
        fm.Show();


    }

on click btn current form will hide and new form will open

Are HTTP headers case-sensitive?

officially, headers are case insensitive, however, it is common practice to capitalize the first letter of every word.
but, because it is common practice, certain programs like IE assume the headers are capitalized.
so while the docs say the are case insensitive, bad programmers have basically changed the docs.

Is there a shortcut to make a block comment in Xcode?

I modified the code of Nikola Milicevic a little bit so it also remove comment block if code is already commented:

on run {input, parameters}
    repeat with anInput in input
        if "/*" is in anInput then
            set input to replaceText("/*", "", input as string)
            set input to replaceText("*/", "", input as string)

            return input
            exit repeat
        end if
    end repeat
    return "/*" & (input as string) & "*/"
end run

on replaceText(find, replace, textString)
    set prevTIDs to AppleScript's text item delimiters
    set AppleScript's text item delimiters to find
    set textString to text items of textString
    set AppleScript's text item delimiters to replace
    set textString to "" & textString
    set AppleScript's text item delimiters to prevTIDs
    return textString
end replaceText

Hope this will help someone.enter image description here

Docker error : no space left on device

  1. Clean dangled images docker rmi $(docker images -f "dangling=true" -q)
  2. Remove unwanted volumes
  3. Remove unused images
  4. Remove unused containers

How to add a button to UINavigationBar?

swift 3

    let cancelBarButton = UIBarButtonItem(title: "Cancel", style: .done, target: self, action: #selector(cancelPressed(_:)))
    cancelBarButton.setTitleTextAttributes( [NSFontAttributeName : UIFont.cancelBarButtonFont(),
                                                          NSForegroundColorAttributeName : UIColor.white], for: .normal)
    self.navigationItem.leftBarButtonItem = cancelBarButton


    func cancelPressed(_ sender: UIBarButtonItem ) {
        self.dismiss(animated: true, completion: nil)
    }

How to clear variables in ipython?

I tried

%reset -f

and cleared all the variables and contents without prompt. -f does the force action on the given command without prompting for yes/no.

Wish this helps.. :)

Improve INSERT-per-second performance of SQLite

The answer to your question is that the newer SQLite 3 has improved performance, use that.

This answer Why is SQLAlchemy insert with sqlite 25 times slower than using sqlite3 directly? by SqlAlchemy Orm Author has 100k inserts in 0.5 sec, and I have seen similar results with python-sqlite and SqlAlchemy. Which leads me to believe that performance has improved with SQLite 3.

Remove all newlines from inside a string

As mentioned by @john, the most robust answer is:

string = "a\nb\rv"
new_string = " ".join(string.splitlines())

Converting of Uri to String

If you want to pass a Uri to another activity, try the method intent.setData(Uri uri) https://developer.android.com/reference/android/content/Intent.html#setData(android.net.Uri)

In another activity, via intent.getData() to obtain the Uri.

What is the difference between _tmain() and main() in C++?

With a little effort of templatizing this, it wold work with any list of objects.

#include <iostream>
#include <string>
#include <vector>

char non_repeating_char(std::string str){
    while(str.size() >= 2){
        std::vector<size_t> rmlist; 
        for(size_t  i = 1;  i < str.size(); i++){        
            if(str[0] == str[i]) {
                rmlist.push_back(i);
            }      
        }          

        if(rmlist.size()){            
            size_t s = 0;  // Need for terator position adjustment   
            str.erase(str.begin() + 0);
            ++s;
            for (size_t j : rmlist){   
                str.erase(str.begin() + (j-s));                
                ++s;
            }
         continue;
        }
        return str[0];
   }
    if(str.size() == 1) return str[0];
    else return -1;
}

int main(int argc, char ** args)
{
    std::string test = "FabaccdbefafFG";
    test = args[1];
    char non_repeating = non_repeating_char(test);
    Std::cout << non_repeating << '\n';
}

Unix tail equivalent command in Windows Powershell

PowerShell Community Extensions (PSCX) provides the Get-FileTail cmdlet. It looks like a suitable solution for the task. Note: I did not try it with extremely large files but the description says it efficiently tails the contents and it is designed for large log files.

NAME
    Get-FileTail

SYNOPSIS
    PSCX Cmdlet: Tails the contents of a file - optionally waiting on new content.

SYNTAX
    Get-FileTail [-Path] <String[]> [-Count <Int32>] [-Encoding <EncodingParameter>] [-LineTerminator <String>] [-Wait] [<CommonParameters>]

    Get-FileTail [-LiteralPath] <String[]> [-Count <Int32>] [-Encoding <EncodingParameter>] [-LineTerminator <String>] [-Wait] [<CommonParameters>]

DESCRIPTION
    This implentation efficiently tails the cotents of a file by reading lines from the end rather then processing the entire file. This behavior is crucial for ef
    ficiently tailing large log files and large log files over a network.  You can also specify the Wait parameter to have the cmdlet wait and display new content
    as it is written to the file.  Use Ctrl+C to break out of the wait loop.  Note that if an encoding is not specified, the cmdlet will attempt to auto-detect the
     encoding by reading the first character from the file. If no character haven't been written to the file yet, the cmdlet will default to using Unicode encoding
    . You can override this behavior by explicitly specifying the encoding via the Encoding parameter.

What does !important mean in CSS?

It is used to influence sorting in the CSS cascade when sorting by origin is done. It has nothing to do with specificity like stated here in other answers.

Here is the priority from lowest to highest:

  1. browser styles
  2. user style sheet declarations (without !important)
  3. author style sheet declarations (without !important)
  4. !important author style sheets
  5. !important user style sheets

After that specificity takes place for the rules still having a finger in the pie.

References:

Is it possible to view RabbitMQ message contents directly from the command line?

If you want multiple messages from a queue, say 10 messages, the command to use is:

rabbitmqadmin get queue=<QueueName> ackmode=ack_requeue_true count=10

If you don't want the messages requeued, just change ackmode to ack_requeue_false.

Remove portion of a string after a certain character

preg_replace offers one way:

$newText = preg_replace('/\bBy.*$/', '', $text);

Java - What does "\n" mean?

In the specific case of the code example from the original question, the

System.out.print("\n");

is there to move to a new line between incrementing i.

So the first print statement prints all of the elements of Grid[0][j]. When the innermost for loop has completed, the "\n" gets printed and then all of the elements of Grid[1][j] are printed on the next line, and this is repeated until you have a 10x10 grid of the elements of the 2-dimensional array, Grid.

How to make the script wait/sleep in a simple way in unity

here is more simple way without StartCoroutine:

float t = 0f;
float waittime = 1f;

and inside Update/FixedUpdate:

if (t < 0){
    t += Time.deltaTIme / waittime;
    yield return t;
}

Save Javascript objects in sessionStorage

Use case:

 sesssionStorage.setObj(1,{date:Date.now(),action:'save firstObject'});
 sesssionStorage.setObj(2,{date:Date.now(),action:'save 2nd object'}); 
 //Query first object
  sesssionStorage.getObj(1)
  //Retrieve date created of 2nd object
  new Date(sesssionStorage.getObj(1).date)

API

Storage.prototype.setObj = function(key, obj) {

        return this.setItem(key, JSON.stringify(obj))
    };
    
    Storage.prototype.getObj = function(key) {
        return JSON.parse(this.getItem(key))
    };

Handling onchange event in HTML.DropDownList Razor MVC

Description

You can use another overload of the DropDownList method. Pick the one you need and pass in a object with your html attributes.

Sample

@Html.DropDownList("CategoryID", null, new { @onchange="location = this.value;" })

More Information

Show only two digit after decimal

Many other answers only do formatting. This approach will return value instead of only print format.

double number1 = 10.123456;
double number2 = (int)(Math.round(number1 * 100))/100.0;
System.out.println(number2);

How to beautify JSON in Python?

Use the indent argument of the dumps function in the json module.

From the docs:

>>> import json
>>> print json.dumps({'4': 5, '6': 7}, sort_keys=True, indent=4)
{
    "4": 5,
    "6": 7
}

Could not open input file: composer.phar

First try this: dont use the php composer.phar [parameters] simply use composer [parameters] if this doesn't work for you than try the rest. Hope it helps.

Get $_POST from multiple checkboxes

It's pretty simple. Pay attention and you'll get it right away! :)

You will create a html array, which will be then sent to php array. Your html code will look like this:

<input type="checkbox" name="check_list[1]" alt="Checkbox" value="checked">
<input type="checkbox" name="check_list[2]" alt="Checkbox" value="checked">
<input type="checkbox" name="check_list[3]" alt="Checkbox" value="checked">

Where [1] [2] [3] are the IDs of your messages, meaning that you will echo your $row['Report ID'] in their place.

Then, when you submit the form, your PHP array will look like this:

print_r($check_list)

[1] => checked [3] => checked

Depending on which were checked and which were not.

I'm sure you can continue from this point forward.

No generated R.java file in my project

This is actually a bug in the tutorials code. I was having the same issue and I finally realized the issue was in the "note_edit.xml" file.

Some of the layout_heigh/width attributes were set to "match_parent" which is not a valid value, they're supposed to be set to "fill_parent".

This was throwing a bug, that was causing the generation of the R.java file to fail. So, if you're having this issue, or a similar one, check all of your xml files and make sure that none of them have any errors.

How to Diff between local uncommitted changes and origin

To see non-staged (non-added) changes to existing files

git diff

Note that this does not track new files. To see staged, non-commited changes

git diff --cached

JDK was not found on the computer for NetBeans 6.5

I have got the JDK installed

You haven't specified the version. I think it is not 6 nor 5.

JDK 6 was the latest version at time of NetBeans 6.0 - 6.9 are developed. For that reason, They require JDK 6 (or JDK 5) and do not run on JDK 7 or later.

Download JDK 6
Download latest version of NetBeans

How to export datagridview to excel using vb.net?

A simple way of generating a printable report from a Datagridview is to place the datagridview on a Panel object. It is possible to draw a bitmap of the panel.

Here's how I do it.

'create the bitmap with the dimentions of the Panel Dim bmp As New Bitmap(Panel1.Width, Panel1.Height)

'draw the Panel to the bitmap "bmp" Panel1.DrawToBitmap(bmp, Panel1.ClientRectangle)

I create a multi page tiff by "breaking my datagridview items into pages. this is how i detect the start of a new page:

'i add the rows to my datagrid one at a time and then check if the scrollbar is active. 'if the scrollbar is active i save the row to a variable and then i remove it from the 'datagridview and roll back my counter integer by one(thus the next run will include this 'row.

Private Function VScrollBarVisible() As Boolean
    Dim ctrl As New Control
    For Each ctrl In DataGridView_Results.Controls
        If ctrl.GetType() Is GetType(VScrollBar) Then
            If ctrl.Visible = True Then
                Return True
            Else
                Return False
            End If
        End If
    Next
    Return Nothing
End Function

I hope this helps

What is the use of a private static variable in Java?

If a variable is defined as public static it can be accessed via its class name from any class.

Usually functions are defined as public static which can be accessed just by calling the implementing class name.

A very good example of it is the sleep() method in Thread class

Thread.sleep(2500);

If a variable is defined as private static it can be accessed only within that class so no class name is needed or you can still use the class name (upto you). The difference between private var_name and private static var_name is that private static variables can be accessed only by static methods of the class while private variables can be accessed by any method of that class(except static methods)

A very good example of it is while defining database connections or constants which require declaring variable as private static .

Another common example is

private static int numberOfCars=10;

public static int returnNumber(){

return numberOfCars;

}

Get the Application Context In Fragment In Android?

Use

getActivity().getApplicationContext()

to obtain the context in any fragment

String vs. StringBuilder

Yes, the performance difference is significant. See the KB article "How to improve string concatenation performance in Visual C#".

I have always tried to code for clarity first, and then optimize for performance later. That's much easier than doing it the other way around! However, having seen the enormous performance difference in my applications between the two, I now think about it a little more carefully.

Luckily, it's relatively straightforward to run performance analysis on your code to see where you're spending the time, and then to modify it to use StringBuilder where needed.

Disabling vertical scrolling in UIScrollView

On iOS 11 please remember to add the following, if you're interested in creating a scrollview that sticks to the screen bounds rather than a safe area.:

if (@available(iOS 11.0, *)) {
    [self.scrollView setContentInsetAdjustmentBehavior:UIScrollViewContentInsetAdjustmentNever];
}

How to convert current date to epoch timestamp?

from time import time
>>> int(time())
1542449530


>>> time()
1542449527.6991141
>>> int(time())
1542449530
>>> str(time()).replace(".","")
'154244967282'

But Should it not return ?

'15424495276991141'

What does it mean when the size of a VARCHAR2 in Oracle is declared as 1 byte?

it means ONLY one byte will be allocated per character - so if you're using multi-byte charsets, your 1 character won't fit

if you know you have to have at least room enough for 1 character, don't use the BYTE syntax unless you know exactly how much room you'll need to store that byte

when in doubt, use VARCHAR2(1 CHAR)

same thing answered here Difference between BYTE and CHAR in column datatypes

Also, in 12c the max for varchar2 is now 32k, not 4000. If you need more than that, use CLOB

in Oracle, don't use VARCHAR

Convert Rows to columns using 'Pivot' in SQL Server

This is for dynamic # of weeks.

Full example here:SQL Dynamic Pivot

DECLARE @DynamicPivotQuery AS NVARCHAR(MAX)
DECLARE @ColumnName AS NVARCHAR(MAX)

--Get distinct values of the PIVOT Column 
SELECT @ColumnName= ISNULL(@ColumnName + ',','') + QUOTENAME(Week)
FROM (SELECT DISTINCT Week FROM #StoreSales) AS Weeks

--Prepare the PIVOT query using the dynamic 
SET @DynamicPivotQuery = 
  N'SELECT Store, ' + @ColumnName + ' 
    FROM #StoreSales
    PIVOT(SUM(xCount) 
          FOR Week IN (' + @ColumnName + ')) AS PVTTable'
--Execute the Dynamic Pivot Query
EXEC sp_executesql @DynamicPivotQuery

Using Spring MVC Test to unit test multipart POST request

If you are using Spring4/SpringBoot 1.x, then it's worth mentioning that you can add "text" (json) parts as well . This can be done via MockMvcRequestBuilders.fileUpload().file(MockMultipartFile file) (which is needed as method .multipart() is not available in this version):

@Test
public void test() throws Exception {

   mockMvc.perform( 
       MockMvcRequestBuilders.fileUpload("/files")
         // file-part
         .file(makeMultipartFile( "file-part" "some/path/to/file.bin", "application/octet-stream"))
        // text part
         .file(makeMultipartTextPart("json-part", "{ \"foo\" : \"bar\" }", "application/json"))
       .andExpect(status().isOk())));

   }

   private MockMultipartFile(String requestPartName, String filename, 
       String contentType, String pathOnClassPath) {

       return new MockMultipartFile(requestPartName, filename, 
          contentType, readResourceFile(pathOnClasspath);
   }

   // make text-part using MockMultipartFile
   private MockMultipartFile makeMultipartTextPart(String requestPartName, 
       String value, String contentType) throws Exception {

       return new MockMultipartFile(requestPartName, "", contentType,
               value.getBytes(Charset.forName("UTF-8")));   
   }


   private byte[] readResourceFile(String pathOnClassPath) throws Exception {
      return Files.readAllBytes(Paths.get(Thread.currentThread().getContextClassLoader()
         .getResource(pathOnClassPath).toUri()));
   }

}

How do I add python3 kernel to jupyter (IPython)

for recent versions of jupyter/ipython: use jupyter kernelspec

Full doc: https://ipython.readthedocs.io/en/latest/install/kernel_install.html

list current kernels

$ jupyter kernelspec list
Available kernels:
  python2    .../Jupyter/kernels/python2
  python3    .../Jupyter/kernels/python3

In my case, the python3 kernel setup was broken because the py3.5 linked was no longer there, replaced by a py3.6

add/remove kernels

Remove:

$ jupyter kernelspec uninstall python3

Add a new one: Using the Python you wish to add and pointing to the python which runs your jupiter:

$ /path/to/kernel/env/bin/python -m ipykernel install --prefix=/path/to/jupyter/env --name 'python-my-env'

See more examples in https://ipython.readthedocs.io/en/6.5.0/install/kernel_install.html#kernels-for-different-environments

List again:

$ jupyter kernelspec list
Available kernels:
  python3    /usr/local/lib/python3.6/site-packages/ipykernel/resources
  python2    /Users/stefano/Library/Jupyter/kernels/python2

Doc: https://jupyter-client.readthedocs.io/en/latest/kernels.html#kernelspecs

Details

Kernels available are listed under the kernels folder in Jupyter DATA DIRECTORY (see http://jupyter.readthedocs.io/en/latest/projects/jupyter-directories.html for details).

For instance on macosx that would be /Users/YOURUSERNAME/Library/Jupyter/kernels/

the kernel is simply described by a kernel.json file, eg. for /Users/me/Library/Jupyter/kernels/python3/kernel.json

{
 "argv": [
  "/usr/local/opt/python3/bin/python3.5",
  "-m",
  "ipykernel",
  "-f",
  "{connection_file}"
 ],
 "language": "python",
 "display_name": "Python 3"
}

Rather then manipulating that by hand, you can use the kernelspec command (as above). It was previously available through ipython now through jupyter (http://ipython.readthedocs.io/en/stable/install/kernel_install.html#kernels-for-different-environments - https://jupyter-client.readthedocs.io/en/latest/kernels.html#kernelspecs).

$ jupyter kernelspec help
Manage Jupyter kernel specifications.

Subcommands
-----------

Subcommands are launched as `jupyter kernelspec cmd [args]`. For information on
using subcommand 'cmd', do: `jupyter kernelspec cmd -h`.

list
    List installed kernel specifications.
install
    Install a kernel specification directory.
uninstall
    Alias for remove
remove
    Remove one or more Jupyter kernelspecs by name.
install-self
    [DEPRECATED] Install the IPython kernel spec directory for this Python.

To see all available configurables, use `--help-all`

Kernels for other languages

By the way, not strictly related to this question but there's a lot of other kernels available... https://github.com/jupyter/jupyter/wiki/Jupyter-kernels

How do I work with a git repository within another repository?

If I understand your problem well you want the following things:

  1. Have your media files stored in one single git repository, which is used by many projects
  2. If you modify a media file in any of the projects in your local machine, it should immediately appear in every other project (so you don't want to commit+push+pull all the time)

Unfortunately there is no ultimate solution for what you want, but there are some things by which you can make your life easier.

First you should decide one important thing: do you want to store for every version in your project repository a reference to the version of the media files? So for example if you have a project called example.com, do you need know which style.css it used 2 weeks ago, or the latest is always (or mostly) the best?

If you don't need to know that, the solution is easy:

  1. create a repository for the media files and one for each project
  2. create a symbolic link in your projects which point to the locally cloned media repository. You can either create a relative symbolic link (e.g. ../media) and assume that everybody will checkout the project so that the media directory is in the same place, or write the name of the symbolic link into .gitignore, and everybody can decide where he/she puts the media files.

In most of the cases, however, you want to know this versioning information. In this case you have two choices:

  1. Store every project in one big repository. The advantage of this solution is that you will have only 1 copy of the media repository. The big disadvantage is that it is much harder to switch between project versions (if you checkout to a different version you will always modify ALL projects)

  2. Use submodules (as explained in answer 1). This way you will store the media files in one repository, and the projects will contain only a reference to a specific media repo version. But this way you will normally have many local copies of the media repository, and you cannot easily modify a media file in all projects.

If I were you I would probably choose the first or third solution (symbolic links or submodules). If you choose to use submodules you can still do a lot of things to make your life easier:

  1. Before committing you can rename the submodule directory and put a symlink to a common media directory. When you're ready to commit, you can remove the symlink and remove the submodule back, and then commit.

  2. You can add one of your copy of the media repository as a remote repository to all of your projects.

You can add local directories as a remote this way:

cd /my/project2/media
git remote add project1 /my/project1/media

If you modify a file in /my/project1/media, you can commit it and pull it from /my/project2/media without pushing it to a remote server:

cd /my/project1/media
git commit -a -m "message"
cd /my/project2/media
git pull project1 master

You are free to remove these commits later (with git reset) because you haven't shared them with other users.

Proper way to handle multiple forms on one page in Django

If you are using approach with class-based views and different 'action' attrs i mean

Put different URLs in the action for the two forms. Then you'll have two different view functions to deal with the two different forms.

You can easily handle errors from different forms using overloaded get_context_data method, e.x:

views.py:

class LoginView(FormView):
    form_class = AuthFormEdited
    success_url = '/'
    template_name = 'main/index.html'

    def dispatch(self, request, *args, **kwargs):
        return super(LoginView, self).dispatch(request, *args, **kwargs)

    ....

    def get_context_data(self, **kwargs):
        context = super(LoginView, self).get_context_data(**kwargs)
        context['login_view_in_action'] = True
        return context

class SignInView(FormView):
    form_class = SignInForm
    success_url = '/'
    template_name = 'main/index.html'

    def dispatch(self, request, *args, **kwargs):
        return super(SignInView, self).dispatch(request, *args, **kwargs)

    .....

    def get_context_data(self, **kwargs):
        context = super(SignInView, self).get_context_data(**kwargs)
        context['login_view_in_action'] = False
        return context

template:

<div class="login-form">
<form action="/login/" method="post" role="form">
    {% csrf_token %}
    {% if login_view_in_action %}
        {% for e in form.non_field_errors %}
            <div class="alert alert-danger alert-dismissable">
                {{ e }}
                <a class="panel-close close" data-dismiss="alert">×</a>
            </div>
        {% endfor %}
    {% endif %}
    .....
    </form>
</div>

<div class="signin-form">
<form action="/registration/" method="post" role="form">
    {% csrf_token %}
    {% if not login_view_in_action %}
        {% for e in form.non_field_errors %}
            <div class="alert alert-danger alert-dismissable">
                {{ e }}
                <a class="panel-close close" data-dismiss="alert">×</a>
            </div>
        {% endfor %}
    {% endif %}
   ....
  </form>
</div>

What is the current choice for doing RPC in Python?

XML-RPC is part of the Python standard library:

What's the difference between a temp table and table variable in SQL Server?

It surprises me that no one mentioned the key difference between these two is that the temp table supports parallel insert while the table variable doesn't. You should be able to see the difference from the execution plan. And here is the video from SQL Workshops on Channel 9.

This also explains why you should use a table variable for smaller tables, otherwise use a temp table, as SQLMenace answered before.

SQL - How do I get only the numbers after the decimal?

You can use FLOOR:

select x, ABS(x) - FLOOR(ABS(x))
from (
    select 2.938 as x
) a

Output:

x                                       
-------- ----------
2.938    0.938

Or you can use SUBSTRING:

select x, SUBSTRING(cast(x as varchar(max)), charindex(cast(x as varchar(max)), '.') + 3, len(cast(x as varchar(max))))
from (
    select 2.938 as x
) a

Init array of structs in Go

You can have it this way:

It is important to mind the commas after each struct item or set of items.

earnings := []LineItemsType{

        LineItemsType{

            TypeName: "Earnings",

            Totals: 0.0,

            HasTotal: true,

            items: []LineItems{

                LineItems{

                    name: "Basic Pay",

                    amount: 100.0,
                },

                LineItems{

                    name: "Commuter Allowance",

                    amount: 100.0,
                },
            },
        },
        LineItemsType{

            TypeName: "Earnings",

            Totals: 0.0,

            HasTotal: true,

            items: []LineItems{

                LineItems{

                    name: "Basic Pay",

                    amount: 100.0,
                },

                LineItems{

                    name: "Commuter Allowance",

                    amount: 100.0,
                },
            },
        },
    }

Calculate correlation with cor(), only for numerical columns

I found an easier way by looking at the R script generated by Rattle. It looks like below:

correlations <- cor(mydata[,c(1,3,5:87,89:90,94:98)], use="pairwise", method="spearman")

How do I format date in jQuery datetimepicker?

This works for me. Since it "extends" datepicker we can still use dateFormat:'dd/mm/yy'.

$(function() {
    $('.jqueryui-marker-datepicker').datetimepicker({
        showSecond: true,
        dateFormat: 'dd/mm/yy',
      timeFormat: 'hh:mm:ss',
      stepHour: 2,
      stepMinute: 10,
      stepSecond: 10

     });
});

How to output messages to the Eclipse console when developing for Android

Log.v("blah", "blah blah");

You need to add the android Log view in eclipse to see them. There are also other methods depending on the severity of the message (error, verbose, warning, etc..).

Regex to match 2 digits, optional decimal, two digits

You mentioned that you want the regex to match each of those strings, yet you previously mention that the is 1-2 digits before the decimal?

This will match 1-2 digits followed by a possible decimal, followed by another 1-2 digits but FAIL on your example of .33

\d{1,2}\.?\d{1,2}

This will match 0-2 digits followed by a possible deciaml, followed by another 1-2 digits and match on your example of .33

\d{0,2}\.?\d{1,2}

Not sure exactly which one you're looking for.

Add items in array angular 4

Yes there is a way to do it.

First declare a class.

//anyfile.ts
export class Custom
{
  name: string, 
  empoloyeeID: number
}

Then in your component import the class

import {Custom} from '../path/to/anyfile.ts'
.....
export class FormComponent implements OnInit {
 name: string;
 empoloyeeID : number;
 empList: Array<Custom> = [];
 constructor() {

 }

 ngOnInit() {
 }
 onEmpCreate(){
   //console.log(this.name,this.empoloyeeID);
   let customObj = new Custom();
   customObj.name = "something";
   customObj.employeeId = 12; 
   this.empList.push(customObj);
   this.name ="";
   this.empoloyeeID = 0; 
 }
}

Another way would be to interfaces read the documentation once - https://www.typescriptlang.org/docs/handbook/interfaces.html

Also checkout this question, it is very interesting - When to use Interface and Model in TypeScript / Angular2

VERR_VMX_MSR_VMXON_DISABLED when starting an image from Oracle virtual box

Which version VirtualBox do you use? I found the same problem and when use update latest version on my X64 win7 machine VirtualBox-4.3.4-91027-Win But I uninstall it and back to VirtualBox-4.2.18-88781-Win

It works well, try it until Oracle fix it.

Redirect all output to file in Bash

That part is written to stderr, use 2> to redirect it. For example:

foo > stdout.txt 2> stderr.txt

or if you want in same file:

foo > allout.txt 2>&1

Note: this works in (ba)sh, check your shell for proper syntax

Migrating from VMWARE to VirtualBox

After many attempts I was finally able to get this working. Essentially what I did was download and use the vmware converter to merge the two disks into one. After that I was able to attach the newly created disk to VitrualBox.

The steps involved are very simple:

BEFORE YOU DO ANYTHING!

1) MAKE A BACKUP!!! Even if you follow these instruction, you could screw things up, so make a backup. Just shutdown the VM and then make a copy of the directory where VM resides.

2) Uninstall VMware Tools from the VM that you are going to convert. If for some reason you forget this step, you can still uninstall it after getting everything running under VirtualBox by following these steps. Do yourself the favor and just do it now.

NOW THE FUN PART!!!

1) Download and install the VMware Converter. I used 5.0.1 build-875114, just use the latest.

2) Download and install VirtualBox

3) Fire up VMWare convertor:

Fire up VMWare convertor

4) Click on Convert machine

6) Browse to the .vmx for your VM and click Next.

Convert machine

7) Give the new VM a name and select the location where you want to put it. Click Next

Give the new VM a name and select the location

8) Click Next on the Options screen. You shouldn't have to change anything here.

Click <code>Next</code> on the <code>Options</code> screen.

9) Click Finish on the Summary screen to begin the conversion.

Click <code>Finish</code> on the <code>Summary</code> screen

10) The conversion should start. This will take a LOOONG time so be patient.

The conversion should start.

11) Hopefully all went well, if it did, you should see that the conversion is completed:

conversion is completed

12) Now open up VirtualBox and click New.

open up VirtualBox and click <code>New</code>

13) Give your VM a name and select what Type and Version it is. Click Next.

Give your VM a name and select what <code>Type</code> and <code>Version</code> it is.

14) Select the size of the memory you want to give it. Click Next.

Select the size of the memory you want to give it.

15) For the Hard Drive, click Use and existing hard drive file and select the newly converted .vmdk file.

Use and existing hard drive file

16) Now Click Settings and select the Storage menu. The issue is that by default VirtualBox will add the drive as an IDE. This won't work and we need as we need to put it on a SCSI controller.

put it on a SCSI controller

17) Select the IDE controller and the Remove Controller button.

Select the IDE controller and the <code>Remove Controller</code> button.

18) Now click the Add Controller button and select Add SCSI Controller

Add SCSI Controller

19) Click the Add Hard Disk button.

Add Hard Disk

20) Click Choose existing disk

Choose existing disk

21) Select your .vmdk file. Click OK

Select your <code>.vmdk</code> file.

22) Select the System menu.

Select the <code>System</code> menu.

23) Click Enable IO APIC. Then click OK

Click <code>Enable IO APIC</code>.

24) Congrats!!! Your VM is now confgiured! Click Start to startup the VM!

Click <code>Start</code> to startup the VM!

Is there a list of screen resolutions for all Android based phones and tablets?

Here is a list of almost all resolutions of tablets :

2560*1600
1366*768
1280*800
1280*768
1024*768
1024*600
960*640
960*540
854*480
800*600
800*480
800*400

Of this, the most common resolutions are :

1280*800
1280*768
1024*600
1024*800
1024*768
800*400
800*480

Happy designing .. ! :)

How to use split?

According to MDN, the split() method divides a String into an ordered set of substrings, puts these substrings into an array, and returns the array.

Example

var str = 'Hello my friend'

var split1 = str.split(' ') // ["Hello", "my", "friend"]
var split2 = str.split('') // ["H", "e", "l", "l", "o", " ", "m", "y", " ", "f", "r", "i", "e", "n", "d"]

In your case

var str = 'something -- something_else'
var splitArr = str.split(' -- ') // ["something", "something_else"]

console.log(splitArr[0]) // something
console.log(splitArr[1]) // something_else

Is it possible to use pip to install a package from a private GitHub repository?

Just copy the remote from the original git clone command (or from git remote -v). You will get something like this:

Next, you need to replace : with / next to the domain name.

So install using:

pip install git+ssh://[email protected]/your_account/my_pro.git

excel vba getting the row,cell value from selection.address

Is this what you are looking for ?

Sub getRowCol()

    Range("A1").Select ' example

    Dim col, row
    col = Split(Selection.Address, "$")(1)
    row = Split(Selection.Address, "$")(2)

    MsgBox "Column is : " & col
    MsgBox "Row is : " & row

End Sub

How to get a view table query (code) in SQL Server 2008 Management Studio

right-click the view in the object-explorer, select "script view as...", then "create to" and then "new query editor window"

Redirecting from cshtml page

This clearly is a bad case of controller logic in a view. It would be better to do this in a controller and return the desired view.

[ChildActionOnly]
public ActionResult Results() 
{
    EnumerableRowCollection<DataRow> custs = ViewBag.Customers;
    bool anyRows = custs.Any();

    if(anyRows == false)
    {
        return View("NoResults");
    }
    else
    {
        return View("OtherView");
    }
}

Modify NoResults.cshtml to a Partial.

And call this as a Partial view in the parent view

@Html.Partial("Results")

You might have to pass the Customer collection as a model to the Result action or in a ViewDataDictionary due to reasons explained here: Can't access ViewBag in a partial view in ASP.NET MVC3

The ChildActionOnly attribute will make sure you cannot go to this page by navigating and that this view must be rendered as a partial, thus by a parent view. cfr: Using ChildActionOnly in MVC

Removing multiple keys from a dictionary safely

Some timing tests for cpython 3 shows that a simple for loop is the fastest way, and it's quite readable. Adding in a function doesn't cause much overhead either:

timeit results (10k iterations):

  • all(x.pop(v) for v in r) # 0.85
  • all(map(x.pop, r)) # 0.60
  • list(map(x.pop, r)) # 0.70
  • all(map(x.__delitem__, r)) # 0.44
  • del_all(x, r) # 0.40
  • <inline for loop>(x, r) # 0.35
def del_all(mapping, to_remove):
      """Remove list of elements from mapping."""
      for key in to_remove:
          del mapping[key]

For small iterations, doing that 'inline' was a bit faster, because of the overhead of the function call. But del_all is lint-safe, reusable, and faster than all the python comprehension and mapping constructs.

How do I execute code AFTER a form has loaded?

You could also try putting your code in the Activated event of the form, if you want it to occur, just when the form is activated. You would need to put in a boolean "has executed" check though if it is only supposed to run on the first activation.

Angular Directive refresh on parameter change

angular.module('app').directive('conversation', function() {
    return {
        restrict: 'E',
        link: function ($scope, $elm, $attr) {
            $scope.$watch("some_prop", function (newValue, oldValue) {
                  var typeId = $attr.type-id;
                  // Your logic.
            });
        }
    };
}

How to make node.js require absolute? (instead of relative)

Just want to follow up on the great answer from Paolo Moretti and Browserify. If you are using a transpiler (e.g., babel, typescript) and you have separate folders for source and transpiled code like src/ and dist/, you could use a variation of the solutions as

node_modules

With the following directory structure:

app
  node_modules
    ... // normal npm dependencies for app
  src
    node_modules
      app
        ... // source code
  dist
    node_modules
      app
        ... // transpiled code

you can then let babel etc to transpile src directory to dist directory.

symlink

Using symlink we can get rid some levels of nesting:

app
  node_modules
    ... // normal npm dependencies for app
  src
    node_modules
      app // symlinks to '..'
    ... // source code
  dist
    node_modules
      app // symlinks to '..'
    ... // transpiled code

A caveat with babel --copy-files The --copy-files flag of babel does not deal with symlinks well. It may keep navigating into the .. symlink and recusively seeing endless files. A workaround is to use the following directory structure:

app
  node_modules
    app // symlink to '../src'
    ... // normal npm dependencies for app
  src
    ... // source code
  dist
    node_modules
      app // symlinks to '..'
    ... // transpiled code

In this way, code under src will still have app resolved to src, whereas babel would not see symlinks anymore.

Change value of variable with dplyr

We can use replace to change the values in 'mpg' to NA that corresponds to cyl==4.

mtcars %>%
     mutate(mpg=replace(mpg, cyl==4, NA)) %>%
     as.data.frame()

error: pathspec 'test-branch' did not match any file(s) known to git

I got this error because the instruction on the Web was

git checkout https://github.com/veripool/verilog-mode

which I did in a directory where (on my own initiative) i had run git init. The correct Web instruction (for newbies like me) should have been

git clone https://github.com/veripool/verilog-mode

Generate a random point within a circle (uniformly)

Think about it this way. If you have a rectangle where one axis is radius and one is angle, and you take the points inside this rectangle that are near radius 0. These will all fall very close to the origin (that is close together on the circle.) However, the points near radius R, these will all fall near the edge of the circle (that is, far apart from each other.)

This might give you some idea of why you are getting this behavior.

The factor that's derived on that link tells you how much corresponding area in the rectangle needs to be adjusted to not depend on the radius once it's mapped to the circle.

Edit: So what he writes in the link you share is, "That’s easy enough to do by calculating the inverse of the cumulative distribution, and we get for r:".

The basic premise is here that you can create a variable with a desired distribution from a uniform by mapping the uniform by the inverse function of the cumulative distribution function of the desired probability density function. Why? Just take it for granted for now, but this is a fact.

Here's my somehwat intuitive explanation of the math. The density function f(r) with respect to r has to be proportional to r itself. Understanding this fact is part of any basic calculus books. See sections on polar area elements. Some other posters have mentioned this.

So we'll call it f(r) = C*r;

This turns out to be most of the work. Now, since f(r) should be a probability density, you can easily see that by integrating f(r) over the interval (0,R) you get that C = 2/R^2 (this is an exercise for the reader.)

Thus, f(r) = 2*r/R^2

OK, so that's how you get the formula in the link.

Then, the final part is going from the uniform random variable u in (0,1) you must map by the inverse function of the cumulative distribution function from this desired density f(r). To understand why this is the case you need to find an advanced probability text like Papoulis probably (or derive it yourself.)

Integrating f(r) you get F(r) = r^2/R^2

To find the inverse function of this you set u = r^2/R^2 and then solve for r, which gives you r = R * sqrt(u)

This totally makes sense intuitively too, u = 0 should map to r = 0. Also, u = 1 shoudl map to r = R. Also, it goes by the square root function, which makes sense and matches the link.

.datepicker('setdate') issues, in jQuery

As Scobal's post implies, the datepicker is looking for a Date object - not just a string! So, to modify your example code to do what you want:

var queryDate = new Date('2009/11/01'); // Dashes won't work
$('#datePicker').datepicker('setDate', queryDate);

Setting up redirect in web.config file

  1. Open web.config in the directory where the old pages reside
  2. Then add code for the old location path and new destination as follows:

    <configuration>
      <location path="services.htm">
        <system.webServer>
          <httpRedirect enabled="true" destination="http://domain.com/services" httpResponseStatus="Permanent" />
        </system.webServer>
      </location>
      <location path="products.htm">
        <system.webServer>
          <httpRedirect enabled="true" destination="http://domain.com/products" httpResponseStatus="Permanent" />
        </system.webServer>
      </location>
    </configuration>
    

You may add as many location paths as necessary.

How do you write to a folder on an SD card in Android?

File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath() + "/dir1/dir2");
dir.mkdirs();
File file = new File(dir, "filename");

FileOutputStream f = new FileOutputStream(file);
...

How to set environment variable for everyone under my linux system?

Every process running under the Linux kernel receives its own, unique environment that it inherits from its parent. In this case, the parent will be either a shell itself (spawning a sub shell), or the 'login' program (on a typical system).

As each process' environment is protected, there is no way to 'inject' an environmental variable to every running process, so even if you modify the default shell .rc / profile, it won't go into effect until each process exits and reloads its start up settings.

Look in /etc/ to modify the default start up variables for any particular shell. Just realize that users can (and often do) change them in their individual settings.

Unix is designed to obey the user, within limits.

NB: Bash is not the only shell on your system. Pay careful attention to what the /bin/sh symbolic link actually points to. On many systems, this could actually be dash which is (by default, with no special invocation) POSIXLY correct. Therefore, you should take care to modify both defaults, or scripts that start with /bin/sh will not inherit your global defaults. Similarly, take care to avoid syntax that only bash understands when editing both, aka avoiding bashisms.

SQL Server 2008 Connection Error "No process is on the other end of the pipe"

This problem was caused for me by this error which appeared just prior in the application error log.

"A read operation on a large object failed while sending data to the client. A common cause for this is if the application is running in READ UNCOMMITTED isolation level. This connection will be terminated."

I was storing PDFs in a SQL table and when attempting to SELECT from that table it spit out that error, which resulted in the error mentioned in your question.

The solution was to delete the columns that had large amounts of text, in my case Base64 encoded files.

Ignore files that have already been committed to a Git repository

If you want to stop tracking file without deleting the file from your local system, which I prefer for ignoring config/database.yml file. Simply try:

git rm --cached config/database.yml
# this will delete your file from git history but not from your local system.

now, add this file to .gitignore file and commit the changes. And from now on, any changes made to config/database.yml will not get tracked by git.

$ echo config/database.yml >> .gitignore

Thanks

reading text file with utf-8 encoding using java

I ran into the same problem every time it finds a special character marks it as ??. to solve this, I tried using the encoding: ISO-8859-1

BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("txtPath"),"ISO-8859-1"));

while ((line = br.readLine()) != null) {

}

I hope this can help anyone who sees this post.

How to Upload Image file in Retrofit 2

Using Retrofit 2.0 you may use this:

@Multipart
    @POST("uploadImage")
    Call<ResponseBody> uploadImage(@Part("file\"; fileName=\"myFile.png\" ")RequestBody requestBodyFile, @Part("image") RequestBody requestBodyJson);

Make a request:

File imgFile = new File("YOUR IMAGE FILE PATH");
RequestBody requestBodyFile = RequestBody.create(MediaType.parse("image/*"), imgFile);
RequestBody requestBodyJson = RequestBody.create(MediaType.parse("text/plain"),
                    retrofitClient.getJsonObject(uploadRequest));



//make sync call
Call<ResponseBody> uploadBundle = uploadImpl.uploadImage(requestBodyFile, requestBodyJson);
Response<BaseResponse> response = uploadBundle.execute();

please refer https://square.github.io/retrofit/

Expected linebreaks to be 'LF' but found 'CRLF' linebreak-style

The same situation occurred when I was using VSCode with eslint. If you use VSCode,

1 - Click area that name can be both LF or CRLF where at the bottom right of the VScode.

2 - Select LF from the drop-down menu.

That's worked for me.

enter image description here

How to check that Request.QueryString has a specific value or not in ASP.NET?

string.IsNullOrEmpty(Request.QueryString["aspxerrorpath"]) //true -> there is no value

Will return if there is a value

How to create a TextArea in Android

<EditText
    android:id="@+id/comments_textbox"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="comments"
    android:inputType="textMultiLine"
    android:longClickable="false" />

use it to create multi line text box like textArea in Html

VB.net Need Text Box to Only Accept Numbers

This worked for me... just clear the textbox completely as non-numeric keys are pressed.

Private Sub TextBox2_TextChanged(sender As Object, e As EventArgs) Handles TextBox2.TextChanged
    If IsNumeric(TextBox2.Text) Then
        'nada
    Else
        TextBox2.Clear()
    End If
End Sub

How to get detailed list of connections to database in sql server 2005?

As @Hutch pointed out, one of the major limitations of sp_who2 is that it does not take any parameters so you cannot sort or filter it by default. You can save the results into a temp table, but then the you have to declare all the types ahead of time (and remember to DROP TABLE).

Instead, you can just go directly to the source on master.dbo.sysprocesses

I've constructed this to output almost exactly the same thing that sp_who2 generates, except that you can easily add ORDER BY and WHERE clauses to get meaningful output.

SELECT  spid,
        sp.[status],
        loginame [Login],
        hostname, 
        blocked BlkBy,
        sd.name DBName, 
        cmd Command,
        cpu CPUTime,
        physical_io DiskIO,
        last_batch LastBatch,
        [program_name] ProgramName   
FROM master.dbo.sysprocesses sp 
JOIN master.dbo.sysdatabases sd ON sp.dbid = sd.dbid
ORDER BY spid 

How to prevent SIGPIPEs (or handle them properly)

You generally want to ignore the SIGPIPE and handle the error directly in your code. This is because signal handlers in C have many restrictions on what they can do.

The most portable way to do this is to set the SIGPIPE handler to SIG_IGN. This will prevent any socket or pipe write from causing a SIGPIPE signal.

To ignore the SIGPIPE signal, use the following code:

signal(SIGPIPE, SIG_IGN);

If you're using the send() call, another option is to use the MSG_NOSIGNAL option, which will turn the SIGPIPE behavior off on a per call basis. Note that not all operating systems support the MSG_NOSIGNAL flag.

Lastly, you may also want to consider the SO_SIGNOPIPE socket flag that can be set with setsockopt() on some operating systems. This will prevent SIGPIPE from being caused by writes just to the sockets it is set on.

How do I rename both a Git local and remote branch name?

It can also be done the following way.

At first rename local branch, then remote branch.

Renaming the local branch:

If logged in another branch,

git branch -m old_branch new_branch 

If logged in the same branch,

git branch -m new_branch

Renaming remote branch:

git push origin :old_branch    // Delete the remote branch

git push --set-upstream origin new_branch   // Create a new remote branch

Is there a 'foreach' function in Python 3?

Other examples:

Python Foreach Loop:

array = ['a', 'b']
for value in array:
    print(value)
    # a
    # b

Python For Loop:

array = ['a', 'b']
for index in range(len(array)):
    print("index: %s | value: %s" % (index, array[index]))
    # index: 0 | value: a
    # index: 1 | value: b

How to Get True Size of MySQL Database?

If you want to find the size of all MySQL databases, us this command, it will show their respective sizes in megabytes;

SELECT table_schema "database", sum(data_length + index_length)/1024/1024 "size in MB" FROM information_schema.TABLES GROUP BY table_schema;

If you have large databases, you can use the following command to show the result in gigabytes;

SELECT table_schema "database", sum(data_length + index_length)/1024/1024/1024 "size in GB" FROM information_schema.TABLES GROUP BY table_schema;

If you want to show the size of only a specific database, for example YOUR_DATABASE_NAME, you could use the following query;

SELECT table_schema "database", sum(data_length + index_length)/1024/1024/1024 "size in GB" FROM information_schema.TABLES WHERE table_schema='YOUR_DATABASE_NAME' GROUP BY table_schema;

Which is better, return value or out parameter?

Additionally, return values are compatible with asynchronous design paradigms.

You cannot designate a function "async" if it uses ref or out parameters.

In summary, Return Values allow method chaining, cleaner syntax (by eliminating the necessity for the caller to declare additional variables), and allow for asynchronous designs without the need for substantial modification in the future.