Programs & Examples On #End user

IE11 prevents ActiveX from running

Try this tag on the pages that use the ActiveX control:

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

Note: this has to be the very first element in the <head> section.

How to connect to MySQL Database?

Looking at the code below, I tried it and found: Instead of writing DBCon = DBConnection.Instance(); you should put DBConnection DBCon - new DBConnection(); (That worked for me)

and instead of MySqlComman cmd = new MySqlComman(query, DBCon.GetConnection()); you should put MySqlCommand cmd = new MySqlCommand(query, DBCon.GetConnection()); (it's missing the d)

Background color not showing in print preview

Use the following in your @media print style sheet.

h1 {
    background-color:#404040;
    background-image:url("img/404040.png");
    background-repeat:repeat;
    box-shadow: inset 0 0 0 1000px #404040;
    border:30px solid #404040;
    height:0;
    width:100%;
    color:#FFFFFF !important;
    margin:0 -20px;
    line-height:0px;
}

Here are a couple things to note:

  • background-color is the absolute fallback and is there for posterity mostly.
  • background-image uses a 1px x 1px pixel of #404040 made into a PNG. If the user has images enabled it may work, if not...
  • Set the box-shadow, if that doesn't work...
  • Border = 1/2 your desired height and/or width of box, solid, color. In the example above I wanted a 60px height box.
  • Zero out the heigh/width depending on what you're controlling in the border attribute.
  • Font color will default to black unless you use !important
  • Set line-height to 0 to fix for the box not having physical dimension.
  • Make and host your own PNGs :-)
  • If the text in the block needs to wrap, put it in a div and position the div using position:relative; and remove line-height.

See my fiddle for a more detailed demonstration.

How do I convert a Python program to a runnable .exe Windows program?

If it is a simple py script refer here

Else for GUI :

$ pip3 install cx_Freeze

1) Create a setup.py file and put in the same directory as of the .py file you want to convert.

2)Copy paste the following lines in the setup.py and do change the "filename.py" into the filename you specified.

from cx_Freeze import setup, Executable
setup(
    name="GUI PROGRAM",
    version="0.1",
    description="MyEXE",
    executables=[Executable("filename.py", base="Win32GUI")],
    )

3) Run the setup.py "$python setup.py build"

4)A new directory will be there there called "build". Inside it you will get your .exe file to be ready to launced directly. (Make sure you copy paste the images files and other external files into the build directory)

Regex to Match Symbols: !$%^&*()_+|~-=`{}[]:";'<>?,./

The regular expression for this is really simple. Just use a character class. The hyphen is a special character in character classes, so it needs to be first:

/[-!$%^&*()_+|~=`{}\[\]:";'<>?,.\/]/

You also need to escape the other regular expression metacharacters.

Edit: The hyphen is special because it can be used to represent a range of characters. This same character class can be simplified with ranges to this:

/[$-/:-?{-~!"^_`\[\]]/

There are three ranges. '$' to '/', ':' to '?', and '{' to '~'. the last string of characters can't be represented more simply with a range: !"^_`[].

Use an ACSII table to find ranges for character classes.

PDF files do not open in Internet Explorer with Adobe Reader 10.0 - users get an empty gray screen. How can I fix this for my users?

In my case the solution was quite simple. I added this header and the browsers opened the file in every test. header('Content-Disposition: attachment; filename="filename.pdf"');

Convert UTC datetime string to local datetime

Here is a quick and dirty version that uses the local systems settings to work out the time difference. NOTE: This will not work if you need to convert to a timezone that your current system is not running in. I have tested this with UK settings under BST timezone

from datetime import datetime
def ConvertP4DateTimeToLocal(timestampValue):
   assert isinstance(timestampValue, int)

   # get the UTC time from the timestamp integer value.
   d = datetime.utcfromtimestamp( timestampValue )

   # calculate time difference from utcnow and the local system time reported by OS
   offset = datetime.now() - datetime.utcnow()

   # Add offset to UTC time and return it
   return d + offset

What is the best project structure for a Python application?

This blog post by Jean-Paul Calderone is commonly given as an answer in #python on Freenode.

Filesystem structure of a Python project

Do:

  • name the directory something related to your project. For example, if your project is named "Twisted", name the top-level directory for its source files Twisted. When you do releases, you should include a version number suffix: Twisted-2.5.
  • create a directory Twisted/bin and put your executables there, if you have any. Don't give them a .py extension, even if they are Python source files. Don't put any code in them except an import of and call to a main function defined somewhere else in your projects. (Slight wrinkle: since on Windows, the interpreter is selected by the file extension, your Windows users actually do want the .py extension. So, when you package for Windows, you may want to add it. Unfortunately there's no easy distutils trick that I know of to automate this process. Considering that on POSIX the .py extension is a only a wart, whereas on Windows the lack is an actual bug, if your userbase includes Windows users, you may want to opt to just have the .py extension everywhere.)
  • If your project is expressable as a single Python source file, then put it into the directory and name it something related to your project. For example, Twisted/twisted.py. If you need multiple source files, create a package instead (Twisted/twisted/, with an empty Twisted/twisted/__init__.py) and place your source files in it. For example, Twisted/twisted/internet.py.
  • put your unit tests in a sub-package of your package (note - this means that the single Python source file option above was a trick - you always need at least one other file for your unit tests). For example, Twisted/twisted/test/. Of course, make it a package with Twisted/twisted/test/__init__.py. Place tests in files like Twisted/twisted/test/test_internet.py.
  • add Twisted/README and Twisted/setup.py to explain and install your software, respectively, if you're feeling nice.

Don't:

  • put your source in a directory called src or lib. This makes it hard to run without installing.
  • put your tests outside of your Python package. This makes it hard to run the tests against an installed version.
  • create a package that only has a __init__.py and then put all your code into __init__.py. Just make a module instead of a package, it's simpler.
  • try to come up with magical hacks to make Python able to import your module or package without having the user add the directory containing it to their import path (either via PYTHONPATH or some other mechanism). You will not correctly handle all cases and users will get angry at you when your software doesn't work in their environment.

How can I detect the encoding/codepage of a text file

Since it basically comes down to heuristics, it may help to use the encoding of previously received files from the same source as a first hint.

Most people (or applications) do stuff in pretty much the same order every time, often on the same machine, so its quite likely that when Bob creates a .csv file and sends it to Mary it'll always be using Windows-1252 or whatever his machine defaults to.

Where possible a bit of customer training never hurts either :-)

How to force open links in Chrome not download them?

To make certain file types OPEN on your computer, instead of Chrome Downloading...

You have to download the file type once, then right after that download, look at the status bar at the bottom of the browser. Click the arrow next to that file and choose "always open files of this type". DONE.

Now the file type will always OPEN using your default program.

To reset this feature, go to Settings / Advance Settings and under the "Download.." section, there's a button to reset 'all' Auto Downloads

Hope this helps.. :-)

Visual Instructions found here:

http://www.presentermedia.com/blog/2013/10/my-file-automatically-opens-instead-of-saving-with-chrome/

how to clear JTable

If we use tMOdel.setRowCount(0); we can get Empty table.

DefaultTableModel tMOdel = (DefaultTableModel) jtableName.getModel();
tMOdel.setRowCount(0);

YouTube embedded video: set different thumbnail

This tool gave me following results which helps me achieve the task as following code.

<div onclick="play();" id="vidwrap" style="height:315px;width:560px;background: black url('http://example.com/image.jpg') no-repeat center;overflow:hidden;cursor:pointer;"></div>
<script type="text/javascript">
    function play(){
        document.getElementById('vidwrap').innerHTML = '<iframe width="560" height="315" src="http://www.youtube.com/embed/xxxxxxxxx?autoplay=1" frameborder="0"></iframe>';
    }
</script>

What is the shortcut in IntelliJ IDEA to find method / functions?

I tried SHIFT + SHIFT and ALT + CMD + O

But I think the most powerful and easy to use feature is find in all files CMD + SHIFT + F.

Choose regex and write .*partOfMethodName.*\( and it shows all places and can see the actual source code in place without going to that specific file.

Android webview slow

I was having this same issue and I had to work it out. I tried these solutions, but at the end the performance, at least for the scrolling didn't improve at all. So here the workaroud that I did perform and the explanation of why it did work for me.

If you had the chance to explore the drag events, just a little, by creating a "MiWebView" Class, overwriting the "onTouchEvent" method and at least printed the time in which every drag event occurs, you'll see that they are separated in time for (down to) 9ms away. That is a very short time in between events.

Take a look at the WebView Source Code, and just see the onTouchEvent function. It is just impossible for it to be handled by the processor in less than 9ms (Keep on dreaming!!!). That's why you constantly see the "Miss a drag as we are waiting for WebCore's response for touch down." message. The code just can't be handled on time.

How to fix it? First, you can not re-write the onTouchEvent code to improve it, it is just too much. But, you can "mock it" in order to limit the event rate for dragging movements let's say to 40ms or 50ms. (this depends on the processor).

All touch events go like this: ACTION_DOWN -> ACTION_MOVE......ACTION_MOVE -> ACTION_UP. So we need to keep the DOWN and UP movements and filter the MOVE rate (these are the bad guys).

And here is a way to do it (you can add more event types like 2 fingers touch, all I'm interested here is the single finger scrolling).

import android.content.Context;
import android.view.MotionEvent;
import android.webkit.WebView;


public class MyWebView extends WebView{

    public MyWebView(Context context) {
        super(context);
        // TODO Auto-generated constructor stub
    }

    private long lastMoveEventTime = -1;
    private int eventTimeInterval = 40;

    @Override
    public boolean onTouchEvent(MotionEvent ev) {

        long eventTime = ev.getEventTime();
        int action = ev.getAction();

        switch (action){
            case MotionEvent.ACTION_MOVE: {
                if ((eventTime - lastMoveEventTime) > eventTimeInterval){
                    lastMoveEventTime = eventTime;
                    return super.onTouchEvent(ev);
                }
                break;
            }
            case MotionEvent.ACTION_DOWN:
            case MotionEvent.ACTION_UP: {
                return super.onTouchEvent(ev);
            }
        }
        return true;
    }
}

Of course Use this class instead of WebView and you'll see the difference when scrolling.

This is just an approach to a solution, yet still not fully implemented for all lag cases due to screen touching when using WebView. However it is the best solution I found, at least for my specific needs.

Get random sample from list while maintaining ordering of items?

Simple-to-code O(N + K*log(K)) way

Take a random sample without replacement of the indices, sort the indices, and take them from the original.

indices = random.sample(range(len(myList)), K)
[myList[i] for i in sorted(indices)]

Or more concisely:

[x[1] for x in sorted(random.sample(enumerate(myList),K))]

Optimized O(N)-time, O(1)-auxiliary-space way

You can alternatively use a math trick and iteratively go through myList from left to right, picking numbers with dynamically-changing probability (N-numbersPicked)/(total-numbersVisited). The advantage of this approach is that it's an O(N) algorithm since it doesn't involve sorting!

from __future__ import division

def orderedSampleWithoutReplacement(seq, k):
    if not 0<=k<=len(seq):
        raise ValueError('Required that 0 <= sample_size <= population_size')

    numbersPicked = 0
    for i,number in enumerate(seq):
        prob = (k-numbersPicked)/(len(seq)-i)
        if random.random() < prob:
            yield number
            numbersPicked += 1

Proof of concept and test that probabilities are correct:

Simulated with 1 trillion pseudorandom samples over the course of 5 hours:

>>> Counter(
        tuple(orderedSampleWithoutReplacement([0,1,2,3], 2))
        for _ in range(10**9)
    )
Counter({
    (0, 3): 166680161, 
    (1, 2): 166672608, 
    (0, 2): 166669915, 
    (2, 3): 166667390, 
    (1, 3): 166660630, 
    (0, 1): 166649296
})

Probabilities diverge from true probabilities by less a factor of 1.0001. Running this test again resulted in a different order meaning it isn't biased towards one ordering. Running the test with fewer samples for [0,1,2,3,4], k=3 and [0,1,2,3,4,5], k=4 had similar results.

edit: Not sure why people are voting up wrong comments or afraid to upvote... NO, there is nothing wrong with this method. =)

(Also a useful note from user tegan in the comments: If this is python2, you will want to use xrange, as usual, if you really care about extra space.)

edit: Proof: Considering the uniform distribution (without replacement) of picking a subset of k out of a population seq of size len(seq), we can consider a partition at an arbitrary point i into 'left' (0,1,...,i-1) and 'right' (i,i+1,...,len(seq)). Given that we picked numbersPicked from the left known subset, the remaining must come from the same uniform distribution on the right unknown subset, though the parameters are now different. In particular, the probability that seq[i] contains a chosen element is #remainingToChoose/#remainingToChooseFrom, or (k-numbersPicked)/(len(seq)-i), so we simulate that and recurse on the result. (This must terminate since if #remainingToChoose == #remainingToChooseFrom, then all remaining probabilities are 1.) This is similar to a probability tree that happens to be dynamically generated. Basically you can simulate a uniform probability distribution by conditioning on prior choices (as you grow the probability tree, you pick the probability of the current branch such that it is aposteriori the same as prior leaves, i.e. conditioned on prior choices; this will work because this probability is uniformly exactly N/k).

edit: Timothy Shields mentions Reservoir Sampling, which is the generalization of this method when len(seq) is unknown (such as with a generator expression). Specifically the one noted as "algorithm R" is O(N) and O(1) space if done in-place; it involves taking the first N element and slowly replacing them (a hint at an inductive proof is also given). There are also useful distributed variants and miscellaneous variants of reservoir sampling to be found on the wikipedia page.

edit: Here's another way to code it below in a more semantically obvious manner.

from __future__ import division
import random

def orderedSampleWithoutReplacement(seq, sampleSize):
    totalElems = len(seq)
    if not 0<=sampleSize<=totalElems:
        raise ValueError('Required that 0 <= sample_size <= population_size')

    picksRemaining = sampleSize
    for elemsSeen,element in enumerate(seq):
        elemsRemaining = totalElems - elemsSeen
        prob = picksRemaining/elemsRemaining
        if random.random() < prob:
            yield element
            picksRemaining -= 1

from collections import Counter         
Counter(
    tuple(orderedSampleWithoutReplacement([0,1,2,3], 2))
    for _ in range(10**5)

)

Calling a java method from c++ in Android

If it's an object method, you need to pass the object to CallObjectMethod:

jobject result = env->CallObjectMethod(obj, messageMe, jstr);

What you were doing was the equivalent of jstr.messageMe().

Since your is a void method, you should call:

env->CallVoidMethod(obj, messageMe, jstr);

If you want to return a result, you need to change your JNI signature (the ()V means a method of void return type) and also the return type in your Java code.

How to export and import environment variables in windows?

To export user variables, open a command prompt and use regedit with /e

Example :

regedit /e "%userprofile%\Desktop\my_user_env_variables.reg" "HKEY_CURRENT_USER\Environment"

How to make a window always stay on top in .Net?

Set the form's .TopMost property to true.

You probably don't want to leave it this way all the time: set it when your external process starts and put it back when it finishes.

Create a global variable in TypeScript

Okay, so this is probably even uglier that what you did, but anyway...

but I do the same so...

What you can do to do it in pure TypeScript, is to use the eval function like so :

declare var something: string;
eval("something = 'testing';")

And later you'll be able to do

if (something === 'testing')

This is nothing more than a hack to force executing the instruction without TypeScript refusing to compile, and we declare var for TypeScript to compile the rest of the code.

equivalent to push() or pop() for arrays?

You can use LinkedList. It has methods peek, poll and offer.

Service Reference Error: Failed to generate code for the service reference

Have to uncheck the Reuse types in all referenced assemblies from Configure service reference option

Check this for details

How to change the order of DataFrame columns?

I think this is a slightly neater solution:

df.insert(0, 'mean', df.pop("mean"))

This solution is somewhat similar to @JoeHeffer 's solution but this is one liner.

Here we remove the column "mean" from the dataframe and attach it to index 0 with the same column name.

Why doesn't RecyclerView have onItemClickListener()?

it worked for me. Hope it will help. Most simplest way.

Inside View Holder

class GeneralViewHolder extends RecyclerView.ViewHolder {
    View cachedView = null;

    public GeneralViewHolder(View itemView) {
        super(itemView);
        cachedView = itemView;
    }

Inside OnBindViewHolder()

@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
            final GeneralViewHolder generalViewHolder = (GeneralViewHolder) holder;
            generalViewHolder.cachedView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Toast.makeText(context, "item Clicked at "+position, Toast.LENGTH_SHORT).show();
                }
            });

And let me know, do you have any question about this solution ?

Scale an equation to fit exact page width

The graphicx package provides the command \resizebox{width}{height}{object}:

\documentclass{article}
\usepackage{graphicx}
\begin{document}
\hrule
%%%
\makeatletter%
\setlength{\@tempdima}{\the\columnwidth}% the, well columnwidth
\settowidth{\@tempdimb}{(\ref{Equ:TooLong})}% the width of the "(1)"
\addtolength{\@tempdima}{-\the\@tempdimb}% which cannot be used for the math
\addtolength{\@tempdima}{-1em}%
% There is probably some variable giving the required minimal distance
% between math and label, but because I do not know it I used 1em instead.
\addtolength{\@tempdima}{-1pt}% distance must be greater than "1em"
\xdef\Equ@width{\the\@tempdima}% space remaining for math
\begin{equation}%
\resizebox{\Equ@width}{!}{$\displaystyle{% to get everything inside "big"
 A+B+C+D+E+F+G+H+I+J+K+L+M+N+O+P+Q+R+S+T+U+V+W+X+Y+Z}$}%
\label{Equ:TooLong}%
\end{equation}%
\makeatother%
%%%
\hrule
\end{document}

How to find the kafka version in linux

I found an easy way to do this without searching directories or log files:

kafka-dump-log --version

Output looks like this:

5.3.0-ccs (Commit:6481debc2be778ee)

Accessing Websites through a Different Port?

when viewing a website it gets assigned a random port, it will always come from port 80 (usually always, unless the server admin has changed the port) there's no way for someone to change that port unless you have control of the server.

Why does jQuery or a DOM method such as getElementById not find the element?

the problem is that the dom element 'speclist' is not created at the time the javascript code is getting executed. So I put the javascript code inside a function and called that function on body onload event.

function do_this_first(){
   //appending code
}

<body onload="do_this_first()">
</body>

init-param and context-param

<context-param> 
    <param-name>contextConfigLocation</param-name>
    <param-value>
        classpath*:/META-INF/PersistenceContext.xml
    </param-value>
</context-param>

I have initialized my PersistenceContext.xml within <context-param> because all my servlets will be interacting with database in MVC framework.

Howerver,

<servlet>
    <servlet-name>jersey-servlet</servlet-name>
    <servlet-class>com.sun.jersey.spi.spring.container.servlet.SpringServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            classpath:ApplicationContext.xml
        </param-value>
    </init-param>
    <init-param>
        <param-name>com.sun.jersey.config.property.packages</param-name>
        <param-value>com.organisation.project.rest</param-value>
    </init-param>
</servlet>

in the aforementioned code, I am configuring jersey and the ApplicationContext.xml only to rest layer. For the same I am using </init-param>

iOS 10: "[App] if we're in the real pre-commit handler we can't actually add any new fences due to CA restriction"

We can mute it in this way (device and simulator need different values):

Add the Name OS_ACTIVITY_MODE and the Value ${DEBUG_ACTIVITY_MODE} and check it (in Product -> Scheme -> Edit Scheme -> Run -> Arguments -> Environment).

enter image description here

Add User-Defined Setting DEBUG_ACTIVITY_MODE, then add Any iOS Simulator SDK for Debug and set it's value to disable (in Project -> Build settings -> + -> User-Defined Setting)

enter image description here

How can I change the remote/target repository URL on Windows?

One more way to do this is:

git config remote.origin.url https://github.com/abc/abc.git

To see the existing URL just do:

git config remote.origin.url

What is a daemon thread in Java?

Daemon threads are like assistants. Non-Daemon threads are like front performers. Assistants help performers to complete a job. When the job is completed, no help is needed by performers to perform anymore. As no help is needed the assistants leave the place. So when the jobs of Non-Daemon threads is over, Daemon threads march away.

Does a `+` in a URL scheme/host/path represent a space?

use encodeURIComponent function to fix url, it works on Browser and node.js

res.redirect("/signin?email="+encodeURIComponent("[email protected]"));


> encodeURIComponent("http://a.com/a+b/c")
'http%3A%2F%2Fa.com%2Fa%2Bb%2Fc'

how to get program files x86 env variable?

On a 64-bit machine running in 64-bit mode:

  • echo %programfiles% ==> C:\Program Files
  • echo %programfiles(x86)% ==> C:\Program Files (x86)

On a 64-bit machine running in 32-bit (WOW64) mode:

  • echo %programfiles% ==> C:\Program Files (x86)
  • echo %programfiles(x86)% ==> C:\Program Files (x86)

On a 32-bit machine running in 32-bit mode:

  • echo %programfiles% ==> C:\Program Files
  • echo %programfiles(x86)% ==> %programfiles(x86)%

Viewing full version tree in git

You can try the following:

gitk --all

You can tell gitk what to display using anything that git rev-list understands, so if you just want a few branches, you can do:

gitk master origin/master origin/experiment

... or more exotic things like:

gitk --simplify-by-decoration --all

How to disable back swipe gesture in UINavigationController on iOS 7

This is the way on Swift 3

works for me

    self.navigationController?.interactivePopGestureRecognizer?.isEnabled = false

Boolean.parseBoolean("1") = false...?

Returns true if comes 'y', '1', 'true', 'on'or whatever you add in similar way

boolean getValue(String value) {
  return ("Y".equals(value.toUpperCase()) 
      || "1".equals(value.toUpperCase())
      || "TRUE".equals(value.toUpperCase())
      || "ON".equals(value.toUpperCase()) 
     );
}

High Quality Image Scaling Library

you could try this one if it's a lowres cgi 2D Image Filter

how to release localhost from Error: listen EADDRINUSE

I have solved this issue by adding below in my package.json for killing active PORT - 4000 (in my case) Running on WSL2/Linux/Mac

"scripts": {
    "dev": "nodemon app.js",
    "predev":"fuser -k 4000/tcp && echo 'Terminated' || echo 'Nothing was running on the PORT'",
  }

Source

Check if a string has white space

With additions to the language it is much easier, plus you can take advantage of early return:

// Use includes method on string
function hasWhiteSpace(s) {
  const whitespaceChars = [' ', '\t', '\n'];
  return whitespaceChars.some(char => s.includes(char));
}

// Use character comparison
function hasWhiteSpace(s) {
  const whitespaceChars = [' ', '\t', '\n'];
  return Array.from(s).some(char => whitespaceChars.includes(char));
}

const withSpace = "Hello World!";
const noSpace = "HelloWorld!";

console.log(hasWhiteSpace(withSpace));
console.log(hasWhiteSpace(noSpace));

console.log(hasWhiteSpace2(withSpace));
console.log(hasWhiteSpace2(noSpace));

I did not run performance benchmark but these should be faster than regex but for small text snippets there won't be that much difference anyway.

Convert an ISO date to the date format yyyy-mm-dd in JavaScript

To extend on rk rk's solution: In case you want the format to include the time, you can add the toTimeString() to your string, and then strip the GMT part, as follows:

var d = new Date('2013-03-10T02:00:00Z');
var fd = d.toLocaleDateString() + ' ' + d.toTimeString().substring(0, d.toTimeString().indexOf("GMT"));

how to convert `content://media/external/images/media/Y` to `file:///storage/sdcard0/Pictures/X.jpg` in android?

If you just want the bitmap, This too works

InputStream inputStream = mContext.getContentResolver().openInputStream(uri);
Bitmap bmp = BitmapFactory.decodeStream(inputStream);
if( inputStream != null ) inputStream.close();

sample uri : content://media/external/images/media/12345

How to return a string value from a Bash function

The most straightforward and robust solution is to use command substitution, as other people wrote:

assign()
{
    local x
    x="Test"
    echo "$x"
}

x=$(assign) # This assigns string "Test" to x

The downside is performance as this requires a separate process.

The other technique suggested in this topic, namely passing the name of a variable to assign to as an argument, has side effects, and I wouldn't recommend it in its basic form. The problem is that you will probably need some variables in the function to calculate the return value, and it may happen that the name of the variable intended to store the return value will interfere with one of them:

assign()
{
    local x
    x="Test"
    eval "$1=\$x"
}

assign y # This assigns string "Test" to y, as expected

assign x # This will NOT assign anything to x in this scope
         # because the name "x" is declared as local inside the function

You might, of course, not declare internal variables of the function as local, but you really should always do it as otherwise you may, on the other hand, accidentally overwrite an unrelated variable from the parent scope if there is one with the same name.

One possible workaround is an explicit declaration of the passed variable as global:

assign()
{
    local x
    eval declare -g $1
    x="Test"
    eval "$1=\$x"
}

If name "x" is passed as an argument, the second row of the function body will overwrite the previous local declaration. But the names themselves might still interfere, so if you intend to use the value previously stored in the passed variable prior to write the return value there, be aware that you must copy it into another local variable at the very beginning; otherwise the result will be unpredictable! Besides, this will only work in the most recent version of BASH, namely 4.2. More portable code might utilize explicit conditional constructs with the same effect:

assign()
{
    if [[ $1 != x ]]; then
      local x
    fi
    x="Test"
    eval "$1=\$x"
}

Perhaps the most elegant solution is just to reserve one global name for function return values and use it consistently in every function you write.

How can I completely remove TFS Bindings

Here you can find another tool (including source code) to remove both SCC footprint from the solution and project files and the .vssscc and .vspscc files. In addition, it removes the output and other configurable directories.

Hth

Stefan

How would I check a string for a certain letter in Python?

in keyword allows you to loop over a collection and check if there is a member in the collection that is equal to the element.

In this case string is nothing but a list of characters:

dog = "xdasds"
if "x" in dog:
     print "Yes!"

You can check a substring too:

>>> 'x' in "xdasds"
True
>>> 'xd' in "xdasds"
True
>>> 
>>> 
>>> 'xa' in "xdasds"
False

Think collection:

>>> 'x' in ['x', 'd', 'a', 's', 'd', 's']
True
>>> 

You can also test the set membership over user defined classes.

For user-defined classes which define the __contains__ method, x in y is true if and only if y.__contains__(x) is true.

Difference between links and depends_on in docker_compose.yml

[Update Sep 2016]: This answer was intended for docker compose file v1 (as shown by the sample compose file below). For v2, see the other answer by @Windsooon.

[Original answer]:

It is pretty clear in the documentation. depends_on decides the dependency and the order of container creation and links not only does these, but also

Containers for the linked service will be reachable at a hostname identical to the alias, or the service name if no alias was specified.

For example, assuming the following docker-compose.yml file:

web:
  image: example/my_web_app:latest
  links:
    - db
    - cache

db:
  image: postgres:latest

cache:
  image: redis:latest

With links, code inside web will be able to access the database using db:5432, assuming port 5432 is exposed in the db image. If depends_on were used, this wouldn't be possible, but the startup order of the containers would be correct.

What are rvalues, lvalues, xvalues, glvalues, and prvalues?

I guess this document might serve as a not so short introduction : n3055

The whole massacre began with the move semantics. Once we have expressions that can be moved and not copied, suddenly easy to grasp rules demanded distinction between expressions that can be moved, and in which direction.

From what I guess based on the draft, the r/l value distinction stays the same, only in the context of moving things get messy.

Are they needed? Probably not if we wish to forfeit the new features. But to allow better optimization we should probably embrace them.

Quoting n3055:

  • An lvalue (so-called, historically, because lvalues could appear on the left-hand side of an assignment expression) designates a function or an object. [Example: If E is an expression of pointer type, then *E is an lvalue expression referring to the object or function to which E points. As another example, the result of calling a function whose return type is an lvalue reference is an lvalue.]
  • An xvalue (an “eXpiring” value) also refers to an object, usually near the end of its lifetime (so that its resources may be moved, for example). An xvalue is the result of certain kinds of expressions involving rvalue references. [Example: The result of calling a function whose return type is an rvalue reference is an xvalue.]
  • A glvalue (“generalized” lvalue) is an lvalue or an xvalue.
  • An rvalue (so-called, historically, because rvalues could appear on the right-hand side of an assignment expression) is an xvalue, a temporary object or subobject thereof, or a value that is not associated with an object.
  • A prvalue (“pure” rvalue) is an rvalue that is not an xvalue. [Example: The result of calling a function whose return type is not a reference is a prvalue]

The document in question is a great reference for this question, because it shows the exact changes in the standard that have happened as a result of the introduction of the new nomenclature.

clk'event vs rising_edge()

Practical example:

Imagine that you are modelling something like an I2C bus (signals called SCL for clock and SDA for data), where the bus is tri-state and both nets have a weak pull-up. Your testbench should model the pull-up resistor on the PCB with a value of 'H'.

scl <= 'H'; -- Testbench resistor pullup

Your I2C master or slave devices can drive the bus to '1' or '0' or leave it alone by assigning a 'Z'

Assigning a '1' to the SCL net will cause an event to happen, because the value of SCL changed.

  • If you have a line of code that relies on (scl'event and scl = '1'), then you'll get a false trigger.

  • If you have a line of code that relies on rising_edge(scl), then you won't get a false trigger.

Continuing the example: you assign a '0' to SCL, then assign a 'Z'. The SCL net goes to '0', then back to 'H'.

Here, going from '1' to '0' isn't triggering either case, but going from '0' to 'H' will trigger a rising_edge(scl) condition (correct), but the (scl'event and scl = '1') case will miss it (incorrect).

General Recommenation:

Use rising_edge(clk) and falling_edge(clk) instead of clk'event for all code.

Simple PHP form: Attachment to email (code golf)

A combination of this http://www.webcheatsheet.com/PHP/send_email_text_html_attachment.php#attachment

with the php upload file example would work. In the upload file example instead of using move_uploaded_file to move it from the temporary folder you would just open it:

$attachment = chunk_split(base64_encode(file_get_contents($tmp_file))); 

where $tmp_file = $_FILES['userfile']['tmp_name'];

and send it as an attachment like the rest of the example.

All in one file / self contained:

<? if(isset($_POST['submit'])){
//process and email
}else{
//display form
}
?>

I think its a quick exercise to get what you need working based on the above two available examples.

P.S. It needs to get uploaded somewhere before Apache passes it along to PHP to do what it wants with it. That would be your system's temp folder by default unless it was changed in the config file.

How to redirect the output of an application in background to /dev/null

These will also redirect both:

yourcommand  &> /dev/null

yourcommand  >& /dev/null

though the bash manual says the first is preferred.

Reading a text file with SQL Server

if you want to read the file into a table at one time you should use BULK INSERT. ON the other hand if you preffer to parse the file line by line to make your own checks, you should take a look at this web: https://www.simple-talk.com/sql/t-sql-programming/reading-and-writing-files-in-sql-server-using-t-sql/ It is possible that you need to activate your xp_cmdshell or other OLE Automation features. Simple Google it and the script will appear. Hope to be useful.

Check if string begins with something?

Use stringObject.substring

if (pathname.substring(0, 6) == "/sub/1") {
    // ...
}

CSS: Center block, but align contents to the left

Normally you should use margin: 0 auto on the div as mentioned in the other answers, but you'll have to specify a width for the div. If you don't want to specify a width you could either (this is depending on what you're trying to do) use margins, something like margin: 0 200px; , this should make your content seems as if it's centered, you could also see the answer of Leyu to my question

What is sharding and why is it important?

In my opinion the application tier should have no business determining where data should be stored

This is a good rule but like most things not always correct.

When you do your architecture you start with responsibilities and collaborations. Once you determine your functional architecture, you have to balance the non-functional forces.

If one of these non-functional forces is massive scalability, you have to adapt your architecture to cater for this force even if it means that your data storage abstraction now leaks into your application tier.

How to use a class from one C# project with another C# project

To provide another much simpler solution:-

  1. Within the project, right click and select "Add -> Existing"
  2. Navigate to the class file in the adjacent project.
  3. The Add button is also a dropdown, click the dropdown and select

"Add as link"

Thats it.

Calling Javascript function from server side

You can call the function from code behind like this :

MyForm.aspx.cs

protected void MyButton_Click(object sender, EventArgs e)
{
    Page.ClientScript.RegisterStartupScript(this.GetType(), "myScript", "AnotherFunction();", true);
}

MyForm.aspx

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>My Page</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
    function Test() {
        alert("hi");
        $("#ButtonRow").show();
    }
    function AnotherFunction()
    {
        alert("This is another function");
    }
</script>
</head>
<body>
<form id="form2" runat="server">
<table>
    <tr><td>
            <asp:RadioButtonList ID="SearchCategory" runat="server" onchange="Test()"  RepeatDirection="Horizontal"  BorderStyle="Solid">
               <asp:ListItem>Merchant</asp:ListItem>
               <asp:ListItem>Store</asp:ListItem>
               <asp:ListItem>Terminal</asp:ListItem>
            </asp:RadioButtonList>
        </td>
    </tr>
    <tr id="ButtonRow"style="display:none">
         <td>
            <asp:Button ID="MyButton" runat="server" Text="Click Here" OnClick="MyButton_Click" />
        </td>
    </tr>
    </table> 
</form>

Iterate a list with indexes in Python

Here it is a solution using map function:

>>> a = [3, 7, 19]
>>> map(lambda x: (x, a[x]), range(len(a)))
[(0, 3), (1, 7), (2, 19)]

And a solution using list comprehensions:

>>> a = [3,7,19]
>>> [(x, a[x]) for x in range(len(a))]
[(0, 3), (1, 7), (2, 19)]

SQL Server Pivot Table with multiple column aggregates

I used your own pivot as a nested query and came to this result:

SELECT
  [sub].[chardate],
  SUM(ISNULL([Australia], 0)) AS [Transactions Australia],
  SUM(CASE WHEN [Australia] IS NOT NULL THEN [TotalAmount] ELSE 0 END) AS [Amount Australia],
  SUM(ISNULL([Austria], 0)) AS [Transactions Austria],
  SUM(CASE WHEN [Austria] IS NOT NULL THEN [TotalAmount] ELSE 0 END) AS [Amount Austria]
FROM
(
  select * 
  from  mytransactions
  pivot (sum (totalcount) for country in ([Australia], [Austria])) as pvt
) AS [sub]
GROUP BY
  [sub].[chardate],
  [sub].[numericmonth]
ORDER BY 
  [sub].[numericmonth] ASC

Here is the Fiddle.

How to add 30 minutes to a JavaScript Date object?

I know that the topic is way too old. But I am pretty sure that there are some developpers who still need this, so I made this simple script for you. I hope you enjoy it!

Hello back, It's 2020 and I've added some modification hope it will help a lot better now!

_x000D_
_x000D_
function strtotime(date, addTime){
  let generatedTime=date.getTime();
  if(addTime.seconds) generatedTime+=1000*addTime.seconds; //check for additional seconds 
  if(addTime.minutes) generatedTime+=1000*60*addTime.minutes;//check for additional minutes 
  if(addTime.hours) generatedTime+=1000*60*60*addTime.hours;//check for additional hours 
  return new Date(generatedTime);
}

Date.prototype.strtotime = function(addTime){
  return strtotime(new Date(), addTime); 
}

let futureDate = new Date().strtotime({
    hours: 16, //Adding one hour
    minutes: 45, //Adding fourty five minutes
    seconds: 0 //Adding 0 seconds return to not adding any second so  we can remove it.
});
_x000D_
<button onclick="console.log(futureDate)">Travel to the future</button>
_x000D_
_x000D_
_x000D_

How to calculate the sum of the datatable column in asp.net?

To calculate the sum of a column in a DataTable use the DataTable.Compute method.

Example of usage from the linked MSDN article:

DataTable table = dataSet.Tables["YourTableName"];

// Declare an object variable.
object sumObject;
sumObject = table.Compute("Sum(Amount)", string.Empty);

Display the result in your Total Amount Label like so:

lblTotalAmount.Text = sumObject.ToString();

How to change Apache Tomcat web server port number

You need to edit the Tomcat/conf/server.xml and change the connector port. The connector setting should look something like this:

<Connector port="8080" maxHttpHeaderSize="8192"
           maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
           enableLookups="false" redirectPort="8443" acceptCount="100"
           connectionTimeout="20000" disableUploadTimeout="true" />

Just change the connector port from default 8080 to another valid port number.

How do I get a list of files in a directory in C++?

void getFilesList(String filePath,String extension, vector<string> & returnFileName)
{
    WIN32_FIND_DATA fileInfo;
    HANDLE hFind;   
    String  fullPath = filePath + extension;
    hFind = FindFirstFile(fullPath.c_str(), &fileInfo);
    if (hFind == INVALID_HANDLE_VALUE){return;} 
    else {
        return FileName.push_back(filePath+fileInfo.cFileName);
        while (FindNextFile(hFind, &fileInfo) != 0){
            return FileName.push_back(filePath+fileInfo.cFileName);}
        }
 }


 String optfileName ="";        
 String inputFolderPath =""; 
 String extension = "*.jpg*";
 getFilesList(inputFolderPath,extension,filesPaths);
 vector<string>::const_iterator it = filesPaths.begin();
 while( it != filesPaths.end())
 {
    frame = imread(*it);//read file names
            //doyourwork here ( frame );
    sprintf(buf, "%s/Out/%d.jpg", optfileName.c_str(),it->c_str());
    imwrite(buf,frame);   
    it++;
 }

get launchable activity name of package from adb

I didn't find it listed so updating the list.

You need to have the apk installed and running in front on your phone for this solution:

Windows CMD line:

adb shell dumpsys window windows | findstr <any unique string from your pkg Name>

Linux Terminal:

adb shell dumpsys window windows | grep -i <any unique string from your Pkg Name>

OUTPUT for Calculator package would be:

Window #7 Window{39ced4b1 u0 com.android.calculator2/com.android.calculator2.Calculator}:

    mOwnerUid=10036 mShowToOwnerOnly=true package=com.android.calculator2 appop=NONE

    mToken=AppWindowToken{29a4bed4 token=Token{2f850b1a ActivityRecord{eefe5c5 u0 com.android.calculator2/.Calculator t322}}}

    mRootToken=AppWindowToken{29a4bed4 token=Token{2f850b1a ActivityRecord{eefe5c5 u0 com.android.calculator2/.Calculator t322}}}

    mAppToken=AppWindowToken{29a4bed4 token=Token{2f850b1a ActivityRecord{eefe5c5 u0 com.android.calculator2/.Calculator t322}}}

    WindowStateAnimator{3e160d22 com.android.calculator2/com.android.calculator2.Calculator}:

      mSurface=Surface(name=com.android.calculator2/com.android.calculator2.Calculator)

  mCurrentFocus=Window{39ced4b1 u0 com.android.calculator2/com.android.calculator2.Calculator}

  mFocusedApp=AppWindowToken{29a4bed4 token=Token{2f850b1a ActivityRecord{eefe5c5 u0 com.android.calculator2/.Calculator t322}}}

Main part is, First Line:

Window #7 Window{39ced4b1 u0 com.android.calculator2/com.android.calculator2.Calculator}:

First part of the output is package name:

com.android.calculator2

Second Part of output (which is after /) can be two things, in our case its:

com.android.calculator2.Calculator

  1. <PKg name>.<activity name> = <com.android.calculator2>.<Calculator>

    so .Calculator is our activity

  2. If second part is entirely different from Package name and doesn't seem to contain pkg name which was before / in out output, then entire second part can be used as main activity.

How to connect to local instance of SQL Server 2008 Express

var.connectionstring = "server=localhost; database=dbname; integrated security=yes"

or

var.connectionstring = "server=localhost; database=dbname; login=yourlogin; pwd=yourpass"

How to set all elements of an array to zero or any same value?

You could use memset, if you sure about the length.

memset(ptr, 0x00, length)

IIS Manager in Windows 10

Actually you must make sure that the IIS Management Console feature is explicitly checked. On my win 10 pro I had to do it manually, checking the root only was not enough!

What is a segmentation fault?

A segmentation fault or access violation occurs when a program attempts to access a memory location that is not exist, or attempts to access a memory location in a way that is not allowed.

 /* "Array out of bounds" error 
   valid indices for array foo
   are 0, 1, ... 999 */
   int foo[1000];
   for (int i = 0; i <= 1000 ; i++) 
   foo[i] = i;

Here i[1000] not exist, so segfault occurs.

Causes of segmentation fault:

it arise primarily due to errors in use of pointers for virtual memory addressing, particularly illegal access.

De-referencing NULL pointers – this is special-cased by memory management hardware.

Attempting to access a nonexistent memory address (outside process’s address space).

Attempting to access memory the program does not have rights to (such as kernel structures in process context).

Attempting to write read-only memory (such as code segment).

in a "using" block is a SqlConnection closed on return or exception?

Here is my Template. Everything you need to select data from an SQL server. Connection is closed and disposed and errors in connection and execution are caught.

string connString = System.Configuration.ConfigurationManager.ConnectionStrings["CompanyServer"].ConnectionString;
string selectStatement = @"
    SELECT TOP 1 Person
    FROM CorporateOffice
    WHERE HeadUpAss = 1 AND Title LIKE 'C-Level%'
    ORDER BY IntelligenceQuotient DESC
";
using (SqlConnection conn = new SqlConnection(connString))
{
    using (SqlCommand comm = new SqlCommand(selectStatement, conn))
    {
        try
        {
            conn.Open();
            using (SqlDataReader dr = comm.ExecuteReader())
            {
                if (dr.HasRows)
                {
                    while (dr.Read())
                    {
                        Console.WriteLine(dr["Person"].ToString());
                    }
                }
                else Console.WriteLine("No C-Level with Head Up Ass Found!? (Very Odd)");
            }
        }
        catch (Exception e) { Console.WriteLine("Error: " + e.Message); }
        if (conn.State == System.Data.ConnectionState.Open) conn.Close();
    }
}

* Revised: 2015-11-09 *
As suggested by NickG; If too many braces are annoying you, format like this...

using (SqlConnection conn = new SqlConnection(connString))
   using (SqlCommand comm = new SqlCommand(selectStatement, conn))
   {
      try
      {
         conn.Open();
         using (SqlDataReader dr = comm.ExecuteReader())
            if (dr.HasRows)
               while (dr.Read()) Console.WriteLine(dr["Person"].ToString());
            else Console.WriteLine("No C-Level with Head Up Ass Found!? (Very Odd)");
      }
      catch (Exception e) { Console.WriteLine("Error: " + e.Message); }
      if (conn.State == System.Data.ConnectionState.Open) conn.Close();
   }

Then again, if you work for EA or DayBreak games, you can just forgo any line-breaks as well because those are just for people who have to come back and look at your code later and who really cares? Am I right? I mean 1 line instead of 23 means I'm a better programmer, right?

using (SqlConnection conn = new SqlConnection(connString)) using (SqlCommand comm = new SqlCommand(selectStatement, conn)) { try { conn.Open(); using (SqlDataReader dr = comm.ExecuteReader()) if (dr.HasRows) while (dr.Read()) Console.WriteLine(dr["Person"].ToString()); else Console.WriteLine("No C-Level with Head Up Ass Found!? (Very Odd)"); } catch (Exception e) { Console.WriteLine("Error: " + e.Message); } if (conn.State == System.Data.ConnectionState.Open) conn.Close(); }

Phew... OK. I got that out of my system and am done amusing myself for a while. Carry on.

Get selected key/value of a combo box using jQuery

<select name="foo" id="foo">
 <option value="1">a</option>
 <option value="2">b</option>
 <option value="3">c</option>
  </select>
  <input type="button" id="button" value="Button" />
  });
  <script> ("#foo").val() </script>

which returns 1 if you have selected a and so on..

Consider marking event handler as 'passive' to make the page more responsive

For jquery-ui-dragable with jquery-ui-touch-punch I fixed it similar to Iván Rodríguez, but with one more event override for touchmove:

jQuery.event.special.touchstart = {
    setup: function( _, ns, handle ) {
        this.addEventListener('touchstart', handle, { passive: !ns.includes('noPreventDefault') });
    }
};
jQuery.event.special.touchmove = {
    setup: function( _, ns, handle ) {
        this.addEventListener('touchmove', handle, { passive: !ns.includes('noPreventDefault') });
    }
};

How do you specify a different port number in SQL Management Studio?

If you're connecting to a named instance and UDP is not available when connecting to it, then you may need to specify the protocol as well.

Example: tcp:192.168.1.21\SQL2K5,1443

Is Ruby pass by reference or by value?

The other answerers are all correct, but a friend asked me to explain this to him and what it really boils down to is how Ruby handles variables, so I thought I would share some simple pictures / explanations I wrote for him (apologies for the length and probably some oversimplification):


Q1: What happens when you assign a new variable str to a value of 'foo'?

str = 'foo'
str.object_id # => 2000

enter image description here

A: A label called str is created that points at the object 'foo', which for the state of this Ruby interpreter happens to be at memory location 2000.


Q2: What happens when you assign the existing variable str to a new object using =?

str = 'bar'.tap{|b| puts "bar: #{b.object_id}"} # bar: 2002
str.object_id # => 2002

enter image description here

A: The label str now points to a different object.


Q3: What happens when you assign a new variable = to str?

str2 = str
str2.object_id # => 2002

enter image description here

A: A new label called str2 is created that points at the same object as str.


Q4: What happens if the object referenced by str and str2 gets changed?

str2.replace 'baz'
str2 # => 'baz'
str  # => 'baz'
str.object_id # => 2002
str2.object_id # => 2002

enter image description here

A: Both labels still point at the same object, but that object itself has mutated (its contents have changed to be something else).


How does this relate to the original question?

It's basically the same as what happens in Q3/Q4; the method gets its own private copy of the variable / label (str2) that gets passed in to it (str). It can't change which object the label str points to, but it can change the contents of the object that they both reference to contain else:

str = 'foo'

def mutate(str2)
  puts "str2: #{str2.object_id}"
  str2.replace 'bar'
  str2 = 'baz'
  puts "str2: #{str2.object_id}"
end

str.object_id # => 2004
mutate(str) # str2: 2004, str2: 2006
str # => "bar"
str.object_id # => 2004

Escaping quotes and double quotes

In Powershell 5 escaping double quotes can be done by backtick (`). But sometimes you need to provide your double quotes escaped which can be done by backslash + backtick (\`). Eg in this curl call:

C:\Windows\System32\curl.exe -s -k -H "Content-Type: application/json" -XPOST localhost:9200/index_name/inded_type -d"{\`"velocity\`":3.14}"

Excel: How to check if a cell is empty with VBA?

This site uses the method isEmpty().

Edit: content grabbed from site, before the url will going to be invalid.

Worksheets("Sheet1").Range("A1").Sort _
    key1:=Worksheets("Sheet1").Range("A1")
Set currentCell = Worksheets("Sheet1").Range("A1")
Do While Not IsEmpty(currentCell)
    Set nextCell = currentCell.Offset(1, 0)
    If nextCell.Value = currentCell.Value Then
        currentCell.EntireRow.Delete
    End If
    Set currentCell = nextCell
Loop

In the first step the data in the first column from Sheet1 will be sort. In the second step, all rows with same data will be removed.

ReferenceError: $ is not defined

i was facing the same problem in the wp-admin section of the site. I enqueued the underscore script cdn and it fixed the problem.

function kk_admin_scripts() {
    wp_enqueue_script('underscore', '//cdnjs.cloudflare.com/ajax/libs/lodash.js/0.10.0/lodash.min.js' );
}
add_action( 'admin_enqueue_scripts', 'kk_admin_scripts' );

Fastest way to check if a file exist using standard C++/C++11/C?

Using MFC it is possible with the following

CFileStatus FileStatus;
BOOL bFileExists = CFile::GetStatus(FileName,FileStatus);

Where FileName is a string representing the file you are checking for existance

How to override trait function and call it from the overridden function?

Using another trait:

trait ATrait {
    function calc($v) {
        return $v+1;
    }
}

class A {
    use ATrait;
}

trait BTrait {
    function calc($v) {
        $v++;
        return parent::calc($v);
    }
}

class B extends A {
    use BTrait;
}

print (new B())->calc(2); // should print 4

Maven "build path specifies execution environment J2SE-1.5", even though I changed it to 1.7

I'm using Juno 4.2 with latest spring, maven plugin and JDK1.6.0_25.

I faced same issue and here is my fix that make default after each Eclipse restart:

  1. List item
  2. Right-click on the maven project
  3. Java Build Path
  4. Libraries tab
  5. Select current wrong JRE item
  6. Click Edit
  7. Select the last option (Workspace default JRE (jdk1.6.0_25)

Trying to Validate URL Using JavaScript

I know it's quite an old question but since it does not have any accepted answer, I suggest you to use the URI.js framework: https://github.com/medialize/URI.js

You can use it to check for malformed URI using a try/catch block:

function isValidURL(url)
{
    try {
        (new URI(url));
        return true;
    }
    catch (e) {
        // Malformed URI
        return false;
    }
}

Of course it will consider something like "%@" as a well formed relative URI... So I suggest you read the URI.js API to perform more checks, for example if you want to make sure that the user entered a well formed absolute URL you may do like this:

function isValidURL(url)
{
    try {
        var uri = new URI(url);
        // URI has a scheme and a host
        return (!!uri.scheme() && !!uri.host());
    }
    catch (e) {
        // Malformed URI
        return false;
    }
}

HTML form with two submit buttons and two "target" attributes

In case you are up to HTML5, you can just use the attribute formaction. This allows you to have a different form action for each button.

<!DOCTYPE html>
<html>
  <body>
    <form>
      <input type="submit" formaction="firsttarget.php" value="Submit to first" />
      <input type="submit" formaction="secondtarget.php" value="Submit to second" />
    </form>
  </body>
</html>

Multiple radio button groups in one form

Set equal name attributes to create a group;

_x000D_
_x000D_
<form>_x000D_
  <fieldset id="group1">_x000D_
    <input type="radio" value="value1" name="group1">_x000D_
    <input type="radio" value="value2" name="group1">_x000D_
  </fieldset>_x000D_
_x000D_
  <fieldset id="group2">_x000D_
    <input type="radio" value="value1" name="group2">_x000D_
    <input type="radio" value="value2" name="group2">_x000D_
    <input type="radio" value="value3" name="group2">_x000D_
  </fieldset>_x000D_
</form>
_x000D_
_x000D_
_x000D_

What does "Fatal error: Unexpectedly found nil while unwrapping an Optional value" mean?

Since the above answers clearly explains how to play safely with Optionals. I will try explain what Optionals are really in swift.

Another way to declare an optional variable is

var i : Optional<Int>

And Optional type is nothing but an enumeration with two cases, i.e

 enum Optional<Wrapped> : ExpressibleByNilLiteral {
    case none 
    case some(Wrapped)
    .
    .
    .
}

So to assign a nil to our variable 'i'. We can do var i = Optional<Int>.none or to assign a value, we will pass some value var i = Optional<Int>.some(28)

According to swift, 'nil' is the absence of value. And to create an instance initialized with nil We have to conform to a protocol called ExpressibleByNilLiteral and great if you guessed it, only Optionals conform to ExpressibleByNilLiteral and conforming to other types is discouraged.

ExpressibleByNilLiteral has a single method called init(nilLiteral:) which initializes an instace with nil. You usually wont call this method and according to swift documentation it is discouraged to call this initializer directly as the compiler calls it whenever you initialize an Optional type with nil literal.

Even myself has to wrap (no pun intended) my head around Optionals :D Happy Swfting All.

Pattern matching using a wildcard

You can also use package data.table and it's Like function, details given below How to select R data.table rows based on substring match (a la SQL like)

How to convert a column number (e.g. 127) into an Excel column (e.g. AA)

If you are wanting to reference the cell progmatically then you will get much more readable code if you use the Cells method of a sheet. It takes a row and column index instead of a traditonal cell reference. It is very similar to the Offset method.

How to put labels over geom_bar for each bar in R with ggplot2

Try this:

ggplot(data=dat, aes(x=Types, y=Number, fill=sample)) + 
     geom_bar(position = 'dodge', stat='identity') +
     geom_text(aes(label=Number), position=position_dodge(width=0.9), vjust=-0.25)

ggplot output

Add property to an array of objects

I came up against this problem too, and in trying to solve it I kept crashing the chrome tab that was running my app. It looks like the spread operator for objects was the culprit.

With a little help from adrianolsk’s comment and sidonaldson's answer above, I used Object.assign() the output of the spread operator from babel, like so:

this.options.map(option => {
  // New properties to be added
  const newPropsObj = {
    newkey1:value1,
    newkey2:value2
  };

  // Assign new properties and return
  return Object.assign(option, newPropsObj);
});

How to allow access outside localhost

you can also introspect all HTTP traffic running over your tunnels using ngrok , then you can expose using ngrok http --host-header=rewrite 4200

What is the cause for "angular is not defined"

You have not placed the script tags for angular js

you can do so by using cdn or downloading the angularjs for your project and then referencing it

after this you have to add your own java script in your case main.js

that should do

What are the correct version numbers for C#?

Version     .NET Framework  Visual Studio   Important Features
C# 1.0  .NET Framework 1.0/1.1  Visual Studio .NET 2002     

    Basic features

C# 2.0  .NET Framework 2.0  Visual Studio 2005  

    Generics
    Partial types
    Anonymous methods
    Iterators
    Nullable types
    Private setters (properties)
    Method group conversions (delegates)
    Covariance and Contra-variance
    Static classes

C# 3.0  .NET Framework 3.0\3.5  Visual Studio 2008  

    Implicitly typed local variables
    Object and collection initializers
    Auto-Implemented properties
    Anonymous types
    Extension methods
    Query expressions
    Lambda expressions
    Expression trees
    Partial Methods

C# 4.0  .NET Framework 4.0  Visual Studio 2010  

    Dynamic binding (late binding)
    Named and optional arguments
    Generic co- and contravariance
    Embedded interop types

C# 5.0  .NET Framework 4.5  Visual Studio 2012/2013     

    Async features
    Caller information

C# 6.0  .NET Framework 4.6  Visual Studio 2013/2015     

    Expression Bodied Methods
    Auto-property initializer
    nameof Expression
    Primary constructor
    Await in catch block
    Exception Filter
    String Interpolation

C# 7.0  .NET Core 2.0   Visual Studio 2017  

    out variables
    Tuples
    Discards
    Pattern Matching
    Local functions
    Generalized async return types
    Numeric literal syntax improvements
C# 8.0  .NET Core 3.0   Visual Studio 2019  

    
    Readonly members
    Default interface methods
    Pattern matching enhancements:
        Switch expressions
        Property patterns
        Tuple patterns
        Positional patterns
    Using declarations
    Static local functions
    Disposable ref structs
    Nullable reference types
    Asynchronous streams
    Asynchronous disposable
    Indices and ranges
    Null-coalescing assignment
    Unmanaged constructed types
    Stackalloc in nested expressions
    Enhancement of interpolated verbatim strings

How to overwrite files with Copy-Item in PowerShell

How about calling the .NET Framework methods?

You can do ANYTHING with them... :

[System.IO.File]::Copy($src, $dest, $true);

The $true argument makes it overwrite.

How to have the formatter wrap code with IntelliJ?

Do you mean that the formatter does not break long lines? Check Settings / Project Settings / Code Style / Wrapping.

Update: in later versions of IntelliJ, the option is under Settings / Editor / Code Style. And select Wrap when typing reaches right margin.

TERM environment variable not set

You've answered the question with this statement:

Cron calls this .sh every 2 minutes

Cron does not run in a terminal, so why would you expect one to be set?

The most common reason for getting this error message is because the script attempts to source the user's .profile which does not check that it's running in a terminal before doing something tty related. Workarounds include using a shebang line like:

#!/bin/bash -p

Which causes the sourcing of system-level profile scripts which (one hopes) does not attempt to do anything too silly and will have guards around code that depends on being run from a terminal.

If this is the entirety of the script, then the TERM error is coming from something other than the plain content of the script.

Deciding between HttpClient and WebClient

Unpopular opinion from 2020:

When it comes to ASP.NET apps I still prefer WebClient over HttpClient because:

  1. The modern implementation comes with async/awaitable task-based methods
  2. Has smaller memory footprint and 2x-5x faster (other answers already mention that)
  3. It's suggested to "reuse a single instance of HttpClient for the lifetime of your application". But ASP.NET has no "lifetime of application", only lifetime of a request.

How to set JAVA_HOME path on Ubuntu?

add JAVA_HOME to the file:

/etc/environment

for it to be available to the entire system (you would need to restart Ubuntu though)

Composer update memory limit

I'm running Laravel 6 with Homestead and also ran into this problem. As suggested here in the other answers you can prefix COMPOSER_MEMORY_LIMIT=-1 to a single command and run the command normally. If you'd like to update your PHP config to always allow unlimited memory follow these steps.

vagrant up
vagrant ssh
php --version # 7.4
php --ini # Shows path to the php.ini file that's loaded
cd /etc/php/7.4/cli # your PHP version. Each PHP version has a folder
sudo vi php.ini

Add memory_limit=-1 to your php.ini file. If you're having trouble using Vim or making edits to the php.ini file check this answer about how to edit the php.ini file with Vim. The file should look something like this:

; Maximum amount of memory a script may consume
; http://php.net/memory-limit
memory_limit = -1

Note that this could eat up infinite amount of memory on your machine. Probably not a good idea for production lol. With Laravel Valet had to follow this article and update the memory value here:

sudo vi /usr/local/etc/php/7.4/conf.d/php-memory-limits.ini

Then restart the server with Valet:

valet restart

This answer was also helpful for changing the config with Laravel Valet on Mac so the changes take effect.

The HTTP request is unauthorized with client authentication scheme 'Ntlm'. The authentication header received from the server was 'Negotiate,NTLM'

Try setting 'clientCredentialType' to 'Windows' instead of 'Ntlm'.

I think that this is what the server is expecting - i.e. when it says the server expects "Negotiate,NTLM", that actually means Windows Auth, where it will try to use Kerberos if available, or fall back to NTLM if not (hence the 'negotiate')

I'm basing this on somewhat reading between the lines of: Selecting a Credential Type

How to add a default "Select" option to this ASP.NET DropDownList control?

If you want to make the first item unselectable, try this:

DropDownList1.Items.Insert(0, new ListItem("Select", "-1"));
DropDownList1.Items[0].Attributes.Add("disabled", "disabled");

What's the difference between Instant and LocalDateTime?

Instant corresponds to time on the prime meridian (Greenwich).

Whereas LocalDateTime relative to OS time zone settings, and

cannot represent an instant without additional information such as an offset or time-zone.

Excel 2013 horizontal secondary axis

You should follow the guidelines on Add a secondary horizontal axis:

Add a secondary horizontal axis

To complete this procedure, you must have a chart that displays a secondary vertical axis. To add a secondary vertical axis, see Add a secondary vertical axis.

  1. Click a chart that displays a secondary vertical axis. This displays the Chart Tools, adding the Design, Layout, and Format tabs.

  2. On the Layout tab, in the Axes group, click Axes.

    enter image description here

  3. Click Secondary Horizontal Axis, and then click the display option that you want.

enter image description here


Add a secondary vertical axis

You can plot data on a secondary vertical axis one data series at a time. To plot more than one data series on the secondary vertical axis, repeat this procedure for each data series that you want to display on the secondary vertical axis.

  1. In a chart, click the data series that you want to plot on a secondary vertical axis, or do the following to select the data series from a list of chart elements:

    • Click the chart.

      This displays the Chart Tools, adding the Design, Layout, and Format tabs.

    • On the Format tab, in the Current Selection group, click the arrow in the Chart Elements box, and then click the data series that you want to plot along a secondary vertical axis.

      enter image description here

  2. On the Format tab, in the Current Selection group, click Format Selection. The Format Data Series dialog box is displayed.

    Note: If a different dialog box is displayed, repeat step 1 and make sure that you select a data series in the chart.

  3. On the Series Options tab, under Plot Series On, click Secondary Axis and then click Close.

    A secondary vertical axis is displayed in the chart.

  4. To change the display of the secondary vertical axis, do the following:

    • On the Layout tab, in the Axes group, click Axes.

    • Click Secondary Vertical Axis, and then click the display option that you want.

  5. To change the axis options of the secondary vertical axis, do the following:

    • Right-click the secondary vertical axis, and then click Format Axis.

    • Under Axis Options, select the options that you want to use.

creating Hashmap from a JSON String

public class JsonMapExample {

    public static void main(String[] args) {
        String json = "{\"phonetype\":\"N95\",\"cat\":\"WP\"}";
        Map<String, String> map = new HashMap<String, String>();
        ObjectMapper mapper = new ObjectMapper();

        try {
            //convert JSON string to Map
            map = mapper.readValue(json, new TypeReference<HashMap<String, String>>() {});
            System.out.println(map);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Output:

{phonetype=N95, cat=WP}

You can see this link it's helpful http://www.mkyong.com/java/how-to-convert-java-map-to-from-json-jackson/

How to parse data in JSON format?

Very simple:

import json
data = json.loads('{"one" : "1", "two" : "2", "three" : "3"}')
print data['two']

VB.NET - How to move to next item a For Each Loop?

For Each I As Item In Items
    If I = x Then Continue For

    ' Do something
Next

HTTP redirect: 301 (permanent) vs. 302 (temporary)

The main issue with 301 is browser will cache the redirection even if you disabled the redirection from the server level.

Its always better to use 302 if you are enabling the redirection for a short maintenance window.

How to start Fragment from an Activity

In order to accomplish this, it is best to design fragment construct to receive that data and save that data in its bundle arguments.

   class FragmentA extends Fragment{
    public static FragmentA newInstance(YourDataClass data) {

            FragmentA f = new FragmentA();
            Bundle b = new Bundle();
            b.putString("data", data);
            f.setArguments(b);

            return f;
        }
    }

In order to start the fragment from the class, you can do the following

 Fragment newFragment = FragmentA.newInstance(objectofyourclassdata);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);

// Commit the transaction
transaction.commit();

However, the data class must be parceable or serializable.

For full information on fragments and best practices on use of fragments, please spend some time on official docs, it is super useful, at least my experience

https://developer.android.com/guide/components/fragments#java

How to change environment's font size?

enter image description here

I have mine set to "editor.fontSize": 12,

Save the file, you will see the effect right the way.

enter image description here

Enjoy !

How do I add a project as a dependency of another project?

Assuming the MyEjbProject is not another Maven Project you own or want to build with maven, you could use system dependencies to link to the existing jar file of the project like so

<project>
   ...
   <dependencies>
      <dependency>
         <groupId>yourgroup</groupId>
         <artifactId>myejbproject</artifactId>
         <version>2.0</version>
         <scope>system</scope>
         <systemPath>path/to/myejbproject.jar</systemPath>
      </dependency>
   </dependencies>
   ...
</project>

That said it is usually the better (and preferred way) to install the package to the repository either by making it a maven project and building it or installing it the way you already seem to do.


If they are, however, dependent on each other, you can always create a separate parent project (has to be a "pom" project) declaring the two other projects as its "modules". (The child projects would not have to declare the third project as their parent). As a consequence you'd get a new directory for the new parent project, where you'd also quite probably put the two independent projects like this:

parent
|- pom.xml
|- MyEJBProject
|   `- pom.xml
`- MyWarProject
    `- pom.xml

The parent project would get a "modules" section to name all the child modules. The aggregator would then use the dependencies in the child modules to actually find out the order in which the projects are to be built)

<project>
   ...
   <artifactId>myparentproject</artifactId>
   <groupId>...</groupId>
   <version>...</version>

   <packaging>pom</packaging>
   ...
   <modules>
     <module>MyEJBModule</module>
     <module>MyWarModule</module>
   </modules>
   ...
</project>

That way the projects can relate to each other but (once they are installed in the local repository) still be used independently as artifacts in other projects


Finally, if your projects are not in related directories, you might try to give them as relative modules:

filesystem
 |- mywarproject
 |   `pom.xml
 |- myejbproject
 |   `pom.xml
 `- parent
     `pom.xml

now you could just do this (worked in maven 2, just tried it):

<!--parent-->
<project>
  <modules>
    <module>../mywarproject</module>
    <module>../myejbproject</module>
  </modules>
</project>

How do I use WPF bindings with RelativeSource?

If you want to bind to another property on the object:

{Binding Path=PathToProperty, RelativeSource={RelativeSource Self}}

If you want to get a property on an ancestor:

{Binding Path=PathToProperty,
    RelativeSource={RelativeSource AncestorType={x:Type typeOfAncestor}}}

If you want to get a property on the templated parent (so you can do 2 way bindings in a ControlTemplate)

{Binding Path=PathToProperty, RelativeSource={RelativeSource TemplatedParent}}

or, shorter (this only works for OneWay bindings):

{TemplateBinding Path=PathToProperty}

Change the column label? e.g.: change column "A" to column "Name"

I would like to present another answer to this as the currently accepted answer doesn't work for me (I use LibreOffice). This solution should work in Excel, LibreOffice and OpenOffice:

First, insert a new row at the beginning of the sheet. Within that row, define the names you need: new row

Then, in the menu bar, go to View -> Freeze Cells -> Freeze First Row. It'll look like this now: new top row

Now whenever you scroll down in the document, the first row will be "pinned" to the top: new behaviour

Set a path variable with spaces in the path in a Windows .cmd file or batch file

If you need to store permanent path (path is not changed when cmd is restart)

  1. Run the Command Prompt as administrator (Right click on cmd.exe and select run as administrator)

  2. In cmd setx path "%path%;your new path" then enter

  3. Check whether the path is taken correctly by typing path and pressing enter

ExecuteNonQuery: Connection property has not been initialized.

just try this..

you need to open the connection using connection.open() on the SqlCommand.Connection object before executing ExecuteNonQuery()

How to remove a Gitlab project?

This is taken from feb 2018

Follow the following test

  1. Gitlab Home Page
  2. Select your projects button under Projects Menus
  3. Click your desired project
  4. Select Settings (from left sidebar)
  5. Click Advanced settings
  6. Click Remove Project

Or Click the following Link

Note : USER_NAME will replace by your username

PROJECT_NAME will replace by your repository name

https://gitlab.com/USER_NAME/PROJECT_NAME/edit

click Expand under Advanced settings portion

Click remove project bottom of the page

enter image description here

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

I had taken .svn folder from my fellow developer and replaced my .svn folder with this. It worked for me. Don't know what may be other consequences!

How can one pull the (private) data of one's own Android app?

adb backup will write an Android-specific archive:

adb backup  -f myAndroidBackup.ab  com.corp.appName

This archive can be converted to tar format using:

dd if=myAndroidBackup.ab bs=4K iflag=skip_bytes skip=24 | openssl zlib -d > myAndroidBackup.tar

Reference:

http://nelenkov.blogspot.ca/2012/06/unpacking-android-backups.html

Search for "Update" at that link.


Alternatively, use Android backup extractor to extract files from the Android backup (.ab) file.

Py_Initialize fails - unable to load the file system codec

For those working in Visual Studio simply add the include, Lib and libs directories to the Include Directories and Library Directories under Projects Properties -> Configuration Properties > VC++ Directories :

For example I have Anaconda3 on my system and working with Visual Studio 2015 This is how the settings looks like (note the Include and Library directories) : enter image description here

Edit:

As also pointed out by bossi setting PYTHONPATH in your user Environment Variables section seems necessary. a sample input can be like this (in my case):

C:\Users\Master\Anaconda3\Lib;C:\Users\Master\Anaconda3\libs;C:\Users\Master\Anaconda3\Lib\site-packages;C:\Users\Master\Anaconda3\DLLs

is necessary it seems.

Also, you need to restart Visual Studio after you set up the PYTHONPATH in your user Environment Variables for the changes to take effect.

Also note that :

Make sure the PYTHONHOME environment variable is set to the Python interpreter you want to use. The C++ projects in Visual Studio rely on this variable to locate files such as python.h, which are used when creating a Python extension.

How to solve "Kernel panic - not syncing - Attempted to kill init" -- without erasing any user data

Solution is :-

  1. Restart
  2. Go to advanced menu and then click on 'e'(edit the boot parameters)
  3. Go down to the line which starts with linux and press End
  4. Press space
  5. Add the following at the end -> kernel.panic=1
  6. Press F10 to restart

This basically forces your PC to restart because by default it does not restart after a kernel panic.

Why should C++ programmers minimize use of 'new'?

new() shouldn't be used as little as possible. It should be used as carefully as possible. And it should be used as often as necessary as dictated by pragmatism.

Allocation of objects on the stack, relying on their implicit destruction, is a simple model. If the required scope of an object fits that model then there's no need to use new(), with the associated delete() and checking of NULL pointers. In the case where you have lots of short-lived objects allocation on the stack should reduce the problems of heap fragmentation.

However, if the lifetime of your object needs to extend beyond the current scope then new() is the right answer. Just make sure that you pay attention to when and how you call delete() and the possibilities of NULL pointers, using deleted objects and all of the other gotchas that come with the use of pointers.

Node JS Promise.all and forEach

I had through the same situation. I solved using two Promise.All().

I think was really good solution, so I published it on npm: https://www.npmjs.com/package/promise-foreach

I think your code will be something like this

var promiseForeach = require('promise-foreach')
var jsonItems = [];
promiseForeach.each(jsonItems,
    [function (jsonItems){
        return new Promise(function(resolve, reject){
            if(jsonItems.type === 'file'){
                jsonItems.getFile().then(function(file){ //or promise.all?
                    resolve(file.getSize())
                })
            }
        })
    }],
    function (result, current) {
        return {
            type: current.type,
            size: jsonItems.result[0]
        }
    },
    function (err, newList) {
        if (err) {
            console.error(err)
            return;
        }
        console.log('new jsonItems : ', newList)
    })

How to automatically insert a blank row after a group of data

This won't work if the data is not sequential (1 2 3 4 but 5 7 3 1 5) as in that case you can't sort it.

Here is how I solve that issue for me:

Column A initial data that needs to contain 5 rows between each number - 5 4 6 8 9

Column B - 1 2 3 4 5 (final number represents the number of empty rows that you need to be between numbers in column A) copy-paste 1-5 in column B as long as you have numbers in column A.

Jump to D column, in D1 type 1. In D2 type this formula - =IF(B2=1,1+D1,D1) Drag it to the same length as column B.

Back to Column C - at C1 cell type this formula - =IF(B1=1,INDIRECT("a"&(D1)),""). Drag it down and we done. Now in column C we have same sequence of numbers as in column A distributed separately by 4 rows.

Converting int to string in C

void itos(int value, char* str, size_t size) {
    snprintf(str, size, "%d", value);
}

..works with call by reference. Use it like this e.g.:

int someIntToParse;
char resultingString[length(someIntToParse)];

itos(someIntToParse, resultingString, length(someIntToParse));

now resultingString will hold your C-'string'.

How do you get a list of the names of all files present in a directory in Node.js?

I've recently built a tool for this that does just this... It fetches a directory asynchronously and returns a list of items. You can either get directories, files or both, with folders being first. You can also paginate the data in case where you don't want to fetch the entire folder.

https://www.npmjs.com/package/fs-browser

This is the link, hope it helps someone!

What is the difference between find(), findOrFail(), first(), firstOrFail(), get(), list(), toArray()

  1. find($id) takes an id and returns a single model. If no matching model exist, it returns null.

  2. findOrFail($id) takes an id and returns a single model. If no matching model exist, it throws an error1.

  3. first() returns the first record found in the database. If no matching model exist, it returns null.

  4. firstOrFail() returns the first record found in the database. If no matching model exist, it throws an error1.

  5. get() returns a collection of models matching the query.

  6. pluck($column) returns a collection of just the values in the given column. In previous versions of Laravel this method was called lists.

  7. toArray() converts the model/collection into a simple PHP array.


Note: a collection is a beefed up array. It functions similarly to an array, but has a lot of added functionality, as you can see in the docs.

Unfortunately, PHP doesn't let you use a collection object everywhere you can use an array. For example, using a collection in a foreach loop is ok, put passing it to array_map is not. Similarly, if you type-hint an argument as array, PHP won't let you pass it a collection. Starting in PHP 7.1, there is the iterable typehint, which can be used to accept both arrays and collections.

If you ever want to get a plain array from a collection, call its all() method.


1 The error thrown by the findOrFail and firstOrFail methods is a ModelNotFoundException. If you don't catch this exception yourself, Laravel will respond with a 404, which is what you want most of the time.

How to disable action bar permanently

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_my);
    getSupportActionBar().hide();
}

How to use "raise" keyword in Python

You can use it to raise errors as part of error-checking:

if (a < b):
    raise ValueError()

Or handle some errors, and then pass them on as part of error-handling:

try:
    f = open('file.txt', 'r')
except IOError:
    # do some processing here
    # and then pass the error on
    raise

Android: Difference between onInterceptTouchEvent and dispatchTouchEvent?

There is a lot of confusion about these methods, but it is actually not that complicated. Most of the confusion is because:

  1. If your View/ViewGroup or any of its children do not return true in onTouchEvent, dispatchTouchEvent and onInterceptTouchEvent will ONLY be called for MotionEvent.ACTION_DOWN. Without a true from onTouchEvent, the parent view will assume your view does not need the MotionEvents.
  2. When none of the children of a ViewGroup return true in onTouchEvent, onInterceptTouchEvent will ONLY be called for MotionEvent.ACTION_DOWN, even if your ViewGroup returns true in onTouchEvent.

Processing order is like this:

  1. dispatchTouchEvent is called.
  2. onInterceptTouchEvent is called for MotionEvent.ACTION_DOWN or when any of the children of the ViewGroup returned true in onTouchEvent.
  3. onTouchEvent is first called on the children of the ViewGroup and when none of the children returns true it is called on the View/ViewGroup.

If you want to preview TouchEvents/MotionEvents without disabling the events on your children, you must do two things:

  1. Override dispatchTouchEvent to preview the event and return super.dispatchTouchEvent(ev);
  2. Override onTouchEvent and return true, otherwise you won’t get any MotionEvent except MotionEvent.ACTION_DOWN.

If you want to detect some gesture like a swipe event, without disabling other events on your children as long as you did not detect the gesture, you can do it like this:

  1. Preview the MotionEvents as described above and set a flag when you detected your gesture.
  2. Return true in onInterceptTouchEvent when your flag is set to cancel MotionEvent processing by your children. This is also a convenient place to reset your flag, because onInterceptTouchEvent won’t be called again until the next MotionEvent.ACTION_DOWN.

Example of overrides in a FrameLayout (my example in is C# as I’m programming with Xamarin Android, but the logic is the same in Java):

public override bool DispatchTouchEvent(MotionEvent e)
{
    // Preview the touch event to detect a swipe:
    switch (e.ActionMasked)
    {
        case MotionEventActions.Down:
            _processingSwipe = false;
            _touchStartPosition = e.RawX;
            break;
        case MotionEventActions.Move:
            if (!_processingSwipe)
            {
                float move = e.RawX - _touchStartPosition;
                if (move >= _swipeSize)
                {
                    _processingSwipe = true;
                    _cancelChildren = true;
                    ProcessSwipe();
                }
            }
            break;
    }
    return base.DispatchTouchEvent(e);
}

public override bool OnTouchEvent(MotionEvent e)
{
    // To make sure to receive touch events, tell parent we are handling them:
    return true;
}

public override bool OnInterceptTouchEvent(MotionEvent e)
{
    // Cancel all children when processing a swipe:
    if (_cancelChildren)
    {
        // Reset cancel flag here, as OnInterceptTouchEvent won't be called until the next MotionEventActions.Down:
        _cancelChildren = false;
        return true;
    }
    return false;
}

Extract values in Pandas value_counts()

Code

train["label_Name"].value_counts().to_frame()

where : label_Name Mean column_name

result (my case) :-

0    29720 
1     2242 
Name: label, dtype: int64

How to not wrap contents of a div?

If your div has a fixed-width it shouldn't expand, because you've fixed its width. However, modern browsers support a min-width CSS property.

You can emulate the min-width property in old IE browsers by using CSS expressions or by using auto width and having a spacer object in the container. This solution isn't elegant but may do the trick:

<div id="container" style="float: left">
  <div id="spacer" style="height: 1px; width: 300px"></div>
  <button>Button 1 text</button>
  <button>Button 2 text</button>
</div>

What's the longest possible worldwide phone number I should consider in SQL varchar(length) for phone

Assuming you don't store things like the '+', '()', '-', spaces and what-have-yous (and why would you, they are presentational concerns which would vary based on local customs and the network distributions anyways), the ITU-T recommendation E.164 for the international telephone network (which most national networks are connected via) specifies that the entire number (including country code, but not including prefixes such as the international calling prefix necessary for dialling out, which varies from country to country, nor including suffixes, such as PBX extension numbers) be at most 15 characters.

Call prefixes depend on the caller, not the callee, and thus shouldn't (in many circumstances) be stored with a phone number. If the database stores data for a personal address book (in which case storing the international call prefix makes sense), the longest international prefixes you'd have to deal with (according to Wikipedia) are currently 5 digits, in Finland.

As for suffixes, some PBXs support up to 11 digit extensions (again, according to Wikipedia). Since PBX extension numbers are part of a different dialing plan (PBXs are separate from phone companies' exchanges), extension numbers need to be distinguishable from phone numbers, either with a separator character or by storing them in a different column.

Wait one second in running program

Is it pausing, but you don't see your red color appear in the cell? Try this:

dataGridView1.Rows[x1].Cells[y1].Style.BackColor = System.Drawing.Color.Red;
dataGridView1.Refresh();
System.Threading.Thread.Sleep(1000);

When to use self over $this?

$this-> is used to refer to a specific instance of a class's variables (member variables) or methods.

Example: 
$derek = new Person();

$derek is now a specific instance of Person. Every Person has a first_name and a last_name, but $derek has a specific first_name and last_name (Derek Martin). Inside the $derek instance, we can refer to those as $this->first_name and $this->last_name

ClassName:: is used to refer to that type of class, and its static variables, static methods. If it helps, you can mentally replace the word "static" with "shared". Because they are shared, they cannot refer to $this, which refers to a specific instance (not shared). Static Variables (i.e. static $db_connection) can be shared among all instances of a type of object. For example, all database objects share a single connection (static $connection).

Static Variables Example: Pretend we have a database class with a single member variable: static $num_connections; Now, put this in the constructor:

function __construct()
{
    if(!isset $num_connections || $num_connections==null)
    {
        $num_connections=0;
    }
    else
    {
        $num_connections++;
    }
}

Just as objects have constructors, they also have destructors, which are executed when the object dies or is unset:

function __destruct()
{
    $num_connections--;
}

Every time we create a new instance, it will increase our connection counter by one. Every time we destroy or stop using an instance, it will decrease the connection counter by one. In this way, we can monitor the number of instances of the database object we have in use with:

echo DB::num_connections;

Because $num_connections is static (shared), it will reflect the total number of active database objects. You may have seen this technique used to share database connections among all instances of a database class. This is done because creating the database connection takes a long time, so it's best to create just one, and share it (this is called a Singleton Pattern).

Static Methods (i.e. public static View::format_phone_number($digits)) can be used WITHOUT first instantiating one of those objects (i.e. They do not internally refer to $this).

Static Method Example:

public static function prettyName($first_name, $last_name)
{
    echo ucfirst($first_name).' '.ucfirst($last_name);
}

echo Person::prettyName($derek->first_name, $derek->last_name);

As you can see, public static function prettyName knows nothing about the object. It's just working with the parameters you pass in, like a normal function that's not part of an object. Why bother, then, if we could just have it not as part of the object?

  1. First, attaching functions to objects helps you keep things organized, so you know where to find them.
  2. Second, it prevents naming conflicts. In a big project, you're likely to have two developers create getName() functions. If one creates a ClassName1::getName(), and the other creates ClassName2::getName(), it's no problem at all. No conflict. Yay static methods!

SELF:: If you are coding outside the object that has the static method you want to refer to, you must call it using the object's name View::format_phone_number($phone_number); If you are coding inside the object that has the static method you want to refer to, you can either use the object's name View::format_phone_number($pn), OR you can use the self::format_phone_number($pn) shortcut

The same goes for static variables: Example: View::templates_path versus self::templates_path

Inside the DB class, if we were referring to a static method of some other object, we would use the object's name: Example: Session::getUsersOnline();

But if the DB class wanted to refer to its own static variable, it would just say self: Example: self::connection;

Hope that helps clear things up :)

How can I split and parse a string in Python?

"2.7.0_bf4fda703454".split("_") gives a list of strings:

In [1]: "2.7.0_bf4fda703454".split("_")
Out[1]: ['2.7.0', 'bf4fda703454']

This splits the string at every underscore. If you want it to stop after the first split, use "2.7.0_bf4fda703454".split("_", 1).

If you know for a fact that the string contains an underscore, you can even unpack the LHS and RHS into separate variables:

In [8]: lhs, rhs = "2.7.0_bf4fda703454".split("_", 1)

In [9]: lhs
Out[9]: '2.7.0'

In [10]: rhs
Out[10]: 'bf4fda703454'

An alternative is to use partition(). The usage is similar to the last example, except that it returns three components instead of two. The principal advantage is that this method doesn't fail if the string doesn't contain the separator.

How do I set the default page of my application in IIS7?

For those who are newbie like me, Open IIS, expand your server name, choose sites, click on your website. On new install, it is Default web site. Click it. On the right side you have Default document option. Double click it. You will see default.htm, default.asp, index.htm etc.. to the extreme right click add. Enter the full name of your file(including extension) that you want to set it as default. click ok. Open cmd prompt as admin and reset iis. Remove all files from c:\inetpub\wwwroot folder like iisstart.html, index.html etc.

Note: This will automatically create web.config file in your c:\inetpub\wwwroot folder. I didnt have any web.config files in my inetpub or wwwroot folders. This automatically created one for me.

Next time when you enter http(s)://servername, it opens the default page you set.

How to make Bootstrap 4 cards the same height in card-columns?

wrap the cards inside

<div class="card-group"></div>

or

<div class="card-deck"></div>

Remove attribute "checked" of checkbox

Both of these should work:

$("#captureImage").prop('checked', false);

AND/OR

$("#captureImage").removeAttr('checked');

... you can try both together.

Simple Deadlock Examples

Here's a code example from the computer science department of a university in Taiwan showing a simple java example with resource locking. That's very "real-life" relevant to me. Code below:

/**
 * Adapted from The Java Tutorial
 * Second Edition by Campione, M. and
 * Walrath, K.Addison-Wesley 1998
 */

/**
 * This is a demonstration of how NOT to write multi-threaded programs.
 * It is a program that purposely causes deadlock between two threads that
 * are both trying to acquire locks for the same two resources.
 * To avoid this sort of deadlock when locking multiple resources, all threads
 * should always acquire their locks in the same order.
 **/
public class Deadlock {
  public static void main(String[] args){
    //These are the two resource objects 
    //we'll try to get locks for
    final Object resource1 = "resource1";
    final Object resource2 = "resource2";
    //Here's the first thread.
    //It tries to lock resource1 then resource2
    Thread t1 = new Thread() {
      public void run() {
        //Lock resource 1
        synchronized(resource1){
          System.out.println("Thread 1: locked resource 1");
          //Pause for a bit, simulating some file I/O or 
          //something. Basically, we just want to give the 
          //other thread a chance to run. Threads and deadlock
          //are asynchronous things, but we're trying to force 
          //deadlock to happen here...
          try{ 
            Thread.sleep(50); 
          } catch (InterruptedException e) {}

          //Now wait 'till we can get a lock on resource 2
          synchronized(resource2){
            System.out.println("Thread 1: locked resource 2");
          }
        }
      }
    };

    //Here's the second thread.  
    //It tries to lock resource2 then resource1
    Thread t2 = new Thread(){
      public void run(){
        //This thread locks resource 2 right away
        synchronized(resource2){
          System.out.println("Thread 2: locked resource 2");
          //Then it pauses, for the same reason as the first 
          //thread does
          try{
            Thread.sleep(50); 
          } catch (InterruptedException e){}

          //Then it tries to lock resource1.  
          //But wait!  Thread 1 locked resource1, and 
          //won't release it till it gets a lock on resource2.  
          //This thread holds the lock on resource2, and won't
          //release it till it gets resource1.  
          //We're at an impasse. Neither thread can run, 
          //and the program freezes up.
          synchronized(resource1){
            System.out.println("Thread 2: locked resource 1");
          }
        }
      }
    };

    //Start the two threads. 
    //If all goes as planned, deadlock will occur, 
    //and the program will never exit.
    t1.start(); 
    t2.start();
  }
}

Eclipse and Windows newlines

There is a handy bash utility - dos2unix - which is a DOS/MAC to UNIX text file format converter, that if not already installed on your distro, should be able to be easily installed via a package manager. dos2unix man page

Getting the Facebook like/share count for a given URL

I don't think Facebook's Open Graph Object i.e. "og_object" provides anything more than comment_count & share_count for a URL. Try this; replace $YOUR_URL with the URL and $ACCESS_TOKEN with your access token in the below link https://graph.facebook.com/v2.5/$YOUR_URL?access_token=$ACCESS_TOKEN

For example:

https://graph.facebook.com/v2.5/http://espn.go.com/nfl/story/_/id/14424066/handing-holiday-gifts-all-32-nfl-teams-nfl?access_token=$ACCESS_TOKEN

{
  og_object: {
    id: "956517601094822",
    description: "Naughty or nice, every NFL team deserves something for Christmas. So in lieu of Santa Claus, Bill Barnwell is here to distribute some gifts.",
    title: "Barnwell: Handing out holiday gifts to all 32 teams",
    type: "article",
    updated_time: "2015-12-23T17:20:55+0000",
    url: "http://espn.go.com/nfl/story/_/id/14424066"
  },
  share: {
    comment_count: 0,
    share_count: 354
  },
  id: "http://espn.go.com/nfl/story/_/id/14424066/handing-holiday-gifts-all-32-nfl-teams-nfl"
}

Also, if you try to get likes, you would get the following error https://graph.facebook.com/http://rottentomatoes.com?fields=likes&summary=1&access_token=$ACCESS_TOKEN

{
  error: {
    message: "(#100) Tried accessing nonexisting field (likes) on node type (URL)",
    type: "OAuthException",
    code: 100,
    fbtrace_id: "H+KksDn+mCf"
  }
}

ggplot2, change title size

+ theme(plot.title = element_text(size=22))

Here is the full set of things you can change in element_text:

element_text(family = NULL, face = NULL, colour = NULL, size = NULL,
  hjust = NULL, vjust = NULL, angle = NULL, lineheight = NULL,
  color = NULL)

How to get the number of characters in a std::string?

When dealing with C++ strings (std::string), you're looking for length() or size(). Both should provide you with the same value. However when dealing with C-Style strings, you would use strlen().

#include <iostream>
#include <string.h>

int main(int argc, char **argv)
{
   std::string str = "Hello!";
   const char *otherstr = "Hello!"; // C-Style string
   std::cout << str.size() << std::endl;
   std::cout << str.length() << std::endl;
   std::cout << strlen(otherstr) << std::endl; // C way for string length
   std::cout << strlen(str.c_str()) << std::endl; // convert C++ string to C-string then call strlen
   return 0;
}

Output:

6
6
6
6

Android JSONObject - How can I loop through a flat JSON object to get each key and value

Short version of Franci's answer:

for(Iterator<String> iter = json.keys();iter.hasNext();) {
    String key = iter.next();
    ...
}

Delete element in a slice

There are two options:

A: You care about retaining array order:

a = append(a[:i], a[i+1:]...)
// or
a = a[:i+copy(a[i:], a[i+1:])]

B: You don't care about retaining order (this is probably faster):

a[i] = a[len(a)-1] // Replace it with the last one. CAREFUL only works if you have enough elements.
a = a[:len(a)-1]   // Chop off the last one.

See the link to see implications re memory leaks if your array is of pointers.

https://github.com/golang/go/wiki/SliceTricks

python multithreading wait till all threads finished

Put the threads in a list and then use the Join method

 threads = []

 t = Thread(...)
 threads.append(t)

 ...repeat as often as necessary...

 # Start all threads
 for x in threads:
     x.start()

 # Wait for all of them to finish
 for x in threads:
     x.join()

MySQL select where column is not empty

We can use CASE for setting blank value to some char or String. I am using NA as Default string.

SELECT phone,   
CASE WHEN phone2 = '' THEN 'NA' END AS phone2 ELSE ISNULL(phone2,0) 
FROM jewishyellow.users  WHERE phone LIKE '813%'

List comprehension with if statement

If you use sufficiently big list not in b clause will do a linear search for each of the item in a. Why not use set? Set takes iterable as parameter to create a new set object.

>>> a = ["a", "b", "c", "d", "e"]
>>> b = ["c", "d", "f", "g"]
>>> set(a).intersection(set(b))
{'c', 'd'}

Shortcut for creating single item list in C#

A different answer to my earlier one, based on exposure to the Google Java Collections:

public static class Lists
{
    public static List<T> Of<T>(T item)
    {
        return new List<T> { item };
    }
}

Then:

List<string> x = Lists.Of("Hello");

I advise checking out the GJC - it's got lots of interesting stuff in. (Personally I'd ignore the "alpha" tag - it's only the open source version which is "alpha" and it's based on a very stable and heavily used internal API.)

How to print out the method name and line number and conditionally disable NSLog?

NSLog(@"%s %d %s %s", __FILE__, __LINE__, __PRETTY_FUNCTION__, __FUNCTION__);

Outputs file name, line number, and function name:

/proj/cocoa/cdcli/cdcli.m 121 managedObjectContext managedObjectContext

__FUNCTION__ in C++ shows mangled name __PRETTY_FUNCTION__ shows nice function name, in cocoa they look the same.

I'm not sure what is the proper way of disabling NSLog, I did:

#define NSLog

And no logging output showed up, however I don't know if this has any side effects.

How to print spaces in Python?

A lone print will output a newline.

print

In 3.x print is a function, therefore:

print()

App.Config Transformation for projects which are not Web Projects in Visual Studio?

Install "Configuration Transform Tool" in Visual Studio from Marketplace and restart VS. You will be able to see menu preview transform for app.config as well.

https://marketplace.visualstudio.com/items?itemName=GolanAvraham.ConfigurationTransform

How to call getResources() from a class which has no context?

Example: Getting app_name string:

Resources.getSystem().getString( R.string.app_name )

How to remove the arrows from input[type="number"] in Opera

Those arrows are part of the Shadow DOM, which are basically DOM elements on your page which are hidden from you. If you're new to the idea, a good introductory read can be found here.

For the most part, the Shadow DOM saves us time and is good. But there are instances, like this question, where you want to modify it.

You can modify these in Webkit now with the right selectors, but this is still in the early stages of development. The Shadow DOM itself has no unified selectors yet, so the webkit selectors are proprietary (and it isn't just a matter of appending -webkit, like in other cases).

Because of this, it seems likely that Opera just hasn't gotten around to adding this yet. Finding resources about Opera Shadow DOM modifications is tough, though. A few unreliable internet sources I've found all say or suggest that Opera doesn't currently support Shadow DOM manipulation.

I spent a bit of time looking through the Opera website to see if there'd be any mention of it, along with trying to find them in Dragonfly...neither search had any luck. Because of the silence on this issue, and the developing nature of the Shadow DOM + Shadow DOM manipulation, it seems to be a safe conclusion that you just can't do it in Opera, at least for now.

Onclick function based on element id

you can try these:

document.getElementById("RootNode").onclick = function(){/*do something*/};

or

$('#RootNode').click(function(){/*do something*/});

or

$(document).on("click", "#RootNode", function(){/*do something*/});

There is a point for the first two method which is, it matters where in your page DOM, you should put them, the whole DOM should be loaded, to be able to find the, which is usually it gets solved if you wrap them in a window.onload or DOMReady event, like:

//in Vanilla JavaScript
window.addEventListener("load", function(){
     document.getElementById("RootNode").onclick = function(){/*do something*/};
});
//for jQuery
$(document).ready(function(){
    $('#RootNode').click(function(){/*do something*/});
});

How to print table using Javascript?

My fellows,

In January 2019 I used a code made before:

 <script type="text/javascript">   
    function imprimir() {
        var divToPrint=document.getElementById("ConsutaBPM");
        newWin= window.open("");
        newWin.document.write(divToPrint.outerHTML);
        newWin.print();
        newWin.close();
    }
</script>

To undestand: ConsutaBPM is a DIV which contains inside phrases and tables. I wanted to print ALL, titles, table, and others. The problem was when TRIED to print the TABLE...

The table mas be defined with BORDER and CELLPADDING:

<table border='1' cellpadding='1' id='Tablbpm1' >

It worked fine!!!

Swift addsubview and remove it

Thanks for help. This is the solution: I created the subview and i add a gesture to remove it

@IBAction func infoView(sender: UIButton) {
    var testView: UIView = UIView(frame: CGRectMake(0, 0, 320, 568))
    testView.backgroundColor = UIColor.blueColor()
    testView.alpha = 0.5
    testView.tag = 100
    testView.userInteractionEnabled = true
    self.view.addSubview(testView)

    let aSelector : Selector = "removeSubview"
    let tapGesture = UITapGestureRecognizer(target:self, action: aSelector)
    testView.addGestureRecognizer(tapGesture)
}

func removeSubview(){
    println("Start remove sibview")
    if let viewWithTag = self.view.viewWithTag(100) {
        viewWithTag.removeFromSuperview()
    }else{
        println("No!")
    }
}

Update:

Swift 3+

@IBAction func infoView(sender: UIButton) {
    let testView: UIView = UIView(frame: CGRect(x: 0, y: 0, width: 320, height: 568))
    testView.backgroundColor = .blue
    testView.alpha = 0.5
    testView.tag = 100
    testView.isUserInteractionEnabled = true
    self.view.addSubview(testView)

    let aSelector : Selector = #selector(GasMapViewController.removeSubview)
    let tapGesture = UITapGestureRecognizer(target:self, action: aSelector)
    testView.addGestureRecognizer(tapGesture)
}

func removeSubview(){
    print("Start remove sibview")
    if let viewWithTag = self.view.viewWithTag(100) {
        viewWithTag.removeFromSuperview()
    }else{
        print("No!")
    }
}

Normalizing images in OpenCV

When you normalize a matrix using NORM_L1, you are dividing every pixel value by the sum of absolute values of all the pixels in the image. As a result, all pixel values become much less than 1 and you get a black image. Try NORM_MINMAX instead of NORM_L1.

EC2 Instance Cloning

There is no explicit Clone button. Basically what you do is create an image, or snapshot of an existing EC2 instance, and then spin up a new instance using that snapshot.

First create an image from an existing EC2 instance.

enter image description here


Check your snapshots list to see if the process is completed. This usually takes around 20 minutes depending on how large your instance drive is.

enter image description here


Then, you need to create a new instance and use that image as the AMI.

enter image description here

enter image description here

R data formats: RData, Rda, Rds etc

In addition to @KenM's answer, another important distinction is that, when loading in a saved object, you can assign the contents of an Rds file. Not so for Rda

> x <- 1:5
> save(x, file="x.Rda")
> saveRDS(x, file="x.Rds")
> rm(x)

## ASSIGN USING readRDS
> new_x1 <- readRDS("x.Rds")
> new_x1
[1] 1 2 3 4 5

## 'ASSIGN' USING load -- note the result
> new_x2 <- load("x.Rda")
loading in to  <environment: R_GlobalEnv> 
> new_x2
[1] "x"
# NOTE: `load()` simply returns the name of the objects loaded. Not the values. 
> x
[1] 1 2 3 4 5

Forward slash in Java Regex

There is actually a reason behind why all these are messed up. A little more digging deeper is done in this thread and might be helpful to understand the reason why "\\" behaves like this.

Subtracting Dates in Oracle - Number or Interval Datatype?

Ok, I don't normally answer my own questions but after a bit of tinkering, I have figured out definitively how Oracle stores the result of a DATE subtraction.

When you subtract 2 dates, the value is not a NUMBER datatype (as the Oracle 11.2 SQL Reference manual would have you believe). The internal datatype number of a DATE subtraction is 14, which is a non-documented internal datatype (NUMBER is internal datatype number 2). However, it is actually stored as 2 separate two's complement signed numbers, with the first 4 bytes used to represent the number of days and the last 4 bytes used to represent the number of seconds.

An example of a DATE subtraction resulting in a positive integer difference:

select date '2009-08-07' - date '2008-08-08' from dual;

Results in:

DATE'2009-08-07'-DATE'2008-08-08'
---------------------------------
                              364

select dump(date '2009-08-07' - date '2008-08-08') from dual;

DUMP(DATE'2009-08-07'-DATE'2008
-------------------------------
Typ=14 Len=8: 108,1,0,0,0,0,0,0

Recall that the result is represented as a 2 seperate two's complement signed 4 byte numbers. Since there are no decimals in this case (364 days and 0 hours exactly), the last 4 bytes are all 0s and can be ignored. For the first 4 bytes, because my CPU has a little-endian architecture, the bytes are reversed and should be read as 1,108 or 0x16c, which is decimal 364.

An example of a DATE subtraction resulting in a negative integer difference:

select date '1000-08-07' - date '2008-08-08' from dual;

Results in:

DATE'1000-08-07'-DATE'2008-08-08'
---------------------------------
                          -368160

select dump(date '1000-08-07' - date '2008-08-08') from dual;

DUMP(DATE'1000-08-07'-DATE'2008-08-0
------------------------------------
Typ=14 Len=8: 224,97,250,255,0,0,0,0

Again, since I am using a little-endian machine, the bytes are reversed and should be read as 255,250,97,224 which corresponds to 11111111 11111010 01100001 11011111. Now since this is in two's complement signed binary numeral encoding, we know that the number is negative because the leftmost binary digit is a 1. To convert this into a decimal number we would have to reverse the 2's complement (subtract 1 then do the one's complement) resulting in: 00000000 00000101 10011110 00100000 which equals -368160 as suspected.

An example of a DATE subtraction resulting in a decimal difference:

select to_date('08/AUG/2004 14:00:00', 'DD/MON/YYYY HH24:MI:SS'
 - to_date('08/AUG/2004 8:00:00', 'DD/MON/YYYY HH24:MI:SS') from dual;

TO_DATE('08/AUG/200414:00:00','DD/MON/YYYYHH24:MI:SS')-TO_DATE('08/AUG/20048:00:
--------------------------------------------------------------------------------
                                                                             .25

The difference between those 2 dates is 0.25 days or 6 hours.

select dump(to_date('08/AUG/2004 14:00:00', 'DD/MON/YYYY HH24:MI:SS')
 - to_date('08/AUG/2004 8:00:00', 'DD/MON/YYYY HH24:MI:SS')) from dual;

DUMP(TO_DATE('08/AUG/200414:00:
-------------------------------
Typ=14 Len=8: 0,0,0,0,96,84,0,0

Now this time, since the difference is 0 days and 6 hours, it is expected that the first 4 bytes are 0. For the last 4 bytes, we can reverse them (because CPU is little-endian) and get 84,96 = 01010100 01100000 base 2 = 21600 in decimal. Converting 21600 seconds to hours gives you 6 hours which is the difference which we expected.

Hope this helps anyone who was wondering how a DATE subtraction is actually stored.


You get the syntax error because the date math does not return a NUMBER, but it returns an INTERVAL:

SQL> SELECT DUMP(SYSDATE - start_date) from test;

DUMP(SYSDATE-START_DATE)
-------------------------------------- 
Typ=14 Len=8: 188,10,0,0,223,65,1,0

You need to convert the number in your example into an INTERVAL first using the NUMTODSINTERVAL Function

For example:

SQL> SELECT (SYSDATE - start_date) DAY(5) TO SECOND from test;

(SYSDATE-START_DATE)DAY(5)TOSECOND
----------------------------------
+02748 22:50:04.000000

SQL> SELECT (SYSDATE - start_date) from test;

(SYSDATE-START_DATE)
--------------------
           2748.9515

SQL> select NUMTODSINTERVAL(2748.9515, 'day') from dual;

NUMTODSINTERVAL(2748.9515,'DAY')
--------------------------------
+000002748 22:50:09.600000000

SQL>

Based on the reverse cast with the NUMTODSINTERVAL() function, it appears some rounding is lost in translation.

Java Synchronized list

Yes, it will work fine as you have synchronized the list . I would suggest you to use CopyOnWriteArrayList.

CopyOnWriteArrayList<String> cpList=new CopyOnWriteArrayList<String>(new ArrayList<String>());

    void remove(String item)
    {
         do something; (doesn't work on the list)
                 cpList..remove(item);
    }

How to call a javaScript Function in jsp on page load without using <body onload="disableView()">

Either use window.onload this way

<script>
    window.onload = function() {
        // ...
    }
</script>

or alternatively

<script>
    window.onload = functionName;
</script>

(yes, without the parentheses)


Or just put the script at the very bottom of page, right before </body>. At that point, all HTML DOM elements are ready to be accessed by document functions.

<body>
    ...

    <script>
        functionName();
    </script>
</body>

How can I change text color via keyboard shortcut in MS word 2010

Alt+H, then type letters FC, then pick the color.

Do copyright dates need to be updated?

The copyright notice on a work establishes a claim to copyright. The date on the notice establishes how far back the claim is made. This means if you update the date, you are no longer claiming the copyright for the original date and that means if somebody has copied the work in the meantime and they claim its theirs on the ground that their publishing the copy was before your claim, then it will be difficult to establish who is the originator of the work.

Therefore, if the claim is based on common law copyright (not formally registered), then the date should be the date of first publication. If the claim is a registered copyright, then the date should be the date claimed in the registration. In cases where the work was substantially revised you may establish a new copyright claim to the revised work by adding another copyright notice with a newer date or by adding an additional date to the existing notice as in "© 2000, 2010". Again, the added date establishes how far back the claim is made on the revision.

Where can I find the .apk file on my device, when I download any app and install?

All user installed apks are located in /data/app/, but you can only access this if you are rooted(afaik, you can try without root and if it doesn't work, rooting isn't hard. I suggest you search xda-developers for rooting instructions)

Use Root explorer or ES File Explorer to access /data/app/ (you have to keep going "up" until you reach the root directory /, kind of like C: in windows, before you can see the data directory(folder)). In ES file explorer you must also tick a checkbox in settings to allow going up to the root directory.

When you are in there you will see all your applications apks, though they might be named strangely. Just copy the wanted .apk and paste in the sd card, after that you can copy it to your computer and when you want to install it just open the .apk in a file manager (be sure to have install from unknown sources enabled in android settings). Even if you only want to send over bluetooth I would recommend copying it to the SD first.

PS Note that paid apps probably won't work being copied this way, since they usually check their licence online. PPS Installing an app this way may not link it with google play(you won't see it in my apps and it won't get updates).

How do I use FileSystemObject in VBA?

After importing the scripting runtime as described above you have to make some slighty modification to get it working in Excel 2010 (my version). Into the following code I've also add the code used to the user to pick a file.

Dim intChoice As Integer
Dim strPath As String

' Select one file
Application.FileDialog(msoFileDialogOpen).AllowMultiSelect = False

' Show the selection window
intChoice = Application.FileDialog(msoFileDialogOpen).Show

' Get back the user option
If intChoice <> 0 Then
    strPath = Application.FileDialog(msoFileDialogOpen).SelectedItems(1)
Else
    Exit Sub
End If

Dim FSO As New Scripting.FileSystemObject
Dim fsoStream As Scripting.TextStream
Dim strLine As String

Set fsoStream = FSO.OpenTextFile(strPath)

Do Until fsoStream.AtEndOfStream = True
    strLine = fsoStream.ReadLine
    ' ... do your work ...
Loop

fsoStream.Close
Set FSO = Nothing

Hope it help!

Best regards

Fabio

how to stop a loop arduino

just use this line to exit function:

return;

Bootstrap row class contains margin-left and margin-right which creates problems

Old topic, but I was recently affected by this.

Using a class "row-fluid" instead of "row" worked fine for me but I'm not sure if it's fully supported going forward.

So after reading Why does the bootstrap .row has a default margin-left of -30px I just used the <div> (without any row class) and it behaved exactly like <div class="row-fluid">

Reflection generic get field value

You should pass the object to get method of the field, so

  Field field = object.getClass().getDeclaredField(fieldName);    
  field.setAccessible(true);
  Object value = field.get(object);

Calling a function on bootstrap modal open

You can use belw code for show and hide bootstrap model.

$('#my-model').on('shown.bs.modal', function (e) {
  // do something here...
})

and if you want to hide model then you can use below code.

$('#my-model').on('hidden.bs.modal', function() {
    // do something here...
});

I hope this answer is useful for your project.

Add an element to an array in Swift

To add to the solutions suggesting append, it's useful to know that this is an amortised constant time operation in many cases:

Complexity: Amortized O(1) unless self's storage is shared with another live array; O(count) if self does not wrap a bridged NSArray; otherwise the efficiency is unspecified.

I'm looking for a cons like operator for Swift. It should return a new immutable array with the element tacked on the end, in constant time, without changing the original array. I've not yet found a standard function that does this. I'll try to remember to report back if I find one!

JDK on OSX 10.7 Lion

You can download jdk6 here http://support.apple.com/kb/DL1573

Wish it helps

How to select rows with no matching entry in another table?

SELECT id FROM table1 WHERE foreign_key_id_column NOT IN (SELECT id FROM table2)

Table 1 has a column that you want to add the foreign key constraint to, but the values in the foreign_key_id_column don't all match up with an id in table 2.

  1. The initial select lists the ids from table1. These will be the rows we want to delete.
  2. The NOT IN clause in the where statement limits the query to only rows where the value in the foreign_key_id_column is not in the list of table 2 ids.
  3. The SELECT statement in parenthesis will get a list of all the ids that are in table 2.

Transpose a range in VBA

Something like this should do it for you.

Sub CombineColumns1()
    Dim xRng As Range
    Dim i As Long, j As Integer
    Dim xNextRow As Long
    Dim xTxt As String
    On Error Resume Next
    With ActiveSheet
        xTxt = .RangeSelection.Address
        Set xRng = Application.InputBox("please select the data range", "Kutools for Excel", xTxt, , , , , 8)
        If xRng Is Nothing Then Exit Sub
        j = xRng.Columns(1).Column
        For i = 4 To xRng.Columns.Count Step 3
            'Need to recalculate the last row, as some of the final columns may not have data in all rows
            xNextRow = .Cells(.Rows.Count, j).End(xlUp).Row + 1

            .Range(xRng.Cells(1, i), xRng.Cells(xRng.Rows.Count, i + 2)).Copy .Cells(xNextRow, j)
            .Range(xRng.Cells(1, i), xRng.Cells(xRng.Rows.Count, i + 2)).Clear
        Next
    End With
End Sub

You could do this too.

Sub TransposeFormulas()
    Dim vFormulas As Variant
    Dim oSel As Range
    If TypeName(Selection) <> "Range" Then
        MsgBox "Please select a range of cells first.", _
                vbOKOnly + vbInformation, "Transpose formulas"
        Exit Sub
    End If
    Set oSel = Selection
    vFormulas = oSel.Formula
    vFormulas = Application.WorksheetFunction.Transpose(vFormulas)
    oSel.Offset(oSel.Rows.Count + 2).Resize(oSel.Columns.Count, oSel.Rows.Count).Formula = vFormulas
End Sub

See this for more info.

http://bettersolutions.com/vba/arrays/transposing.htm

In Android, how do I set margins in dp programmatically?

Simple Kotlin Extension Solutions

Set all/any side independently:

fun View.setMargin(left: Int? = null, top: Int? = null, right: Int? = null, bottom: Int? = null) {
    val params = (layoutParams as? MarginLayoutParams)
    params?.setMargins(
            left ?: params.leftMargin,
            top ?: params.topMargin,
            right ?: params.rightMargin,
            bottom ?: params.bottomMargin)
    layoutParams = params
}

myView.setMargin(10, 5, 10, 5)
// or just any subset
myView.setMargin(right = 10, bottom = 5)

Directly refer to a resource values:

fun View.setMarginRes(@DimenRes left: Int? = null, @DimenRes top: Int? = null, @DimenRes right: Int? = null, @DimenRes bottom: Int? = null) {
    setMargin(
            if (left == null) null else resources.getDimensionPixelSize(left),
            if (top == null) null else resources.getDimensionPixelSize(top),
            if (right == null) null else resources.getDimensionPixelSize(right),
            if (bottom == null) null else resources.getDimensionPixelSize(bottom),
    )
}

myView.setMarginRes(top = R.dimen.my_margin_res)

To directly set all sides equally as a property:

var View.margin: Int
    get() = throw UnsupportedOperationException("No getter for property")
    set(@Px margin) = setMargin(margin, margin, margin, margin)
   
myView.margin = 10 // px

// or as res
var View.marginRes: Int
    get() = throw UnsupportedOperationException("No getter for property")
    set(@DimenRes marginRes) {
        margin = resources.getDimensionPixelSize(marginRes)
    }

myView.marginRes = R.dimen.my_margin_res

To directly set a specific side, you can create a property extension like this:

var View.leftMargin
    get() = marginLeft
    set(@Px leftMargin) = setMargin(left = leftMargin)

var View.leftMarginRes: Int
    get() = throw UnsupportedOperationException("No getter for property")
    set(@DimenRes leftMarginRes) {
        leftMargin = resources.getDimensionPixelSize(leftMarginRes)
    }

This allows you to make horizontal or vertical variants as well:

var View.horizontalMargin
    get() = throw UnsupportedOperationException("No getter for property")
    set(@Px horizontalMargin) = setMargin(left = horizontalMargin, right = horizontalMargin)

var View.horizontalMarginRes: Int
    get() = throw UnsupportedOperationException("No getter for property")
    set(@DimenRes horizontalMarginRes) {
        horizontalMargin = resources.getDimensionPixelSize(horizontalMarginRes)
    }

NOTE: If margin is failing to set, you may too soon before render, meaning params == null. Try wrapping the modification with myView.post{ margin = 10 }

Can jQuery read/write cookies to a browser?

The default JavaScript "API" for setting a cookie is as easy as:

document.cookie = 'mycookie=valueOfCookie;expires=DateHere;path=/'

Use the jQuery cookie plugin like:

$.cookie('mycookie', 'valueOfCookie')

How to get all count of mongoose model?

The collection.count is deprecated, and will be removed in a future version. Use collection.countDocuments or collection.estimatedDocumentCount instead.

userModel.countDocuments(query).exec((err, count) => {
    if (err) {
        res.send(err);
        return;
    }

    res.json({ count: count });
});

Python lookup hostname from IP with 1 second timeout

What you're trying to accomplish is called Reverse DNS lookup.

socket.gethostbyaddr("IP") 
# => (hostname, alias-list, IP)

http://docs.python.org/library/socket.html?highlight=gethostbyaddr#socket.gethostbyaddr

However, for the timeout part I have read about people running into problems with this. I would check out PyDNS or this solution for more advanced treatment.

What is the best regular expression to check if a string is a valid URL?

For convenience here's a one-liner regexp for URL's that will also match localhost where you're more likely to have ports than .com or similar.

(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}(\.[a-z]{2,6}|:[0-9]{3,4})\b([-a-zA-Z0-9@:%_\+.~#?&\/\/=]*)

How to change indentation in Visual Studio Code?

How to turn 4 spaces indents in all files in VS Code to 2 spaces

  • Open file search
  • Turn on Regular Expressions
  • Enter: ( {2})(?: {2})(\b|(?!=[,'";\.:\*\\\/\{\}\[\]\(\)])) in the search field
  • Enter: $1 in the replace field

How to turn 2 spaces indents in all files in VS Code to 4 spaces

  • Open file search
  • Turn on Regular Expressions
  • Enter: ( {2})(\b|(?!=[,'";\.:\\*\\\/{\}\[\]\(\)])) in the search field
  • Enter: $1$1 in the replace field

NOTE: You must turn on PERL Regex first. This is How:

  • Open settings and go to the JSON file
  • add the following to the JSON file "search.usePCRE2": true

Hope someone sees this.

round a single column in pandas

You are very close. You applied the round to the series of values given by df.value1. The return type is thus a Series. You need to assign that series back to the dataframe (or another dataframe with the same Index).

Also, there is a pandas.Series.round method which is basically a short hand for pandas.Series.apply(np.round).

In[2]: 
    df.value1 = df.value1.round()
    print df

Out[2]:
    item  value1  value2
    0    a       1     1.3
    1    a       2     2.5
    2    a       0     0.0
    3    b       3    -1.0
    4    b       5    -1.0

stdlib and colored output in C

Dealing with colour sequences can get messy and different systems might use different Colour Sequence Indicators.

I would suggest you try using ncurses. Other than colour, ncurses can do many other neat things with console UI.

Should black box or white box testing be the emphasis for testers?

What constitutes, "internal knowledge?" Does knowing that such-and-such algorithm was used to solve a problem qualify or does the tester have to see every line of code for it to be "internal?"

I think in any test case, there should be expected results given by the specification used and not determined by how the tester decides to interpret the specification as this can lead to issues where each thinks they are right and blaming the other for the problem.

Call parent method from child class c#

One way to do this would be to pass the instance of ParentClass to the ChildClass on construction

public ChildClass
{
    private ParentClass parent;

    public ChildClass(ParentClass parent)
    {
        this.parent = parent;
    }

    public void LoadData(DateTable dt)
    {
       // do something
       parent.CurrentRow++; // or whatever.
       parent.UpdateProgressBar(); // Call the method
    }
}

Make sure to pass the reference to this when constructing ChildClass inside parent:

if(loadData){

     ChildClass childClass = new ChildClass(this); // here

     childClass.LoadData(this.Datatable);

}

Caveat: This is probably not the best way to organise your classes, but it directly answers your question.

EDIT: In the comments you mention that more than 1 parent class wants to use ChildClass. This is possible with the introduction of an interface, eg:

public interface IParentClass
{
    void UpdateProgressBar();
    int CurrentRow{get; set;}
}

Now, make sure to implement that interface on both (all?) Parent Classes and change child class to this:

public ChildClass
{
    private IParentClass parent;

    public ChildClass(IParentClass parent)
    {
        this.parent = parent;
    }

    public void LoadData(DateTable dt)
    {
       // do something
       parent.CurrentRow++; // or whatever.
       parent.UpdateProgressBar(); // Call the method
    }
}

Now anything that implements IParentClass can construct an instance of ChildClass and pass this to its constructor.

What is the difference between a web API and a web service?

Two things are very simple to understand,

  1. API: It's an layer on application which can serve other application request locally.
  2. Webs Service:Is an API which can serve request and respond over the network form remote system over the web or internet .

Note: All Web Service is API's but not all API' is web services

Getting the text from a drop-down box

Attaches a change event to the select that gets the text for each selected option and writes them in the div.

You can use jQuery it very face and successful and easy to use

<select name="sweets" multiple="multiple">
  <option>Chocolate</option>
  <option>Candy</option>
  <option>Taffy</option>
  <option selected="selected">Caramel</option>
  <option>Fudge</option>
  <option>Cookie</option>
</select>
<div></div>


$("select").change(function () {
  var str = "";

  $("select option:selected").each(function() {
    str += $( this ).text() + " ";
  });

  $( "div" ).text( str );
}).change();

Use RSA private key to generate public key?

People looking for SSH public key...

If you're looking to extract the public key for use with OpenSSH, you will need to get the public key a bit differently

$ ssh-keygen -y -f mykey.pem > mykey.pub

This public key format is compatible with OpenSSH. Append the public key to remote:~/.ssh/authorized_keys and you'll be good to go


docs from SSH-KEYGEN(1)

ssh-keygen -y [-f input_keyfile]  

-y This option will read a private OpenSSH format file and print an OpenSSH public key to stdout.

What is the Maximum Size that an Array can hold?

Here is an answer to your question that goes into detail: http://www.velocityreviews.com/forums/t372598-maximum-size-of-byte-array.html

You may want to mention which version of .NET you are using and your memory size.

You will be stuck to a 2G, for your application, limit though, so it depends on what is in your array.

open cv error: (-215) scn == 3 || scn == 4 in function cvtColor

I also found if your webcam didnt close right or something is using it, then CV2 will give this same error. I had to restart my pc to get it to work again.

How to pip install a package with min and max version range?

An elegant method would be to use the ~= compatible release operator according to PEP 440. In your case this would amount to:

package~=0.5.0

As an example, if the following versions exist, it would choose 0.5.9:

  • 0.5.0
  • 0.5.9
  • 0.6.0

For clarification, each pair is equivalent:

~= 0.5.0
>= 0.5.0, == 0.5.*

~= 0.5
>= 0.5, == 0.*

How to get a DOM Element from a JQuery Selector

I needed to get the element as a string.

jQuery("#bob").get(0).outerHTML;

Which will give you something like:

<input type="text" id="bob" value="hello world" />

...as a string rather than a DOM element.

How do I migrate an SVN repository with history to a new Git repository?

You have to Install

git
git-svn

Copied from this link http://john.albin.net/git/convert-subversion-to-git.

1. Retrieve a list of all Subversion committers

Subversion simply lists the username for each commit. Git’s commits have much richer data, but at its simplest, the commit author needs to have a name and email listed. By default the git-svn tool will just list the SVN username in both the author and email fields. But with a little bit of work, you can create a list of all SVN users and what their corresponding Git name and emails are. This list can be used by git-svn to transform plain svn usernames into proper Git committers.

From the root of your local Subversion checkout, run this command:

svn log -q | awk -F '|' '/^r/ {sub("^ ", "", $2); sub(" $", "", $2); print $2" = "$2" <"$2">"}' | sort -u > authors-transform.txt

That will grab all the log messages, pluck out the usernames, eliminate any duplicate usernames, sort the usernames and place them into a “authors-transform.txt” file. Now edit each line in the file. For example, convert:

jwilkins = jwilkins <jwilkins>

into this:

jwilkins = John Albin Wilkins <[email protected]>

2. Clone the Subversion repository using git-svn

git svn clone [SVN repo URL] --no-metadata -A authors-transform.txt --stdlayout ~/temp

This will do the standard git-svn transformation (using the authors-transform.txt file you created in step 1) and place the git repository in the “~/temp” folder inside your home directory.

3. Convert svn:ignore properties to .gitignore

If your svn repo was using svn:ignore properties, you can easily convert this to a .gitignore file using:

cd ~/temp
git svn show-ignore > .gitignore
git add .gitignore
git commit -m 'Convert svn:ignore properties to .gitignore.'

4. Push repository to a bare git repository

First, create a bare repository and make its default branch match svn’s “trunk” branch name.

git init --bare ~/new-bare.git
cd ~/new-bare.git
git symbolic-ref HEAD refs/heads/trunk

Then push the temp repository to the new bare repository.

cd ~/temp
git remote add bare ~/new-bare.git
git config remote.bare.push 'refs/remotes/*:refs/heads/*'
git push bare

You can now safely delete the ~/temp repository.

5. Rename “trunk” branch to “master”

Your main development branch will be named “trunk” which matches the name it was in Subversion. You’ll want to rename it to Git’s standard “master” branch using:

cd ~/new-bare.git
git branch -m trunk master

6. Clean up branches and tags

git-svn makes all of Subversions tags into very-short branches in Git of the form “tags/name”. You’ll want to convert all those branches into actual Git tags using:

cd ~/new-bare.git
git for-each-ref --format='%(refname)' refs/heads/tags |
cut -d / -f 4 |
while read ref
do
  git tag "$ref" "refs/heads/tags/$ref";
  git branch -D "tags/$ref";
done

This step will take a bit of typing. :-) But, don’t worry; your unix shell will provide a > secondary prompt for the extra-long command that starts with git for-each-ref.

How to prevent form from being submitted?

For prevent form from submittion you only need to do this.

<form onsubmit="event.preventDefault()">
    .....
</form>

By using above code this will prevent your form submittion.

How to print struct variables in console?

Without using external libraries and with new line after each field:

log.Println(
            strings.Replace(
                fmt.Sprintf("%#v", post), ", ", "\n", -1))

How to match hyphens with Regular Expression?

Is this what you are after?

MatchCollection matches = Regex.Matches(mystring, "-");

How do you connect to a MySQL database using Oracle SQL Developer?

Under Tools > Preferences > Databases there is a third party JDBC driver path that must be setup. Once the driver path is setup a separate 'MySQL' tab should appear on the New Connections dialog.

Note: This is the same jdbc connector that is available as a JAR download from the MySQL website.

How to select data of a table from another database in SQL Server?

In SQL Server 2012 and above, you don't need to create a link. You can execute directly

SELECT * FROM [TARGET_DATABASE].dbo.[TABLE] AS _TARGET

I don't know whether previous versions of SQL Server work as well

How to keep console window open

If your using Visual Studio just run the application with Crtl + F5 instead of F5. This will leave the console open when it's finished executing.

Is there a "do ... until" in Python?

There's no prepackaged "do-while", but the general Python way to implement peculiar looping constructs is through generators and other iterators, e.g.:

import itertools

def dowhile(predicate):
  it = itertools.repeat(None)
  for _ in it:
    yield
    if not predicate(): break

so, for example:

i=7; j=3
for _ in dowhile(lambda: i<j):
  print i, j
  i+=1; j-=1

executes one leg, as desired, even though the predicate's already false at the start.

It's normally better to encapsulate more of the looping logic into your generator (or other iterator) -- for example, if you often have cases where one variable increases, one decreases, and you need a do/while loop comparing them, you could code:

def incandec(i, j, delta=1):
  while True:
    yield i, j
    if j <= i: break
    i+=delta; j-=delta

which you can use like:

for i, j in incandec(i=7, j=3):
  print i, j

It's up to you how much loop-related logic you want to put inside your generator (or other iterator) and how much you want to have outside of it (just like for any other use of a function, class, or other mechanism you can use to refactor code out of your main stream of execution), but, generally speaking, I like to see the generator used in a for loop that has little (ideally none) "loop control logic" (code related to updating state variables for the next loop leg and/or making tests about whether you should be looping again or not).

Dynamically create and submit form

Yes, you just forgot the quotes ...

$('<form/>').attr('action','form2.html').submit();

How do I cast a JSON Object to a TypeScript class?

I had the same issue and I have found a library that does the job : https://github.com/pleerock/class-transformer.

It works like this :

let jsonObject = response.json() as Object;
let fooInstance = plainToClass(Models.Foo, jsonObject);
return fooInstance;

It supports nested childs but you have to decorate your class's member.

Using group by on two fields and count in SQL

I think you're looking for: SELECT a, b, COUNT(a) FROM tbl GROUP BY a, b

Online SQL syntax checker conforming to multiple databases

I don't know of any such, and my experience is that it doesn't currently exist. Most are side by side comparisons of two databases. That information requires experts in all the databases encountered, which isn't common. Versions depend too, to know what is supported.

ANSI functions are making strides to ensure syntax is supported across databases, but it's dependent on vendors implementing the spec. And to date, they aren't implementing the entire ANSI spec at a time.

But you can crowd source on sites like this one by asking specific questions and including the databases involved and the versions used.

How to iterate through a table rows and get the cell values using jQuery

I got it and explained in below:

//This table with two rows containing each row, one select in first td, and one input tags in second td and second input in third td;

<table id="tableID" class="table table-condensed">
       <thead>
          <tr>
             <th><label>From Group</lable></th>
             <th><label>To Group</lable></th>
             <th><label>Level</lable></th>

           </tr>
       </thead>
         <tbody>
           <tr id="rowCount">
             <td>
               <select >
                 <option value="">select</option>
                 <option value="G1">G1</option>
                 <option value="G2">G2</option>
                 <option value="G3">G3</option>
                 <option value="G4">G4</option>
               </select>
            </td>
            <td>
              <input type="text" id="" value="" readonly="readonly" />
            </td>
            <td>
              <input type="text" value=""  readonly="readonly" />
            </td>
         </tr>
         <tr id="rowCount">
          <td>
            <select >
              <option value="">select</option>
              <option value="G1">G1</option>
              <option value="G2">G2</option>
              <option value="G3">G3</option>
              <option value="G4">G4</option>
           </select>
         </td>
         <td>
           <input type="text" id="" value="" readonly="readonly" />
         </td>
         <td>
           <input type="text" value=""  readonly="readonly" />
         </td>
      </tr>
  </tbody>
</table>

  <button type="button" class="btn btn-default generate-btn search-btn white-font border-6 no-border" id="saveDtls">Save</button>


//call on click of Save button;
 $('#saveDtls').click(function(event) {

  var TableData = []; //initialize array;                           
  var data=""; //empty var;

  //Here traverse and  read input/select values present in each td of each tr, ;
  $("table#tableID > tbody > tr").each(function(row, tr) {

     TableData[row]={
        "fromGroup":  $('td:eq(0) select',this).val(),
        "toGroup": $('td:eq(1) input',this).val(),
        "level": $('td:eq(2) input',this).val()
 };

  //Convert tableData array to JsonData
  data=JSON.stringify(TableData)
  //alert('data'+data); 
  });
});

When should I use Lazy<T>?

From MSDN:

Use an instance of Lazy to defer the creation of a large or resource-intensive object or the execution of a resource-intensive task, particularly when such creation or execution might not occur during the lifetime of the program.

In addition to James Michael Hare's answer, Lazy provides thread-safe initialization of your value. Take a look at LazyThreadSafetyMode enumeration MSDN entry describing various types of thread safety modes for this class.

Is there a foreach loop in Go?

Yes, Range :

The range form of the for loop iterates over a slice or map.

When ranging over a slice, two values are returned for each iteration. The first is the index, and the second is a copy of the element at that index.

Example :

package main

import "fmt"

var pow = []int{1, 2, 4, 8, 16, 32, 64, 128}

func main() {
    for i, v := range pow {
        fmt.Printf("2**%d = %d\n", i, v)
    }

    for i := range pow {
        pow[i] = 1 << uint(i) // == 2**i
    }
    for _, value := range pow {
        fmt.Printf("%d\n", value)
    }
}
  • You can skip the index or value by assigning to _.
  • If you only want the index, drop the , value entirely.

How to get the previous url using PHP

$_SERVER['HTTP_REFERER'] will give you incomplete url.

If you want http://bawse.3owl.com/jayz__magna_carta_holy_grail.php, $_SERVER['HTTP_REFERER'] will give you http://bawse.3owl.com/ only.

How can I add a box-shadow on one side of an element?

This site helped me: https://gist.github.com/ocean90/1268328 (Note that on that site the left and right are reversed as of the date of this post... but they work as expected). They are corrected in the code below.

<!DOCTYPE html>
<html>
    <head>
        <title>Box Shadow</title>

        <style>
            .box {
                height: 150px;
                width: 300px;
                margin: 20px;
                border: 1px solid #ccc;
            }

            .top {
                box-shadow: 0 -5px 5px -5px #333;
            }

            .right {
                box-shadow: 5px 0 5px -5px #333;
            }

            .bottom {
                box-shadow: 0 5px 5px -5px #333;
            }

            .left {
                box-shadow: -5px 0 5px -5px #333;
            }

            .all {
                box-shadow: 0 0 5px #333;
            }
        </style>
    </head>
    <body>
        <div class="box top"></div>
        <div class="box right"></div>
        <div class="box bottom"></div>
        <div class="box left"></div>
        <div class="box all"></div>
    </body>
</html>

How do I send a file as an email attachment using Linux command line?

From looking at man mailx, the mailx program does not have an option for attaching a file. You could use another program such as mutt.

echo "This is the message body" | mutt -a file.to.attach -s "subject of message" [email protected]

Command line options for mutt can be shown with mutt -h.

How to monitor the memory usage of Node.js?

You can use node.js memoryUsage

const formatMemoryUsage = (data) => `${Math.round(data / 1024 / 1024 * 100) / 100} MB`

const memoryData = process.memoryUsage()

const memoryUsage = {
                rss: `${formatMemoryUsage(memoryData.rss)} -> Resident Set Size - total memory allocated for the process execution`,
                heapTotal: `${formatMemoryUsage(memoryData.heapTotal)} -> total size of the allocated heap`,
                heapUsed: `${formatMemoryUsage(memoryData.heapUsed)} -> actual memory used during the execution`,
                external: `${formatMemoryUsage(memoryData.external)} -> V8 external memory`,
}

console.log(memoryUsage)
/*
{
    "rss": "177.54 MB -> Resident Set Size - total memory allocated for the process execution",
    "heapTotal": "102.3 MB -> total size of the allocated heap",
    "heapUsed": "94.3 MB -> actual memory used during the execution",
    "external": "3.03 MB -> V8 external memory"
}
*/