Programs & Examples On #Stack frame

What is exactly the base pointer and stack pointer? To what do they point?

EDIT: For a better description, see x86 Disassembly/Functions and Stack Frames in a WikiBook about x86 assembly. I try to add some info you might be interested in using Visual Studio.

Storing the caller EBP as the first local variable is called a standard stack frame, and this may be used for nearly all calling conventions on Windows. Differences exist whether the caller or callee deallocates the passed parameters, and which parameters are passed in registers, but these are orthogonal to the standard stack frame problem.

Speaking about Windows programs, you might probably use Visual Studio to compile your C++ code. Be aware that Microsoft uses an optimization called Frame Pointer Omission, that makes it nearly impossible to do walk the stack without using the dbghlp library and the PDB file for the executable.

This Frame Pointer Omission means that the compiler does not store the old EBP on a standard place and uses the EBP register for something else, therefore you have hard time finding the caller EIP without knowing how much space the local variables need for a given function. Of course Microsoft provides an API that allows you to do stack-walks even in this case, but looking up the symbol table database in PDB files takes too long for some use cases.

To avoid FPO in your compilation units, you need to avoid using /O2 or need to explicitly add /Oy- to the C++ compilation flags in your projects. You probably link against the C or C++ runtime, which uses FPO in the Release configuration, so you will have hard time to do stack walks without the dbghlp.dll.

How to save a list as numpy array in python?

import numpy as np 

... ## other code

some list comprehension

t=[nodel[ nodenext[i][j] ] for j in idx]
            #for each link, find the node lables 
            #t is the list of node labels 

Convert the list to a numpy array using the array method specified in the numpy library.

t=np.array(t)

This may be helpful: https://numpy.org/devdocs/user/basics.creation.html

Reading a registry key in C#

see this http://www.codeproject.com/Articles/3389/Read-write-and-delete-from-registry-with-C

Updated:

You can use RegistryKey class under Microsoft.Win32 namespace.

Some important functions of RegistryKey are as follows:

GetValue       //to get value of a key
SetValue       //to set value to a key
DeleteValue    //to delete value of a key
OpenSubKey     //to read value of a subkey (read-only)
CreateSubKey   //to create new or edit value to a subkey
DeleteSubKey   //to delete a subkey
GetValueKind   //to retrieve the datatype of registry key

What is the difference between persist() and merge() in JPA and Hibernate?

The most important difference is this:

  • In case of persist method, if the entity that is to be managed in the persistence context, already exists in persistence context, the new one is ignored. (NOTHING happened)

  • But in case of merge method, the entity that is already managed in persistence context will be replaced by the new entity (updated) and a copy of this updated entity will return back. (from now on any changes should be made on this returned entity if you want to reflect your changes in persistence context)

Cannot kill Python script with Ctrl-C

I think it's best to call join() on your threads when you expect them to die. I've taken some liberty with your code to make the loops end (you can add whatever cleanup needs are required to there as well). The variable die is checked for truth on each pass and when it's True then the program exits.

import threading
import time

class MyThread (threading.Thread):
    die = False
    def __init__(self, name):
        threading.Thread.__init__(self)
        self.name = name

    def run (self):
        while not self.die:
            time.sleep(1)
            print (self.name)

    def join(self):
        self.die = True
        super().join()

if __name__ == '__main__':
    f = MyThread('first')
    f.start()
    s = MyThread('second')
    s.start()
    try:
        while True:
            time.sleep(2)
    except KeyboardInterrupt:
        f.join()
        s.join()

How to extract a string between two delimiters

Try as

String s = "ABC[ This is to extract ]";
        Pattern p = Pattern.compile(".*\\[ *(.*) *\\].*");
        Matcher m = p.matcher(s);
        m.find();
        String text = m.group(1);
        System.out.println(text);

How to catch SQLServer timeout exceptions

Whats the value for the SqlException.ErrorCode property? Can you work with that?

When having timeouts, it may be worth checking the code for -2146232060.

I would set this up as a static const in your data code.

Create Table from View

SELECT * INTO [table_a] FROM dbo.myView

Automatically run %matplotlib inline in IPython Notebook

I think what you want might be to run the following from the command line:

ipython notebook --matplotlib=inline

If you don't like typing it at the cmd line every time then you could create an alias to do it for you.

How to remove/ignore :hover css style on touch devices

Try this easy 2019 jquery solution, although its been around a while;

  1. add this plugin to head:

    src="https://code.jquery.com/ui/1.12.0/jquery-ui.min.js"

  2. add this to js:

    $("*").on("touchend", function(e) { $(this).focus(); }); //applies to all elements

  3. some suggested variations to this are:

    $(":input, :checkbox,").on("touchend", function(e) {(this).focus);}); //specify elements

    $("*").on("click, touchend", function(e) { $(this).focus(); }); //include click event

    css: body { cursor: pointer; } //touch anywhere to end a focus

Notes

  • place plugin before bootstrap.js to avoif affecting tooltips
  • only tested on iphone XR ios 12.1.12, and ipad 3 ios 9.3.5, using Safari or Chrome.

References:

https://code.jquery.com/ui/

https://api.jquery.com/category/selectors/jquery-selector-extensions/

Checking for a null object in C++

  • What is the most typical/common way of doing this with an object C++ (that doesn't involve overloading the == operator)?
  • Is this even the right approach? ie. should I not write functions that take an object as an argument, but rather, write member functions? (But even if so, please answer the original question.)

No, references cannot be null (unless Undefined Behavior has already happened, in which case all bets are already off). Whether you should write a method or non-method depends on other factors.

  • Between a function that takes a reference to an object, or a function that takes a C-style pointer to an object, are there reasons to choose one over the other?

If you need to represent "no object", then pass a pointer to the function, and let that pointer be NULL:

int silly_sum(int const* pa=0, int const* pb=0, int const* pc=0) {
  /* Take up to three ints and return the sum of any supplied values.

  Pass null pointers for "not supplied".

  This is NOT an example of good code.
  */
  if (!pa && (pb || pc)) return silly_sum(pb, pc);
  if (!pb && pc) return silly_sum(pa, pc);
  if (pc) return silly_sum(pa, pb) + *pc;
  if (pa && pb) return *pa + *pb;
  if (pa) return *pa;
  if (pb) return *pb;
  return 0;
}

int main() {
  int a = 1, b = 2, c = 3;
  cout << silly_sum(&a, &b, &c) << '\n';
  cout << silly_sum(&a, &b) << '\n';
  cout << silly_sum(&a) << '\n';
  cout << silly_sum(0, &b, &c) << '\n';
  cout << silly_sum(&a, 0, &c) << '\n';
  cout << silly_sum(0, 0, &c) << '\n';
  return 0;
}

If "no object" never needs to be represented, then references work fine. In fact, operator overloads are much simpler because they take overloads.

You can use something like boost::optional.

Why use double indirection? or Why use pointers to pointers?

The following is a very simple C++ example that shows that if you want to use a function to set a pointer to point to an object, you need a pointer to a pointer. Otherwise, the pointer will keep reverting to null.

(A C++ answer, but I believe it's the same in C.)

(Also, for reference: Google("pass by value c++") = "By default, arguments in C++ are passed by value. When an argument is passed by value, the argument's value is copied into the function's parameter.")

So we want to set the pointer b equal to the string a.

#include <iostream>
#include <string>

void Function_1(std::string* a, std::string* b) {
  b = a;
  std::cout << (b == nullptr);  // False
}

void Function_2(std::string* a, std::string** b) {
  *b = a;
  std::cout << (b == nullptr);  // False
}

int main() {
  std::string a("Hello!");
  std::string* b(nullptr);
  std::cout << (b == nullptr);  // True

  Function_1(&a, b);
  std::cout << (b == nullptr);  // True

  Function_2(&a, &b);
  std::cout << (b == nullptr);  // False
}

// Output: 10100

What happens at the line Function_1(&a, b);?

  • The "value" of &main::a (an address) is copied into the parameter std::string* Function_1::a. Therefore Function_1::a is a pointer to (i.e. the memory address of) the string main::a.

  • The "value" of main::b (an address in memory) is copied into the parameter std::string* Function_1::b. Therefore there are now 2 of these addresses in memory, both null pointers. At the line b = a;, the local variable Function_1::b is then changed to equal Function_1::a (= &main::a), but the variable main::b is unchanged. After the call to Function_1, main::b is still a null pointer.

What happens at the line Function_2(&a, &b);?

  • The treatment of the a variable is the same: within the function, Function_2::a is the address of the string main::a.

  • But the variable b is now being passed as a pointer to a pointer. The "value" of &main::b (the address of the pointer main::b) is copied into std::string** Function_2::b. Therefore within Function_2, dereferencing this as *Function_2::b will access and modify main::b . So the line *b = a; is actually setting main::b (an address) equal to Function_2::a (= address of main::a) which is what we want.

If you want to use a function to modify a thing, be it an object or an address (pointer), you have to pass in a pointer to that thing. The thing that you actually pass in cannot be modified (in the calling scope) because a local copy is made.

(An exception is if the parameter is a reference, such as std::string& a. But usually these are const. Generally, if you call f(x), if x is an object you should be able to assume that f won't modify x. But if x is a pointer, then you should assume that f might modify the object pointed to by x.)

Formula to check if string is empty in Crystal Reports

You can check for IsNull condition.

If IsNull({TABLE.FIELD}) or {TABLE.FIELD} = "" then
  // do something

Difference between OpenJDK and Adoptium/AdoptOpenJDK

In short:

  • OpenJDK has multiple meanings and can refer to:
    • free and open source implementation of the Java Platform, Standard Edition (Java SE)
    • open source repository — the Java source code aka OpenJDK project
    • prebuilt OpenJDK binaries maintained by Oracle
    • prebuilt OpenJDK binaries maintained by the OpenJDK community
  • AdoptOpenJDK — prebuilt OpenJDK binaries maintained by community (open source licensed)

Explanation:

Prebuilt OpenJDK (or distribution) — binaries, built from http://hg.openjdk.java.net/, provided as an archive or installer, offered for various platforms, with a possible support contract.

OpenJDK, the source repository (also called OpenJDK project) - is a Mercurial-based open source repository, hosted at http://hg.openjdk.java.net. The Java source code. The vast majority of Java features (from the VM and the core libraries to the compiler) are based solely on this source repository. Oracle have an alternate fork of this.

OpenJDK, the distribution (see the list of providers below) - is free as in beer and kind of free as in speech, but, you do not get to call Oracle if you have problems with it. There is no support contract. Furthermore, Oracle will only release updates to any OpenJDK (the distribution) version if that release is the most recent Java release, including LTS (long-term support) releases. The day Oracle releases OpenJDK (the distribution) version 12.0, even if there's a security issue with OpenJDK (the distribution) version 11.0, Oracle will not release an update for 11.0. Maintained solely by Oracle.

Some OpenJDK projects - such as OpenJDK 8 and OpenJDK 11 - are maintained by the OpenJDK community and provide releases for some OpenJDK versions for some platforms. The community members have taken responsibility for releasing fixes for security vulnerabilities in these OpenJDK versions.

AdoptOpenJDK, the distribution is very similar to Oracle's OpenJDK distribution (in that it is free, and it is a build produced by compiling the sources from the OpenJDK source repository). AdoptOpenJDK as an entity will not be backporting patches, i.e. there won't be an AdoptOpenJDK 'fork/version' that is materially different from upstream (except for some build script patches for things like Win32 support). Meaning, if members of the community (Oracle or others, but not AdoptOpenJDK as an entity) backport security fixes to updates of OpenJDK LTS versions, then AdoptOpenJDK will provide builds for those. Maintained by OpenJDK community.

OracleJDK - is yet another distribution. Starting with JDK12 there will be no free version of OracleJDK. Oracle's JDK distribution offering is intended for commercial support. You pay for this, but then you get to rely on Oracle for support. Unlike Oracle's OpenJDK offering, OracleJDK comes with longer support for LTS versions. As a developer you can get a free license for personal/development use only of this particular JDK, but that's mostly a red herring, as 'just the binary' is basically the same as the OpenJDK binary. I guess it means you can download security-patched versions of LTS JDKs from Oracle's websites as long as you promise not to use them commercially.

Note. It may be best to call the OpenJDK builds by Oracle the "Oracle OpenJDK builds".

Donald Smith, Java product manager at Oracle writes:

Ideally, we would simply refer to all Oracle JDK builds as the "Oracle JDK", either under the GPL or the commercial license, depending on your situation. However, for historical reasons, while the small remaining differences exist, we will refer to them separately as Oracle’s OpenJDK builds and the Oracle JDK.


OpenJDK Providers and Comparison

----------------------------------------------------------------------------------------
|     Provider      | Free Builds | Free Binary   | Extended | Commercial | Permissive |
|                   | from Source | Distributions | Updates  | Support    | License    |
|--------------------------------------------------------------------------------------|
| AdoptOpenJDK      |    Yes      |    Yes        |   Yes    |   No       |   Yes      |
| Amazon – Corretto |    Yes      |    Yes        |   Yes    |   No       |   Yes      |
| Azul Zulu         |    No       |    Yes        |   Yes    |   Yes      |   Yes      |
| BellSoft Liberica |    No       |    Yes        |   Yes    |   Yes      |   Yes      |
| IBM               |    No       |    No         |   Yes    |   Yes      |   Yes      |
| jClarity          |    No       |    No         |   Yes    |   Yes      |   Yes      |
| OpenJDK           |    Yes      |    Yes        |   Yes    |   No       |   Yes      |
| Oracle JDK        |    No       |    Yes        |   No**   |   Yes      |   No       |
| Oracle OpenJDK    |    Yes      |    Yes        |   No     |   No       |   Yes      |
| ojdkbuild         |    Yes      |    Yes        |   No     |   No       |   Yes      |
| RedHat            |    Yes      |    Yes        |   Yes    |   Yes      |   Yes      |
| SapMachine        |    Yes      |    Yes        |   Yes    |   Yes      |   Yes      |
----------------------------------------------------------------------------------------

Free Builds from Source - the distribution source code is publicly available and one can assemble its own build

Free Binary Distributions - the distribution binaries are publicly available for download and usage

Extended Updates - aka LTS (long-term support) - Public Updates beyond the 6-month release lifecycle

Commercial Support - some providers offer extended updates and customer support to paying customers, e.g. Oracle JDK (support details)

Permissive License - the distribution license is non-protective, e.g. Apache 2.0


Which Java Distribution Should I Use?

In the Sun/Oracle days, it was usually Sun/Oracle producing the proprietary downstream JDK distributions based on OpenJDK sources. Recently, Oracle had decided to do their own proprietary builds only with the commercial support attached. They graciously publish the OpenJDK builds as well on their https://jdk.java.net/ site.

What is happening starting JDK 11 is the shift from single-vendor (Oracle) mindset to the mindset where you select a provider that gives you a distribution for the product, under the conditions you like: platforms they build for, frequency and promptness of releases, how support is structured, etc. If you don't trust any of existing vendors, you can even build OpenJDK yourself.

Each build of OpenJDK is usually made from the same original upstream source repository (OpenJDK “the project”). However each build is quite unique - $free or commercial, branded or unbranded, pure or bundled (e.g., BellSoft Liberica JDK offers bundled JavaFX, which was removed from Oracle builds starting JDK 11).

If no environment (e.g., Linux) and/or license requirement defines specific distribution and if you want the most standard JDK build, then probably the best option is to use OpenJDK by Oracle or AdoptOpenJDK.


Additional information

Time to look beyond Oracle's JDK by Stephen Colebourne

Java Is Still Free by Java Champions community (published on September 17, 2018)

Java is Still Free 2.0.0 by Java Champions community (published on March 3, 2019)

Aleksey Shipilev about JDK updates interview by Opsian (published on June 27, 2019)

How to show loading spinner in jQuery?

You can simply assign a loader image to the same tag on which you later will load content using an Ajax call:

$("#message").html('<span>Loading...</span>');

$('#message').load('index.php?pg=ajaxFlashcard');

You can also replace the span tag with an image tag.

How to add button in ActionBar(Android)?

An activity populates the ActionBar in its onCreateOptionsMenu() method.

Instead of using setcustomview(), just override onCreateOptionsMenu like this:

@Override    
public boolean onCreateOptionsMenu(Menu menu) {
  MenuInflater inflater = getMenuInflater();
  inflater.inflate(R.menu.mainmenu, menu);
  return true;
}

If an actions in the ActionBar is selected, the onOptionsItemSelected() method is called. It receives the selected action as parameter. Based on this information you code can decide what to do for example:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
  switch (item.getItemId()) {
    case R.id.menuitem1:
      Toast.makeText(this, "Menu Item 1 selected", Toast.LENGTH_SHORT).show();
      break;
    case R.id.menuitem2:
      Toast.makeText(this, "Menu item 2 selected", Toast.LENGTH_SHORT).show();
      break;
  }
  return true;
}

How to insert data using wpdb

Just use wpdb->insert(tablename, coloumn, format) and wp will prepare that's query

<?php
global $wpdb;
$wpdb->insert("wp_submitted_form", array(
   "name" => $name,
   "email" => $email,
   "phone" => $phone,
   "country" => $country,
   "course" => $course,
   "message" => $message,
   "datesent" => $now ,
));
?>

Reading file using fscanf() in C

scanf() and friends return the number of input items successfully matched. For your code, that would be two or less (in case of less matches than specified). In short, be a little more careful with the manual pages:

#include <stdio.h>
#include <errno.h>
#include <stdbool.h>

int main(void)
{
    char item[9], status;

    FILE *fp;

    if((fp = fopen("D:\\Sample\\database.txt", "r+")) == NULL) {
        printf("No such file\n");
        exit(1);
    }

    while (true) {
        int ret = fscanf(fp, "%s %c", item, &status);
        if(ret == 2)
            printf("\n%s \t %c", item, status);
        else if(errno != 0) {
            perror("scanf:");
            break;
        } else if(ret == EOF) {
            break;
        } else {
            printf("No match.\n");
        }
    }
    printf("\n");
    if(feof(fp)) {
        puts("EOF");
    }
    return 0;
}

How to resolve Error listenerStart when deploying web-app in Tomcat 5.5?

I encountered this error when the JDK that I compiled the app under was different from the tomcat JVM. I verified that the Tomcat manager was running jvm 1.6.0 but the app was compiled under java 1.7.0.

After upgrading Java and changing JAVA_HOME in our startup script (/etc/init.d/tomcat) the error went away.

git-diff to ignore ^M

TL;DR

Change the core.pager to "tr -d '\r' | less -REX", not the source code

This is why

Those pesky ^M shown are an artifact of the colorization and the pager. enter image description here It is caused by less -R, a default git pager option. (git's default pager is less -REX)

The first thing to note is that git diff -b will not show changes in white space (e.g. the \r\n vs \n)

setup:

git clone https://github.com/CipherShed/CipherShed
cd CipherShed

A quick test to create a unix file and change the line endings will show no changes with git diff -b:

echo -e 'The quick brown fox\njumped over the lazy\ndogs.' > test.txt
git add test.txt
unix2dos.exe test.txt
git diff -b test.txt

We note that forcing a pipe to less does not show the ^M, but enabling color and less -R does:

git diff origin/v0.7.4.0 origin/v0.7.4.1 | less
git -c color.ui=always diff origin/v0.7.4.0 origin/v0.7.4.1 | less -R

The fix is shown by using a pipe to strip the \r (^M) from the output:

git diff origin/v0.7.4.0 origin/v0.7.4.1
git -c core.pager="tr -d '\r' | less -REX"  diff origin/v0.7.4.0 origin/v0.7.4.1

An unwise alternative is to use less -r, because it will pass through all control codes, not just the color codes.

If you want to just edit your git config file directly, this is the entry to update/add:

[core]
        pager = tr -d '\\r' | less -REX

How to convert a .eps file to a high quality 1024x1024 .jpg?

For vector graphics, ImageMagick has both a render resolution and an output size that are independent of each other.

Try something like

convert -density 300 image.eps -resize 1024x1024 image.jpg

Which will render your eps at 300dpi. If 300 * width > 1024, then it will be sharp. If you render it too high though, you waste a lot of memory drawing a really high-res graphic only to down sample it again. I don't currently know of a good way to render it at the "right" resolution in one IM command.

The order of the arguments matters! The -density X argument needs to go before image.eps because you want to affect the resolution that the input file is rendered at.

This is not super obvious in the manpage for convert, but is hinted at:

SYNOPSIS

convert [input-option] input-file [output-option] output-file

How to enter quotes in a Java string?

Not sure what language you're using (you didn't specify), but you should be able to "escape" the quotation mark character with a backslash: "\"ROM\""

Static Vs. Dynamic Binding in Java

In the case of the static binding type of object determined at the compile-time whereas in the dynamic binding type of the object is determined at the runtime.



class Dainamic{

    void run2(){
        System.out.println("dainamic_binding");
    }

}


public class StaticDainamicBinding extends Dainamic {

    void run(){
        System.out.println("static_binding");
    }

    @Override
    void run2() {
        super.run2();
    }

    public static void main(String[] args) {
        StaticDainamicBinding st_vs_dai = new StaticDainamicBinding();
        st_vs_dai.run();
        st_vs_dai.run2();
    }

}

adding text to an existing text element in javascript via DOM

What about this.

_x000D_
_x000D_
var p = document.getElementById("p")_x000D_
p.innerText = p.innerText+" And this is addon."
_x000D_
<p id ="p">This is some text</p>
_x000D_
_x000D_
_x000D_

C++ display stack trace on exception

On Windows, check out BugTrap. Its not longer at the original link, but its still available on CodeProject.

Rails: select unique values from a column

Another way to collect uniq columns with sql:

Model.group(:rating).pluck(:rating)

How to hide a div element depending on Model value? MVC

Try:

<div style="@(Model.booleanVariable ? "display:block" : "display:none")">Some links</div>

Use the "Display" style attribute with your bool model attribute to define the div's visibility.

Changing an AIX password via script?

You can try:

echo "USERNAME:NEWPASSWORD" | chpasswd

Bootstrap get div to align in the center

In bootstrap you can use .text-centerto align center. also add .row and .col-md-* to your code.

align= is deprecated,

Added .col-xs-* for demo

_x000D_
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet" />
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<div class="footer">
  <div class="container">
    <div class="row">
      <div class="col-xs-4">
        <p>Hello there</p>
      </div>
      <div class="col-xs-4 text-center">
        <a href="#" class="btn btn-warning" onclick="changeLook()">Re</a>
        <a href="#" class="btn btn-warning" onclick="changeBack()">Rs</a>
      </div>
      <div class="col-xs-4 text-right">
        <a href="#"><i class="fa fa-facebook-square fa-2x"></i></a>
        <a href="#"><i class="fa fa-twitter fa-2x"></i></a>
        <a href="#"><i class="fa fa-google-plus fa-2x"></i></a>
      </div>
    </div>
  </div>
</div>
_x000D_
_x000D_
_x000D_

UPDATE(OCT 2017)

For those who are reading this and want to use the new version of bootstrap (beta version), you can do the above in a simpler way, using Boostrap Flexbox utilities classes

_x000D_
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet" />
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" />
<div class="container footer">
  <div class="d-flex justify-content-between">
    <div class="p-1">
      <p>Hello there</p>
    </div>
    <div class="p-1">
      <a href="#" class="btn btn-warning" onclick="changeLook()">Re</a>
      <a href="#" class="btn btn-warning" onclick="changeBack()">Rs</a>
    </div>
    <div class="p-1">
      <a href="#"><i class="fa fa-facebook-square fa-2x"></i></a>
      <a href="#"><i class="fa fa-twitter fa-2x"></i></a>
      <a href="#"><i class="fa fa-google-plus fa-2x"></i></a>
    </div>
  </div>
</div>
_x000D_
_x000D_
_x000D_

Undefined Reference to

Try to remove the constructor and destructors, it's working for me....

Validation for 10 digit mobile number and focus input field on invalid

$().ready(function () {

    $.validator.addMethod(
            "tendigits",
            function (value, element) {
                if (value == "")
                    return false;
                return value.match(/^\d{10}$/);
            },
            "Please enter 10 digits Contact # (No spaces or dash)"
            );

    $('#frm_registration').validate({
        rules: {
            phone: "tendigits"
        },
        messages: {
            phone: "Please enter 10 digits Contact # (No spaces or dash)",

        }

    });

})

Capture iOS Simulator video for App Preview

You can record a portion of the screen with built-in screenshot utility:

  1. Press Shift-Command-5 to show a control panel.
  2. Select enter image description here.
  3. Select a portion of the screen you want to record. That would be the iPhone simulator.
  4. Click enter image description here to stop recording.
  5. A thumbnail will appear at the bottom right corner of the screen. You can edit it before saving.

If you want to visualize mouse clicks, after step 1 select Options control and enable Show Mouse Clicks.

Requested registry access is not allowed

If you don't need admin privs for the entire app, or only for a few infrequent changes you can do the changes in a new process and launch it using:

Process.StartInfo.UseShellExecute = true;
Process.StartInfo.Verb = "runas";

which will run the process as admin to do whatever you need with the registry, but return to your app with the normal priviledges. This way it doesn't prompt the user with a UAC dialog every time it launches.

Difference between jQuery parent(), parents() and closest() functions

There is difference between both $(this).closest('div') and $(this).parents('div').eq(0)

Basically closest start matching element from the current element whereas parents start matching elements from parent (one level above the current element)

See http://jsfiddle.net/imrankabir/c1jhocre/1/

What is href="#" and why is it used?

The problem with using href="#" for an empty link is that it will take you to the top of the page which may not be the desired action. To avoid this, for older browsers or non-HTML5 doctypes, use

<a href="javascript:void(0)">Goes Nowhere</a>

Prevent the keyboard from displaying on activity start

declare this code( android:windowSoftInputMode="stateAlwaysHidden") in manifest inside your activity tag .

like this :

<activity android:name=".MainActivity"
  android:windowSoftInputMode="stateAlwaysHidden">

How can I find the number of elements in an array?

sizeof returns the size in bytes of it's argument. This is not what you want, but it can help.

Let's say you have an array:

int array[4];

If you apply sizeof to the array (sizeof(array)), it will return its size in bytes, which in this case is 4 * the size of an int, so a total of maybe 16 bytes (depending on your implementation).

If you apply sizeof to an element of the array (sizeof(array[0])), it will return its size in bytes, which in this case is the size of an int, so a total of maybe 4 bytes (depending on your implementation).

If you divide the first one by the second one, it will be: (4 * the size of an int) / (the size of an int) = 4; That's exactly what you wanted.

So this should do:

sizeof(array) / sizeof(array[0])

Now you would probably like to have a macro to encapsulate this logic and never have to think again how it should be done:

#define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]))

You need the parentheses enclosing all the macro as in any other complex macro, and also enclosing every variable, just to avoid unexpected bugs related to operators precedence.

Now you can use it on any array like this:

int array[6];
ptrdiff_t nmemb;

nmemb = ARRAY_SIZE(array);
/* nmemb == 6 */

Remember that arguments of functions declared as arrays are not really arrays, but pointers to the first element of the array, so this will NOT work on them:

void foo(int false_array[6])
{
        ptrdiff_t nmemb;

        nmemb = ARRAY_SIZE(false_array);
        /* nmemb == sizeof(int *) / sizeof(int) */
        /* (maybe  ==2) */
}

But it can be used in functions if you pass a pointer to an array instead of just the array:

void bar(int (*arrptr)[7])
{
        ptrdiff_t nmemb;

        nmemb = ARRAY_SIZE(*arrptr);
        /* nmemb == 7 */
}

How can I generate an INSERT script for an existing SQL Server table that includes all stored rows?

This script generates insert statements of your existing data. This is a stored procedure which you need to run once and then it is tailor made for you.

I tried to find this kind of stuff for a while but wasn't satisfied with the results, so I wrote this stored procedure.

Example:

Exec [dbo].[INS]  'Dbo.test where 1=1'

(1) Here dbo is schema and test is tablename and 1=1 is condition.

Exec [dbo].[INS]  'Dbo.test where name =''neeraj''' * for string

(2) Here dbo is schema and test is tablename and name='neeraj' is condition.

Here is the stored procedure

/*
Authore : neeraj prasad sharma (please dont remove this :))
Example (1) Exec [dbo].[INS]  'Dbo.test where 1=1'
        (2) Exec [dbo].[INS]  'Dbo.test where name =''neeraj''' * for string

here Dbo is schema and test is tablename and 1=1 is condition

*/


CREATE procedure  [dbo].[INS]                              
(                                                          
   @Query  Varchar(MAX)                                                          
)                              

AS                              

SET nocount ON                  

DECLARE @WithStrINdex as INT                            
DECLARE @WhereStrINdex as INT                            
DECLARE @INDExtouse as INT                            

DECLARE @SchemaAndTAble VArchar(270)                            
DECLARE @Schema_name  varchar(30)                            
DECLARE @Table_name  varchar(240)                            
DECLARE @Condition  Varchar(MAX)                             

SET @WithStrINdex=0                            

SELECT @WithStrINdex=CHARINDEX('With',@Query )                            
, @WhereStrINdex=CHARINDEX('WHERE', @Query)                            

IF(@WithStrINdex!=0)                            
SELECT @INDExtouse=@WithStrINdex                            
ELSE                            
SELECT @INDExtouse=@WhereStrINdex                            

SELECT @SchemaAndTAble=Left (@Query,@INDExtouse-1)                                                     
SELECT @SchemaAndTAble=Ltrim (Rtrim( @SchemaAndTAble))                            

SELECT @Schema_name= Left (@SchemaAndTAble, CharIndex('.',@SchemaAndTAble )-1)                            
,      @Table_name = SUBSTRING(  @SchemaAndTAble , CharIndex('.',@SchemaAndTAble )+1,LEN(@SchemaAndTAble) )                            

,      @CONDITION=SUBSTRING(@Query,@WhereStrINdex+6,LEN(@Query))--27+6                            


DECLARE @COLUMNS  table (Row_number SmallINT , Column_Name VArchar(Max) )                              
DECLARE @CONDITIONS as varchar(MAX)                              
DECLARE @Total_Rows as SmallINT                              
DECLARE @Counter as SmallINT              

DECLARE @ComaCol as varchar(max)            
SELECT @ComaCol=''                   

SET @Counter=1                              
SET @CONDITIONS=''                              

INSERT INTO @COLUMNS                              
SELECT Row_number()Over (Order by ORDINAL_POSITION ) [Count], Column_Name 
FROM INformation_schema.columns 
WHERE Table_schema=@Schema_name AND table_name=@Table_name         


SELECT @Total_Rows= Count(1) 
FROM @COLUMNS                              

SELECT @Table_name= '['+@Table_name+']'                      

SELECT @Schema_name='['+@Schema_name+']'                      

While (@Counter<=@Total_Rows )                              
begin                               
--PRINT @Counter                              

SELECT @ComaCol= @ComaCol+'['+Column_Name+'],'            
FROM @COLUMNS                              
WHERE [Row_number]=@Counter                          

SELECT @CONDITIONS=@CONDITIONS+ ' + Case When ['+Column_Name+'] is null then ''Null'' Else '''''''' + Replace( Convert(varchar(Max),['+Column_Name+']  ) ,'''''''',''''  ) +'''''''' end+'+''','''                                                     
FROM @COLUMNS                              
WHERE [Row_number]=@Counter                              

SET @Counter=@Counter+1                              

End                              

SELECT @CONDITIONS=Right(@CONDITIONS,LEN(@CONDITIONS)-2)                              

SELECT @CONDITIONS=LEFT(@CONDITIONS,LEN(@CONDITIONS)-4)              
SELECT @ComaCol= substring (@ComaCol,0,  len(@ComaCol) )                            

SELECT @CONDITIONS= '''INSERT INTO '+@Schema_name+'.'+@Table_name+ '('+@ComaCol+')' +' Values( '+'''' + '+'+@CONDITIONS                              

SELECT @CONDITIONS=@CONDITIONS+'+'+ ''')'''                              

SELECT @CONDITIONS= 'Select  '+@CONDITIONS +'FRom  ' +@Schema_name+'.'+@Table_name+' With(NOLOCK) ' + ' Where '+@Condition                              
print(@CONDITIONS)                              
Exec(@CONDITIONS)  

How do I use typedef and typedef enum in C?

typedef defines a new data type. So you can have:

typedef char* my_string;
typedef struct{
  int member1;
  int member2;
} my_struct;

So now you can declare variables with these new data types

my_string s;
my_struct x;

s = "welcome";
x.member1 = 10;

For enum, things are a bit different - consider the following examples:

enum Ranks {FIRST, SECOND};
int main()
{
   int data = 20;
   if (data == FIRST)
   {
      //do something
   }
}

using typedef enum creates an alias for a type:

typedef enum Ranks {FIRST, SECOND} Order;
int main()
{
   Order data = (Order)20;  // Must cast to defined type to prevent error

   if (data == FIRST)
   {
      //do something
   }
}

Why use @PostConstruct?

If your class performs all of its initialization in the constructor, then @PostConstruct is indeed redundant.

However, if your class has its dependencies injected using setter methods, then the class's constructor cannot fully initialize the object, and sometimes some initialization needs to be performed after all the setter methods have been called, hence the use case of @PostConstruct.

SQL 'like' vs '=' performance

You are asking the wrong question. In databases is not the operator performance that matters, is always the SARGability of the expression, and the coverability of the overall query. Performance of the operator itself is largely irrelevant.

So, how do LIKE and = compare in terms of SARGability? LIKE, when used with an expression that does not start with a constant (eg. when used LIKE '%something') is by definition non-SARGabale. But does that make = or LIKE 'something%' SARGable? No. As with any question about SQL performance the answer does not lie with the query of the text, but with the schema deployed. These expression may be SARGable if an index exists to satisfy them.

So, truth be told, there are small differences between = and LIKE. But asking whether one operator or other operator is 'faster' in SQL is like asking 'What goes faster, a red car or a blue car?'. You should eb asking questions about the engine size and vechicle weight, not about the color... To approach questions about optimizing relational tables, the place to look is your indexes and your expressions in the WHERE clause (and other clauses, but it usually starts with the WHERE).

When should I use Async Controllers in ASP.NET MVC?

async actions help best when the actions does some I\O operations to DB or some network bound calls where the thread that processes the request will be stalled before it gets answer from the DB or network bound call which you just invoked. It's best you use await with them and it will really improve the responsiveness of your application (because less ASP input\output threads will be stalled while waiting for the DB or any other operation like that). In all my applications whenever many calls to DB very necessary I've always wrapped them in awaiatable method and called that with await keyword.

What is the use of a cursor in SQL Server?

In SQL server, a cursor is used when you need Instead of the T-SQL commands that operate on all the rows in the result set one at a time, we use a cursor when we need to update records in a database table in a singleton fashion, in other words row by row.to fetch one row at a time or row by row.

Working with cursors consists of several steps:

Declare - Declare is used to define a new cursor. Open - A Cursor is opened and populated by executing the SQL statement defined by the cursor. Fetch - When the cursor is opened, rows can be retrieved from the cursor one by one. Close - After data operations, we should close the cursor explicitly. Deallocate - Finally, we need to delete the cursor definition and release all the system resources associated with the cursor. Syntax

DECLARE cursor_name CURSOR [ LOCAL | GLOBAL ] [ FORWARD_ONLY | SCROLL ] [ STATIC | KEYSET | DYNAMIC | FAST_FORWARD ] [ READ_ONLY | SCROLL_LOCKS | OPTIMISTIC ] [ TYPE_WARNING] FOR select_statement [FOR UPDATE [ OF column_name [ ,...n ] ] ] [;]

What is the JavaScript version of sleep()?

The problem with most solutions here is that they rewind the stack. This can be a big problem in some cases.In this example I show how to use iterators in different way to simulate real sleep

In this example the generator is calling it's own next() so once it's going, it's on his own.

var h=a();
h.next().value.r=h; //that's how U run it, best I came up with

//sleep without breaking stack !!!
function *a(){
    var obj= {};

    console.log("going to sleep....2s")

    setTimeout(function(){obj.r.next();},2000)  
     yield obj;

    console.log("woke up");
    console.log("going to sleep no 2....2s")
    setTimeout(function(){obj.r.next();},2000)  
     yield obj;

     console.log("woke up");
    console.log("going to sleep no 3....2s")

     setTimeout(function(){obj.r.next();},2000) 
     yield obj;

    console.log("done");

}

Get the selected option id with jQuery

Th easiest way to this is var id = $(this).val(); from inside an event like on change.

Python Timezone conversion

To convert a time in one timezone to another timezone in Python, you could use datetime.astimezone():

time_in_new_timezone = time_in_old_timezone.astimezone(new_timezone)

Given aware_dt (a datetime object in some timezone), to convert it to other timezones and to print the times in a given time format:

#!/usr/bin/env python3
import pytz  # $ pip install pytz

time_format = "%Y-%m-%d %H:%M:%S%z"
tzids = ['Asia/Shanghai', 'Europe/London', 'America/New_York']
for tz in map(pytz.timezone, tzids):
    time_in_tz = aware_dt.astimezone(tz)
    print(f"{time_in_tz:{time_format}}")

If f"" syntax is unavailable, you could replace it with "".format(**vars())

where you could set aware_dt from the current time in the local timezone:

from datetime import datetime
import tzlocal  # $ pip install tzlocal

local_timezone = tzlocal.get_localzone()
aware_dt = datetime.now(local_timezone) # the current time

Or from the input time string in the local timezone:

naive_dt = datetime.strptime(time_string, time_format)
aware_dt = local_timezone.localize(naive_dt, is_dst=None)

where time_string could look like: '2016-11-19 02:21:42'. It corresponds to time_format = '%Y-%m-%d %H:%M:%S'.

is_dst=None forces an exception if the input time string corresponds to a non-existing or ambiguous local time such as during a DST transition. You could also pass is_dst=False, is_dst=True. See links with more details at Python: How do you convert datetime/timestamp from one timezone to another timezone?

How to animate GIFs in HTML document?

I just ran into this... my gif didn't run on the server that I was testing on, but when I published the code it ran on my desktop just fine...

How to get values of selected items in CheckBoxList with foreach in ASP.NET C#?

foreach (ListItem item in CBLGold.Items)
{
    if (item.Selected)
    {
        string selectedValue = item.Value;
    }
}

Use dynamic (variable) string as regex pattern in JavaScript

To create the regex from a string, you have to use JavaScript's RegExp object.

If you also want to match/replace more than one time, then you must add the g (global match) flag. Here's an example:

var stringToGoIntoTheRegex = "abc";
var regex = new RegExp("#" + stringToGoIntoTheRegex + "#", "g");
// at this point, the line above is the same as: var regex = /#abc#/g;

var input = "Hello this is #abc# some #abc# stuff.";
var output = input.replace(regex, "!!");
alert(output); // Hello this is !! some !! stuff.

JSFiddle demo here.


In the general case, escape the string before using as regex:

Not every string is a valid regex, though: there are some speciall characters, like ( or [. To work around this issue, simply escape the string before turning it into a regex. A utility function for that goes in the sample below:

function escapeRegExp(stringToGoIntoTheRegex) {
    return stringToGoIntoTheRegex.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
}

var stringToGoIntoTheRegex = escapeRegExp("abc"); // this is the only change from above
var regex = new RegExp("#" + stringToGoIntoTheRegex + "#", "g");
// at this point, the line above is the same as: var regex = /#abc#/g;

var input = "Hello this is #abc# some #abc# stuff.";
var output = input.replace(regex, "!!");
alert(output); // Hello this is !! some !! stuff.

JSFiddle demo here.



Note: the regex in the question uses the s modifier, which didn't exist at the time of the question, but does exist -- a s (dotall) flag/modifier in JavaScript -- today.

Datepicker: How to popup datepicker when click on edittext

This worked for me in Jan 2020

XML Part:

  <EditText
            android:id="@+id/etDOB"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:clickable="true"
            android:editable="false"
            android:ems="10"
            android:hint="Enter Your Date of Birth" />

Java Part:

         final Calendar myCalendar = Calendar.getInstance();

         userDOBView  = (EditText)findViewById(R.id.etDOB);


    final DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener(){
      @Override
      public void onDateSet(DatePicker view, int year, int monthOfYear, int  dayOfMonth) {
             myCalendar.set(Calendar.YEAR, year);
             myCalendar.set(Calendar.MONTH, monthOfYear);
             myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
             updateLabel();
      }
    };

    userDOBView.setOnTouchListener(new View.OnTouchListener(){
      @Override
      public boolean onTouch(View v, MotionEvent event){
       if(event.getAction() == MotionEvent.ACTION_DOWN){
         new DatePickerDialog("YourClassName".this, date, 
             myCalendar.get(Calendar.YEAR), 
             myCalendar.get(Calendar.MONTH),         
             myCalendar.get(Calendar.DAY_OF_MONTH)).show();
          }
          return true;
       }
    });
private void updateLabel() {
  String myFormat = "MM/dd/yyyy"; //In which you need put here
  SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);

  // edittext.setText(sdf.format(myCalendar.getTime()));
  userDOBView.setText(sdf.format(myCalendar.getTime()));
} 

Print PDF directly from JavaScript

I used this function to download pdf stream from server.

function printPdf(url) {
        var iframe = document.createElement('iframe');
        // iframe.id = 'pdfIframe'
        iframe.className='pdfIframe'
        document.body.appendChild(iframe);
        iframe.style.display = 'none';
        iframe.onload = function () {
            setTimeout(function () {
                iframe.focus();
                iframe.contentWindow.print();
                URL.revokeObjectURL(url)
                // document.body.removeChild(iframe)
            }, 1);
        };
        iframe.src = url;
        // URL.revokeObjectURL(url)
    }

How to convert from []byte to int in Go Programming

For encoding/decoding numbers to/from byte sequences, there's the encoding/binary package. There are examples in the documentation: see the Examples section in the table of contents.

These encoding functions operate on io.Writer interfaces. The net.TCPConn type implements io.Writer, so you can write/read directly to network connections.

If you've got a Go program on either side of the connection, you may want to look at using encoding/gob. See the article "Gobs of data" for a walkthrough of using gob (skip to the bottom to see a self-contained example).

Subscripts in plots in R

As other users have pointed out, we use expression(). I'd like to answer the original question which involves a comma in the subscript:

How can I write v 1,2 with 1,2 as subscripts?

plot(1:10, 11:20 , main=expression(v["1,2"]))

Also, I'd like to add the reference for those looking to find the full expression syntax in R plotting: For more information see the ?plotmath help page. Running demo(plotmath) will showcase many expressions and relevant syntax.

Remember to use * to join different types of text within an expression.

Here is some of the sample output from demo(plotmath):

enter image description here

What is SOA "in plain english"?

I would suggest you read articles by Thomas Erl and Roger Sessions, this will give you a firm handle on what SOA is all about. These are also good resources, look at the SOA explained for your boss one for a layman explanation

Building a SOA

SOA Design Pattern

Achieving integrity in a SOA

Why your SOA should be like a VW Beetle

SOA explained for your boss

WCF Service Performance

How to set only time part of a DateTime variable in C#

date = new DateTime(date.year, date.month, date.day, HH, MM, SS);

cannot find module "lodash"

If there is a package.json, and in it there is lodash configuration in it. then you should:

npm install

if in the package.json there is no lodash:

npm install --save-dev

Send a ping to each IP on a subnet

Under linux, I think ping -b 192.168.1.255 will work (192.168.1.255 is the broadcast address for 192.168.1.*) however IIRC that doesn't work under windows.

Google maps responsive resize

Move your map variable into a scope where the event listener can use it. You are creating the map inside your initialize() function and nothing else can use it when created that way.

var map; //<-- This is now available to both event listeners and the initialize() function
function initialize() {
  var mapOptions = {
   center: new google.maps.LatLng(40.5472,12.282715),
   zoom: 6,
   mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  map = new google.maps.Map(document.getElementById("map-canvas"),
            mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
google.maps.event.addDomListener(window, "resize", function() {
 var center = map.getCenter();
 google.maps.event.trigger(map, "resize");
 map.setCenter(center); 
});

Extract a single (unsigned) integer from a string

preg_match_all('!\d+!', $some_string, $matches);
$string_of_numbers = implode(' ', $matches[0]);

The first argument in implode in this specific case says "separate each element in matches[0] with a single space." Implode will not put a space (or whatever your first argument is) before the first number or after the last number.

Something else to note is $matches[0] is where the array of matches (that match this regular expression) found are stored.

For further clarification on what the other indexes in the array are for see: http://php.net/manual/en/function.preg-match-all.php

Unable to find valid certification path to requested target - error even after cert imported

Solution when migrating from JDK 8 to JDK 10

JDK 10

root@c339504909345:/opt/jdk-minimal/jre/lib/security #  keytool -cacerts -list
Enter keystore password:
Keystore type: JKS
Keystore provider: SUN

Your keystore contains 80 entries

JDK 8

root@c39596768075:/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/security/cacerts #  keytool -cacerts -list
Enter keystore password:
Keystore type: JKS
Keystore provider: SUN

Your keystore contains 151 entries

Steps to fix

  • I deleted the JDK 10 cert and replaced it with the JDK 8
  • Since I'm building Docker Images, I could quickly do that using Multi-stage builds
    • I'm building a minimal JRE using jlink as /opt/jdk/bin/jlink \ --module-path /opt/jdk/jmods...

So, here's the different paths and the sequence of the commands...

# Java 8
COPY --from=marcellodesales-springboot-builder-jdk8 /usr/lib/jvm/java-8-openjdk-amd64/jre/lib/security/cacerts /etc/ssl/certs/java/cacerts

# Java 10
RUN rm -f /opt/jdk-minimal/jre/lib/security/cacerts
RUN ln -s /etc/ssl/certs/java/cacerts /opt/jdk-minimal/jre/lib/security/cacerts

How to escape regular expression special characters using javascript?

Use the backslash to escape a character. For example:

/\\d/

This will match \d instead of a numeric character

com.google.android.gms:play-services-measurement-base is being requested by various other libraries

replace the "+" with version number, it would choose the latest version. like this:

implementation 'com.google.firebase:firebase-analytics:+'

How to compare timestamp dates with date-only parameter in MySQL?

In case you are using SQL parameters to run the query then this would be helpful

SELECT * FROM table WHERE timestamp between concat(date(?), ' ', '00:00:00') and concat(date(?), ' ', '23:59:59')

Setting timezone to UTC (0) in PHP

You can always check this maintained list to timezones

https://www.php.net/manual/en/function.date.php

Breaking out of nested loops

Use itertools.product!

from itertools import product
for x, y in product(range(10), range(10)):
    #do whatever you want
    break

Here's a link to itertools.product in the python documentation: http://docs.python.org/library/itertools.html#itertools.product

You can also loop over an array comprehension with 2 fors in it, and break whenever you want to.

>>> [(x, y) for y in ['y1', 'y2'] for x in ['x1', 'x2']]
[
    ('x1', 'y1'), ('x2', 'y1'),
    ('x1', 'y2'), ('x2', 'y2')
]

Convert an image to grayscale in HTML/CSS

Just got the same problem today. I've initially used SalmanPK solution but found out that effect differs between FF and other browsers. That's because conversion matrix works on lightness only not luminosity like filters in Chrome/IE . To my surprise I've found out that alternative and simpler solution in SVG also works in FF4+ and produces better results:

<svg xmlns="http://www.w3.org/2000/svg">
  <filter id="desaturate">
    <feColorMatrix type="saturate" values="0"/>
  </filter>
</svg>

With css:

img {
    filter: url(filters.svg#desaturate); /* Firefox 3.5+ */
    filter: gray; /* IE6-9 */
    -webkit-filter: grayscale(1); /* Google Chrome & Safari 6+ */
}

One more caveat is that IE10 doesn't support "filter: gray:" in standards compliant mode anymore, so needs compatibility mode switch in headers to work:

<meta http-equiv="X-UA-Compatible" content="IE=9" />

PHP mysql insert date format

$date_field         = date('Y-m-d',strtotime($_POST['date_field']));
$sql = mysql_query("INSERT INTO user_date (column_name,column_name,column_name) VALUES('',$name,$date_field)") or die (mysql_error());

Changing navigation bar color in Swift

My two cents:

a) setting navigationBar.barTintColor / titleTextAttributes do work in any view (pushed, added..and so on in init..

b) setting appearence does not work everywhere:

  • You can call it on AppDelegate
  • " " 1st level view
  • if You call it again in subsequent pushed views, does MNOT work

SwiftUI note:

a) does not apply (no navigationBar, unless you pass via UIViewControllerRepresentable trick..) b) is valid for SwiftUI: same behaviour.

Getting value from appsettings.json in .net core

From Asp.net core 2.2 to above you can code as below:

Step 1. Create an AppSettings class file.

This file contains some methods to help get value by key from the appsettings.json file. Look like as code below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace ReadConfig.Bsl
{
  public class AppSettings
  {
      private static AppSettings _instance;
      private static readonly object ObjLocked = new object();
      private IConfiguration _configuration;

      protected AppSettings()
      {
      }

      public void SetConfiguration(IConfiguration configuration)
      {
          _configuration = configuration;
      }

      public static AppSettings Instance
      {
          get
          {
              if (null == _instance)
              {
                  lock (ObjLocked)
                  {
                      if (null == _instance)
                          _instance = new AppSettings();
                  }
              }
              return _instance;
          }
      }

      public string GetConnection(string key, string defaultValue = "")
      {
          try
          {
              return _configuration.GetConnectionString(key);
          }
          catch
          {
              return defaultValue;
          }
      }

      public T Get<T>(string key = null)
      {
          if (string.IsNullOrWhiteSpace(key))
              return _configuration.Get<T>();
          else
              return _configuration.GetSection(key).Get<T>();
      }

      public T Get<T>(string key, T defaultValue)
      {
          if (_configuration.GetSection(key) == null)
              return defaultValue;

          if (string.IsNullOrWhiteSpace(key))
              return _configuration.Get<T>();
          else
              return _configuration.GetSection(key).Get<T>();
      }

      public static T GetObject<T>(string key = null)
      {
          if (string.IsNullOrWhiteSpace(key))
              return Instance._configuration.Get<T>();
          else
          {
              var section = Instance._configuration.GetSection(key);
              return section.Get<T>();
          }
      }

      public static T GetObject<T>(string key, T defaultValue)
      {
          if (Instance._configuration.GetSection(key) == null)
              return defaultValue;

          if (string.IsNullOrWhiteSpace(key))
              return Instance._configuration.Get<T>();
          else
              return Instance._configuration.GetSection(key).Get<T>();
      }
  }
}

Step 2. Initial configuration for AppSettings object

We need to declare and load appsettings.json file when the application starts, and load configuration information for AppSettings object. We will do this work in the constructor of the Startup.cs file. Please notice line AppSettings.Instance.SetConfiguration(Configuration);

public Startup(IHostingEnvironment evm)
{
    var builder = new ConfigurationBuilder()
      .SetBasePath(evm.ContentRootPath)
      .AddJsonFile("appsettings.json", true, true)
      .AddJsonFile($"appsettings.{evm.EnvironmentName}.json", true)
      .AddEnvironmentVariables();
    Configuration = builder.Build(); // load all file config to Configuration property 
    AppSettings.Instance.SetConfiguration(Configuration);       
}

Okay, now I have an appsettings.json file with some keys as below:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "ConnectionString": "Data Source=localhost;Initial Catalog=ReadConfig;Persist Security Info=True;User ID=sa;Password=12345;"
  },
  "MailConfig": {
    "Servers": {
      "MailGun": {
        "Pass": "65-1B-C9-B9-27-00",
        "Port": "587",
        "Host": "smtp.gmail.com"
      }
    },
    "Sender": {
      "Email": "[email protected]",
      "Pass": "123456"
    }
  }
}

Step 3. Read config value from an action

I make demo an action in Home controller as below :

public class HomeController : Controller
{
    public IActionResult Index()
    {
        var connectionString = AppSettings.Instance.GetConnection("ConnectionString");
        var emailSender = AppSettings.Instance.Get<string>("MailConfig:Sender:Email");
        var emailHost = AppSettings.Instance.Get<string>("MailConfig:Servers:MailGun:Host");

        string returnText = " 1. Connection String \n";
        returnText += "  " +connectionString;
        returnText += "\n 2. Email info";
        returnText += "\n Sender : " + emailSender;
        returnText += "\n Host : " + emailHost;

        return Content(returnText);
    }
}

And below is the result:

Click to see result

For more information, you can refer article get value from appsettings.json in asp.net core for more detail code.

openCV program compile error "libopencv_core.so.2.4: cannot open shared object file: No such file or directory" in ubuntu 12.04

To make it more clear(and to put it together) I had to do Two things mentioned above.

1- Create a file /etc/ld.so.conf.d/opencv.conf and write to it the paths of folder where your opencv libraries are stored.(Answer by Cookyt)

2- Include the path of your opencv's .so files in LD_LIBRARY_PATH ()

export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/opencv/lib

Maven: Command to update repository after adding dependency to POM

Right, click on the project. Go to Maven -> Update Project.

The dependencies will automatically be installed.

Make a div fill up the remaining width

I was looking for a solution to the opposite problem where I needed a fixed width div in the centre and a fluid width div on either side, so I came up with the following and thought I'd post it here in case anyone needs it.

_x000D_
_x000D_
#wrapper {_x000D_
  clear: both;_x000D_
  width: 100%;_x000D_
}_x000D_
_x000D_
#wrapper div {_x000D_
  display: inline-block;_x000D_
  height: 500px;_x000D_
}_x000D_
_x000D_
#center {_x000D_
  background-color: green;_x000D_
  margin: 0 auto;_x000D_
  overflow: auto;_x000D_
  width: 500px;_x000D_
}_x000D_
_x000D_
#left {_x000D_
  float: left;_x000D_
}_x000D_
_x000D_
#right {_x000D_
  float: right;_x000D_
}_x000D_
_x000D_
.fluid {_x000D_
  background-color: yellow;_x000D_
  width: calc(50% - 250px);_x000D_
}
_x000D_
<div id="wrapper">_x000D_
  <div id="center">_x000D_
    This is fixed width in the centre_x000D_
  </div>_x000D_
  <div id="left" class="fluid">_x000D_
    This is fluid width on the left_x000D_
  </div>_x000D_
  <div id="right" class="fluid">_x000D_
    This is fluid width on the right_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

If you change the width of the #center element then you need to update the width property of .fluid to:

width: calc(50% - [half of center width]px);

How do I use disk caching in Picasso?

Add followning code in Application.onCreate then use it normal

    Picasso picasso = new Picasso.Builder(context)
            .downloader(new OkHttp3Downloader(this,Integer.MAX_VALUE))
            .build();
    picasso.setIndicatorsEnabled(true);
    picasso.setLoggingEnabled(true);
    Picasso.setSingletonInstance(picasso);

If you cache images first then do something like this in ProductImageDownloader.doBackground

final Callback callback = new Callback() {
            @Override
            public void onSuccess() {
                downLatch.countDown();
                updateProgress();
            }

            @Override
            public void onError() {
                errorCount++;
                downLatch.countDown();
                updateProgress();
            }
        };
        Picasso.with(context).load(Constants.imagesUrl+productModel.getGalleryImage())
                .memoryPolicy(MemoryPolicy.NO_CACHE).fetch(callback);
        Picasso.with(context).load(Constants.imagesUrl+productModel.getLeftImage())
                .memoryPolicy(MemoryPolicy.NO_CACHE).fetch(callback);
        Picasso.with(context).load(Constants.imagesUrl+productModel.getRightImage())
                .memoryPolicy(MemoryPolicy.NO_CACHE).fetch(callback);

        try {
            downLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        if(errorCount == 0){
            products.remove(productModel);
            productModel.isDownloaded = true;
            productsDatasource.updateElseInsert(productModel);
        }else {
            //error occurred while downloading images for this product
            //ignore error for now
            // FIXME: 9/27/2017 handle error
            products.remove(productModel);

        }
        errorCount = 0;
        downLatch = new CountDownLatch(3);

        if(!products.isEmpty() /*&& testCount++ < 30*/){
            startDownloading(products.get(0));
        }else {
            //all products with images are downloaded
            publishProgress(100);
        }

and load your images like normal or with disk caching

    Picasso.with(this).load(Constants.imagesUrl+batterProduct.getGalleryImage())
        .networkPolicy(NetworkPolicy.OFFLINE)
        .placeholder(R.drawable.GalleryDefaultImage)
        .error(R.drawable.GalleryDefaultImage)
        .into(viewGallery);

Note:

Red color indicates that image is fetched from network.

Green color indicates that image is fetched from cache memory.

Blue color indicates that image is fetched from disk memory.

Before releasing the app delete or set it false picasso.setLoggingEnabled(true);, picasso.setIndicatorsEnabled(true); if not required. Thankx

Changing the git user inside Visual Studio Code

This could be because of the reason that the credentials are saved and you need to update those credentials and you can do that by following the below steps

control panel-> credential manager ->under generic credential you will be able to see the credentials related to git

Try to update them if that does not work delete them and add new ones

for other platforms or different versions of the operating system you need to find out where the credentails are saved related to git and update them.

jquery to loop through table rows and cells, where checkob is checked, concatenate

UPDATED

I've updated your demo: http://jsfiddle.net/terryyounghk/QS56z/18/

Also, I've changed two ^= to *=. See http://api.jquery.com/category/selectors/

And note the :checked selector. See http://api.jquery.com/checked-selector/

function createcodes() {

    //run through each row
    $('.authors-list tr').each(function (i, row) {

        // reference all the stuff you need first
        var $row = $(row),
            $family = $row.find('input[name*="family"]'),
            $grade = $row.find('input[name*="grade"]'),
            $checkedBoxes = $row.find('input:checked');

        $checkedBoxes.each(function (i, checkbox) {
            // assuming you layout the elements this way, 
            // we'll take advantage of .next()
            var $checkbox = $(checkbox),
                $line = $checkbox.next(),
                $size = $line.next();

            $line.val(
                $family.val() + ' ' + $size.val() + ', ' + $grade.val()
            );

        });

    });
}

converting drawable resource image into bitmap

In res/drawable folder,

1. Create a new Drawable Resources.

2. Input file name.

A new file will be created inside the res/drawable folder.

Replace this code inside the newly created file and replace ic_action_back with your drawable file name.

<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
    android:src="@drawable/ic_action_back"
    android:tint="@color/color_primary_text" />

Now, you can use it with Resource ID, R.id.filename.

Stop node.js program from command line

on linux try: pkill node

on windows:

Taskkill /IM node.exe /F

or

from subprocess import call

call(['taskkill', '/IM', 'node.exe', '/F'])

apply drop shadow to border-top only?

The simple answer is that you can't. box-shadow applies to the whole element only. You could use a different approach and use ::before in CSS to insert an 1-pixel high element into header nav and set the box-shadow on that instead.

Use of ~ (tilde) in R programming Language

The thing on the right of <- is a formula object. It is often used to denote a statistical model, where the thing on the left of the ~ is the response and the things on the right of the ~ are the explanatory variables. So in English you'd say something like "Species depends on Sepal Length, Sepal Width, Petal Length and Petal Width".

The myFormula <- part of that line stores the formula in an object called myFormula so you can use it in other parts of your R code.


Other common uses of formula objects in R

The lattice package uses them to specify the variables to plot.
The ggplot2 package uses them to specify panels for plotting.
The dplyr package uses them for non-standard evaulation.

Add URL link in CSS Background Image?

Try wrapping the spans in an anchor tag and apply the background image to that.

HTML:

<div class="header">
    <a href="/">
        <span class="header-title">My gray sea design</span><br />
        <span class="header-title-two">A beautiful design</span>
    </a>
</div>

CSS:

.header {
    border-bottom:1px solid #eaeaea;
}

.header a {
    display: block;
    background-image: url("./images/embouchure.jpg");
    background-repeat: no-repeat;
    height:160px;
    padding-left:280px;
    padding-top:50px;
    width:470px;
    color: #eaeaea;
}

How to sort a Pandas DataFrame by index?

Dataframes have a sort_index method which returns a copy by default. Pass inplace=True to operate in place.

import pandas as pd
df = pd.DataFrame([1, 2, 3, 4, 5], index=[100, 29, 234, 1, 150], columns=['A'])
df.sort_index(inplace=True)
print(df.to_string())

Gives me:

     A
1    4
29   2
100  1
150  5
234  3

The instance of entity type cannot be tracked because another instance of this type with the same key is already being tracked

I got this error from my background service. I solved which creating a new scope.

                using (var scope = serviceProvider.CreateScope())
                {
                      // Process
                }

Pretty print in MongoDB shell as default

(note: this is answer to original version of the question, which did not have requirements for "default")

You can ask it to be pretty.

db.collection.find().pretty()

How do I use DrawerLayout to display over the ActionBar/Toolbar and under the status bar?

With the release of the latest Android Support Library (rev 22.2.0) we've got a Design Support Library and as part of this a new view called NavigationView. So instead of doing everything on our own with the ScrimInsetsFrameLayout and all the other stuff we simply use this view and everything is done for us.

Example

Step 1

Add the Design Support Library to your build.gradle file

dependencies {
    // Other dependencies like appcompat
    compile 'com.android.support:design:22.2.0'
}

Step 2

Add the NavigationView to your DrawerLayout:

<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
     xmlns:app="http://schemas.android.com/apk/res-auto"
     android:id="@+id/drawer_layout"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     android:fitsSystemWindows="true"> <!-- this is important -->

     <!-- Your contents -->

     <android.support.design.widget.NavigationView
         android:id="@+id/navigation"
         android:layout_width="wrap_content"
         android:layout_height="match_parent"
         android:layout_gravity="start"
         app:menu="@menu/navigation_items" /> <!-- The items to display -->
 </android.support.v4.widget.DrawerLayout>

Step 3

Create a new menu-resource in /res/menu and add the items and icons you wanna display:

<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <group android:checkableBehavior="single">
        <item
            android:id="@+id/nav_home"
            android:icon="@drawable/ic_action_home"
            android:title="Home" />
        <item
            android:id="@+id/nav_example_item_1"
            android:icon="@drawable/ic_action_dashboard"
            android:title="Example Item #1" />
    </group>

    <item android:title="Sub items">
        <menu>
            <item
                android:id="@+id/nav_example_sub_item_1"
                android:title="Example Sub Item #1" />
        </menu>
    </item>

</menu>

Step 4

Init the NavigationView and handle click events:

public class MainActivity extends AppCompatActivity {

    NavigationView mNavigationView;
    DrawerLayout mDrawerLayout;

    // Other stuff

    private void init() {
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mNavigationView = (NavigationView) findViewById(R.id.navigation_view);
        mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(MenuItem menuItem) {
                mDrawerLayout.closeDrawers();
                menuItem.setChecked(true);
                switch (menuItem.getItemId()) {
                    case R.id.nav_home:
                        // TODO - Do something
                        break;
                    // TODO - Handle other items
                }
                return true;
            }
        });
    }
}

Step 5

Be sure to set android:windowDrawsSystemBarBackgrounds and android:statusBarColor in values-v21 otherwise your Drawer won`t be displayed "under" the StatusBar

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Other attributes like colorPrimary, colorAccent etc. -->
    <item name="android:windowDrawsSystemBarBackgrounds">true</item>
    <item name="android:statusBarColor">@android:color/transparent</item>
</style>

Optional Step

Add a Header to the NavigationView. For this simply create a new layout and add app:headerLayout="@layout/my_header_layout" to the NavigationView.

Result

picture showing navigation view

Notes

  • The highlighted color uses the color defined via the colorPrimary attribute
  • The List Items use the color defined via the textColorPrimary attribute
  • The Icons use the color defined via the textColorSecondary attribute

You can also check the example app by Chris Banes which highlights the NavigationView along with the other new views that are part of the Design Support Library (like the FloatingActionButton, TextInputLayout, Snackbar, TabLayout etc.)

Excel VBA - read cell value from code

I think you need this ..

Dim n as Integer   

For n = 5 to 17
  msgbox cells(n,3) '--> sched waste
  msgbox cells(n,4) '--> type of treatm
  msgbox format(cells(n,5),"dd/MM/yyyy") '--> Lic exp
  msgbox cells(n,6) '--> email col
Next

jQuery Find and List all LI elements within a UL within a specific DIV

var column1RelArray = [];
$('#column1 li').each(function(){
    column1RelArray.push($(this).attr('rel'));
});

or fp style

var column1RelArray = $('#column1 li').map(function(){ 
    return $(this).attr('rel'); 
});

How can I scale an entire web page with CSS?

 * {
transform: scale(1.1, 1.1)
}

this will transform every element on the page

how to set default culture info for entire c# application

If you use a Language Resource file to set the labels in your application you need to set the its value:

CultureInfo customCulture = new CultureInfo("en-US");
Languages.Culture = customCulture;

How do JavaScript closures work?

The Straw Man

I need to know how many times a button has been clicked and do something on every third click...

Fairly Obvious Solution

_x000D_
_x000D_
// Declare counter outside event handler's scope
var counter = 0;
var element = document.getElementById('button');

element.addEventListener("click", function() {
  // Increment outside counter
  counter++;

  if (counter === 3) {
    // Do something every third time
    console.log("Third time's the charm!");

    // Reset counter
    counter = 0;
  }
});
_x000D_
<button id="button">Click Me!</button>
_x000D_
_x000D_
_x000D_

Now this will work, but it does encroach into the outer scope by adding a variable, whose sole purpose is to keep track of the count. In some situations, this would be preferable as your outer application might need access to this information. But in this case, we are only changing every third click's behavior, so it is preferable to enclose this functionality inside the event handler.

Consider this option

_x000D_
_x000D_
var element = document.getElementById('button');

element.addEventListener("click", (function() {
  // init the count to 0
  var count = 0;

  return function(e) { // <- This function becomes the click handler
    count++; //    and will retain access to the above `count`

    if (count === 3) {
      // Do something every third time
      console.log("Third time's the charm!");

      //Reset counter
      count = 0;
    }
  };
})());
_x000D_
<button id="button">Click Me!</button>
_x000D_
_x000D_
_x000D_

Notice a few things here.

In the above example, I am using the closure behavior of JavaScript. This behavior allows any function to have access to the scope in which it was created, indefinitely. To practically apply this, I immediately invoke a function that returns another function, and because the function I'm returning has access to the internal count variable (because of the closure behavior explained above) this results in a private scope for usage by the resulting function... Not so simple? Let's dilute it down...

A simple one-line closure

//          _______________________Immediately invoked______________________
//         |                                                                |
//         |        Scope retained for use      ___Returned as the____      |
//         |       only by returned function   |    value of func     |     |
//         |             |            |        |                      |     |
//         v             v            v        v                      v     v
var func = (function() { var a = 'val'; return function() { alert(a); }; })();

All variables outside the returned function are available to the returned function, but they are not directly available to the returned function object...

func();  // Alerts "val"
func.a;  // Undefined

Get it? So in our primary example, the count variable is contained within the closure and always available to the event handler, so it retains its state from click to click.

Also, this private variable state is fully accessible, for both readings and assigning to its private scoped variables.

There you go; you're now fully encapsulating this behavior.

Full Blog Post (including jQuery considerations)

Directing print output to a .txt file

Give print a file keyword argument, where the value of the argument is a file stream. We can create a file stream using the open function:

print("Hello stackoverflow!", file=open("output.txt", "a"))
print("I have a question.", file=open("output.txt", "a"))

From the Python documentation about print:

The file argument must be an object with a write(string) method; if it is not present or None, sys.stdout will be used.

And the documentation for open:

Open file and return a corresponding file object. If the file cannot be opened, an OSError is raised.

The "a" as the second argument of open means "append" - in other words, the existing contents of the file won't be overwritten. If you want the file to be overwritten instead, use "w".


Opening a file with open many times isn't ideal for performance, however. You should ideally open it once and name it, then pass that variable to print's file option. You must remember to close the file afterwards!

f = open("output.txt", "a")
print("Hello stackoverflow!", file=f)
print("I have a question.", file=f)
f.close()

There's also a syntactic shortcut for this, which is the with block. This will close your file at the end of the block for you:

with open("output.txt", "a") as f:
    print("Hello stackoverflow!", file=f)
    print("I have a question.", file=f)

SELECT DISTINCT on one column

The simplest solution would be to use a subquery for finding the minimum ID matching your query. In the subquery you use GROUP BY instead of DISTINCT:

SELECT * FROM [TestData] WHERE [ID] IN (
   SELECT MIN([ID]) FROM [TestData]
   WHERE [SKU] LIKE 'FOO-%'
   GROUP BY [PRODUCT]
)

Proper MIME type for .woff2 fonts

http://dev.w3.org/webfonts/WOFF2/spec/#IMT

It seem that w3c switched it to font/woff2

I see there is some discussion about the proper mime type. In the link we read:

This document defines a top-level MIME type "font" ...

... the officially defined IANA subtypes such as "application/font-woff" ...

The members of the W3C WebFonts WG believe the use of "application" top-level type is not ideal.

and later

6.5. WOFF 2.0

    Type name:

        font
    Subtype name:

        woff2

So proposition from W3C differs from IANA.

We can see that it also differs from woff type: http://dev.w3.org/webfonts/WOFF/spec/#IMT where we read:

Type name:

    application
Subtype name:

    font-woff

which is

application/font-woff

http://www.w3.org/TR/WOFF/#appendix-b

UICollectionView Set number of columns

Because UICollectionView is so flexible, there are multiple ways you could change the number of columns, depending on the kind of layout you use.

The UICollectionViewFlowLayout (which is probably what you're working with) doesn't specify a number of columns directly (because it depends on the view size/orientation). The easiest way to change it would be to set the itemSize property and/or minimumInteritemSpacing/minimumLineSpacing.

How to determine the screen width in terms of dp or dip at runtime in Android?

Try this

Display display = getWindowManager().getDefaultDisplay();
DisplayMetrics outMetrics = new DisplayMetrics ();
display.getMetrics(outMetrics);

float density  = getResources().getDisplayMetrics().density;
float dpHeight = outMetrics.heightPixels / density;
float dpWidth  = outMetrics.widthPixels / density;

OR

Thanks @Tomáš Hubálek

DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();    
float dpHeight = displayMetrics.heightPixels / displayMetrics.density;
float dpWidth = displayMetrics.widthPixels / displayMetrics.density;

AngularJS : When to use service instead of factory

Even when they say that all services and factories are singleton, I don't agree 100 percent with that. I would say that factories are not singletons and this is the point of my answer. I would really think about the name that defines every component(Service/Factory), I mean:

A factory because is not a singleton, you can create as many as you want when you inject, so it works like a factory of objects. You can create a factory of an entity of your domain and work more comfortably with this objects which could be like an object of your model. When you retrieve several objects you can map them in this objects and it can act kind of another layer between the DDBB and the AngularJs model.You can add methods to the objects so you oriented to objects a little bit more your AngularJs App.

Meanwhile a service is a singleton, so we can only create 1 of a kind, maybe not create but we have only 1 instance when we inject in a controller, so a service provides more like a common service(rest calls,functionality.. ) to the controllers.

Conceptually you can think like services provide a service, factories can create multiple instances(objects) of a class

How to get the dimensions of a tensor (in TensorFlow) at graph construction time?

Tensor.get_shape() from this post.

From documentation:

c = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
print(c.get_shape())
==> TensorShape([Dimension(2), Dimension(3)])

Onclick on bootstrap button

Seem no solutions fix the problem:

$(".anima-area").on('click', function (e) {
            return false; //return true;
});
$(".anima-area").on('click', function (e) {
            e.preventDefault();
});
 $(".anima-area").click(function (r) {
           e.preventDefault();
});
$(".anima-area").click(function () {
           return false; //return true;
});

Bootstrap button always maintain th pressed status and block all .click code. If i remove .click function button comeback to work good.

Attach IntelliJ IDEA debugger to a running Java process

Yes! Here is how you set it up.

Run Configuration

Create a Remote run configuration:

  1. Run -> Edit Configurations...
  2. Click the "+" in the upper left
  3. Select the "Remote" option in the left-most pane
  4. Choose a name (I named mine "remote-debugging")
  5. Click "OK" to save:

enter image description here

JVM Options

The configuration above provides three read-only fields. These are options that tell the JVM to open up port 5005 for remote debugging when running your application. Add the appropriate one to the JVM options of the application you are debugging. One way you might do this would be like so:

export JAVA_OPTS="-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005"

But it depends on how your run your application. If you're not sure which of the three applies to you, start with the first and go down the list until you find the one that works.

You can change suspend=n to suspend=y to force your application to wait until you connect with IntelliJ before it starts up. This is helpful if the breakpoint you want to hit occurs on application startup.

Debug

Start your application as you would normally, then in IntelliJ select the new configuration and hit 'Debug'.

enter image description here

IntelliJ will connect to the JVM and initiate remote debugging.

You can now debug the application by adding breakpoints to your code where desired. The output of the application will still appear wherever it did before, but your breakpoints will hit in IntelliJ.

How to detect a mobile device with JavaScript?

Similar to several of the answers above. This simple function, works very well for me. It is current as of 2019

function IsMobileCard()
{
var check =  false;

(function(a){if(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0,4))) check = true;})(navigator.userAgent||navigator.vendor||window.opera);

return check;   
}

MongoDB: exception in initAndListen: 20 Attempted to create a lock file on a read-only directory: /data/db, terminating

Nice solutions, but I wonder why nobody is giving the solution for windows.

If you are using windows you just have to "Run as Administrator" the cmd.

Error: "Input is not proper UTF-8, indicate encoding !" using PHP's simplexml_load_string

After several tries i found htmlentities function works.

$value = htmlentities($value)

Set the value of a variable with the result of a command in a Windows batch file

One needs to be somewhat careful, since the Windows batch command:

for /f "delims=" %%a in ('command') do @set theValue=%%a

does not have the same semantics as the Unix shell statement:

theValue=`command`

Consider the case where the command fails, causing an error.

In the Unix shell version, the assignment to "theValue" still occurs, any previous value being replaced with an empty value.

In the Windows batch version, it's the "for" command which handles the error, and the "do" clause is never reached -- so any previous value of "theValue" will be retained.

To get more Unix-like semantics in Windows batch script, you must ensure that assignment takes place:

set theValue=
for /f "delims=" %%a in ('command') do @set theValue=%%a

Failing to clear the variable's value when converting a Unix script to Windows batch can be a cause of subtle errors.

'names' attribute must be the same length as the vector

I want to explain the error with an example below:

> names(lenses)
[1] "X1..1..1..1..1..3"

names(lenses)=c("ID","Age","Sight","Astigmatism","Tear","Class") Error in names(lenses) = c("ID", "Age", "Sight", "Astigmatism", "Tear", : 'names' attribute [6] must be the same length as the vector [1]

The error happened because of mismatch in a number of attributes. I only have one but trying to add 6 names. In this case, the error happens. See below the correct one:::::>>>>

> names(lenses)=c("ID")
> names(lenses)

[1] "ID"

Now there was no error.

I hope this will help!

check the null terminating character in char*

To make this complete: while others now solved your problem :) I would like to give you a piece of good advice: don't reinvent the wheel.

size_t forward_length = strlen(forward);

Running a shell script through Cygwin on Windows

One more thing - if You edited the shell script in some Windows text editor, which produces the \r\n line-endings, cygwin's bash wouldn't accept those \r. Just run dos2unix testit.sh before executing the script:

C:\cygwin\bin\dos2unix testit.sh
C:\cygwin\bin\bash testit.sh

How to load data from a text file in a PostgreSQL database?

The slightly modified version of COPY below worked better for me, where I specify the CSV format. This format treats backslash characters in text without any fuss. The default format is the somewhat quirky TEXT.

COPY myTable FROM '/path/to/file/on/server' ( FORMAT CSV, DELIMITER('|') );

Creating an iframe with given HTML dynamically

I know this is an old question but I thought I would provide an example using the srcdoc attribute as this is now widely supported and this is question is viewed often.

Using the srcdoc attribute, you can provide inline HTML to embed. It overrides the src attribute if supported. The browser will fall back to the src attribute if unsupported.

I would also recommend using the sandbox attribute to apply extra restrictions to the content in the frame. This is especially important if the HTML is not your own.

_x000D_
_x000D_
const iframe = document.createElement('iframe');_x000D_
const html = '<body>Foo</body>';_x000D_
iframe.srcdoc = html;_x000D_
iframe.sandbox = '';_x000D_
document.body.appendChild(iframe);
_x000D_
_x000D_
_x000D_

If you need to support older browsers, you can check for srcdoc support and fallback to one of the other methods from other answers.

_x000D_
_x000D_
function setIframeHTML(iframe, html) {_x000D_
  if (typeof iframe.srcdoc !== 'undefined') {_x000D_
    iframe.srcdoc = html;_x000D_
  } else {_x000D_
    iframe.sandbox = 'allow-same-origin';_x000D_
    iframe.contentWindow.document.open();_x000D_
    iframe.contentWindow.document.write(html);_x000D_
    iframe.contentWindow.document.close();_x000D_
  }_x000D_
}_x000D_
_x000D_
var iframe = document.createElement('iframe');_x000D_
iframe.sandbox = '';_x000D_
var html = '<body>Foo</body>';_x000D_
_x000D_
document.body.appendChild(iframe);_x000D_
setIframeHTML(iframe, html);
_x000D_
_x000D_
_x000D_

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.

Rotating and spacing axis labels in ggplot2

Change the last line to

q + theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))

By default, the axes are aligned at the center of the text, even when rotated. When you rotate +/- 90 degrees, you usually want it to be aligned at the edge instead:

alt text

The image above is from this blog post.

getOutputStream() has already been called for this response

I had this problem only the second time I went to export. Once I added:

response.getOutputStream().flush();
response.getOutputStream().close();

after the export was done, my code started working all of the time.

Binding a list in @RequestParam

Just complementing what Donal Fellows said, you can use List with @RequestParam

public String controllerMethod(@RequestParam(value="myParam") List<ObjectToParse> myParam){
....
}

Hope it helps!

Clearing NSUserDefaults

I found this:

osascript -e 'tell application "iOS Simulator" to quit'
xcrun simctl list devices | grep -v '^[-=]' | cut -d "(" -f2 | cut -d ")" -f1 | xargs -I {} xcrun simctl erase "{}"

Source: https://gist.github.com/ZevEisenberg/5a172662cb576872d1ab

Python: "Indentation Error: unindent does not match any outer indentation level"

I had this same problem and it had nothing to do with tabs. This was my problem code:

def genericFunction(variable):

    for line in variable:

       line = variable


   if variable != None:
      return variable

Note the above for is indented with more spaces than the line that starts with if. This is bad. All your indents must be consistent. So I guess you could say I had a stray space and not a stray tab.

how to toggle (hide/show) a table onClick of <a> tag in java script

inside your function toggleTable when you do this line

document.getElementById("loginLink").onclick = toggleTable(....

you are actually calling the function again. so toggleTable gets called again, and again and again, you're falling in an infinite recursive call.

make it simple.

function toggleTable()
{
     var elem=document.getElementById("loginTable");
     var hide = elem.style.display =="none";
     if (hide) {
         elem.style.display="table";
    } 
    else {
       elem.style.display="none";
    }
}

see this fiddle

Forcing label to flow inline with input that they label

What I did so that input didn't take up the whole line, and be able to place the input in a paragraph, I used a span tag and display to inline-block

html:

<span>cluster:
        <input class="short-input" type="text" name="cluster">
</span>

css:

span{display: inline-block;}

Pandas read_csv from url

To Import Data through URL in pandas just apply the simple below code it works actually better.

import pandas as pd
train = pd.read_table("https://urlandfile.com/dataset.csv")
train.head()

If you are having issues with a raw data then just put 'r' before URL

import pandas as pd
train = pd.read_table(r"https://urlandfile.com/dataset.csv")
train.head()

What does MissingManifestResourceException mean and how to fix it?

I've encountered this issue with managed C++ project based on WinForms after renaming global namespace (not manually, but with Rename tool of VS2017).

The solution is simple, but isn't mentioned elsewhere.

You have to change RootNamespace entry in vcxproj-file to match the C++ namespace.

How to center a window on the screen in Tkinter?

This method is cross-platform, works for multiple monitors/screens (targets the active screen), and requires no other libraries than Tk. The root window will appear centered without any unwanted "flashing" or animations:

import tkinter as tk

def get_geometry(frame):
    geometry = frame.winfo_geometry()
    match = re.match(r'^(\d+)x(\d+)\+(\d+)\+(\d+)$', geometry)
    return [int(val) for val in match.group(*range(1, 5))]

def center_window(root):
    """Must be called after application is fully initialized
    so that the root window is the true final size."""
    # Avoid unwanted "flashing" by making window transparent until fully ready
    root.attributes('-alpha', 0)

    # Get dimensions of active screen/monitor using fullscreen trick; withdraw
    # window before making it fullscreen to preserve previous dimensions
    root.withdraw()
    root.attributes('-fullscreen', True)
    root.update_idletasks()
    (screen_width, screen_height, *_) = get_geometry(root)
    root.attributes('-fullscreen', False)

    # Restore and get "natural" window dimensions
    root.deiconify()
    root.update_idletasks()
    (window_width, window_height, *_) = get_geometry(root)

    # Compute and set proper window center
    pos_x = round(screen_width / 2 - window_width / 2)
    pos_y = round(screen_height / 2 - window_height / 2)
    root.geometry(f'+{pos_x}+{pos_y}')
    root.update_idletasks()
    
    root.attributes('-alpha', 1)

# Usage:
root = tk.Tk()
center_window(root)

Note that at every point where window geometry is modified, update_idletasks() must be called to force the operation to occur synchronously/immediately. It uses Python 3 functionality but can easily be adapted to Python 2.x if necessary.

How to open a specific port such as 9090 in Google Compute Engine

I had the same problem as you do and I could solve it by following @CarlosRojas instructions with a little difference. Instead of create a new firewall rule I edited the default-allow-internal one to accept traffic from anywhere since creating new rules didn't make any difference.

How to convert DOS/Windows newline (CRLF) to Unix newline (LF) in a Bash script?

Super duper easy with PCRE;

As a script, or replace $@ with your files.

#!/usr/bin/env bash
perl -pi -e 's/\r\n/\n/g' -- $@

This will overwrite your files in place!

I recommend only doing this with a backup (version control or otherwise)

Adding an HTTP Header to the request in a servlet filter

Extend HttpServletRequestWrapper, override the header getters to return the parameters as well:

public class AddParamsToHeader extends HttpServletRequestWrapper {
    public AddParamsToHeader(HttpServletRequest request) {
        super(request);
    }

    public String getHeader(String name) {
        String header = super.getHeader(name);
        return (header != null) ? header : super.getParameter(name); // Note: you can't use getParameterValues() here.
    }

    public Enumeration getHeaderNames() {
        List<String> names = Collections.list(super.getHeaderNames());
        names.addAll(Collections.list(super.getParameterNames()));
        return Collections.enumeration(names);
    }
}

..and wrap the original request with it:

chain.doFilter(new AddParamsToHeader((HttpServletRequest) request), response);

That said, I personally find this a bad idea. Rather give it direct access to the parameters or pass the parameters to it.

get an element's id

In events handler you can get id as follows

_x000D_
_x000D_
function show(btn) {_x000D_
  console.log('Button id:',btn.id);_x000D_
}
_x000D_
<button id="myButtonId" onclick="show(this)">Click me</button>
_x000D_
_x000D_
_x000D_

Xcode project not showing list of simulators

I could not find any solution that would fix my issue. All simulators were there for all projects but the one that I needed them.

Solution:

Build Settings -> Architectures -> Supported Platforms:

changed from iphoneos to iOS

Why can I not create a wheel in python?

It could also be that you have a python3 system only. You therefore have installed the necessary packages via pip3 install , like pip3 install wheel.

You'll need to build your stuff using python3 specifically.

python3 setup.py sdist
python3 setup.py bdist_wheel

Cheers.

Python foreach equivalent

While the answers above are valid, if you are iterating over a dict {key:value} it this is the approach I like to use:

for key, value in Dictionary.items():
    print(key, value)

Therefore, if I wanted to do something like stringify all keys and values in my dictionary, I would do this:

stringified_dictionary = {}
for key, value in Dictionary.items():
    stringified_dictionary.update({str(key): str(value)})
return stringified_dictionary

This avoids any mutation issues when applying this type of iteration, which can cause erratic behavior (sometimes) in my experience.

Initializing a two dimensional std::vector

Use the std::vector::vector(count, value) constructor that accepts an initial size and a default value:

std::vector<std::vector<int> > fog(
    ROW_COUNT,
    std::vector<int>(COLUMN_COUNT)); // Defaults to zero initial value

If a value other than zero, say 4 for example, was required to be the default then:

std::vector<std::vector<int> > fog(
    ROW_COUNT,
    std::vector<int>(COLUMN_COUNT, 4));

I should also mention uniform initialization was introduced in C++11, which permits the initialization of vector, and other containers, using {}:

std::vector<std::vector<int> > fog { { 1, 1, 1 },
                                    { 2, 2, 2 } };
                           

Hadoop "Unable to load native-hadoop library for your platform" warning

For those on OSX with Hadoop installed via Homebrew, follow these steps replacing the path and Hadoop version where appropriate

wget http://www.eu.apache.org/dist/hadoop/common/hadoop-2.7.1/hadoop-2.7.1-src.tar.gz
tar xvf hadoop-2.7.1-src.tar.gz
cd hadoop-2.7.1-src
mvn package -Pdist,native -DskipTests -Dtar
mv lib /usr/local/Cellar/hadoop/2.7.1/

then update hadoop-env.sh with

export HADOOP_OPTS="$HADOOP_OPTS -Djava.net.preferIPv4Stack=true -Djava.security.krb5.realm= -Djava.security.krb5.kdc= -Djava.library.path=/usr/local/Cellar/hadoop/2.7.1/lib/native"

How to handle floats and decimal separators with html5 input type number

Use valueAsNumber instead of .val().

input . valueAsNumber [ = value ]

Returns a number representing the form control's value, if applicable; otherwise, returns null.
Can be set, to change the value.
Throws an INVALID_STATE_ERR exception if the control is neither date- or time-based nor numeric.

Is there a max array length limit in C++?

There are two limits, both not enforced by C++ but rather by the hardware.

The first limit (should never be reached) is set by the restrictions of the size type used to describe an index in the array (and the size thereof). It is given by the maximum value the system's std::size_t can take. This data type is large enough to contain the size in bytes of any object

The other limit is a physical memory limit. The larger your objects in the array are, the sooner this limit is reached because memory is full. For example, a vector<int> of a given size n typically takes multiple times as much memory as an array of type vector<char> (minus a small constant value), since int is usually bigger than char. Therefore, a vector<char> may contain more items than a vector<int> before memory is full. The same counts for raw C-style arrays like int[] and char[].

Additionally, this upper limit may be influenced by the type of allocator used to construct the vector because an allocator is free to manage memory any way it wants. A very odd but nontheless conceivable allocator could pool memory in such a way that identical instances of an object share resources. This way, you could insert a lot of identical objects into a container that would otherwise use up all the available memory.

Apart from that, C++ doesn't enforce any limits.

Vertically align text within a div

Update April 10, 2016

Flexboxes should now be used to vertically (or even horizontally) align items.

_x000D_
_x000D_
body {
    height: 150px;
    border: 5px solid cyan; 
    font-size: 50px;
    
    display: flex;
    align-items: center; /* Vertical center alignment */
    justify-content: center; /* Horizontal center alignment */
}
_x000D_
Middle
_x000D_
_x000D_
_x000D_

A good guide to flexbox can be read on CSS Tricks. Thanks Ben (from comments) for pointing it out. I didn't have time to update.


A good guy named Mahendra posted a very working solution here.

The following class should make the element horizontally and vertically centered to its parent.

.absolute-center {

    /* Internet Explorer 10 */
    display: -ms-flexbox;
    -ms-flex-pack: center;
    -ms-flex-align: center;

    /* Firefox */
    display: -moz-box;
    -moz-box-pack: center;
    -moz-box-align: center;

    /* Safari, Opera, and Chrome */
    display: -webkit-box;
    -webkit-box-pack: center;
    -webkit-box-align: center;

    /* W3C */
    display: box;
    box-pack: center;
    box-align: center;
}

How to detect window.print() finish

compatible with chrome, firefox, opera, Internet Explorer
Note: jQuery required.

<script>

    window.onafterprint = function(e){
        $(window).off('mousemove', window.onafterprint);
        console.log('Print Dialog Closed..');
    };

    window.print();

    setTimeout(function(){
        $(window).one('mousemove', window.onafterprint);
    }, 1);

</script>

How do I read / convert an InputStream into a String in Java?

If you can't use Commons IO (FileUtils/IOUtils/CopyUtils), here's an example using a BufferedReader to read the file line by line:

public class StringFromFile {
    public static void main(String[] args) /*throws UnsupportedEncodingException*/ {
        InputStream is = StringFromFile.class.getResourceAsStream("file.txt");
        BufferedReader br = new BufferedReader(new InputStreamReader(is/*, "UTF-8"*/));
        final int CHARS_PER_PAGE = 5000; //counting spaces
        StringBuilder builder = new StringBuilder(CHARS_PER_PAGE);
        try {
            for(String line=br.readLine(); line!=null; line=br.readLine()) {
                builder.append(line);
                builder.append('\n');
            }
        } 
        catch (IOException ignore) { }

        String text = builder.toString();
        System.out.println(text);
    }
}

Or if you want raw speed I'd propose a variation on what Paul de Vrieze suggested (which avoids using a StringWriter (which uses a StringBuffer internally):

public class StringFromFileFast {
    public static void main(String[] args) /*throws UnsupportedEncodingException*/ {
        InputStream is = StringFromFileFast.class.getResourceAsStream("file.txt");
        InputStreamReader input = new InputStreamReader(is/*, "UTF-8"*/);
        final int CHARS_PER_PAGE = 5000; //counting spaces
        final char[] buffer = new char[CHARS_PER_PAGE];
        StringBuilder output = new StringBuilder(CHARS_PER_PAGE);
        try {
            for(int read = input.read(buffer, 0, buffer.length);
                    read != -1;
                    read = input.read(buffer, 0, buffer.length)) {
                output.append(buffer, 0, read);
            }
        } catch (IOException ignore) { }

        String text = output.toString();
        System.out.println(text);
    }
}

Java, how to compare Strings with String Arrays

I presume you are wanting to check if the array contains a certain value, yes? If so, use the contains method.

if(Arrays.asList(codes).contains(userCode))

unable to start mongodb local server

Andreas Jung:

"Sat Jun 25 09:38:51 [initandlisten] listen(): bind() failed errno:98 Address already in use for socket: 0.0.0.0:27017

is self-speaking.

Another instance of mongod is already running and allocating the MongoDB default port which is 27017.

Either kill the other process or use a different port."

In this case, type the following command

ps wuax | grep mongo

You should see something that looks like this

User           31936   0.5 0.4 2719784 35624   ?? S     7:34pm   0:09.98 mongod
User           31945   0.0 0.0 2423368   184 s000 R+   8:24pm   0:00.00 grep mongo

Now enter the kill command for the mongod instance (31936 in this case):

kill 31936

Determine direct shared object dependencies of a Linux binary?

ldd -v prints the dependency tree under "Version information:' section. The first block in that section are the direct dependencies of the binary.

See Hierarchical ldd(1)

How to do joins in LINQ on multiple fields in single join

The solution with the anonymous type should work fine. LINQ can only represent equijoins (with join clauses, anyway), and indeed that's what you've said you want to express anyway based on your original query.

If you don't like the version with the anonymous type for some specific reason, you should explain that reason.

If you want to do something other than what you originally asked for, please give an example of what you really want to do.

EDIT: Responding to the edit in the question: yes, to do a "date range" join, you need to use a where clause instead. They're semantically equivalent really, so it's just a matter of the optimisations available. Equijoins provide simple optimisation (in LINQ to Objects, which includes LINQ to DataSets) by creating a lookup based on the inner sequence - think of it as a hashtable from key to a sequence of entries matching that key.

Doing that with date ranges is somewhat harder. However, depending on exactly what you mean by a "date range join" you may be able to do something similar - if you're planning on creating "bands" of dates (e.g. one per year) such that two entries which occur in the same year (but not on the same date) should match, then you can do it just by using that band as the key. If it's more complicated, e.g. one side of the join provides a range, and the other side of the join provides a single date, matching if it falls within that range, that would be better handled with a where clause (after a second from clause) IMO. You could do some particularly funky magic by ordering one side or the other to find matches more efficiently, but that would be a lot of work - I'd only do that kind of thing after checking whether performance is an issue.

How to find the extension of a file in C#?

It is worth to mention how to remove the extension also in parallel with getting the extension:

var name = Path.GetFileNameWithoutExtension(fileFullName); // Get the name only

var extension = Path.GetExtension(fileFullName); // Get the extension only

Angular 2 'component' is not a known element

A lot of answers/comments mention components defined in other modules, or that you have to import/declare the component (that you want to use in another component) in its/their containing module.

But in the simple case where you want to use component A from component B when both are defined in the same module, you have to declare both components in the containing module for B to see A, and not only A.

I.e. in my-module.module.ts

import { AComponent } from "./A/A.component";
import { BComponent } from "./B/B.component";

@NgModule({
  declarations: [
    AComponent,   // This is the one that we naturally think of adding ..
    BComponent,   // .. but forget this one and you get a "**'AComponent'** 
                  // is not a known element" error.
  ],
})

Changing every value in a hash in Ruby

If you are curious which inplace variant is the fastest here it is:

Calculating -------------------------------------
inplace transform_values! 1.265k (± 0.7%) i/s -      6.426k in   5.080305s
      inplace update      1.300k (± 2.7%) i/s -      6.579k in   5.065925s
  inplace map reduce    281.367  (± 1.1%) i/s -      1.431k in   5.086477s
      inplace merge!      1.305k (± 0.4%) i/s -      6.630k in   5.080751s
        inplace each      1.073k (± 0.7%) i/s -      5.457k in   5.084044s
      inplace inject    697.178  (± 0.9%) i/s -      3.519k in   5.047857s

SELECT INTO Variable in MySQL DECLARE causes syntax error?

These answers don't cover very well MULTIPLE variables.

Doing the inline assignment in a stored procedure causes those results to ALSO be sent back in the resultset. That can be confusing. To using the SELECT...INTO syntax with multiple variables you do:

SELECT a, b INTO @a, @b FROM mytable LIMIT 1;

The SELECT must return only 1 row, hence LIMIT 1, although that isn't always necessary.

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
    }
}

How to check if all inputs are not empty with jQuery

You can achive this with Regex and Replace or with just trimming.

Regex example:

if ($('input').val().replace(/[\s]/, '') == '') {
    alert('Input is not filled!');
}

With this replace() function you replace white spaces with nothing (removing white spaces).

Trimming Example:

if ($('input').val().trim() == '') {
    alert('Input is not filled!');
}

trim() function removes the leading and trailing white space and line terminator characters from a string.

org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set

I was facing a similar problem when starting up the application (using Spring Boot) with the database server down.

Hibernate can determine the correct dialect to use automatically, but in order to do this, it needs a live connection to the database.

How to execute a Python script from the Django shell?

runscript from django-extensions

python manage.py runscript scripty.py

A sample script.py to test it out:

from django.contrib.auth.models import User
print(User.objects.values())

Mentioned at: http://django-extensions.readthedocs.io/en/latest/command_extensions.html and documented at:

python manage.py runscript --help

There is a tutorial too.

Tested on Django 1.9.6, django-extensions 1.6.7.

How to write/update data into cells of existing XLSX workbook using xlsxwriter in python

Quote from xlsxwriter module documentation:

This module cannot be used to modify or write to an existing Excel XLSX file.

If you want to modify existing xlsx workbook, consider using openpyxl module.

See also:

Switch to another branch without changing the workspace files

Edit: I just noticed that you said you had already created some commits. In that case, use git merge --squash to make a single commit:

git checkout cleanchanges
git merge --squash master
git commit -m "nice commit comment for all my changes"

(Edit: The following answer applies if you have uncommitted changes.)

Just switch branches with git checkout cleanchanges. If the branches refer to the same ref, then all your uncommitted changes will be preserved in your working directory when you switch.

The only time you would have a conflict is if some file in the repository is different between origin/master and cleanchanges. If you just created the branch, then no problem.

As always, if you're at all concerned about losing work, make a backup copy first. Git is designed to not throw away work without asking you first.

How do you run a command as an administrator from the Windows command line?

Although @amr ali's code was great, I had an instance where my bat file contained > < signs, and it choked on them for some reason.

I found this instead. Just put it all before your code, and it works perfectly.

REM  --> Check for permissions
>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system"
REM --> If error flag set, we do not have admin.
if '%errorlevel%' NEQ '0' (
    echo Requesting administrative privileges...
    goto UACPrompt
) else ( goto gotAdmin )
:UACPrompt
    echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
    echo UAC.ShellExecute "%~s0", "", "", "runas", 1 >> "%temp%\getadmin.vbs"
    "%temp%\getadmin.vbs"
    exit /B
:gotAdmin
    if exist "%temp%\getadmin.vbs" ( del "%temp%\getadmin.vbs" )
    pushd "%CD%"
    CD /D "%~dp0"
:--------------------------------------

URL to load resources from the classpath in Java

An extension to Dilums's answer:

Without changing code, you likely need pursue custom implementations of URL related interfaces as Dilum recommends. To simplify things for you, I can recommend looking at the source for Spring Framework's Resources. While the code is not in the form of a stream handler, it has been designed to do exactly what you are looking to do and is under the ASL 2.0 license, making it friendly enough for re-use in your code with due credit.

use of entityManager.createNativeQuery(query,foo.class)

Suppose your query is "select id,name from users where rollNo = 1001".

Here query will return a object with id and name column. Your Response class is like bellow:

public class UserObject{
        int id;
        String name;
        String rollNo;

        public UserObject(Object[] columns) {
            this.id = (columns[0] != null)?((BigDecimal)columns[0]).intValue():0;
            this.name = (String) columns[1];
        }

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getRollNo() {
            return rollNo;
        }

        public void setRollNo(String rollNo) {
            this.rollNo = rollNo;
        }
    }

here UserObject constructor will get a Object Array and set data with object.

public UserObject(Object[] columns) {
            this.id = (columns[0] != null)?((BigDecimal)columns[0]).intValue():0;
            this.name = (String) columns[1];
        }

Your query executing function is like bellow :

public UserObject getUserByRoll(EntityManager entityManager,String rollNo) {

        String queryStr = "select id,name from users where rollNo = ?1";
        try {
            Query query = entityManager.createNativeQuery(queryStr);
            query.setParameter(1, rollNo);

            return new UserObject((Object[]) query.getSingleResult());
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

Here you have to import bellow packages:

import javax.persistence.Query;
import javax.persistence.EntityManager;

Now your main class, you have to call this function. First you have to get EntityManager and call this getUserByRoll(EntityManager entityManager,String rollNo) function. Calling procedure is given bellow:

@PersistenceContext
private EntityManager entityManager;

UserObject userObject = getUserByRoll(entityManager,"1001");

Now you have data in this userObject.

Here is Imports

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

Note:

query.getSingleResult() return a array. You have to maintain the column position and data type.

select id,name from users where rollNo = ?1 

query return a array and it's [0] --> id and [1] -> name.

For more info, visit this Answer

Thanks :)

Can I compile all .cpp files in src/ to .o's in obj/, then link to binary in ./?

Makefile part of the question

This is pretty easy, unless you don't need to generalize try something like the code below (but replace space indentation with tabs near g++)

SRC_DIR := .../src
OBJ_DIR := .../obj
SRC_FILES := $(wildcard $(SRC_DIR)/*.cpp)
OBJ_FILES := $(patsubst $(SRC_DIR)/%.cpp,$(OBJ_DIR)/%.o,$(SRC_FILES))
LDFLAGS := ...
CPPFLAGS := ...
CXXFLAGS := ...

main.exe: $(OBJ_FILES)
   g++ $(LDFLAGS) -o $@ $^

$(OBJ_DIR)/%.o: $(SRC_DIR)/%.cpp
   g++ $(CPPFLAGS) $(CXXFLAGS) -c -o $@ $<

Automatic dependency graph generation

A "must" feature for most make systems. With GCC in can be done in a single pass as a side effect of the compilation by adding -MMD flag to CXXFLAGS and -include $(OBJ_FILES:.o=.d) to the end of the makefile body:

CXXFLAGS += -MMD
-include $(OBJ_FILES:.o=.d)

And as guys mentioned already, always have GNU Make Manual around, it is very helpful.

How can I use Python to get the system hostname?

To get fully qualified hostname use socket.getfqdn()

import socket

print socket.getfqdn()

Script @php artisan package:discover handling the post-autoload-dump event returned with error code 1

in this case, I use space for APP_NAME key in .env file.

and have below error :

The environment file is invalid!
Failed to parse dotenv file due to unexpected whitespace. Failed at [my name].
Script @php artisan package:discover handling the post-autoload-dump event returned with error code 1

Don't use space in APP_NAME key !!

XAMPP Port 80 in use by "Unable to open process" with PID 4

Simply set Apache to listen on a different port. This can be done by clicking on the "Config" button on the same line as the "Apache" module, select the "httpd.conf" file in the dropdown, then change the "Listen 80" line to "Listen 8080". Save the file and close it.

Now it avoids Port 80 and uses Port 8080 instead without issue. The only additional thing you need to do is make sure to put localhost:8080 in the browser so the browser knows to look on Port 8080. Otherwise it defaults to Port 80 and won't find your local site.

curl posting with header application/x-www-form-urlencoded

<?php
//
// A very simple PHP example that sends a HTTP POST to a remote site
//

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL,"http://xxxxxxxx.xxx/xx/xx");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,
            "dispnumber=567567567&extension=6");
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));


// receive server response ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$server_output = curl_exec ($ch);

curl_close ($ch);

// further processing ....
if ($server_output == "OK") { ... } else { ... }

?>

How to create number input field in Flutter?

The TextField widget is required to set keyboardType: TextInputType.number, and inputFormatters: <TextInputFormatter>[FilteringTextInputFormatter.digitsOnly] to accept numbers only as input.

     TextField(
            keyboardType: TextInputType.number,
            inputFormatters: <TextInputFormatter>[
              FilteringTextInputFormatter.digitsOnly
            ], // Only numbers can be entered
          ),

Example in DartPad

screenshot of dartpad

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

    void main() => runApp(new MyApp());
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          home: HomePage(),
          theme: ThemeData(primarySwatch: Colors.blue),
        );
      }
    }
    
    class HomePage extends StatefulWidget {
      @override
      State<StatefulWidget> createState() {
        return HomePageState();
      }
    }
    
    class HomePageState extends State<HomePage> {
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          backgroundColor: Colors.white,
          body: Container(
              padding: const EdgeInsets.all(40.0),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Text("This Input accepts Numbers only"),
                  SizedBox(height: 20),
                  TextField(
                    decoration: InputDecoration(
                      focusedBorder: OutlineInputBorder(
                        borderSide:
                            BorderSide(color: Colors.greenAccent, width: 5.0),
                      ),
                      enabledBorder: OutlineInputBorder(
                        borderSide: BorderSide(color: Colors.red, width: 5.0),
                      ),
                      hintText: 'Mobile Number',
                    ),
                    keyboardType: TextInputType.number,
                    inputFormatters: <TextInputFormatter>[
                      FilteringTextInputFormatter.digitsOnly
                    ], // Only numbers can be entered
                  ),
                  SizedBox(height: 20),
                  Text("You can test be Typing"),
                ],
              )),
        );
      }
    }

I can't understand why this JAXB IllegalAnnotationException is thrown

All below options worked for me.

Option 1: Annotation for FIELD at class & field level with getter/setter methods

 @XmlRootElement(name = "fields")
 @XmlAccessorType(XmlAccessType.FIELD)
    public class Fields {

        @XmlElement(name = "field")
        List<Field> fields = new ArrayList<Field>();
            //getter, setter
    }

Option 2: No Annotation for FIELD at class level(@XmlAccessorType(XmlAccessType.FIELD) and with only getter method. Adding Setter method will throw the error as we are not including the Annotation in this case. Remember, setter is not required when you explicitly set the values in your XML file.

@XmlRootElement(name = "fields")
    public class Fields {

        @XmlElement(name = "field")
        List<Field> fields = new ArrayList<Field>();
            //getter
    }

Option 3: Annotation at getter method alone. Remember we can also use the setter method here as we are not doing any FIELD level annotation in this case.

@XmlRootElement(name = "fields")
    public class Fields {

        List<Field> fields = new ArrayList<Field>();

        @XmlElement(name = "field")
        //getter

        //setter
    }

Hope this helps you!

Java count occurrence of each item in an array

Count String occurence using hashmap, streams & collections

import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

public class StringOccurence {

public static void main(String args[]) {

    String[] stringArray = { "name1", "name1", "name2", "name2", "name2" };
    countStringOccurence(stringArray);
    countStringOccurenceUsingStream(stringArray);
    countStringOccurenceUsingCollections(stringArray);
}

private static void countStringOccurenceUsingCollections(String[] stringArray) {
    // TODO Auto-generated method stub
    List<String> asList = Arrays.asList(stringArray);
    Set<String> set = new HashSet<String>(asList);
    for (String string : set) {
        System.out.println(string + "   -->   " + Collections.frequency(asList, string));
    }

}

private static void countStringOccurenceUsingStream(String[] stringArray) {
    // TODO Auto-generated method stub
    Arrays.stream(stringArray).collect(Collectors.groupingBy(s -> s))
            .forEach((k, v) -> System.out.println(k + "   -->   " + v.size()));
}

private static void countStringOccurence(String[] stringArray) {
    // TODO Auto-generated method stub
    Map<String, Integer> map = new HashMap<String, Integer>();
    for (String s : stringArray) {
        if (map.containsKey(s)) {
            map.put(s, map.get(s) + 1);
        } else {
            map.put(s, 1);
        }
    }

    for (Map.Entry<String, Integer> entry : map.entrySet()) {
        System.out.println(entry.getKey() + "   -->   " + entry.getValue());
    }

}

}

Converting an integer to binary in C

You can convert decimal to bin, hexa to decimal, hexa to bin, vice-versa etc by following this example. CONVERTING DECIMAL TO BIN

int convert_to_bin(int number){
    int binary = 0, counter = 0;
    while(number > 0){
        int remainder = number % 2;
        number /= 2;
        binary += pow(10, counter) * remainder;
        counter++;
    }   
}

Then you can print binary equivalent like this:

printf("08%d", convert_to_bin(13)); //shows leading zeros

How do I measure time elapsed in Java?

Your new class:

public class TimeWatch {    
    long starts;

    public static TimeWatch start() {
        return new TimeWatch();
    }

    private TimeWatch() {
        reset();
    }

    public TimeWatch reset() {
        starts = System.currentTimeMillis();
        return this;
    }

    public long time() {
        long ends = System.currentTimeMillis();
        return ends - starts;
    }

    public long time(TimeUnit unit) {
        return unit.convert(time(), TimeUnit.MILLISECONDS);
    }
}

Usage:

    TimeWatch watch = TimeWatch.start();
    // do something
    long passedTimeInMs = watch.time();
    long passedTimeInSeconds = watch.time(TimeUnit.SECONDS);

Afterwards, the time passed can be converted to whatever format you like, with a calender for example

Greetz, GHad

How to automatically crop and center an image

Example with img tag but without background-image

This solution retains the img tag so that we do not lose the ability to drag or right-click to save the image but without background-image just center and crop with css.

Maintain the aspect ratio fine except in very hight images. (check the link)

(view in action)

Markup

<div class="center-cropped">
    <img src="http://placehold.it/200x150" alt="" />
</div>

? CSS

div.center-cropped {
  width: 100px;
  height: 100px;
  overflow:hidden;
}
div.center-cropped img {
  height: 100%;
  min-width: 100%;
  left: 50%;
  position: relative;
  transform: translateX(-50%);
}

Way to ng-repeat defined number of times instead of repeating over array?

First, create an angular filter using LoDash:

angular.module('myApp').filter('times', function(){
   return function(value){
      return _.times(value || 0);
   }
});

The LoDash times function is capable of handling null, undefined, 0, numbers, and string representation of numbers.

Then, use it in your HTML as this:

<span ng-repeat="i in 5 | times">
 <!--DO STUFF-->
</span>

or

<span ng-repeat="i in myVar | times">
 <!--DO STUFF-->
</span>

Creating a random string with A-Z and 0-9 in Java

Three steps to implement your function:

Step#1 You can specify a string, including the chars A-Z and 0-9.

Like.

 String candidateChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";

Step#2 Then if you would like to generate a random char from this candidate string. You can use

 candidateChars.charAt(random.nextInt(candidateChars.length()));

Step#3 At last, specify the length of random string to be generated (in your description, it is 17). Writer a for-loop and append the random chars generated in step#2 to StringBuilder object.

Based on this, here is an example public class RandomTest {

public static void main(String[] args) {

    System.out.println(generateRandomChars(
            "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890", 17));
}

/**
 * 
 * @param candidateChars
 *            the candidate chars
 * @param length
 *            the number of random chars to be generated
 * 
 * @return
 */
public static String generateRandomChars(String candidateChars, int length) {
    StringBuilder sb = new StringBuilder();
    Random random = new Random();
    for (int i = 0; i < length; i++) {
        sb.append(candidateChars.charAt(random.nextInt(candidateChars
                .length())));
    }

    return sb.toString();
}

}

How to get started with Windows 7 gadgets

I have started writing one tutorial for everyone on this topic, see making gadgets for Windows 7.

How to insert a timestamp in Oracle?

One can simply use

INSERT INTO MY_TABLE(MY_TIMESTAMP_FIELD)
VALUES (TIMESTAMP '2019-02-15 13:22:11.871+02:00');

This way you won't have to worry about date format string, just use default timestamp format.

Works with Oracle 11, have no idea if it does for earlier Oracle versions.

What is the difference between %g and %f in C?

As Unwind points out f and g provide different default outputs.

Roughly speaking if you care more about the details of what comes after the decimal point I would do with f and if you want to scale for large numbers go with g. From some dusty memories f is very nice with small values if your printing tables of numbers as everything stays lined up but something like g is needed if you stand a change of your numbers getting large and your layout matters. e is more useful when your numbers tend to be very small or very large but never near ten.

An alternative is to specify the output format so that you get the same number of characters representing your number every time.

Sorry for the woolly answer but it is a subjective out put thing that only gets hard answers if the number of characters generated is important or the precision of the represented value.

Enum ToString with user friendly strings

I happen to be a VB.NET fan, so here's my version, combining the DescriptionAttribute method with an extension method. First, the results:

Imports System.ComponentModel ' For <Description>

Module Module1
  ''' <summary>
  ''' An Enum type with three values and descriptions
  ''' </summary>
  Public Enum EnumType
    <Description("One")>
    V1 = 1

    ' This one has no description
    V2 = 2

    <Description("Three")>
    V3 = 3
  End Enum

  Sub Main()
    ' Description method is an extension in EnumExtensions
    For Each v As EnumType In [Enum].GetValues(GetType(EnumType))
      Console.WriteLine("Enum {0} has value {1} and description {2}",
        v,
        CInt(v),
        v.Description
      )
    Next
    ' Output:
    ' Enum V1 has value 1 and description One
    ' Enum V2 has value 2 and description V2
    ' Enum V3 has value 3 and description Three
  End Sub
End Module

Basic stuff: an enum called EnumType with three values V1, V2 and V3. The "magic" happens in the Console.WriteLine call in Sub Main(), where the last argument is simply v.Description. This returns "One" for V1, "V2" for V2, and "Three" for V3. This Description-method is in fact an extension method, defined in another module called EnumExtensions:

Option Strict On
Option Explicit On
Option Infer Off

Imports System.Runtime.CompilerServices
Imports System.Reflection
Imports System.ComponentModel

Module EnumExtensions
  Private _Descriptions As New Dictionary(Of String, String)

  ''' <summary>
  ''' This extension method adds a Description method
  ''' to all enum members. The result of the method is the
  ''' value of the Description attribute if present, else
  ''' the normal ToString() representation of the enum value.
  ''' </summary>
  <Extension>
  Public Function Description(e As [Enum]) As String
    ' Get the type of the enum
    Dim enumType As Type = e.GetType()
    ' Get the name of the enum value
    Dim name As String = e.ToString()

    ' Construct a full name for this enum value
    Dim fullName As String = enumType.FullName + "." + name

    ' See if we have looked it up earlier
    Dim enumDescription As String = Nothing
    If _Descriptions.TryGetValue(fullName, enumDescription) Then
      ' Yes we have - return previous value
      Return enumDescription
    End If

    ' Find the value of the Description attribute on this enum value
    Dim members As MemberInfo() = enumType.GetMember(name)
    If members IsNot Nothing AndAlso members.Length > 0 Then
      Dim descriptions() As Object = members(0).GetCustomAttributes(GetType(DescriptionAttribute), False)
      If descriptions IsNot Nothing AndAlso descriptions.Length > 0 Then
        ' Set name to description found
        name = DirectCast(descriptions(0), DescriptionAttribute).Description
      End If
    End If

    ' Save the name in the dictionary:
    _Descriptions.Add(fullName, name)

    ' Return the name
    Return name
  End Function
End Module

Because looking up description attributes using Reflection is slow, the lookups are also cached in a private Dictionary, that is populated on demand.

(Sorry for the VB.NET solution - it should be relatively straighforward to translate it to C#, and my C# is rusty on new subjects like extensions)

How do I convert an array object to a string in PowerShell?

$a = "This", "Is", "a", "cat"

foreach ( $word in $a ) { $sent = "$sent $word" }
$sent = $sent.Substring(1)

Write-Host $sent

Failed to Connect to MySQL at localhost:3306 with user root

Open System Preference > MySQL > Initialize Database > Use Legacy Password Encription

Python Accessing Nested JSON Data

I did not realize that the first nested element is actually an array. The correct way access to the post code key is as follows:

r = requests.get('http://api.zippopotam.us/us/ma/belmont')
j = r.json()

print j['state']
print j['places'][1]['post code']

Query for array elements inside JSON type

Create a table with column as type json

CREATE TABLE friends ( id serial primary key, data jsonb);

Now let's insert json data

INSERT INTO friends(data) VALUES ('{"name": "Arya", "work": ["Improvements", "Office"], "available": true}');
INSERT INTO friends(data) VALUES ('{"name": "Tim Cook", "work": ["Cook", "ceo", "Play"], "uses": ["baseball", "laptop"], "available": false}');

Now let's make some queries to fetch data

select data->'name' from friends;
select data->'name' as name, data->'work' as work from friends;

You might have noticed that the results comes with inverted comma( " ) and brackets ([ ])

    name    |            work            
------------+----------------------------
 "Arya"     | ["Improvements", "Office"]
 "Tim Cook" | ["Cook", "ceo", "Play"]
(2 rows)

Now to retrieve only the values just use ->>

select data->>'name' as name, data->'work'->>0 as work from friends;
select data->>'name' as name, data->'work'->>0 as work from friends where data->>'name'='Arya';

Build Android Studio app via command line

Adding value to all these answers,

many have asked the command for running App in AVD after build sucessful.

adb install -r {path-to-your-bild-folder}/{yourAppName}.apk

Waiting for another flutter command to release the startup lock

If you are using Windows, you can open the task manager and under the 'Processes' tab search for processes named 'dart'. End all those tasks.

Given a class, see if instance has method (Ruby)

If you're checking to see if an object can respond to a series of methods, you could do something like:

methods = [:valid?, :chase, :test]

def has_methods?(something, methods)
  methods & something.methods == methods
end

the methods & something.methods will join the two arrays on their common/matching elements. something.methods includes all of the methods you're checking for, it'll equal methods. For example:

[1,2] & [1,2,3,4,5]
==> [1,2]

so

[1,2] & [1,2,3,4,5] == [1,2]
==> true

In this situation, you'd want to use symbols, because when you call .methods, it returns an array of symbols and if you used ["my", "methods"], it'd return false.

How to create a file in Ruby

If the objective is just to create a file, the most direct way I see is:

 FileUtils.touch "foobar.txt"

Sound effects in JavaScript / HTML5

The selected answer will work in everything except IE. I wrote a tutorial on how to make it work cross browser = http://www.andy-howard.com/how-to-play-sounds-cross-browser-including-ie/index.html

Here is the function I wrote;

function playSomeSounds(soundPath)
 {

 var trident = !!navigator.userAgent.match(/Trident\/7.0/);
 var net = !!navigator.userAgent.match(/.NET4.0E/);
 var IE11 = trident && net
 var IEold = ( navigator.userAgent.match(/MSIE/i) ? true : false );
 if(IE11 || IEold){
 document.all.sound.src = soundPath;
 }
 else
 {
 var snd = new Audio(soundPath); // buffers automatically when created
 snd.play();
 }
 };

You also need to add the following tag to the html page:

<bgsound id="sound">

Finally you can call the function and simply pass through the path here:

playSomeSounds("sounds/welcome.wav");

Enable ASP.NET ASMX web service for HTTP POST / GET requests

Try to declare UseHttpGet over your method.

[ScriptMethod(UseHttpGet = true)]
public string HelloWorld()
{
    return "Hello World";
}

Mock a constructor with parameter

The code you posted works for me with the latest version of Mockito and Powermockito. Maybe you haven't prepared A? Try this:

A.java

public class A {
     private final String test;

    public A(String test) {
        this.test = test;
    }

    public String check() {
        return "checked " + this.test;
    }
}

MockA.java

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

@RunWith(PowerMockRunner.class)
@PrepareForTest(A.class)
public class MockA {
    @Test
    public void test_not_mocked() throws Throwable {
        assertThat(new A("random string").check(), equalTo("checked random string"));
    }
    @Test
    public void test_mocked() throws Throwable {
         A a = mock(A.class); 
         when(a.check()).thenReturn("test");
         PowerMockito.whenNew(A.class).withArguments(Mockito.anyString()).thenReturn(a);
         assertThat(new A("random string").check(), equalTo("test"));
    }
}

Both tests should pass with mockito 1.9.0, powermockito 1.4.12 and junit 4.8.2

Access key value from Web.config in Razor View-MVC3 ASP.NET

FOR MVC

-- WEB.CONFIG CODE IN APP SETTING -- <add key="PhaseLevel" value="1" />

-- ON VIEWS suppose you want to show or hide something based on web.config Value--

-- WRITE THIS ON TOP OF YOUR PAGE-- @{ var phase = System.Configuration.ConfigurationManager.AppSettings["PhaseLevel"].ToString(); }

-- USE ABOVE VALUE WHERE YOU WANT TO SHOW OR HIDE.

@if (phase != "1") { @Html.Partial("~/Views/Shared/_LeftSideBarPartial.cshtml") }

Text-decoration: none not working

Add this statement on your header tag:

<style>
a:link{
  text-decoration: none!important;
  cursor: pointer;
}
</style>

How to merge two sorted arrays into a sorted array?

public static int[] merge(int[] listA, int[] listB) {
        int[] mergedList = new int[ listA.length + listB.length];
        int i = 0; // Counter for listA
        int j = 0; // Counter for listB
        int k = 0; // Counter for mergedList
        while (true) {
            if (i >= listA.length && j >= listB.length) {
                break;
            }
            if (i < listA.length && j < listB.length) { // If both counters are valid.
                if (listA[i] <= listB[j]) {
                    mergedList[k] = listA[i];
                    k++;
                    i++;
                } else {
                    mergedList[k] = listB[j];
                    k++;
                    j++;
                }
            } else if (i < listA.length && j >= listB.length) { // If only A's counter is valid.
                mergedList[k] = listA[i];
                k++;
                i++;
            } else if (i <= listA.length && j < listB.length) { // If only B's counter is valid
                mergedList[k] = listB[j];
                k++;
                j++;
            }
        }
        return mergedList;
    }

How to center a (background) image within a div?

This works for me:

.network-connections-icon {
  background-image: url(url);
  background-size: 100%;
  width: 56px;
  height: 56px;
  margin: 0 auto;
}

Hibernate Annotations - Which is better, field or property access?

Both :

The EJB3 spec requires that you declare annotations on the element type that will be accessed, i.e. the getter method if you use property access, the field if you use field access.

https://docs.jboss.org/hibernate/annotations/3.5/reference/en/html_single/#entity-mapping

How to break out of a loop in Bash?

while true ; do
    ...
    if [ something ]; then
        break
    fi
done

How can I parse a string with a comma thousand separator to a number?

Yes remove the commas:

parseFloat(yournumber.replace(/,/g, ''));

RegEx to match stuff between parentheses

var getMatchingGroups = function(s) {
  var r=/\((.*?)\)/g, a=[], m;
  while (m = r.exec(s)) {
    a.push(m[1]);
  }
  return a;
};

getMatchingGroups("something/([0-9])/([a-z])"); // => ["[0-9]", "[a-z]"]

How to reset a select element with jQuery

Reset single select field to default option.

<select id="name">
    <option>select something</option>
    <option value="1" >something 1</option>
    <option value="2" selected="selected" >Default option</option>
</select>
<script>
    $('name').val( $('name').find("option[selected]").val() );
</script>


Or if you want to reset all form fields to the default option:

<script>
    $('select').each( function() {
        $(this).val( $(this).find("option[selected]").val() );
    });
</script>

Add newline to VBA or Visual Basic 6

Visual Basic has built-in constants for newlines:

vbCr = Chr$(13) = CR (carriage-return character) - used by Mac OS and Apple II family

vbLf = Chr$(10) = LF (line-feed character) - used by Linux and Mac OS X

vbCrLf = Chr$(13) & Chr$(10) = CRLF (carriage-return followed by line-feed) - used by Windows

vbNewLine = the same as vbCrLf

How to find the files that are created in the last hour in unix

If the dir to search is srch_dir then either

$ find srch_dir -cmin -60 # change time

or

$ find srch_dir -mmin -60 # modification time

or

$ find srch_dir -amin -60 # access time

shows files created, modified or accessed in the last hour.

correction :ctime is for change node time (unsure though, please correct me )

How do I set up Eclipse/EGit with GitHub?

Install Mylyn connector for GitHub from this update site, it provides great integration: you can directly import your repositories using Import > Projects from Git > GitHub. You can set the default repository folder in Preferences > Git.

When should use Readonly and Get only properties

readonly properties are used to create a fail-safe code. i really like the Encapsulation posts series of Mark Seemann about properties and backing fields:

http://blog.ploeh.dk/2011/05/24/PokayokeDesignFromSmellToFragrance.aspx

taken from Mark's example:

public class Fragrance : IFragrance
{
    private readonly string name;

    public Fragrance(string name)
    {
        if (name == null)
        {
            throw new ArgumentNullException("name");
        }

        this.name = name;
    }

    public string Spread()
    {
        return this.name;
    }
}

in this example you use the readonly name field to make sure the class invariant is always valid. in this case the class composer wanted to make sure the name field is set only once (immutable) and is always present.

Best way to convert an ArrayList to a string

If you're using Eclipse Collections, you can use the makeString() method.

ArrayList<String> list = new ArrayList<String>();
list.add("one");
list.add("two");
list.add("three");

Assert.assertEquals(
    "one\ttwo\tthree",
    ArrayListAdapter.adapt(list).makeString("\t"));

If you can convert your ArrayList to a FastList, you can get rid of the adapter.

Assert.assertEquals(
    "one\ttwo\tthree",
    FastList.newListWith("one", "two", "three").makeString("\t"));

Note: I am a committer for Eclipse Collections.

Oracle Insert via Select from multiple tables where one table may not have a row

insert into account_type_standard (account_type_Standard_id, tax_status_id, recipient_id)
select account_type_standard_seq.nextval,
   ts.tax_status_id, 
   ( select r.recipient_id
     from recipient r
     where r.recipient_code = ?
   )
from tax_status ts
where ts.tax_status_code = ?

Possible to change where Android Virtual Devices are saved?

Go to the Android tools directory. Edit the android.bat command file. At about the end of the command file, find a line similar to

call %java_exe% -Djava.ext.dirs=%java_ext_dirs% -Dcom.android.sdkmanager.toolsdir="%tools_dir%" -Dcom.android.sdkmanager.workdir="%work_dir%" -jar %jar_path% %*

and replace

call %java_exe%

with

call %java_exe% -Duser.home={your_prefer_dir}

where {your_prefer_dire} is your preferred directory without braces but add doublequotes,

e.g.

call %java_exe% -Duser.home="E:\Program Files (x86)\android-sdk-windows"

Python coding standards/best practices

"In python do you generally use PEP 8 -- Style Guide for Python Code as your coding standards/guidelines? Are there any other formalized standards that you prefer?"

As mentioned by you follow PEP 8 for the main text, and PEP 257 for docstring conventions

Along with Python Style Guides, I suggest that you refer the following:

  1. Code Like a Pythonista: Idiomatic Python
  2. Common mistakes and Warts
  3. How not to write Python code
  4. Python gotcha

Lodash remove duplicates from array

For a simple array, you have the union approach, but you can also use :

_.uniq([2, 1, 2]);

How to clear cache of Eclipse Indigo

I think you can find the answer you want in these two posts. They are mentioning Flash Builder, but essentially, the talk is about its Eclipse base.

Clear improperly cached compile errors in FlexBuilder: http://blog.aherrman.com/2010/05/clear-improperly-cached-compile-errors.html

How to fix Flash Builder broken workspace: http://va.lent.in/how-to-fix-flash-builder-broken-workspace/

NSDictionary to NSArray?

There are a few things that could be happening here.

Is the dictionary you have listed the myDict? If so, then you don't have an object with a key of @"items", and the dict variable will be nil. You need to iterate through myDict directly.

Another thing to check is if _myArray is a valid instance of an NSMutableArray. If it's nil, the addObject: method will silently fail.

And a final thing to check is that the objects inside your dictionary are properly encased in NSNumbers (or some other non-primitive type).