Programs & Examples On #Refactoring databases

If statements for Checkboxes

In VB.Net

If Check1.checked and Not (Check2.checked) Then

ElseIf Check2.Checked and not Check1.Checked then

End If

jquery AJAX and json format

I never had any luck with that approach. I always do this (hope this helps):

var obj = {};

obj.first_name = $("#namec").val();
obj.last_name = $("#surnamec").val();
obj.email = $("#emailc").val();
obj.mobile = $("#numberc").val();
obj.password = $("#passwordc").val();

Then in your ajax:

$.ajax({
        type: "POST",
        url: hb_base_url + "consumer",
        contentType: "application/json",
        dataType: "json",
        data: JSON.stringify(obj),
        success: function(response) {
            console.log(response);
        },
        error: function(response) {
            console.log(response);
        }
    });

Remove characters from a String in Java

Kotlin Solution

Kotlin has a built-in function for this, removeSuffix (Documentation)

var text = "filename.xml"
text = text.removeSuffix(".xml") // "filename"

If the suffix does not exist in the string, it just returns the original

var text = "not_a_filename"
text = text.removeSuffix(".xml") // "not_a_filename"

You can also check out removePrefix and removeSurrounding which are similar

Visual C++ executable and missing MSVCR100d.dll

For me the problem appeared in this situation:

I installed VS2012 and did not need VS2010 anymore. I wanted to get my computer clean and also removed the VS2010 runtime executables, thinking that no other program would use it. Then I wanted to test my DLL by attaching it to a program (let's call it program X). I got the same error message. I thought that I did something wrong when compiling the DLL. However, the real problem was that I attached the DLL to program X, and program X was compiled in VS2010 with debug info. That is why the error was thrown. I recompiled program X in VS2012, and the error was gone.

$.browser is undefined error

The .browser call has been removed in jquery 1.9 have a look at http://jquery.com/upgrade-guide/1.9/ for more details.

String Concatenation using '+' operator

It doesn't - the C# compiler does :)

So this code:

string x = "hello";
string y = "there";
string z = "chaps";
string all = x + y + z;

actually gets compiled as:

string x = "hello";
string y = "there";
string z = "chaps";
string all = string.Concat(x, y, z);

(Gah - intervening edit removed other bits accidentally.)

The benefit of the C# compiler noticing that there are multiple string concatenations here is that you don't end up creating an intermediate string of x + y which then needs to be copied again as part of the concatenation of (x + y) and z. Instead, we get it all done in one go.

EDIT: Note that the compiler can't do anything if you concatenate in a loop. For example, this code:

string x = "";
foreach (string y in strings)
{
    x += y;
}

just ends up as equivalent to:

string x = "";
foreach (string y in strings)
{
    x = string.Concat(x, y);
}

... so this does generate a lot of garbage, and it's why you should use a StringBuilder for such cases. I have an article going into more details about the two which will hopefully answer further questions.

ClassCastException, casting Integer to Double

This means that your ArrayList has integers in some elements. The casting should work unless there's an integer in one of your elements.

One way to make sure that your arraylist has no integers is by declaring it as a Doubles array.

    ArrayList<Double> marks = new ArrayList<Double>();

What is the correct JSON content type?

If you're in a client-side environment, investigating about the cross-browser support is mandatory for a well supported web application.

The right HTTP Content-Type would be application/json, as others already highlighted too, but some clients do not handle it very well, that's why jQuery recommends the default text/html.

Format a message using MessageFormat.format() in Java

You need to use double apostrophe instead of single in the "You''re", eg:

String text = java.text.MessageFormat.format("You''re about to delete {0} rows.", 5);
System.out.println(text);

Android sample bluetooth code to send a simple string via bluetooth

private OutputStream outputStream;
private InputStream inStream;

private void init() throws IOException {
    BluetoothAdapter blueAdapter = BluetoothAdapter.getDefaultAdapter();
    if (blueAdapter != null) {
        if (blueAdapter.isEnabled()) {
            Set<BluetoothDevice> bondedDevices = blueAdapter.getBondedDevices();

            if(bondedDevices.size() > 0) {
                Object[] devices = (Object []) bondedDevices.toArray();
                BluetoothDevice device = (BluetoothDevice) devices[position];
                ParcelUuid[] uuids = device.getUuids();
                BluetoothSocket socket = device.createRfcommSocketToServiceRecord(uuids[0].getUuid());
                socket.connect();
                outputStream = socket.getOutputStream();
                inStream = socket.getInputStream();
            }

            Log.e("error", "No appropriate paired devices.");
        } else {
            Log.e("error", "Bluetooth is disabled.");
        }
    }
}

public void write(String s) throws IOException {
    outputStream.write(s.getBytes());
}

public void run() {
    final int BUFFER_SIZE = 1024;
    byte[] buffer = new byte[BUFFER_SIZE];
    int bytes = 0;
    int b = BUFFER_SIZE;

    while (true) {
        try {
            bytes = inStream.read(buffer, bytes, BUFFER_SIZE - bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

How do I find the last column with data?

I think we can modify the UsedRange code from @Readify's answer above to get the last used column even if the starting columns are blank or not.

So this lColumn = ws.UsedRange.Columns.Count modified to

this lColumn = ws.UsedRange.Column + ws.UsedRange.Columns.Count - 1 will give reliable results always

enter image description here

?Sheet1.UsedRange.Column + Sheet1.UsedRange.Columns.Count - 1

Above line Yields 9 in the immediate window.

Deleting Row in SQLite in Android

Works great!

public void deleteNewMelk(String melkCode) {
    getWritableDatabase().delete(your_table, your_column +"=?", new String[]{melkCode});
}

LINQ where clause with lambda expression having OR clauses and null values returning incomplete results

You are checking Parent properties for null in your delegate. The same should work with lambda expressions too.

List<AnalysisObject> analysisObjects = analysisObjectRepository
        .FindAll()
        .Where(x => 
            (x.ID == packageId) || 
            (x.Parent != null &&
                (x.Parent.ID == packageId || 
                (x.Parent.Parent != null && x.Parent.Parent.ID == packageId)))
        .ToList();

'ng' is not recognized as an internal or external command, operable program or batch file

note: you may lose values once system restarts.

You can also add system environment variables without Admin rights in Windows 10.

Go to Control panel --> user accounts

Change my environment variables

environment variables --> select **Path** and click edit

click **New** and add path to it

now don't restart, close any opened cmd or powershell, reopen cmd and test by ng version command if you see this it is confirmed working fine.

ng version --> Angular cli

hope this helps

Click a button programmatically

in c# this is working :D

protect void button1_Click(object sender, EventArgs e){
    button2_Click(button2, null);
}

protect void button2_Click(object sender, EventeArgs e){
    //some codes here
}

for vb.net

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)   Handles Button1.Click
    Button2_Click(Sender, e)
End Sub

Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs)   Handles Button2.Click
    //some codes here
End Sub

What's the main difference between int.Parse() and Convert.ToInt32

Parse() methods provide the number styles which cannot be used for Convert(). For example:

int i;
bool b = int.TryParse( "123-",
           System.Globalization.NumberStyles.AllowTrailingSign,
           System.Globalization.CultureInfo.InvariantCulture,
           out i);

would parse the numbers with trailing sign so that i == -123
The trailing sign is popular in ERP systems.

Best font for coding

I like Consolas a lot. This top-10 list is a good resource for others. It includes examples and descriptions.

What is the difference between 'classic' and 'integrated' pipeline mode in IIS7?

IIS 6.0 and previous versions :

ASP.NET integrated with IIS via an ISAPI extension, a C API ( C Programming language based API ) and exposed its own application and request processing model.

This effectively exposed two separate server( request / response ) pipelines, one for native ISAPI filters and extension components, and another for managed application components. ASP.NET components would execute entirely inside the ASP.NET ISAPI extension bubble AND ONLY for requests mapped to ASP.NET in the IIS script map configuration.

Requests to non ASP.NET content types:- images, text files, HTML pages, and script-less ASP pages, were processed by IIS or other ISAPI extensions and were NOT visible to ASP.NET.

The major limitation of this model was that services provided by ASP.NET modules and custom ASP.NET application code were NOT available to non ASP.NET requests

What's a SCRIPT MAP ?

Script maps are used to associate file extensions with the ISAPI handler that executes when that file type is requested. The script map also has an optional setting that verifies that the physical file associated with the request exists before allowing the request to be processed

A good example can be seen here

IIS 7 and above

IIS 7.0 and above have been re-engineered from the ground up to provide a brand new C++ API based ISAPI.

IIS 7.0 and above integrates the ASP.NET runtime with the core functionality of the Web Server, providing a unified(single) request processing pipeline that is exposed to both native and managed components known as modules ( IHttpModules )

What this means is that IIS 7 processes requests that arrive for any content type, with both NON ASP.NET Modules / native IIS modules and ASP.NET modules providing request processing in all stages This is the reason why NON ASP.NET content types (.html, static files ) can be handled by .NET modules.

  • You can build new managed modules (IHttpModule) that have the ability to execute for all application content, and provided an enhanced set of request processing services to your application.
  • Add new managed Handlers ( IHttpHandler)

bootstrap jquery show.bs.modal event won't fire

$(document).on('shown.bs.modal','.modal', function () {

/// TODO EVENTS

});

Python executable not finding libpython shared library

This worked for me...

$ sudo apt-get install python2.7-dev

Difference between binary tree and binary search tree

  • Binary search tree: when inorder traversal is made on binary tree, you get sorted values of inserted items
  • Binary tree: no sorted order is found in any kind of traversal

Change Image of ImageView programmatically in Android

Short answer

Just copy an image into your res/drawable folder and use

imageView.setImageResource(R.drawable.my_image);

Details

The variety of answers can cause a little confusion. We have

The methods with Background in their name all belong to the View class, not to ImageView specifically. But since ImageView inherits from View you can use them, too. The methods with Image in their name belong specifically to ImageView.

The View methods all do the same thing as each other (though setBackgroundDrawable() is deprecated), so we will just focus on setBackgroundResource(). Similarly, the ImageView methods all do the same thing, so we will just focus on setImageResource(). The only difference between the methods is they type of parameter you pass in.

Setup

Here is a FrameLayout that contains an ImageView. The ImageView initially doesn't have any image in it. (I only added the FrameLayout so that I could put a border around it. That way you can see the edge of the ImageView.)

enter image description here

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <FrameLayout
        android:id="@+id/frameLayout"
        android:layout_width="250dp"
        android:layout_height="250dp"
        android:background="@drawable/border"
        android:layout_centerInParent="true">

        <ImageView
            android:id="@+id/imageView"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>

    </FrameLayout>
</RelativeLayout>

Below we will compare the different methods.

setImageResource()

If you use ImageView's setImageResource(), then the image keeps its aspect ratio and is resized to fit. Here are two different image examples.

  • imageView.setImageResource(R.drawable.sky);
  • imageView.setImageResource(R.drawable.balloons);

enter image description here

setBackgroundResource()

Using View's setBackgroundResource(), on the other hand, causes the image resource to be stretched to fill the view.

  • imageView.setBackgroundResource(R.drawable.sky);
  • imageView.setBackgroundResource(R.drawable.balloons);

enter image description here

Both

The View's background image and the ImageView's image are drawn separately, so you can set them both.

imageView.setBackgroundResource(R.drawable.sky);
imageView.setImageResource(R.drawable.balloons);

enter image description here

How to randomly select an item from a list?

You could just:

from random import randint

foo = ["a", "b", "c", "d", "e"]

print(foo[randint(0,4)])

How do you use youtube-dl to download live streams (that are live)?

Before, this could be downloaded with streamlink but YouTube changed HLS rewinding with DASH. Therefore the way to do it below (that Prashant Adlinge commented) no longer works for YouTube:

streamlink --hls-live-restart STREAMURL best

More info here

How to move a file?

The accepted answer is not the right one, because the question is not about renaming a file into a file, but moving many files into a directory. shutil.move will do the work, but for this purpose os.rename is useless (as stated on comments) because destination must have an explicit file name.

invalid use of non-static member function

You must make Foo::comparator static or wrap it in a std::mem_fun class object. This is because lower_bounds() expects the comparer to be a class of object that has a call operator, like a function pointer or a functor object. Also, if you are using C++11 or later, you can also do as dwcanillas suggests and use a lambda function. C++11 also has std::bind too.

Examples:

// Binding:
std::lower_bounds(first, last, value, std::bind(&Foo::comparitor, this, _1, _2));
// Lambda:
std::lower_bounds(first, last, value, [](const Bar & first, const Bar & second) { return ...; });

Git update submodules recursively

The way I use is:

git submodule update --init --recursive
git submodule foreach --recursive git fetch
git submodule foreach git merge origin master

How to check if user input is not an int value

Try this one:

    for (;;) {
        if (!sc.hasNextInt()) {
            System.out.println(" enter only integers!: ");
            sc.next(); // discard
            continue;
        }
        choose = sc.nextInt();
        if (choose >= 0) {
            System.out.print("no problem with input");

        } else {
            System.out.print("invalid inputs");

        }
    break;
  }

Controlling number of decimal digits in print output in R

One more solution able to control the how many decimal digits to print out based on needs (if you don't want to print redundant zero(s))

For example, if you have a vector as elements and would like to get sum of it

elements <- c(-1e-05, -2e-04, -3e-03, -4e-02, -5e-01, -6e+00, -7e+01, -8e+02)
sum(elements)
## -876.5432

Apparently, the last digital as 1 been truncated, the ideal result should be -876.54321, but if set as fixed printing decimal option, e.g sprintf("%.10f", sum(elements)), redundant zero(s) generate as -876.5432100000

Following the tutorial here: printing decimal numbers, if able to identify how many decimal digits in the certain numeric number, like here in -876.54321, there are 5 decimal digits need to print, then we can set up a parameter for format function as below:

decimal_length <- 5
formatC(sum(elements), format = "f", digits = decimal_length)
## -876.54321

We can change the decimal_length based on each time query, so it can satisfy different decimal printing requirement.

SQL update fields of one table from fields of another one

I have been working with IBM DB2 database for more then decade and now trying to learn PostgreSQL.

It works on PostgreSQL 9.3.4, but does not work on DB2 10.5:

UPDATE B SET
     COLUMN1 = A.COLUMN1,
     COLUMN2 = A.COLUMN2,
     COLUMN3 = A.COLUMN3
FROM A
WHERE A.ID = B.ID

Note: Main problem is FROM cause that is not supported in DB2 and also not in ANSI SQL.

It works on DB2 10.5, but does NOT work on PostgreSQL 9.3.4:

UPDATE B SET
    (COLUMN1, COLUMN2, COLUMN3) =
               (SELECT COLUMN1, COLUMN2, COLUMN3 FROM A WHERE ID = B.ID)

FINALLY! It works on both PostgreSQL 9.3.4 and DB2 10.5:

UPDATE B SET
     COLUMN1 = (SELECT COLUMN1 FROM A WHERE ID = B.ID),
     COLUMN2 = (SELECT COLUMN2 FROM A WHERE ID = B.ID),
     COLUMN3 = (SELECT COLUMN3 FROM A WHERE ID = B.ID)

Convert js Array() to JSon object for use with JQuery .ajax

There is actuly a difference between array object and JSON object. Instead of creating array object and converting it into a json object(with JSON.stringify(arr)) you can do this:

var sels = //Here is your array of SELECTs
var json = { };

for(var i = 0, l = sels.length; i < l; i++) {
  json[sels[i].id] = sels[i].value;
}

There is no need of converting it into JSON because its already a json object. To view the same use json.toSource();

How to make the python interpreter correctly handle non-ASCII characters in string operations?

For what it was worth, my character set was utf-8 and I had included the classic "# -*- coding: utf-8 -*-" line.

However, I discovered that I didn't have Universal Newlines when reading this data from a webpage.

My text had two words, separated by "\r\n". I was only splitting on the \n and replacing the "\n".

Once I looped through and saw the character set in question, I realized the mistake.

So, it could also be within the ASCII character set, but a character that you didn't expect.

how to check if string contains '+' character

[+]is simpler

    String s = "ddjdjdj+kfkfkf";

    if(s.contains ("+"))
    {
        String parts[] = s.split("[+]");
        s =  parts[0]; // i want to strip part after  +
    }
    System.out.println(s);

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

If you are using WebStorm and you are on Windows i would recommend you to click settings/editor/code style/general tab and select "windows(\r\n) from the dropdown menu.These steps will also apply for Rider.

enter image description here

Computational complexity of Fibonacci Sequence

Recursive algorithm's time complexity can be better estimated by drawing recursion tree, In this case the recurrence relation for drawing recursion tree would be T(n)=T(n-1)+T(n-2)+O(1) note that each step takes O(1) meaning constant time,since it does only one comparison to check value of n in if block.Recursion tree would look like

          n
   (n-1)      (n-2)
(n-2)(n-3) (n-3)(n-4) ...so on

Here lets say each level of above tree is denoted by i hence,

i
0                        n
1            (n-1)                 (n-2)
2        (n-2)    (n-3)      (n-3)     (n-4)
3   (n-3)(n-4) (n-4)(n-5) (n-4)(n-5) (n-5)(n-6)

lets say at particular value of i, the tree ends, that case would be when n-i=1, hence i=n-1, meaning that the height of the tree is n-1. Now lets see how much work is done for each of n layers in tree.Note that each step takes O(1) time as stated in recurrence relation.

2^0=1                        n
2^1=2            (n-1)                 (n-2)
2^2=4        (n-2)    (n-3)      (n-3)     (n-4)
2^3=8   (n-3)(n-4) (n-4)(n-5) (n-4)(n-5) (n-5)(n-6)    ..so on
2^i for ith level

since i=n-1 is height of the tree work done at each level will be

i work
1 2^1
2 2^2
3 2^3..so on

Hence total work done will sum of work done at each level, hence it will be 2^0+2^1+2^2+2^3...+2^(n-1) since i=n-1. By geometric series this sum is 2^n, Hence total time complexity here is O(2^n)

How do I cast a JSON Object to a TypeScript class?

While it is not casting per se; I have found https://github.com/JohnWhiteTB/TypedJSON to be a useful alternative.

@JsonObject
class Person {
    @JsonMember
    firstName: string;

    @JsonMember
    lastName: string;

    public getFullname() {
        return this.firstName + " " + this.lastName;
    }
}
var person = TypedJSON.parse('{ "firstName": "John", "lastName": "Doe" }', Person);

person instanceof Person; // true
person.getFullname(); // "John Doe"

How to increase time in web.config for executing sql query

You should add the httpRuntime block and deal with executionTimeout (in seconds).

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
...
 <system.web>
   <httpRuntime executionTimeout="90" maxRequestLength="4096"
    useFullyQualifiedRedirectUrl="false"
    minFreeThreads="8"
    minLocalRequestFreeThreads="4"
    appRequestQueueLimit="100" />
 </system.web>
... 
</configuration>

For more information, please, see msdn page.

How to download a file using a Java REST service and a data stream

See example here: Input and Output binary streams using JERSEY?

Pseudo code would be something like this (there are a few other similar options in above mentioned post):

@Path("file/")
@GET
@Produces({"application/pdf"})
public StreamingOutput getFileContent() throws Exception {
     public void write(OutputStream output) throws IOException, WebApplicationException {
        try {
          //
          // 1. Get Stream to file from first server
          //
          while(<read stream from first server>) {
              output.write(<bytes read from first server>)
          }
        } catch (Exception e) {
            throw new WebApplicationException(e);
        } finally {
              // close input stream
        }
    }
}

What does the "More Columns than Column Names" error mean?

It uses commas as separators. So you can either set sep="," or just use read.csv:

x <- read.csv(file="http://www.irs.gov/file_source/pub/irs-soi/countyinflow1011.csv")
dim(x)
## [1] 113593      9

The error is caused by spaces in some of the values, and unmatched quotes. There are no spaces in the header, so read.table thinks that there is one column. Then it thinks it sees multiple columns in some of the rows. For example, the first two lines (header and first row):

State_Code_Dest,County_Code_Dest,State_Code_Origin,County_Code_Origin,State_Abbrv,County_Name,Return_Num,Exmpt_Num,Aggr_AGI
00,000,96,000,US,Total Mig - US & For,6973489,12948316,303495582

And unmatched quotes, for example on line 1336 (row 1335) which will confuse read.table with the default quote argument (but not read.csv):

01,089,24,033,MD,Prince George's County,13,30,1040

Finding the max/min value in an array of primitives using Java

You could easily do it with an IntStream and the max() method.

Example

public static int maxValue(final int[] intArray) {
  return IntStream.range(0, intArray.length).map(i -> intArray[i]).max().getAsInt();
}

Explanation

  1. range(0, intArray.length) - To get a stream with as many elements as present in the intArray.

  2. map(i -> intArray[i]) - Map every element of the stream to an actual element of the intArray.

  3. max() - Get the maximum element of this stream as OptionalInt.

  4. getAsInt() - Unwrap the OptionalInt. (You could also use here: orElse(0), just in case the OptionalInt is empty.)

How can I remove the top and right axis in matplotlib?

Library Seaborn has this built in with function .despine().

Just add:

import seaborn as sns

Now create your graph. And add at the end:

sns.despine()

If you look at some of the default parameter values of the function it removes the top and right spine and keeps the bottom and left spine:

sns.despine(top=True, right=True, left=False, bottom=False)

Check out further documentation here: https://seaborn.pydata.org/generated/seaborn.despine.html

How to run or debug php on Visual Studio Code (VSCode)

There is a much easier way to run PHP, no configuration needed:

  1. Install the Code Runner Extension
  2. Open the PHP code file in Text Editor
    • use shortcut Ctrl+Alt+N
    • or press F1 and then select/type Run Code,
    • or right click the Text Editor and then click Run Code in editor context menu
    • or click Run Code button in editor title menu
    • or click Run Code button in context menu of file explorer

Besides, you could select part of the PHP code and run the code snippet. Very convenient!

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') });
    }
};

Any way to break if statement in PHP?

i have a simple solution without lot of changes. the initial statement is

I want to break the if statement above and stop executing echo "yes"; or such codes which are no longer necessary to be executed, there may be or may not be an additional condition, is there way to do this?

so, it seem simple. try code like this.

$a="test";
if("test"==$a)
{
  if (1==0){
      echo "yes"; // this line while never be executed. 
      // and can be reexecuted simply by changing if (1==0) to if (1==1) 
  }
}
echo "finish";

if you want to try without this code, it's simple. and you can back when you want. another solution is comment blocks. or simply thinking and try in another separated code and copy paste only the result in your final code. and if a code is no longer nescessary, in your case, the result can be

$a="test";
echo "finish";

with this code, the original statement is completely respected.. :) and more readable!

How to set shadows in React Native for android?

You can try

//ios    
shadowOpacity: 0.3,
shadowRadius: 3,
shadowOffset: {
    height: 0,
    width: 0
},
//android
elevation: 1

How to check if a process is running via a batch script

Another possibility I came up with, inspired by using grep, is:

tasklist /FI "IMAGENAME eq myapp.exe" 2>NUL | find /I /N "myapp.exe">NUL
if "%ERRORLEVEL%"=="0" echo Program is running

It doesn't need to save an extra file, so I prefer this method.

Finding an item in a List<> using C#

You have a few options:

  1. Using Enumerable.Where:

    list.Where(i => i.Property == value).FirstOrDefault();       // C# 3.0+
    
  2. Using List.Find:

    list.Find(i => i.Property == value);                         // C# 3.0+
    list.Find(delegate(Item i) { return i.Property == value; }); // C# 2.0+
    

Both of these options return default(T) (null for reference types) if no match is found.

As mentioned in the comments below, you should use the appropriate form of comparison for your scenario:

  • == for simple value types or where use of operator overloads are desired
  • object.Equals(a,b) for most scenarios where the type is unknown or comparison has potentially been overridden
  • string.Equals(a,b,StringComparison) for comparing strings
  • object.ReferenceEquals(a,b) for identity comparisons, which are usually the fastest

How to set an HTTP proxy in Python 2.7?

For installing pip with get-pip.py behind a proxy I went with the steps below. My server was even behind a jump server.

From the jump server:

ssh -R 18080:proxy-server:8080 my-python-server

On the "python-server"

export https_proxy=https://localhost:18080 ; export http_proxy=http://localhost:18080 ; export ftp_proxy=$http_proxy
python get-pip.py

Success.

Google Maps API warning: NoApiKeys

Google maps requires an API key for new projects since june 2016. For more information take a look at the Google Developers Blog. Also more information in german you'll find at this blog post from the clickstorm Blog.

How do I install and use curl on Windows?

Follow download wizard

Follow the screens one by one to select type of package (curl executable), OS (Win64), flavor (Generic), CPU (x86_64) and the download link.

unzip download and find curl.exe (I found it in src folder, one may find it in bin folder for different OS/flavor)

To make it available from the command line, add the executable path to the system path (Adding directory to PATH Environment Variable in Windows).

Enjoy curl.

beyond top level package error in relative import

Assumption:
If you are in the package directory, A and test_A are separate packages.

Conclusion:
..A imports are only allowed within a package.

Further notes:
Making the relative imports only available within packages is useful if you want to force that packages can be placed on any path located on sys.path.

EDIT:

Am I the only one who thinks that this is insane!? Why in the world is the current working directory not considered to be a package? – Multihunter

The current working directory is usually located in sys.path. So, all files there are importable. This is behavior since Python 2 when packages did not yet exist. Making the running directory a package would allow imports of modules as "import .A" and as "import A" which then would be two different modules. Maybe this is an inconsistency to consider.

How to set an "Accept:" header on Spring RestTemplate request?

You could set an interceptor "ClientHttpRequestInterceptor" in your RestTemplate to avoid setting the header every time you send a request.

public class HeaderRequestInterceptor implements ClientHttpRequestInterceptor {

        private final String headerName;

        private final String headerValue;

        public HeaderRequestInterceptor(String headerName, String headerValue) {
            this.headerName = headerName;
            this.headerValue = headerValue;
        }

        @Override
        public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
            request.getHeaders().set(headerName, headerValue);
            return execution.execute(request, body);
        }
    }

Then

List<ClientHttpRequestInterceptor> interceptors = new ArrayList<ClientHttpRequestInterceptor>();
interceptors.add(new HeaderRequestInterceptor("Accept", MediaType.APPLICATION_JSON_VALUE));

RestTemplate restTemplate = new RestTemplate();
restTemplate.setInterceptors(interceptors);

Fit image into ImageView, keep aspect ratio and then resize ImageView to image dimensions?

Use Simple math to resize the image . either you can resize ImageView or you can resize drawable image than set on ImageView . find the width and height of your bitmap which you want to set on ImageView and call the desired method. suppose your width 500 is greater than height than call method

//250 is the width you want after resize bitmap
Bitmat bmp = BitmapScaler.scaleToFitWidth(bitmap, 250) ;
ImageView image = (ImageView) findViewById(R.id.picture);
image.setImageBitmap(bmp);

You use this class for resize bitmap.

public class BitmapScaler{
// Scale and maintain aspect ratio given a desired width
// BitmapScaler.scaleToFitWidth(bitmap, 100);
 public static Bitmap scaleToFitWidth(Bitmap b, int width)
  {
    float factor = width / (float) b.getWidth();
    return Bitmap.createScaledBitmap(b, width, (int) (b.getHeight() * factor), true);
  }


  // Scale and maintain aspect ratio given a desired height
  // BitmapScaler.scaleToFitHeight(bitmap, 100);
  public static Bitmap scaleToFitHeight(Bitmap b, int height)
  {
    float factor = height / (float) b.getHeight();
    return Bitmap.createScaledBitmap(b, (int) (b.getWidth() * factor), height, true);
   }
 }

xml code is

<ImageView
android:id="@+id/picture"
android:layout_width="250dp"
android:layout_height="250dp"
android:layout_gravity="center_horizontal"
android:layout_marginTop="20dp"
android:adjustViewBounds="true"
android:scaleType="fitcenter" />

Deploying Maven project throws java.util.zip.ZipException: invalid LOC header (bad signature)

The solution for me was to run mvn with -X:

$ mvn package -X

Then look backwards through the output until you see the failure and then keep going until you see the last jar file that mvn tried to process:

...
... <<output ommitted>>
...
[DEBUG] Processing JAR /Users/snowch/.m2/repository/org/eclipse/jetty/jetty-server/9.2.15.v20160210/jetty-server-9.2.15.v20160210.jar
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 3.607 s
[INFO] Finished at: 2017-10-04T14:30:13+01:00
[INFO] Final Memory: 23M/370M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-shade-plugin:3.1.0:shade (default) on project kafka-connect-on-cloud-foundry: Error creating shaded jar: invalid LOC header (bad signature) -> [Help 1]
org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.apache.maven.plugins:maven-shade-plugin:3.1.0:shade (default) on project kafka-connect-on-cloud-foundry: Error creating shaded jar: invalid LOC header (bad signature)

Look at the last jar before it failed and remove that from the local repository, i.e.

$ rm -rf /Users/snowch/.m2/repository/org/eclipse/jetty/jetty-server/9.2.15.v20160210/

How to convert BigInteger to String in java

//How to solve BigDecimal & BigInteger and return a String.

  BigDecimal x = new BigDecimal( a );
  BigDecimal y = new BigDecimal( b ); 
  BigDecimal result = BigDecimal.ZERO;
  BigDecimal result = x.add(y);
  return String.valueOf(result); 

Converting HTML to Excel?

We copy/paste html pages from our ERP to Excel using "paste special.. as html/unicode" and it works quite well with tables.

How to run ~/.bash_profile in mac terminal

If you change .bash_profile, it only applies to new Terminal sessions.

To apply it to an existing session, run source ~/.bash_profile. You can run any Bash script this way - think of executing source as the same as typing commands in the Terminal window (from the specified script).

More info: How to reload .bash_profile from the command line?

Bonus: You can make environment variables available to OSX applications - not just the current Bash session but apps like Visual Studio Code or IntelliJ - using launchctl setenv GOPATH "${GOPATH:-}"

Word wrap for a label in Windows Forms

I had to find a quick solution, so I just used a TextBox with those properties:

var myLabel = new TextBox
                    {
                        Text = "xxx xxx xxx",
                        WordWrap = true,
                        AutoSize = false,
                        Enabled = false,
                        Size = new Size(60, 30),
                        BorderStyle = BorderStyle.None,
                        Multiline =  true,
                        BackColor =  container.BackColor
                    };

Jquery checking success of ajax post

If you need a failure function, you can't use the $.get or $.post functions; you will need to call the $.ajax function directly. You pass an options object that can have "success" and "error" callbacks.

Instead of this:

$.post("/post/url.php", parameters, successFunction);

you would use this:

$.ajax({
    url: "/post/url.php",
    type: "POST",
    data: parameters,
    success: successFunction,
    error: errorFunction
});

There are lots of other options available too. The documentation lists all the options available.

Shell Script — Get all files modified after <date>

This will work for some number of files. You want to include "-print0" and "xargs -0" in case any of the paths have spaces in them. This example looks for files modified in the last 7 days. To find those modified before the last 7 days, use "+7".

find . -mtime -7 -print0 | xargs -0 tar -cjf /foo/archive.tar.bz2

As this page warns, xargs can cause the tar command to be executed multiple times if there are a lot of arguments, and the "-c" flag could cause problems. In that case, you would want this:

find . -mtime -7 -print0 | xargs -0 tar -rf /foo/archive.tar

You can't update a zipped tar archive with tar, so you would have to bzip2 or gzip it in a second step.

How do I Geocode 20 addresses without receiving an OVER_QUERY_LIMIT response?

I'm facing the same problem trying to geocode 140 addresses.

My workaround was adding usleep(100000) for each loop of next geocoding request. If status of the request is OVER_QUERY_LIMIT, the usleep is increased by 50000 and request is repeated, and so on.

And of cause all received data (lat/long) are stored in XML file not to run request every time the page is loading.

How to get the device's IMEI/ESN programmatically in android?

use below code:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        String[] permissions = {Manifest.permission.READ_PHONE_STATE};
        if (ActivityCompat.checkSelfPermission(this,
                Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(permissions, READ_PHONE_STATE);
        }
    } else {
        try {
            TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
                return;
            }
            String imei = telephonyManager.getDeviceId();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

And call onRequestPermissionsResult method following code:

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    switch (requestCode) {
        case READ_PHONE_STATE:
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED)
                try {
                    TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
                    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
                        return;
                    }
                    String imei = telephonyManager.getDeviceId();

                } catch (Exception e) {
                    e.printStackTrace();
                }
    }
}

Add following permission in your AndroidManifest.xml:

<uses-permission android:name="android.permission.READ_PHONE_STATE" />

Javascript: 'window' is not defined

The window object represents an open window in a browser. Since you are not running your code within a browser, but via Windows Script Host, the interpreter won't be able to find the window object, since it does not exist, since you're not within a web browser.

Get the previous month's first and last day dates in c#

The canonical use case in e-commerce is credit card expiration dates, MM/yy. Subtract one second instead of one day. Otherwise the card will appear expired for the entire last day of the expiration month.

DateTime expiration = DateTime.Parse("07/2013");
DateTime endOfTheMonthExpiration = new DateTime(
  expiration.Year, expiration.Month, 1).AddMonths(1).AddSeconds(-1);

VBA Date as integer

Just use CLng(Date).

Note that you need to use Long not Integer for this as the value for the current date is > 32767

How do I get the MAX row with a GROUP BY in LINQ query?

This can be done using GroupBy and SelectMany in LINQ lamda expression

var groupByMax = list.GroupBy(x=>x.item1).SelectMany(y=>y.Where(z=>z.item2 == y.Max(i=>i.item2)));

How to add default value for html <textarea>?

Please note that if you made changes to textarea, after it had rendered; You will get the updated value instead of the initialized value.

<!doctype html>
<html lang="en">
    <head>
        <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
        <script>
            $(function () {
                $('#btnShow').click(function () {
                    alert('text:' + $('#addressFieldName').text() + '\n value:' + $('#addressFieldName').val());
                });
            });
            function updateAddress() {
                $('#addressFieldName').val('District: Peshawar \n');
            }
        </script>
    </head>
    <body>
        <?php
        $address = "School: GCMHSS NO.1\nTehsil: ,\nDistrict: Haripur";
        ?>
        <textarea id="addressFieldName" rows="4" cols="40" tabindex="5" ><?php echo $address; ?></textarea>
        <?php echo '<script type="text/javascript">updateAddress();</script>'; ?>
        <input type="button" id="btnShow" value='show' />
    </body>
</html>

As you can see the value of textarea will be different than the text in between the opening and closing tag of concern textarea.

Sending POST parameters with Postman doesn't work, but sending GET parameters does

I faced the same issue in PostMan and Advance REST Client both. I checked through fiddler and found that my request payload is not converted into JSON format.

I am passing my data in Body as x-www-form-urlencoded enter image description here

You can fix it by using Content-Type as application/x-www-form-urlencoded in request header. enter image description here

Check if a string within a list contains a specific string with Linq

I think you want Any:

if (myList.Any(str => str.Contains("Mdd LH")))

It's well worth becoming familiar with the LINQ standard query operators; I would usually use those rather than implementation-specific methods (such as List<T>.ConvertAll) unless I was really bothered by the performance of a specific operator. (The implementation-specific methods can sometimes be more efficient by knowing the size of the result etc.)

How to convert float to varchar in SQL Server

float only has a max. precision of 15 digits. Digits after the 15th position are therefore random, and conversion to bigint (max. 19 digits) or decimal does not help you.

PHP: How to generate a random, unique, alphanumeric string for use in a secret link?

A simple solution is to convert base 64 to alphanumeric by discarding the non-alphanumeric characters.

This one uses random_bytes() for a cryptographically secure result.

function random_alphanumeric(int $length): string
{
    $result='';
    do
    {
        //Base 64 produces 4 characters for each 3 bytes, so most times this will give enough bytes in a single pass
        $bytes=random_bytes(($length+3-strlen($result))*2);
        //Discard non-alhpanumeric characters
        $result.=str_replace(['/','+','='],['','',''],base64_encode($bytes));
        //Keep adding characters until the string is long enough
        //Add a few extra because the last 2 or 3 characters of a base 64 string tend to be less diverse
    }while(strlen($result)<$length+3);
    return substr($result,0,$length);
}

Edit: I just revisited this because I need something a bit more flexible. Here is a solution that performs a bit better than the above and gives the option to specify any subset of the ASCII character set:

<?php
class RandomText
{
    protected
        $allowedChars,
        //Maximum index to use
        $allowedCount,
        //Index values will be taken from a pool of this size
        //It is a power of 2 to keep the distribution of values even
        $distributionSize,
        //This many characters will be generated for each output character
        $ratio;
    /**
     * @param string $allowedChars characters to choose from
     */
    public function __construct(string $allowedChars)
    {
        $this->allowedCount = strlen($allowedChars);
        if($this->allowedCount < 1 || $this->allowedCount > 256) throw new \Exception('At least 1 and no more than 256 allowed character(s) must be specified.');
        $this->allowedChars = $allowedChars;
        //Find the power of 2 equal or greater than the number of allowed characters
        $this->distributionSize = pow(2,ceil(log($this->allowedCount, 2)));
        //Generating random bytes is the expensive part of this algorithm
        //In most cases some will be wasted so it is helpful to produce some extras, but not too many
        //On average, this is how many characters needed to produce 1 character in the allowed set
        //50% of the time, more characters will be needed. My tests have shown this to perform well.
        $this->ratio = $this->distributionSize / $this->allowedCount;
    }

    /**
     * @param int $length string length of required result
     * @return string random text
     */
    public function get(int $length) : string
    {
        if($length < 1) throw new \Exception('$length must be >= 1.');
        $result = '';
        //Keep track of result length to prevent having to compute strlen()
        $l = 0;
        $indices = null;
        $i = null;
        do
        {
            //Bytes will be used to index the character set. Convert to integers.
            $indices = unpack('C*', random_bytes(ceil(($length - $l) * $this->ratio)));
            foreach($indices as $i)
            {
                //Reduce to the smallest range that gives an even distribution
                $i %= $this->distributionSize;
                //If the index is within the range of characters, add one char to the string
                if($i < $this->allowedCount)
                {
                    $l++;
                    $result .= $this->allowedChars[$i];
                }
                if($l >= $length) break;
            }
        }while($l < $length);
        return $result;
    }
}

Javascript Array of Functions

A short way to run 'em all:

[first_function, ..., nth_function].forEach (function(f) {
    f('a string');
}); 

VBA vlookup reference in different sheet

try this:

Dim ws as Worksheet

Set ws = Thisworkbook.Sheets("Sheet2")

With ws
    .Range("E2").Formula = "=VLOOKUP(D2,Sheet1!$A:$C,1,0)"
End With

End Sub

This just the simplified version of what you want.
No need to use Application if you will just output the answer in the Range("E2").

If you want to stick with your logic, declare the variables.
See below for example.

Sub Test()

Dim rng As Range
Dim ws1, ws2 As Worksheet
Dim MyStringVar1 As String

Set ws1 = ThisWorkbook.Sheets("Sheet1")
Set ws2 = ThisWorkbook.Sheets("Sheet2")
Set rng = ws2.Range("D2")

With ws2
    On Error Resume Next 'add this because if value is not found, vlookup fails, you get 1004
    MyStringVar1 = Application.WorksheetFunction.VLookup(rng, ws1.Range("A1:C65536").Value, 1, False)
    On Error GoTo 0
    If MyStringVar1 = "" Then MsgBox "Item not found" Else MsgBox MyStringVar1
End With

End Sub

Hope this get's you started.

npm ERR! registry error parsing json - While trying to install Cordova for Ionic Framework in Windows 8

I had the same issue and the following fixed my issue:

  1. Set the registry: npm config set registry "http://registry.npmjs.org/"
  2. Removed the entry in hosts file (using Windows 7) => C:\Windows\System32\drivers\etc\hosts

Javascript - Regex to validate date format

Please find in the below code which enables to perform the date validation for any of the supplied format or based on user locale to validate start/from and end/to dates. There could be some better approaches but have come up with this. Have tested it for the formats like: MM/dd/yyyy, dd/MM/yyyy, yyyy-MM-dd, yyyy.MM.dd, yyyy/MM/dd and dd-MM-yyyy.

Note supplied date format and date string go hand in hand.

    <script type="text/javascript">
function validate(format) {

    if(isAfterCurrentDate(document.getElementById('start').value, format)) {
        alert('Date is after the current date.');
    } else {
        alert('Date is not after the current date.');
    }
    if(isBeforeCurrentDate(document.getElementById('start').value, format)) {
        alert('Date is before current date.');
    } else {
        alert('Date is not before current date.');
    }
    if(isCurrentDate(document.getElementById('start').value, format)) {
        alert('Date is current date.');
    } else {
        alert('Date is not a current date.');
    }
    if (isBefore(document.getElementById('start').value, document.getElementById('end').value, format)) {
        alert('Start/Effective Date cannot be greater than End/Expiration Date');
    } else {
        alert('Valid dates...');
    }
    if (isAfter(document.getElementById('start').value, document.getElementById('end').value, format)) {
        alert('End/Expiration Date cannot be less than Start/Effective Date');
    } else {
        alert('Valid dates...');
    }
    if (isEquals(document.getElementById('start').value, document.getElementById('end').value, format)) {
        alert('Dates are equals...');
    } else {
        alert('Dates are not equals...');
    }
    if (isDate(document.getElementById('start').value, format)) {
        alert('Is valid date...');
    } else {
        alert('Is invalid date...');
    }
}

/**
 * This method gets the year index from the supplied format
 */
function getYearIndex(format) {

    var tokens = splitDateFormat(format);

    if (tokens[0] === 'YYYY'
            || tokens[0] === 'yyyy') {
        return 0;
    } else if (tokens[1]=== 'YYYY'
            || tokens[1] === 'yyyy') {
        return 1;
    } else if (tokens[2] === 'YYYY'
            || tokens[2] === 'yyyy') {
        return 2;
    }
    // Returning the default value as -1
    return -1;
}

/**
 * This method returns the year string located at the supplied index
 */
function getYear(date, index) {

    var tokens = splitDateFormat(date);
    return tokens[index];
}

/**
 * This method gets the month index from the supplied format
 */
function getMonthIndex(format) {

    var tokens = splitDateFormat(format);

    if (tokens[0] === 'MM'
            || tokens[0] === 'mm') {
        return 0;
    } else if (tokens[1] === 'MM'
            || tokens[1] === 'mm') {
        return 1;
    } else if (tokens[2] === 'MM'
            || tokens[2] === 'mm') {
        return 2;
    }
    // Returning the default value as -1
    return -1;
}

/**
 * This method returns the month string located at the supplied index
 */
function getMonth(date, index) {

    var tokens = splitDateFormat(date);
    return tokens[index];
}

/**
 * This method gets the date index from the supplied format
 */
function getDateIndex(format) {

    var tokens = splitDateFormat(format);

    if (tokens[0] === 'DD'
            || tokens[0] === 'dd') {
        return 0;
    } else if (tokens[1] === 'DD'
            || tokens[1] === 'dd') {
        return 1;
    } else if (tokens[2] === 'DD'
            || tokens[2] === 'dd') {
        return 2;
    }
    // Returning the default value as -1
    return -1;
}

/**
 * This method returns the date string located at the supplied index
 */
function getDate(date, index) {

    var tokens = splitDateFormat(date);
    return tokens[index];
}

/**
 * This method returns true if date1 is before date2 else return false
 */
function isBefore(date1, date2, format) {
    // Validating if date1 date is greater than the date2 date
    if (new Date(getYear(date1, getYearIndex(format)), 
            getMonth(date1, getMonthIndex(format)) - 1, 
            getDate(date1, getDateIndex(format))).getTime()
        > new Date(getYear(date2, getYearIndex(format)), 
            getMonth(date2, getMonthIndex(format)) - 1, 
            getDate(date2, getDateIndex(format))).getTime()) {
        return true;
    } 
    return false;                
}

/**
 * This method returns true if date1 is after date2 else return false
 */
function isAfter(date1, date2, format) {
    // Validating if date2 date is less than the date1 date
    if (new Date(getYear(date2, getYearIndex(format)), 
            getMonth(date2, getMonthIndex(format)) - 1, 
            getDate(date2, getDateIndex(format))).getTime()
        < new Date(getYear(date1, getYearIndex(format)), 
            getMonth(date1, getMonthIndex(format)) - 1, 
            getDate(date1, getDateIndex(format))).getTime()
        ) {
        return true;
    } 
    return false;                
}

/**
 * This method returns true if date1 is equals to date2 else return false
 */
function isEquals(date1, date2, format) {
    // Validating if date1 date is equals to the date2 date
    if (new Date(getYear(date1, getYearIndex(format)), 
            getMonth(date1, getMonthIndex(format)) - 1, 
            getDate(date1, getDateIndex(format))).getTime()
        === new Date(getYear(date2, getYearIndex(format)), 
            getMonth(date2, getMonthIndex(format)) - 1, 
            getDate(date2, getDateIndex(format))).getTime()) {
        return true;
    } 
    return false;
}

/**
 * This method validates and returns true if the supplied date is 
 * equals to the current date.
 */
function isCurrentDate(date, format) {
    // Validating if the supplied date is the current date
    if (new Date(getYear(date, getYearIndex(format)), 
            getMonth(date, getMonthIndex(format)) - 1, 
            getDate(date, getDateIndex(format))).getTime()
        === new Date(new Date().getFullYear(), 
                new Date().getMonth(), 
                new Date().getDate()).getTime()) {
        return true;
    } 
    return false;                
}

/**
 * This method validates and returns true if the supplied date value 
 * is before the current date.
 */
function isBeforeCurrentDate(date, format) {
    // Validating if the supplied date is before the current date
    if (new Date(getYear(date, getYearIndex(format)), 
            getMonth(date, getMonthIndex(format)) - 1, 
            getDate(date, getDateIndex(format))).getTime()
        < new Date(new Date().getFullYear(), 
                new Date().getMonth(), 
                new Date().getDate()).getTime()) {
        return true;
    } 
    return false;                
}

/**
 * This method validates and returns true if the supplied date value 
 * is after the current date.
 */
function isAfterCurrentDate(date, format) {
    // Validating if the supplied date is before the current date
    if (new Date(getYear(date, getYearIndex(format)), 
            getMonth(date, getMonthIndex(format)) - 1, 
            getDate(date, getDateIndex(format))).getTime()
        > new Date(new Date().getFullYear(),
                new Date().getMonth(), 
                new Date().getDate()).getTime()) {
        return true;
    } 
    return false;                
}

/**
 * This method splits the supplied date OR format based 
 * on non alpha numeric characters in the supplied string.
 */
function splitDateFormat(dateFormat) {
    // Spliting the supplied string based on non characters
    return dateFormat.split(/\W/);
}

/*
 * This method validates if the supplied value is a valid date.
 */
function isDate(date, format) {                
    // Validating if the supplied date string is valid and not a NaN (Not a Number)
    if (!isNaN(new Date(getYear(date, getYearIndex(format)), 
            getMonth(date, getMonthIndex(format)) - 1, 
            getDate(date, getDateIndex(format))))) {                    
        return true;
    } 
    return false;                                      
}

Below is the HTML snippet

    <input type="text" name="start" id="start" size="10" value="05/31/2016" />
    <br/> 
    <input type="text" name="end" id="end" size="10" value="04/28/2016" />
    <br/>
    <input type="button" value="Submit" onclick="javascript:validate('MM/dd/yyyy');" />

gpg failed to sign the data fatal: failed to write commit object [Git 2.10.0]

Very much like @birchlabs, after a lot of digging/searching I found that it wasn't GPG, but rather GPG Suite. I did cask reinstall gpg-suite and it solved it for me.

C# string reference type?

For curious minds and to complete the conversation: Yes, String is a reference type:

unsafe
{
     string a = "Test";
     string b = a;
     fixed (char* p = a)
     {
          p[0] = 'B';
     }
     Console.WriteLine(a); // output: "Best"
     Console.WriteLine(b); // output: "Best"
}

But note that this change only works in an unsafe block! because Strings are immutable (From MSDN):

The contents of a string object cannot be changed after the object is created, although the syntax makes it appear as if you can do this. For example, when you write this code, the compiler actually creates a new string object to hold the new sequence of characters, and that new object is assigned to b. The string "h" is then eligible for garbage collection.

string b = "h";  
b += "ello";  

And keep in mind that:

Although the string is a reference type, the equality operators (== and !=) are defined to compare the values of string objects, not references.

T-SQL substring - separating first and last name

The code below works with Last, First M name strings. Substitute "Name" with your name string column name. Since you have a period as a final character when there is a middle initial, you would replace the 2's with 3's in each of the lines (2, 6, and 8)- and change "RIGHT(Name, 1)" to "RIGHT(Name, 2)" in line 8.

SELECT  SUBSTRING(Name, 1, CHARINDEX(',', Name) - 1) LastName ,
CASE WHEN LEFT(RIGHT(Name, 2), 1) <> ' '
     THEN LTRIM(SUBSTRING(Name, CHARINDEX(',', Name) + 1, 99))
     ELSE LEFT(LTRIM(SUBSTRING(Name, CHARINDEX(',', Name) + 1, 99)),
               LEN(LTRIM(SUBSTRING(Name, CHARINDEX(',', Name) + 1, 99)))
               - 2)
END FirstName ,
CASE WHEN LEFT(RIGHT(Name, 2), 1) = ' ' THEN RIGHT(Name, 1)
     ELSE NULL
END MiddleName

How to draw a line with matplotlib?

I was checking how ax.axvline does work, and I've written a small function that resembles part of its idea:

import matplotlib.pyplot as plt
import matplotlib.lines as mlines

def newline(p1, p2):
    ax = plt.gca()
    xmin, xmax = ax.get_xbound()

    if(p2[0] == p1[0]):
        xmin = xmax = p1[0]
        ymin, ymax = ax.get_ybound()
    else:
        ymax = p1[1]+(p2[1]-p1[1])/(p2[0]-p1[0])*(xmax-p1[0])
        ymin = p1[1]+(p2[1]-p1[1])/(p2[0]-p1[0])*(xmin-p1[0])

    l = mlines.Line2D([xmin,xmax], [ymin,ymax])
    ax.add_line(l)
    return l

So, if you run the following code you will realize how does it work. The line will span the full range of your plot (independently on how big it is), and the creation of the line doesn't rely on any data point within the axis, but only in two fixed points that you need to specify.

import numpy as np
x = np.linspace(0,10)
y = x**2

p1 = [1,20]
p2 = [6,70]

plt.plot(x, y)
newline(p1,p2)
plt.show()

enter image description here

How can I get the current stack trace in Java?

This is an old post, but here is my solution :

Thread.currentThread().dumpStack();

More info and more methods there : http://javarevisited.blogspot.fr/2013/04/how-to-get-current-stack-trace-in-java-thread.html

How to remove symbols from a string with Python?

I often just open the console and look for the solution in the objects methods. Quite often it's already there:

>>> a = "hello ' s"
>>> dir(a)
[ (....) 'partition', 'replace' (....)]
>>> a.replace("'", " ")
'hello   s'

Short answer: Use string.replace().

python how to pad numpy array with zeros

I understand that your main problem is that you need to calculate d=b-a but your arrays have different sizes. There is no need for an intermediate padded c

You can solve this without padding:

import numpy as np

a = np.array([[ 1.,  1.,  1.,  1.,  1.],
              [ 1.,  1.,  1.,  1.,  1.],
              [ 1.,  1.,  1.,  1.,  1.]])

b = np.array([[ 3.,  3.,  3.,  3.,  3.,  3.],
              [ 3.,  3.,  3.,  3.,  3.,  3.],
              [ 3.,  3.,  3.,  3.,  3.,  3.],
              [ 3.,  3.,  3.,  3.,  3.,  3.]])

d = b.copy()
d[:a.shape[0],:a.shape[1]] -=  a

print d

Output:

[[ 2.  2.  2.  2.  2.  3.]
 [ 2.  2.  2.  2.  2.  3.]
 [ 2.  2.  2.  2.  2.  3.]
 [ 3.  3.  3.  3.  3.  3.]]

Javascript: How to loop through ALL DOM elements on a page?

You can try with document.getElementsByClassName('special_class');

C++, copy set to vector

set<T> s;
//....
vector<T> v;
v.assign(s.begin(), s.end());

What dependency is missing for org.springframework.web.bind.annotation.RequestMapping?

Add this below dependency in your pom.xml

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
</dependency>

This is used for @RestController, @RequestMapping

How to add ID property to Html.BeginForm() in asp.net mvc?

May be a bit late but in my case i had to put the id in the 2nd anonymous object. This is because the 1st one is for route values i.e the return Url.

@using (Html.BeginForm("Login", "Account", new {  ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { id = "signupform", role = "form" }))

Hope this can help somebody :)

Where is the Keytool application?

here: C:\Program Files\Java\jre7\bin it is an exe keytool.exe

How to validate phone numbers using regex

I answered this question on another SO question before deciding to also include my answer as an answer on this thread, because no one was addressing how to require/not require items, just handing out regexs: Regex working wrong, matching unexpected things

From my post on that site, I've created a quick guide to assist anyone with making their own regex for their own desired phone number format, which I will caveat (like I did on the other site) that if you are too restrictive, you may not get the desired results, and there is no "one size fits all" solution to accepting all possible phone numbers in the world - only what you decide to accept as your format of choice. Use at your own risk.

Quick cheat sheet

  • Start the expression: /^
  • If you want to require a space, use: [\s] or \s
  • If you want to require parenthesis, use: [(] and [)] . Using \( and \) is ugly and can make things confusing.
  • If you want anything to be optional, put a ? after it
  • If you want a hyphen, just type - or [-] . If you do not put it first or last in a series of other characters, though, you may need to escape it: \-
  • If you want to accept different choices in a slot, put brackets around the options: [-.\s] will require a hyphen, period, or space. A question mark after the last bracket will make all of those optional for that slot.
  • \d{3} : Requires a 3-digit number: 000-999. Shorthand for [0-9][0-9][0-9].
  • [2-9] : Requires a digit 2-9 for that slot.
  • (\+|1\s)? : Accept a "plus" or a 1 and a space (pipe character, |, is "or"), and make it optional. The "plus" sign must be escaped.
  • If you want specific numbers to match a slot, enter them: [246] will require a 2, 4, or 6. (?:77|78) or [77|78] will require 77 or 78.
  • $/ : End the expression

Fastest way to extract frames using ffmpeg?

I tried it. 3600 frame in 32 seconds. your method is really slow. You should try this.

ffmpeg -i file.mpg -s 240x135 -vf fps=1 %d.jpg

jQuery ajax error function

You can use something like this:
note: responseText returns server response and statusText returns the predefined
message for status error.for e.g:
responseText returns something like "Not Found (#404)" in some frameworks like Yii2 but
statusText returns "Not Found".

$.ajax({
    cache: false,
    url: "addInterview_Code.asp",
    type: "POST",
    datatype: "text",
    data: strData,
    success: function (html) {
        alert('successful : ' + html);
        $("#result").html("Successful");
    },
    error: function (data) {
        console.log(data.status + ':' + data.statusText,data.responseText);
    }
});

Selecting pandas column by location

You can access multiple columns by passing a list of column indices to dataFrame.ix.

For example:

>>> df = pandas.DataFrame({
             'a': np.random.rand(5),
             'b': np.random.rand(5),
             'c': np.random.rand(5),
             'd': np.random.rand(5)
         })

>>> df
          a         b         c         d
0  0.705718  0.414073  0.007040  0.889579
1  0.198005  0.520747  0.827818  0.366271
2  0.974552  0.667484  0.056246  0.524306
3  0.512126  0.775926  0.837896  0.955200
4  0.793203  0.686405  0.401596  0.544421

>>> df.ix[:,[1,3]]
          b         d
0  0.414073  0.889579
1  0.520747  0.366271
2  0.667484  0.524306
3  0.775926  0.955200
4  0.686405  0.544421

Can't update: no tracked branch

This isuse because of coflict merge. If you have new commit in origin and not get those files; also you have changed the local master branch files then you got this error. You should fetch again to a new directory and copy your files into that path. Finally, you should commit and push your changes.

Python 'list indices must be integers, not tuple"

The problem is that [...] in python has two distinct meanings

  1. expr [ index ] means accessing an element of a list
  2. [ expr1, expr2, expr3 ] means building a list of three elements from three expressions

In your code you forgot the comma between the expressions for the items in the outer list:

[ [a, b, c] [d, e, f] [g, h, i] ]

therefore Python interpreted the start of second element as an index to be applied to the first and this is what the error message is saying.

The correct syntax for what you're looking for is

[ [a, b, c], [d, e, f], [g, h, i] ]

Skip first line(field) in loop using CSV file?

csvreader.next() Return the next row of the reader’s iterable object as a list, parsed according to the current dialect.

Express.js: how to get remote client address

If you are running behind a proxy like NGiNX or what have you, only then you should check for 'x-forwarded-for':

var ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;

If the proxy isn't 'yours', I wouldn't trust the 'x-forwarded-for' header, because it can be spoofed.

Is there a Google Sheets formula to put the name of the sheet into a cell?

You have 2 options, and I am not sure if I am a fan of either of them, but that is my opinion. You may feel differently:

Option 1: Force the function to run.

A function in a cell does not run unless it references a cell that has changed. Changing a sheet name does not trigger any functions in the spreadsheet. But we can force the function to run by passing a range to it and whenever an item in that range changes, the function will trigger.

You can use the below script to create a custom function which will retrieve the name:

function mySheetName() {
  var key = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getName();
  return key;
}

and in the cell place the following:

=mySheetName(A1:Z)

Now if any value in a cell in that passed range changes the script will run. This takes a second to run the script and sets a message in the cell each time any value is changed so this could become annoying very quickly. As already mentioned, it also requires a change in the range to cause it to trigger, so not really helpful on a fairly static file.

Option 2: Use the OnChange Event

While the run time feels better than the above option, and this does not depend on a value changing in the spreadsheet's cells, I do not like this because it forces where the name goes. You could use a Utilities sheet to define this location in various sheets if you wish. Below is the basic idea and may get you started if you like this option.

The OnChange event is triggered when the sheet name is changed. You can make the code below more sophisticated to check for errors, check the sheet ID to only work on a given sheet, etc. The basic code, however, is:

function setSheetName(e) {
  var key = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getName();
  SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange('K1').setValue(key);
}

Once you have saved the code, in the script editor set the Current Project's On Change Trigger to this function. It will write the sheet name to cell K1 on any change event. To set the trigger, select Current project's triggers under the Edit menu.

form serialize javascript (no framework)

This could be done by very simple function as follows

_x000D_
_x000D_
function serialize(form) {
        let requestArray = [];
        form.querySelectorAll('[name]').forEach((elem) => {
            requestArray.push(elem.name + '=' + elem.value);
        });
        if(requestArray.length > 0)
            return requestArray.join('&');
        else
            return false;
    }

 serialized = serialize(document.querySelector('form'))
  console.log(serialized);
_x000D_
<form>

  <input type='text' name='fname' value='Johne'/>
  <input type='text' name='lname' value='Doe'/>
  <input type='text' name='contact[]' value='99999999'/>
  <input type='text' name='contact[]' value='34423434345'/>

</form>
_x000D_
_x000D_
_x000D_

How to center-justify the last line of text in CSS?

Solution (not the best, but still working for some cases) for non-dinamic text with fixed width.Usefull for situations when there are a little space to "stretch" text to the end of the penultimate line. Make some symbols in the end of the paragraph (experiment with their length) and hide it; apply to the paragraph absolute position or just correct free space with padding/marging.

Good compabitity/crossbrowser way for center-justifying text.

Example (paragraph before):

_x000D_
_x000D_
.paragraph {_x000D_
    width:455px;_x000D_
    text-align:justify;_x000D_
}_x000D_
_x000D_
.center{_x000D_
  display:block;_x000D_
  text-align:center;_x000D_
  margin-top:-17px;_x000D_
}
_x000D_
<div class="paragraph">Cras justo odio, dapibus ac facilisis in, egestas eget quam. Nullam id dolor id nibh ultricies vehicula ut id elit. Etiam porta sem malesuada magna mollis euismod. Nullam id dolor id nibh ultricies vehicula ut id elit. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla vitae elit libero, a pharetra augue. Praesent commodo cursus magna,<br><center>vel scelerisque nisl consectetur et.</center></div>
_x000D_
_x000D_
_x000D_

And after the fix:

_x000D_
_x000D_
.paragraph {_x000D_
    width:455px;_x000D_
    text-align:justify;_x000D_
    position:relative;_x000D_
}_x000D_
.center{_x000D_
  display:block;_x000D_
  text-align:center;_x000D_
  margin-top:-17px;_x000D_
}_x000D_
.paragraph b{_x000D_
  opacity:0;_x000D_
_x000D_
-ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";_x000D_
filter: alpha(opacity=0);_x000D_
-moz-opacity: 0;_x000D_
-khtml-opacity: 0;_x000D_
}
_x000D_
<div class="paragraph">Cras justo odio, dapibus ac facilisis in, egestas eget quam. Nullam id dolor id nibh ultricies vehicula ut id elit. Etiam porta sem malesuada magna mollis euismod. Nullam id dolor id nibh ultricies vehicula ut id elit. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla vitae elit libero, a pharetra augue. Praesent commodo cursus magna, <b>__</b><br><div class="center">vel scelerisque nisl consectetur et.</div></div>
_x000D_
_x000D_
_x000D_

The 'json' native gem requires installed build tools

1) Download Ruby 1.9.3

2) cmd check command: ruby -v 'return result ruby 1.9.3 then success full install ruby

3) Download DevKit file from http://rubyinstaller.org/downloads (DevKit-tdm-32-4.5.2-20110712-1620-sfx.exe)

4) Extract DevKit to path C:\Ruby193\DevKit

5) cd C:\Ruby193\DevKit

6) ruby dk.rb init

7) ruby dk.rb review

8) ruby dk.rb install

9) cmd : gem install rails -v3.1.1 'few time installing full process'

10) cmd : rails -v 'return result rails 3.1.1 then its success fully install'

enjoy Ruby on Rails...

Twitter bootstrap scrollable table

I added .table-responsive to the table and it worked. From the docs

Create responsive tables by wrapping any .table with .table-responsive{-sm|-md|-lg|-xl}, making the table scroll horizontally at each max-width breakpoint of up to (but not including) 576px, 768px, 992px, and 1120px, respectively.

Order a MySQL table by two columns

ORDER BY article_rating, article_time DESC

will sort by article_time only if there are two articles with the same rating. From all I can see in your example, this is exactly what happens.

? primary sort                         secondary sort ?
1.  50 | This article rocks          | Feb 4, 2009    3.
2.  35 | This article is pretty good | Feb 1, 2009    2.
3.  5  | This Article isn't so hot   | Jan 25, 2009   1.

but consider:

? primary sort                         secondary sort ?
1.  50 | This article rocks          | Feb 2, 2009    3.
1.  50 | This article rocks, too     | Feb 4, 2009    4.
2.  35 | This article is pretty good | Feb 1, 2009    2.
3.  5  | This Article isn't so hot   | Jan 25, 2009   1.

How To Run PHP From Windows Command Line in WAMPServer

UPDATED After few research, best solution was to use that info another stackoverflow thread to avoid ctrl+z input and also from the scree output. So, instead of php -a you should use call "php.exe" -f NAMED_SCRIPT.php

OLD Readline not possible under Windows, so none of existent php shells written in php will work. But there's a workaround using -a interactive mode.

2 commmon problems here. You cannot see result until executes CTRL Z command to indicate the final of code/file like EOF. When you do, result in most cases is printed result and fast closed window. Anyway, you will be returned to cmd not the -a interactive mode.

Save this content into a .bat file, and define your PHP PATH into Windows variables, or modify php.exe to "full path to exe" instead:

::
:: PHP Shell launch wrapper
::
@ECHO off
call "php.exe" -a

echo.
echo.

call "PHP Shell.bat"

This is a simple Batch launching -a mode of php.exe. When it launchs php, stop script even no pause is wrote because is "into" the interactive waiting for input. When you hit CTRL Z, gets the SIGSTEP (next step) not the SIGSTOP (close, CTRL+C usually), then read the next intruction, wich is a recursive call to .bat itself. Because you're always into PHP -a mode, no exit command. You must use CTRL+C or hit the exit cross with mouse. (No alt+f4)

You can also use "Bat to Exe" converter to easy use.

golang why don't we have a set datastructure

One reason is that it is easy to create a set from map:

s := map[int]bool{5: true, 2: true}
_, ok := s[6] // check for existence
s[8] = true // add element 
delete(s, 2) // remove element

Union

s_union := map[int]bool{}
for k, _ := range s1{
    s_union[k] = true
}
for k, _ := range s2{
    s_union[k] = true
}

Intersection

s_intersection := map[int]bool{}
for k,_ := range s1 { 
  if s2[k] {
    s_intersection[k] = true
  }
}

It is not really that hard to implement all other set operations.

Adding div element to body or document in JavaScript

Using Javascript

var elemDiv = document.createElement('div');
elemDiv.style.cssText = 'position:absolute;width:100%;height:100%;opacity:0.3;z-index:100;background:#000;';
document.body.appendChild(elemDiv);

Using jQuery

$('body').append('<div style="position:absolute;width:100%;height:100%;opacity:0.3;z-index:100;background:#000;"></div>');

Center button under form in bootstrap

If you're using Bootstrap 4, try this:

<div class="mx-auto text-center">
    <button id="button" name="button" class="btn btn-primary">Press Me!</button>
</div>

How to convert string date to Timestamp in java?

tl;dr

java.sql.Timestamp                  
.valueOf(                           // Class-method parses SQL-style formatted date-time strings.
    "2007-11-11 12:13:14"
)                                   // Returns a `Timestamp` object.
.toInstant()                        // Converts from terrible legacy classes to modern *java.time* class.

java.sql.Timestamp.valueOf parses SQL format

If you can use the full four digits for the year, your input string of 2007-11-11 12:13:14 would be in standard SQL format assuming this value is meant to be in UTC time zone.

The java.sql.Timestamp class has a valueOf method to directly parse such strings.

String input = "2007-11-11 12:13:14" ;
java.sql.Timestamp ts = java.sql.Timestamp.valueOf( input ) ;

java.time

In Java 8 and later, the java.time framework makes it easier to verify the results. The j.s.Timestamp class has a nasty habit of implicitly applying your JVM’s current default timestamp when generating a string representation via its toString method. In contrast, the java.time classes by default use the standard ISO 8601 formats.

System.out.println( "Output: " + ts.toInstant().toString() );

Chrome, Javascript, window.open in new tab

You can't directly control this, because it's an option controlled by Internet Explorer users.

Opening pages using Window.open with a different window name will open in a new browser window like a popup, OR open in a new tab, if the user configured the browser to do so.

EDIT:

A more detailed explanation:

1. In modern browsers, window.open will open in a new tab rather than a popup.

2. You can force a browser to use a new window (‘popup’) by specifying options in the 3rd parameter

3. If the window.open call was not part of a user-initiated event, it’ll open in a new window.

4. A “user initiated event” does not have to the same function call – but it must originate in the function invoked by a user click

5. If a user initiated event delegates or defers a function call (in an event listener or delegate not bound to the click event, or by using setTimeout for example), it loses it’s status as “user initiated”

6. Some popup blockers will allow windows opened from user initiated events, but not those opened otherwise.

7. If any popup is blocked, those normally allowed by a blocker (via user initiated events) will sometimes also be blocked. Some examples…

Forcing a window to open in a new browser instance, instead of a new tab:

window.open('page.php', '', 'width=1000');

The following would qualify as a user-initiated event, even though it calls another function:

function o(){
  window.open('page.php');
}
$('button').addEvent('click', o);

The following would not qualify as a user-initiated event, since the setTimeout defers it:

function g(){
  setTimeout(o, 1);
}
function o(){
  window.open('page.php');
}
$('button').addEvent('click', g);

Converting JSON data to Java object

If, by any change, you are in an application which already uses http://restfb.com/ then you can do:

import com.restfb.json.JsonObject;

...

JsonObject json = new JsonObject(jsonString);
json.get("title");

etc.

How can I use the HTML5 canvas element in IE?

You could use the newly released Chrome Frame plugin for IE, but it requires that the HTML 5 website includes the special meta tag that enables the plugin.

http://code.google.com/chrome/chromeframe/

Chrome Frame seems to use Explore Canvas (excanvas.js).

error: package com.android.annotations does not exist

Annotations come from the support's library which are packaged in android.support.annotation.

As another option you can use @NonNull annotation which denotes that a parameter, field or method return value can never be null.
It is imported from import android.support.annotation.NonNull;

Configuring so that pip install can work from github

You need the whole python package, with a setup.py file in it.

A package named foo would be:

foo # the installable package
+-- foo
¦   +-- __init__.py
¦   +-- bar.py
+-- setup.py

And install from github like:

$ pip install git+ssh://[email protected]/myuser/foo.git
or
$ pip install git+https://github.com/myuser/foo.git@v123
or
$ pip install git+https://github.com/myuser/foo.git@newbranch

More info at https://pip.pypa.io/en/stable/reference/pip_install/#vcs-support

Perform a Shapiro-Wilk Normality Test

You failed to specify the exact columns (data) to test for normality. Use this instead

shapiro.test(heisenberg$HWWIchg)

Producing a new line in XSLT

I have found a difference between literal newlines in <xsl:text> and literal newlines using &#xA;.

While literal newlines worked fine in my environment (using both Saxon and the default Java XSLT processor) my code failed when it was executed by another group running in a .NET environment.

Changing to entities (&#xA;) got my file generation code running consistently on both Java and .NET.

Also, literal newlines are vulnerable to being reformatted by IDEs and can inadvertently get lost when the file is maintained by someone 'not in the know'.

Can't start Tomcat as Windows Service

I had the similar issue, But installing tomcat 32bit and jdk 32 bit worked, This happens mostly because of mismatch Bit.

Export/import jobs in Jenkins

There's a plugin called Job Import Plugin that may be what you are looking for. I have used it. It does have issues with importing projects from a server that doesn't allow anonymous access.

For Completeness: If you have command line access to both, you can do the procedure already mentioned by Khez for Moving, Copying and Renaming Jenkins Jobs.

Directly export a query to CSV using SQL Developer

You can use the spool command (SQL*Plus documentation, but one of many such commands SQL Developer also supports) to write results straight to disk. Each spool can change the file that's being written to, so you can have several queries writing to different files just by putting spool commands between them:

spool "\path\to\spool1.txt"

select /*csv*/ * from employees;

spool "\path\to\spool2.txt"

select /*csv*/ * from locations;

spool off;

You'd need to run this as a script (F5, or the second button on the command bar above the SQL Worksheet). You might also want to explore some of the formatting options and the set command, though some of those do not translate to SQL Developer.

Since you mentioned CSV in the title I've included a SQL Developer-specific hint that does that formatting for you.

A downside though is that SQL Developer includes the query in the spool file, which you can avoid by having the commands and queries in a script file that you then run as a script.

Inconsistent Accessibility: Parameter type is less accessible than method

You can get Parameter (class that have less accessibility) as object then convert it to your class by as keyword.

Padding is invalid and cannot be removed?

Another scenario, again for the benefit of people searching.

For me this error occurred during the Dispose() method which masked a previous error unrelated to encryption.

Once the other component was fixed, this exception went away.

Reading/writing an INI file

If you only need read access and not write access and you are using the Microsoft.Extensions.Confiuration (comes bundled in by default with ASP.NET Core but works with regular programs too) you can use the NuGet package Microsoft.Extensions.Configuration.Ini to import ini files in to your configuration settings.

public Startup(IHostingEnvironment env)
{
    var builder = new ConfigurationBuilder()
        .SetBasePath(env.ContentRootPath)
        .AddIniFile("SomeConfig.ini", optional: false);
    Configuration = builder.Build();
}

Error - "UNION operator must have an equal number of expressions" when using CTE for recursive selection

The problem lays here:

--This result set has 3 columns
select LOC_id,LOC_locatie,LOC_deelVan_LOC_id from tblLocatie t
where t.LOC_id = 1 -- 1 represents an example

union all

--This result set has 1 columns   
select t.LOC_locatie + '>' from tblLocatie t
inner join q parent on parent.LOC_id = t.LOC_deelVan_LOC_id

In order to use union or union all number of columns and their types should be identical cross all result sets.

I guess you should just add the column LOC_deelVan_LOC_id to your second result set

Java Timestamp - How can I create a Timestamp with the date 23/09/2007?

By Timestamp, I presume you mean java.sql.Timestamp. You will notice that this class has a constructor that accepts a long argument. You can parse this using the DateFormat class:

DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
Date date = dateFormat.parse("23/09/2007");
long time = date.getTime();
new Timestamp(time);

How do I force files to open in the browser instead of downloading (PDF)?

Either use

<embed src="file.pdf" />

if embedding is an option or my new plugin, PIFF: https://github.com/terrasoftlabs/piff

How to create a date object from string in javascript

Very simple:

var dt=new Date("2011/11/30");

Date should be in ISO format yyyy/MM/dd.

split string only on first instance of specified character

Non-regex solution

I ran some benchmarks, and this solution won hugely:1

str.slice(str.indexOf(delim) + delim.length)

// as function
function gobbleStart(str, delim) {
    return str.slice(str.indexOf(delim) + delim.length);
}

// as polyfill
String.prototype.gobbleStart = function(delim) {
    return this.slice(this.indexOf(delim) + delim.length);
};

Performance comparison with other solutions

The only close contender was the same line of code, except using substr instead of slice.

Other solutions I tried involving split or RegExps took a big performance hit and were about 2 orders of magnitude slower. Using join on the results of split, of course, adds an additional performance penalty.

Why are they slower? Any time a new object or array has to be created, JS has to request a chunk of memory from the OS. This process is very slow.

Here are some general guidelines, in case you are chasing benchmarks:

  • New dynamic memory allocations for objects {} or arrays [] (like the one that split creates) will cost a lot in performance.
  • RegExp searches are more complicated and therefore slower than string searches.
  • If you already have an array, destructuring arrays is about as fast as explicitly indexing them, and looks awesome.

Removing beyond the first instance

Here's a solution that will slice up to and including the nth instance. It's not quite as fast, but on the OP's question, gobble(element, '_', 1) is still >2x faster than a RegExp or split solution and can do more:

/*
`gobble`, given a positive, non-zero `limit`, deletes
characters from the beginning of `haystack` until `needle` has
been encountered and deleted `limit` times or no more instances
of `needle` exist; then it returns what remains. If `limit` is
zero or negative, delete from the beginning only until `-(limit)`
occurrences or less of `needle` remain.
*/
function gobble(haystack, needle, limit = 0) {
  let remain = limit;
  if (limit <= 0) { // set remain to count of delim - num to leave
    let i = 0;
    while (i < haystack.length) {
      const found = haystack.indexOf(needle, i);
      if (found === -1) {
        break;
      }
      remain++;
      i = found + needle.length;
    }
  }

  let i = 0;
  while (remain > 0) {
    const found = haystack.indexOf(needle, i);
    if (found === -1) {
      break;
    }
    remain--;
    i = found + needle.length;
  }
  return haystack.slice(i);
}

With the above definition, gobble('path/to/file.txt', '/') would give the name of the file, and gobble('prefix_category_item', '_', 1) would remove the prefix like the first solution in this answer.


  1. Tests were run in Chrome 70.0.3538.110 on macOSX 10.14.

Sum all the elements java arraylist

I haven't tested it but it should work.

public double incassoMargherita()
{
    double sum = 0;
    for(int i = 0; i < m.size(); i++)
    {
        sum = sum + m.get(i);
    }
    return sum;
}

Leaflet - How to find existing markers, and delete markers?

(1) add layer group and array to hold layers and reference to layers as global variables:

var search_group = new L.LayerGroup(); var clickArr = new Array();

(2) add map

(3) Add group layer to map

map.addLayer(search_group);

(4) the add to map function, with a popup that contains a link, which when clicked will have a remove option. This link will have, as its id the lat long of the point. This id will then be compared to when you click on one of your created markers and you want to delete it.

 map.on('click', function(e) {
        var clickPositionMarker = L.marker([e.latlng.lat,e.latlng.lng],{icon: idMarker});
        clickArr.push(clickPositionMarker);
        mapLat = e.latlng.lat;
        mapLon = e.latlng.lng;
        clickPositionMarker.addTo(search_group).bindPopup("<a name='removeClickM' id="+e.latlng.lat+"_"+e.latlng.lng+">Remove Me</a>")
                .openPopup();   

                /*   clickPositionMarker.on('click', function(e) {
                  markerDelAgain(); 
                }); */


});

(5) The remove function, compare the marker lat long to the id fired in the remove:

$(document).on("click","a[name='removeClickM']", function (e) {

      // Stop form from submitting normally
    e.preventDefault();

    for(i=0;i<clickArr.length;i++) {

    if(search_group.hasLayer(clickArr[i]))
    {
        if(clickArr[i]._latlng.lat+"_"+clickArr[i]._latlng.lng==$(this).attr('id'))
            {
                hideLayer(search_group,clickArr[i]);
                clickArr.splice(clickArr.indexOf(clickArr[i]), 1);
            }

    }

    }  

How to undo a git pull?

Even though the above solutions do work,This answer is for you in case you want to reverse the clock instead of undoing a git pull.I mean if you want to get your exact repo the way it was X Mins back then run the command

git reset --hard branchName@{"X Minutes ago"}

Note: before you actually go ahead and run this command please only try this command if you are sure about the time you want to go back to and heres about my situation.

I was currently on a branch develop, I was supposed to checkout to a new branch and pull in another branch lets say Branch A but I accidentally ran git pull origin B before checking out.

so to undo this change I tried this command

git reset --hard develop@{"10 Minutes ago"}

if you are on windows cmd and get error: unknown switch `e

try adding quotes like this

git reset --hard 'develop@{"10 Minutes ago"}'

.bashrc: Permission denied

The .bashrc file is in your user home directory (~/.bashrc or ~vagrant/.bashrc both resolve to the same path), inside the VM's filesystem. This file is invisible on the host machine, so you can't use any Windows editors to edit it directly.

You have two simple choices:

  1. Learn how to use a console-based text editor. My favourite is vi (or vim), which takes 15 minutes to learn the basics and is much quicker for simple edits than anything else.

    vi .bashrc

  2. Copy .bashrc out to /vagrant (which is a shared directory) and edit it using your Windows editors. Make sure not to save it back with any extensions.

    cp .bashrc /vagrant ... edit using your host machine ... cp /vagrant/.bashrc .

I'd recommend getting to know the command-line based editors. Once you're working inside the VM, it's best to stay there as otherwise you might just get confused.

You (the vagrant user) are the owner of your home .bashrc so you do have permissions to edit it.

Once edited, you can execute it by typing source .bashrc I prefer to logout and in again (there may be more than one file executed on login).

Python: Tuples/dictionaries as keys, select, sort

Your best option will be to create a simple data structure to model what you have. Then you can store these objects in a simple list and sort/retrieve them any way you wish.

For this case, I'd use the following class:

class Fruit:
    def __init__(self, name, color, quantity): 
        self.name = name
        self.color = color
        self.quantity = quantity

    def __str__(self):
        return "Name: %s, Color: %s, Quantity: %s" % \
     (self.name, self.color, self.quantity)

Then you can simply construct "Fruit" instances and add them to a list, as shown in the following manner:

fruit1 = Fruit("apple", "red", 12)
fruit2 = Fruit("pear", "green", 22)
fruit3 = Fruit("banana", "yellow", 32)
fruits = [fruit3, fruit2, fruit1] 

The simple list fruits will be much easier, less confusing, and better-maintained.

Some examples of use:

All outputs below is the result after running the given code snippet followed by:

for fruit in fruits:
    print fruit

Unsorted list:

Displays:

Name: banana, Color: yellow, Quantity: 32
Name: pear, Color: green, Quantity: 22
Name: apple, Color: red, Quantity: 12

Sorted alphabetically by name:

fruits.sort(key=lambda x: x.name.lower())

Displays:

Name: apple, Color: red, Quantity: 12
Name: banana, Color: yellow, Quantity: 32
Name: pear, Color: green, Quantity: 22

Sorted by quantity:

fruits.sort(key=lambda x: x.quantity)

Displays:

Name: apple, Color: red, Quantity: 12
Name: pear, Color: green, Quantity: 22
Name: banana, Color: yellow, Quantity: 32

Where color == red:

red_fruit = filter(lambda f: f.color == "red", fruits)

Displays:

Name: apple, Color: red, Quantity: 12

setTimeout or setInterval?

They essentially try to do the same thing, but the setInterval approach will be more accurate than the setTimeout approach, since setTimeout waits 1000ms, runs the function and then sets another timeout. So the wait period is actually a bit more than 1000ms (or a lot more if your function takes a long time to execute).

Although one might think that setInterval will execute exactly every 1000ms, it is important to note that setInterval will also delay, since JavaScript isn't a multi-threaded language, which means that - if there are other parts of the script running - the interval will have to wait for that to finish.

In this Fiddle, you can clearly see that the timeout will fall behind, while the interval is almost all the time at almost 1 call/second (which the script is trying to do). If you change the speed variable at the top to something small like 20 (meaning it will try to run 50 times per second), the interval will never quite reach an average of 50 iterations per second.

The delay is almost always negligible, but if you're programming something really precise, you should go for a self-adjusting timer (which essentially is a timeout-based timer that constantly adjusts itself for the delay it's created)

Calling JavaScript Function From CodeBehind

You can't call a Javascript function from the CodeBehind, because the CodeBehind file contains the code that executes server side on the web server. Javascript code executes in the web browser on the client side.

PostgreSQL - fetch the row which has the Max value for a column

Here's another method, which happens to use no correlated subqueries or GROUP BY. I'm not expert in PostgreSQL performance tuning, so I suggest you try both this and the solutions given by other folks to see which works better for you.

SELECT l1.*
FROM lives l1 LEFT OUTER JOIN lives l2
  ON (l1.usr_id = l2.usr_id AND (l1.time_stamp < l2.time_stamp 
   OR (l1.time_stamp = l2.time_stamp AND l1.trans_id < l2.trans_id)))
WHERE l2.usr_id IS NULL
ORDER BY l1.usr_id;

I am assuming that trans_id is unique at least over any given value of time_stamp.

Easiest way to change font and font size

Use this one to change only font size not the name of the font

label1.Font = new System.Drawing.Font(label1.Font.Name, 24F);

Why do we need middleware for async flow in Redux?

To Answer the question:

Why can't the container component call the async API, and then dispatch the actions?

I would say for at least two reasons:

The first reason is the separation of concerns, it's not the job of the action creator to call the api and get data back, you have to have to pass two argument to your action creator function, the action type and a payload.

The second reason is because the redux store is waiting for a plain object with mandatory action type and optionally a payload (but here you have to pass the payload too).

The action creator should be a plain object like below:

function addTodo(text) {
  return {
    type: ADD_TODO,
    text
  }
}

And the job of Redux-Thunk midleware to dispache the result of your api call to the appropriate action.

SQL SERVER DATETIME FORMAT

case when isdate(inputdate) = 1 
then convert(datetime, cast(inputdate,datetime2), 103)
else
case when isdate(inputdate) = 0 
then convert(datetime, cast(inputdate,datetime2), 103)

Use of Greater Than Symbol in XML

CDATA is a better general solution.

OpenCV - Saving images to a particular folder of choice

Thank you everyone. Your ways are perfect. I would like to share another way I used to fix the problem. I used the function os.chdir(path) to change local directory to path. After which I saved image normally.

Common CSS Media Queries Break Points


@media only screen and (min-width : 320px) and (max-width : 480px) {/*--- Mobile portrait ---*/}
@media only screen and (min-width : 480px) and (max-width : 595px) {/*--- Mobile landscape ---*/}
@media only screen and (min-width : 595px) and (max-width : 690px) {/*--- Small tablet portrait ---*/}
@media only screen and (min-width : 690px) and (max-width : 800px) {/*--- Tablet portrait ---*/}
@media only screen and (min-width : 800px) and (max-width : 1024px) {/*--- Small tablet landscape ---*/}
@media only screen and (min-width : 1024px) and (max-width : 1224px) {/*--- Tablet landscape --- */}

HTML image not showing in Gmail

I know Gmail already fix all the problem above, the alt and stuff now.

And this is unrelated to the question but probably someone experiences the same as me.

So my web designer use "image" tag instead of "img", but the symptom was the same. It works on outlook but not Gmail.
It takes me an hour to realize. Sigh, such a waste of time.

So make sure the tag is "img" not "image" as well.

How to prevent user from typing in text field without disabling the field?

One option is to bind a handler to the input event.

The advantage of this approach is that we don't prevent keyboard behaviors that the user expects (e.g. tab, page up/down, etc.).

Another advantage is that it also handles the case when the input value is changed by pasting text through the context menu.

This approach works best if you only care about keeping the input empty. If you want to maintain a specific value, you'll have to track that somewhere else (in a data attribute?) since it will not be available when the input event is received.

_x000D_
_x000D_
const inputEl = document.querySelector('input');_x000D_
_x000D_
inputEl.addEventListener('input', (event) => {_x000D_
  event.target.value = '';_x000D_
});
_x000D_
<input type="text" />
_x000D_
_x000D_
_x000D_

Tested in Safari 10, Firefox 49, Chrome 54, IE 11.

How to simulate a touch event in Android?

Valentin Rocher's method works if you've extended your view, but if you're using an event listener, use this:

view.setOnTouchListener(new OnTouchListener()
{
    public boolean onTouch(View v, MotionEvent event)
    {
        Toast toast = Toast.makeText(
            getApplicationContext(), 
            "View touched", 
            Toast.LENGTH_LONG
        );
        toast.show();

        return true;
    }
});


// Obtain MotionEvent object
long downTime = SystemClock.uptimeMillis();
long eventTime = SystemClock.uptimeMillis() + 100;
float x = 0.0f;
float y = 0.0f;
// List of meta states found here: developer.android.com/reference/android/view/KeyEvent.html#getMetaState()
int metaState = 0;
MotionEvent motionEvent = MotionEvent.obtain(
    downTime, 
    eventTime, 
    MotionEvent.ACTION_UP, 
    x, 
    y, 
    metaState
);

// Dispatch touch event to view
view.dispatchTouchEvent(motionEvent);

For more on obtaining a MotionEvent object, here is an excellent answer: Android: How to create a MotionEvent?

How can I see the request headers made by curl when sending a request to the server?

The only way I managed to see my outgoing headers (curl with php) was using the following options:

curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);

Getting your debug info:

$data = curl_exec($ch);
var_dump($data);
var_dump(curl_getinfo($ch));

How to use onResume()?

The best way to understand would be to have all the LifeCycle methods overridden in your activity and placing a breakpoint(if checking in emulator) or a Log in each one of them. You'll get to know which one gets called when.

Just as an spoiler, onCreate() gets called first, then if you paused the activity by either going to home screen or by launching another activity, onPause() gets called. If the OS destroys the activity in the meantime, onDestroy() gets called. If you resume the app and the app already got destroyed, onCreate() will get called, or else onResume() will get called.

Edit: I forgot about onStop(), it gets called before onDestroy().

Do the exercise I mentioned and you'll be having a better understanding.

How to create JSON Object using String?

JSONArray may be what you want.

String message;
JSONObject json = new JSONObject();
json.put("name", "student");

JSONArray array = new JSONArray();
JSONObject item = new JSONObject();
item.put("information", "test");
item.put("id", 3);
item.put("name", "course1");
array.put(item);

json.put("course", array);

message = json.toString();

// message
// {"course":[{"id":3,"information":"test","name":"course1"}],"name":"student"}

Creating new database from a backup of another Database on the same server?

Think of it like an archive. MyDB.Bak contains MyDB.mdf and MyDB.ldf.

Restore with Move to say HerDB basically grabs MyDB.mdf (and ldf) from the back up, and copies them as HerDB.mdf and ldf.

So if you already had a MyDb on the server instance you are restoring to it wouldn't be touched.

Calculate relative time in C#

Turkish localized version of Vincents answer.

    const int SECOND = 1;
    const int MINUTE = 60 * SECOND;
    const int HOUR = 60 * MINUTE;
    const int DAY = 24 * HOUR;
    const int MONTH = 30 * DAY;

    var ts = new TimeSpan(DateTime.UtcNow.Ticks - yourDate.Ticks);
    double delta = Math.Abs(ts.TotalSeconds);

    if (delta < 1 * MINUTE)
        return ts.Seconds + " saniye önce";

    if (delta < 45 * MINUTE)
        return ts.Minutes + " dakika önce";

    if (delta < 24 * HOUR)
        return ts.Hours + " saat önce";

    if (delta < 48 * HOUR)
        return "dün";

    if (delta < 30 * DAY)
        return ts.Days + " gün önce";

    if (delta < 12 * MONTH)
    {
        int months = Convert.ToInt32(Math.Floor((double)ts.Days / 30));
        return months + " ay önce";
    }
    else
    {
        int years = Convert.ToInt32(Math.Floor((double)ts.Days / 365));
        return years + " yil önce";
    }

How to select following sibling/xml tag using xpath

How would I accomplish the nextsibling and is there an easier way of doing this?

You may use:

tr/td[@class='name']/following-sibling::td

but I'd rather use directly:

tr[td[@class='name'] ='Brand']/td[@class='desc']

This assumes that:

  1. The context node, against which the XPath expression is evaluated is the parent of all tr elements -- not shown in your question.

  2. Each tr element has only one td with class attribute valued 'name' and only one td with class attribute valued 'desc'.

regex to remove all text before a character

The regular expression:

^[^_]*_(.*)$

Then get the part between parenthesis. In perl:

my var = "3.04_somename.jpg";
$var =~ m/^[^_]*_(.*)$/;
my fileName = $1;

In Java:

String var = "3.04_somename.jpg";
String fileName = "";
Pattern pattern = Pattern.compile("^[^_]*_(.*)$");
Matcher matcher = pattern.matcher(var);
if (matcher.matches()) {
    fileName = matcher.group(1);
}

...

How to make modal dialog in WPF?

Did you try showing your window using the ShowDialog method?

Don't forget to set the Owner property on the dialog window to the main window. This will avoid weird behavior when Alt+Tabbing, etc.

How to remove a package in sublime text 2

Sublime Text 3

Procedure


Run Sublime Text.


Select Preferences ? Package Control.

Or

Use ctrl+shift+p shortcut for (Win, Linux) or cmd+shift+p for (OS X).


Select Remove Package. Package Control: Remove Package


Start typing name of the package you want to remove and select it from the list of installed packages.


Wait for the uninstallation to complete.

YouTube Autoplay not working

This code allows you to autoplay iframe video

<iframe src="https://www.youtube.com/embed/2MpUj-Aua48?rel=0&modestbranding=1&autohide=1&mute=1&showinfo=0&controls=0&autoplay=1"  width="560" height="315"  frameborder="0" allowfullscreen></iframe>

Here Is working fiddle

How to make a promise from setTimeout

This is not an answer to the original question. But, as an original question is not a real-world problem it should not be a problem. I tried to explain to a friend what are promises in JavaScript and the difference between promise and callback.

Code below serves as an explanation:

//very basic callback example using setTimeout
//function a is asynchronous function
//function b used as a callback
function a (callback){
    setTimeout (function(){
       console.log ('using callback:'); 
       let mockResponseData = '{"data": "something for callback"}'; 
       if (callback){
          callback (mockResponseData);
       }
    }, 2000);

} 

function b (dataJson) {
   let dataObject = JSON.parse (dataJson);
   console.log (dataObject.data);   
}

a (b);

//rewriting above code using Promise
//function c is asynchronous function
function c () {
   return new Promise(function (resolve, reject) {
     setTimeout (function(){
       console.log ('using promise:'); 
       let mockResponseData = '{"data": "something for promise"}'; 
       resolve(mockResponseData); 
    }, 2000);      
   }); 

}

c().then (b);

JsFiddle

Mockito - NullpointerException when stubbing Method

When using JUnit 5 or above. You have to inject the class annotated with @Mock in an @BeforeEach setup.

How to use the ProGuard in Android Studio?

You're probably not actually signing the release build of the APK via the signing wizard. You can either build the release APK from the command line with the command:

./gradlew assembleRelease

or you can choose the release variant from the Build Variants view and build it from the GUI:

IDE main window showing Build Variants

psql: FATAL: role "postgres" does not exist

The \du command return:

Role name = postgres@implicit_files

And that command postgres=# \password postgres return error:

ERROR: role "postgres" does not exist.

But that postgres=# \password postgres@implicit_files run fine.

Also after sudo -u postgres createuser -s postgres the first variant also work.

OraOLEDB.Oracle provider is not registered on the local machine

If you have windows 64 bits, try to install oracle driver 32 bits first then 64 bits driver, thats what i do and is working

Python dictionary: Get list of values for list of keys

Or just mydict.keys() That's a builtin method call for dictionaries. Also explore mydict.values() and mydict.items().

//Ah, OP post confused me.

Ruby optional parameters

It is possible :) Just change definition

def ldap_get ( base_dn, filter, scope=LDAP::LDAP_SCOPE_SUBTREE, attrs=nil )

to

def ldap_get ( base_dn, filter, *param_array, attrs=nil )
scope = param_array.first || LDAP::LDAP_SCOPE_SUBTREE

scope will be now in array on its first place. When you provide 3 arguments, then you will have assigned base_dn, filter and attrs and param_array will be [] When 4 and more arguments then param_array will be [argument1, or_more, and_more]

Downside is... it is unclear solution, really ugly. This is to answer that it is possible to ommit argument in the middle of function call in ruby :)

Another thing you have to do is to rewrite default value of scope.

Android ClassNotFoundException: Didn't find class on path

In my case it was proguard minification process that removed some important classes from my production apk.

The solution was to edit the proguard-rules.pro file and add the following:

-keep class com.someimportant3rdpartypackage.** { *; }

How to detect the end of loading of UITableView

Using private API:

@objc func tableViewDidFinishReload(_ tableView: UITableView) {
    print(#function)
    cellsAreLoaded = true
}

Using public API:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // cancel the perform request if there is another section
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(tableViewDidLoadRows:) object:tableView];

    // create a perform request to call the didLoadRows method on the next event loop.
    [self performSelector:@selector(tableViewDidLoadRows:) withObject:tableView afterDelay:0];

    return [self.myDataSource numberOfRowsInSection:section];
}

// called after the rows in the last section is loaded
-(void)tableViewDidLoadRows:(UITableView*)tableView{
    self.cellsAreLoaded = YES;
}

A possible better design is to add the visible cells to a set, then when you need to check if the table is loaded you can instead do a for loop around this set, e.g.

var visibleCells = Set<UITableViewCell>()

override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    visibleCells.insert(cell)
}

override func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    visibleCells.remove(cell)
}

// example property you want to show on a cell that you only want to update the cell after the table is loaded. cellForRow also calls configure too for the initial state.
var count = 5 {
    didSet {
        for cell in visibleCells {
            configureCell(cell)
        }
    }
}

How to draw circle in html page?

You can use border-radius property, or make a div with fixed height and width and a background with png circle.

How to refresh an access form

"Requery" is indeed what you what you want to run, but you could do that in Form A's "On Got Focus" event. If you have code in your Form_Load, perhaps you can move it to Form_Got_Focus.

rawQuery(query, selectionArgs)

For completeness and correct resource management:

        ICursor cursor = null;
        try
        {

            cursor = db.RawQuery("SELECT * FROM " + RECORDS_TABLE + " WHERE " + RECORD_ID + "=?", new String[] { id + "" });

            if (cursor.Count > 0)
            {
                cursor.MoveToFirst();
            }
            return GetRecordFromCursor(cursor); // Copy cursor props to custom obj
        }
        finally // IMPORTANT !!! Ensure cursor is not left hanging around ...
        {
            if(cursor != null)
                cursor.Close();
        }

How can I calculate the number of lines changed between two commits in Git?

Assuming that you want to compare all of your commits between abcd123 (the first commit) and wxyz789 (the last commit), inclusive:

git log wxyz789^..abcd123 --oneline --shortstat --author="Mike Surname"

This gives succinct output like:

abcd123 Made things better
 3 files changed, 14 insertions(+), 159 deletions(-)
wxyz789 Made things more betterer
 26 files changed, 53 insertions(+), 58 deletions(-)

Get only specific attributes with from Laravel Collection

I have now come up with an own solution to this:

1. Created a general function to extract specific attributes from arrays

The function below extract only specific attributes from an associative array, or an array of associative arrays (the last is what you get when doing $collection->toArray() in Laravel).

It can be used like this:

$data = array_extract( $collection->toArray(), ['id','url'] );

I am using the following functions:

function array_is_assoc( $array )
{
        return is_array( $array ) && array_diff_key( $array, array_keys(array_keys($array)) );
}



function array_extract( $array, $attributes )
{
    $data = [];

    if ( array_is_assoc( $array ) )
    {
        foreach ( $attributes as $attribute )
        {
            $data[ $attribute ] = $array[ $attribute ];
        }
    }
    else
    {
        foreach ( $array as $key => $values )
        {
            $data[ $key ] = [];

            foreach ( $attributes as $attribute )
            {
                $data[ $key ][ $attribute ] = $values[ $attribute ];
            }
        }   
    }

    return $data;   
}

This solution does not focus on performance implications on looping through the collections in large datasets.

2. Implement the above via a custom collection i Laravel

Since I would like to be able to simply do $collection->extract('id','url'); on any collection object, I have implemented a custom collection class.

First I created a general Model, which extends the Eloquent model, but uses a different collection class. All you models need to extend this custom model, and not the Eloquent Model then.

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model as EloquentModel;
use Lib\Collection;
class Model extends EloquentModel
{
    public function newCollection(array $models = [])
    {
        return new Collection( $models );
    }    
}
?>

Secondly I created the following custom collection class:

<?php
namespace Lib;
use Illuminate\Support\Collection as EloquentCollection;
class Collection extends EloquentCollection
{
    public function extract()
    {
        $attributes = func_get_args();
        return array_extract( $this->toArray(), $attributes );
    }
}   
?>

Lastly, all models should then extend your custom model instead, like such:

<?php
namespace App\Models;
class Article extends Model
{
...

Now the functions from no. 1 above are neatly used by the collection to make the $collection->extract() method available.

What is the equivalent of Java static methods in Kotlin?

In Java, we can write in below way

class MyClass {
  public static int myMethod() { 
  return 1;
  }
}

In Kotlin, we can write in below way

class MyClass {
  companion object {
     fun myMethod() : Int = 1
  }
}

a companion is used as static in Kotlin.

How do I set the rounded corner radius of a color drawable using xml?

Try below code

<shape xmlns:android="http://schemas.android.com/apk/res/android">
<corners
    android:bottomLeftRadius="30dp"
    android:bottomRightRadius="30dp"
    android:topLeftRadius="30dp"
    android:topRightRadius="30dp" />
<solid android:color="#1271BB" />

<stroke
    android:width="5dp"
    android:color="#1271BB" />

<padding
    android:bottom="1dp"
    android:left="1dp"
    android:right="1dp"
    android:top="1dp" /></shape>

Saving changes after table edit in SQL Server Management Studio

To work around this problem, use SQL statements to make the changes to the metadata structure of a table.

This problem occurs when "Prevent saving changes that require table re-creation" option is enabled.

Source: Error message when you try to save a table in SQL Server 2008: "Saving changes is not permitted"

How to list all methods for an object in Ruby?

To expound upon @clyfe's answer. You can get a list of your instance methods using the following code (assuming that you have an Object Class named "Parser"):

Parser.new.methods - Object.new.methods

Any way to write a Windows .bat file to kill processes?

As TASKKILL might be unavailable on some Home/basic editions of windows here some alternatives:

TSKILL processName

or

TSKILL PID

Have on mind that processName should not have the .exe suffix and is limited to 18 characters.

Another option is WMIC :

wmic Path win32_process Where "Caption Like 'MyProcess%.exe'" Call Terminate

wmic offer even more flexibility than taskkill with its SQL-like matchers .With wmic Path win32_process get you can see the available fileds you can filter (and % can be used as a wildcard).

How to search in array of object in mongodb

Use $elemMatch to find the array of particular object

db.users.findOne({"_id": id},{awards: {$elemMatch: {award:'Turing Award', year:1977}}})

Call async/await functions in parallel

There is another way without Promise.all() to do it in parallel:

First, we have 2 functions to print numbers:

function printNumber1() {
   return new Promise((resolve,reject) => {
      setTimeout(() => {
      console.log("Number1 is done");
      resolve(10);
      },1000);
   });
}

function printNumber2() {
   return new Promise((resolve,reject) => {
      setTimeout(() => {
      console.log("Number2 is done");
      resolve(20);
      },500);
   });
}

This is sequential:

async function oneByOne() {
   const number1 = await printNumber1();
   const number2 = await printNumber2();
} 
//Output: Number1 is done, Number2 is done

This is parallel:

async function inParallel() {
   const promise1 = printNumber1();
   const promise2 = printNumber2();
   const number1 = await promise1;
   const number2 = await promise2;
}
//Output: Number2 is done, Number1 is done

HTML5 Pre-resize images before uploading

You can use dropzone.js if you want to use simple and easy upload manager with resizing before upload functions.

It has builtin resize functions, but you can provide your own if you want.

String to Binary in C#

It sounds like you basically want to take an ASCII string, or more preferably, a byte[] (as you can encode your string to a byte[] using your preferred encoding mode) into a string of ones and zeros? i.e. 101010010010100100100101001010010100101001010010101000010111101101010

This will do that for you...

//Formats a byte[] into a binary string (010010010010100101010)
public string Format(byte[] data)
{
    //storage for the resulting string
    string result = string.Empty;
    //iterate through the byte[]
    foreach(byte value in data)
    {
        //storage for the individual byte
        string binarybyte = Convert.ToString(value, 2);
        //if the binarybyte is not 8 characters long, its not a proper result
        while(binarybyte.Length < 8)
        {
            //prepend the value with a 0
            binarybyte = "0" + binarybyte;
        }
        //append the binarybyte to the result
        result += binarybyte;
    }
    //return the result
    return result;
}

How to copy text programmatically in my Android app?

@FlySwat already gave the correct answer, I am just sharing the complete answer:

Use ClipboardManager.setPrimaryClip (http://developer.android.com/reference/android/content/ClipboardManager.html) method:

ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE); 
ClipData clip = ClipData.newPlainText("label", "Text to copy");
clipboard.setPrimaryClip(clip); 

Where label is a User-visible label for the clip data and text is the actual text in the clip. According to official docs.

It is important to use this import:

import android.content.ClipboardManager;

POI setting Cell Background to a Custom Color

You can set custom color using this-

check out this - click hear

XSSFWorkbook workbook = new XSSFWorkbook();

IndexedColorMap colorMap = workbook.getStylesSource().getIndexedColors();
Font tableHeadOneFontStyle = workbook.createFont();
        tableHeadOneFontStyle.setBold( true );
        tableHeadOneFontStyle.setColor( IndexedColors.BLACK.getIndex() );

XSSFCellStyle tableHeaderOneColOneStyle = workbook.createCellStyle();
        tableHeaderOneColOneStyle.setFont( tableHeadOneFontStyle );
        tableHeaderOneColOneStyle
                .setFillForegroundColor( new XSSFColor( new java.awt.Color( 255, 231, 153 ), colorMap ) );
        tableHeaderOneColOneStyle.setFillPattern( FillPatternType.SOLID_FOREGROUND );
        tableHeaderOneColOneStyle = setLeftRightBorderColor( tableHeaderOneColOneStyle );
        tableHeaderOneColOneStyle = alignCenter( tableHeaderOneColOneStyle );

iOS (iPhone, iPad, iPodTouch) view real-time console log terminal

EDIT: Please use @cbowns solution - deviceconsole is compatible with iOS9 and much easier to use.

This is a open-source program that displays the iDevice's system log in Terminal (in a manner similar to tail -F). No jailbreak is required, and the output is fully grep'able so you can filter to see output from your program only. What's particularly good about this solution is you can view the log whether or not the app was launched in debug mode from XCode.

Here's how:

Grab the libimobiledevice binary for Mac OS X from my github account at https://github.com/benvium/libimobiledevice-macosx/zipball/master

Follow the install instructions here: https://github.com/benvium/libimobiledevice-macosx/blob/master/README.md

Connect your device, open up Terminal.app and type:

idevicesyslog

Up pops a real-time display of the device's system log.

With it being a console app, you can filter the log using unix commands, such as grep

For instance, see all log messages from a particular app:

idevicesyslog | grep myappname

Taken from my blog at http://pervasivecode.blogspot.co.uk/2012/06/view-log-output-of-any-app-on-iphone-or.html

What's the C# equivalent to the With statement in VB?

Aside from object initializers (usable only in constructor calls), the best you can get is:

var it = Stuff.Elements.Foo;
it.Name = "Bob Dylan";
it.Age = 68;
...

mysql select from n last rows

Last 5 rows retrieve in mysql

This query working perfectly

SELECT * FROM (SELECT * FROM recharge ORDER BY sno DESC LIMIT 5)sub ORDER BY sno ASC

or

select sno from(select sno from recharge order by sno desc limit 5) as t where t.sno order by t.sno asc

How does one use the onerror attribute of an img element

This is actually tricky, especially if you plan on returning an image url for use cases where you need to concatenate strings with the onerror condition image URL, e.g. you might want to programatically set the url parameter in CSS.

The trick is that image loading is asynchronous by nature so the onerror doesn't happen sunchronously, i.e. if you call returnPhotoURL it immediately returns undefined bcs the asynchronous method of loading/handling the image load just began.

So, you really need to wrap your script in a Promise then call it like below. NOTE: my sample script does some other things but shows the general concept:

returnPhotoURL().then(function(value){
    doc.getElementById("account-section-image").style.backgroundImage = "url('" + value + "')";
}); 


function returnPhotoURL(){
    return new Promise(function(resolve, reject){
        var img = new Image();
        //if the user does not have a photoURL let's try and get one from gravatar
        if (!firebase.auth().currentUser.photoURL) {
            //first we have to see if user han an email
            if(firebase.auth().currentUser.email){
                //set sign-in-button background image to gravatar url
                img.addEventListener('load', function() {
                    resolve (getGravatar(firebase.auth().currentUser.email, 48));
                }, false);
                img.addEventListener('error', function() {
                    resolve ('//rack.pub/media/fallbackImage.png');
                }, false);            
                img.src = getGravatar(firebase.auth().currentUser.email, 48);
            } else {
                resolve ('//rack.pub/media/fallbackImage.png');
            }
        } else {
            img.addEventListener('load', function() {
                resolve (firebase.auth().currentUser.photoURL);
            }, false);
            img.addEventListener('error', function() {
                resolve ('https://rack.pub/media/fallbackImage.png');
            }, false);      
            img.src = firebase.auth().currentUser.photoURL;
        }
    });
}

How to perform update operations on columns of type JSONB in Postgres 9.4

If you're able to upgrade to Postgresql 9.5, the jsonb_set command is available, as others have mentioned.

In each of the following SQL statements, I've omitted the where clause for brevity; obviously, you'd want to add that back.

Update name:

UPDATE test SET data = jsonb_set(data, '{name}', '"my-other-name"');

Replace the tags (as oppose to adding or removing tags):

UPDATE test SET data = jsonb_set(data, '{tags}', '["tag3", "tag4"]');

Replacing the second tag (0-indexed):

UPDATE test SET data = jsonb_set(data, '{tags,1}', '"tag5"');

Append a tag (this will work as long as there are fewer than 999 tags; changing argument 999 to 1000 or above generates an error. This no longer appears to be the case in Postgres 9.5.3; a much larger index can be used):

UPDATE test SET data = jsonb_set(data, '{tags,999999999}', '"tag6"', true);

Remove the last tag:

UPDATE test SET data = data #- '{tags,-1}'

Complex update (delete the last tag, insert a new tag, and change the name):

UPDATE test SET data = jsonb_set(
    jsonb_set(data #- '{tags,-1}', '{tags,999999999}', '"tag3"', true), 
    '{name}', '"my-other-name"');

It's important to note that in each of these examples, you're not actually updating a single field of the JSON data. Instead, you're creating a temporary, modified version of the data, and assigning that modified version back to the column. In practice, the result should be the same, but keeping this in mind should make complex updates, like the last example, more understandable.

In the complex example, there are three transformations and three temporary versions: First, the last tag is removed. Then, that version is transformed by adding a new tag. Next, the second version is transformed by changing the name field. The value in the data column is replaced with the final version.

Creating a Menu in Python

It looks like you've just finished step 3. Instead of running a function, you just print out a statement. A function is defined in the following way:

def addstudent():
    print("Student Added.")

then called by writing addstudent().

I would recommend using a while loop for your input. You can define the menu option outside the loop, put the print statement inside the loop, and do while(#valid option is not picked), then put the if statements after the while. Or you can do a while loop and continue the loop if a valid option is not selected.

Additionally, a dictionary is defined in the following way:

my_dict = {key:definition,...}

PHP: date function to get month of the current date

See http://php.net/date

date('m') or date('n') or date('F') ...

Update

m Numeric representation of a month, with leading zeros 01 through 12

n Numeric representation of a month, without leading zeros 1 through 12

F Alphabetic representation of a month January through December

....see the docs link for even more options.

isset() and empty() - what to use

Here are the outputs of isset() and empty() for the 4 possibilities: undeclared, null, false and true.

$a=null;
$b=false;
$c=true;

var_dump(array(isset($z1),isset($a),isset($b),isset($c)),true); //$z1 previously undeclared
var_dump(array(empty($z2),empty($a),empty($b),empty($c)),true); //$z2 previously undeclared

//array(4) { [0]=> bool(false) [1]=> bool(false) [2]=> bool(true) [3]=> bool(true) } 
//array(4) { [0]=> bool(true) [1]=> bool(true) [2]=> bool(true) [3]=> bool(false) } 

You'll notice that all the 'isset' results are opposite of the 'empty' results except for case $b=false. All the values (except null which isn't a value but a non-value) that evaluate to false will return true when tested for by isset and false when tested by 'empty'.

So use isset() when you're concerned about the existence of a variable. And use empty when you're testing for true or false. If the actual type of emptiness matters, use is_null and ===0, ===false, ===''.

How can you create pop up messages in a batch script?

I put together a script based on the good answers here & in other posts

You can set title timeout & even sleep to schedule it for latter & \n for new line

also you get back the key press into a variable (%pop.key%).

Here is my code

ScrollTo function in AngularJS

Another suggestion. One directive with selector.

HTML:

<button type="button" scroll-to="#catalogSection">Scroll To</button>

Angular:

app.directive('scrollTo', function () {
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            element.on('click', function () {

                var target = $(attrs.scrollTo);
                if (target.length > 0) {
                    $('html, body').animate({
                        scrollTop: target.offset().top
                    });
                }
            });
        }
    }
});

Also notice $anchorScroll

SOAP-ERROR: Parsing WSDL: Couldn't load from - but works on WAMP

This issue can be caused by the libxml entity loader having been disabled.

Try running libxml_disable_entity_loader(false); before instantiating SoapClient.

Differences between action and actionListener

As BalusC indicated, the actionListener by default swallows exceptions, but in JSF 2.0 there is a little more to this. Namely, it doesn't just swallows and logs, but actually publishes the exception.

This happens through a call like this:

context.getApplication().publishEvent(context, ExceptionQueuedEvent.class,                                                          
    new ExceptionQueuedEventContext(context, exception, source, phaseId)
);

The default listener for this event is the ExceptionHandler which for Mojarra is set to com.sun.faces.context.ExceptionHandlerImpl. This implementation will basically rethrow any exception, except when it concerns an AbortProcessingException, which is logged. ActionListeners wrap the exception that is thrown by the client code in such an AbortProcessingException which explains why these are always logged.

This ExceptionHandler can be replaced however in faces-config.xml with a custom implementation:

<exception-handlerfactory>
   com.foo.myExceptionHandler
</exception-handlerfactory>

Instead of listening globally, a single bean can also listen to these events. The following is a proof of concept of this:

@ManagedBean
@RequestScoped
public class MyBean {

    public void actionMethod(ActionEvent event) {

        FacesContext.getCurrentInstance().getApplication().subscribeToEvent(ExceptionQueuedEvent.class, new SystemEventListener() {

        @Override
        public void processEvent(SystemEvent event) throws AbortProcessingException {
            ExceptionQueuedEventContext content = (ExceptionQueuedEventContext)event.getSource();
            throw new RuntimeException(content.getException());
        }

        @Override
        public boolean isListenerForSource(Object source) {
            return true;
        }
        });

        throw new RuntimeException("test");
    }

}

(note, this is not how one should normally code listeners, this is only for demonstration purposes!)

Calling this from a Facelet like this:

<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:f="http://java.sun.com/jsf/core">
    <h:body>
        <h:form>
            <h:commandButton value="test" actionListener="#{myBean.actionMethod}"/>
        </h:form>
    </h:body>
</html>

Will result in an error page being displayed.

Difference between CLOCK_REALTIME and CLOCK_MONOTONIC?

POSIX 7 quotes

POSIX 7 specifies both at http://pubs.opengroup.org/onlinepubs/9699919799/functions/clock_getres.html:

CLOCK_REALTIME:

This clock represents the clock measuring real time for the system. For this clock, the values returned by clock_gettime() and specified by clock_settime() represent the amount of time (in seconds and nanoseconds) since the Epoch.

CLOCK_MONOTONIC (optional feature):

For this clock, the value returned by clock_gettime() represents the amount of time (in seconds and nanoseconds) since an unspecified point in the past (for example, system start-up time, or the Epoch). This point does not change after system start-up time. The value of the CLOCK_MONOTONIC clock cannot be set via clock_settime().

clock_settime() gives an important hint: POSIX systems are able to arbitrarily change CLOCK_REALITME with it, so don't rely on it flowing neither continuously nor forward. NTP could be implemented using clock_settime(), and could only affect CLOCK_REALITME.

The Linux kernel implementation seems to take boot time as the epoch for CLOCK_MONOTONIC: Starting point for CLOCK_MONOTONIC

How to check if input date is equal to today's date?

TodayDate = new Date();
if (TodayDate > AnotherDate) {} else{}

< = also works, Although with =, it might have to match the milliseconds.

Getting Lat/Lng from Google marker

Here is the JSFiddle Demo. In Google Maps API V3 it's pretty simple to track the lat and lng of a draggable marker. Let's start with the following HTML and CSS as our base.

<div id='map_canvas'></div>
<div id="current">Nothing yet...</div>

#map_canvas{
    width: 400px;
    height: 300px;
}

#current{
     padding-top: 25px;
}

Here is our initial JavaScript initializing the google map. We create a marker that we want to drag and set it's draggable property to true. Of course keep in mind it should be attached to an onload event of your window for it to be loaded, but i'll skip to the code:

var map = new google.maps.Map(document.getElementById('map_canvas'), {
    zoom: 1,
    center: new google.maps.LatLng(35.137879, -82.836914),
    mapTypeId: google.maps.MapTypeId.ROADMAP
});

var myMarker = new google.maps.Marker({
    position: new google.maps.LatLng(47.651968, 9.478485),
    draggable: true
});

Here we attach two events dragstart to track the start of dragging and dragend to drack when the marker stop getting dragged, and the way we attach it is to use google.maps.event.addListener. What we are doing here is setting the div current's content when marker is getting dragged and then set the marker's lat and lng when drag stops. Google mouse event has a property name 'latlng' that returns 'google.maps.LatLng' object when the event triggers. So, what we are doing here is basically using the identifier for this listener that gets returned by the google.maps.event.addListener and get the property latLng to extract the dragend's current position. Once we get that Lat Lng when the drag stops we'll display within your current div:

google.maps.event.addListener(myMarker, 'dragend', function(evt){
    document.getElementById('current').innerHTML = '<p>Marker dropped: Current Lat: ' + evt.latLng.lat().toFixed(3) + ' Current Lng: ' + evt.latLng.lng().toFixed(3) + '</p>';
});

google.maps.event.addListener(myMarker, 'dragstart', function(evt){
    document.getElementById('current').innerHTML = '<p>Currently dragging marker...</p>';
});

Lastly, we'll center our marker and display it on the map:

map.setCenter(myMarker.position);
myMarker.setMap(map);

Let me know if you have any questions regarding my answer.

Google Maps API Multiple Markers with Infowindows

Here is the code snippet which will work for sure. You can visit below link for working jsFiddle and explainantion in detail. How to locate multiple addresses on google maps with perfect zoom

var infowindow = new google.maps.InfoWindow();  
google.maps.event.addListener(marker, 'mouseover', (function(marker) {  
           return function() {  
               var content = address;  
               infowindow.setContent(content);  
               infowindow.open(map, marker);  
           }  
         })(marker));  

AVD Manager - Cannot Create Android Virtual Device

Had the exact same trouble... loading the ARM EABI v7a System Image worked for me too. Thanks very much.

I had previously seen on the Android SDK manager that a system image with the same name (ARM EABI v7a System Image) WAS installed on my system for a more recent SDK (Android 4.2). Consequently I thought it would negate the need to install the earlier Android 2.2 SDK ARM image, but apparently not.

How to import a single table in to mysql database using command line

All of these options are fine, if you have the option to re-export the data.

But if you need to use an existing SQL file, and use a specific table from it, then this perl script in the TimeSheet blog, with enable you to extract the table to a separate SQL file, and then import it.

The original link is dead, so it is a good thing that someone has put it instead of the author, Jared Cheney, on GitHub, in this link.

Crop image in PHP

If you are trying to generate thumbnails, you must first resize the image using imagecopyresampled();. You must resize the image so that the size of the smaller side of the image is equal to the corresponding side of the thumb.

For example, if your source image is 1280x800px and your thumb is 200x150px, you must resize your image to 240x150px and then crop it to 200x150px. This is so that the aspect ratio of the image won't change.

Here's a general formula for creating thumbnails:

$image = imagecreatefromjpeg($_GET['src']);
$filename = 'images/cropped_whatever.jpg';

$thumb_width = 200;
$thumb_height = 150;

$width = imagesx($image);
$height = imagesy($image);

$original_aspect = $width / $height;
$thumb_aspect = $thumb_width / $thumb_height;

if ( $original_aspect >= $thumb_aspect )
{
   // If image is wider than thumbnail (in aspect ratio sense)
   $new_height = $thumb_height;
   $new_width = $width / ($height / $thumb_height);
}
else
{
   // If the thumbnail is wider than the image
   $new_width = $thumb_width;
   $new_height = $height / ($width / $thumb_width);
}

$thumb = imagecreatetruecolor( $thumb_width, $thumb_height );

// Resize and crop
imagecopyresampled($thumb,
                   $image,
                   0 - ($new_width - $thumb_width) / 2, // Center the image horizontally
                   0 - ($new_height - $thumb_height) / 2, // Center the image vertically
                   0, 0,
                   $new_width, $new_height,
                   $width, $height);
imagejpeg($thumb, $filename, 80);

Haven't tested this but it should work.

EDIT

Now tested and working.

Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state

I just closed all open chrome instances, stopped my project and then start it again. that fixed the problem for me.

using href links inside <option> tag

    <select name="career" id="career" onchange="location = this.value;">
        <option value="resume" selected> All Applications </option>
        <option value="resume&j=14">Seo Expert</option>
        <option value="resume&j=21">Project Manager</option>
        <option value="resume&j=33">Php Developer</option>
    </select>

What does the term "Tuple" Mean in Relational Databases?

As I understand it a table has a set K of keys and a typing function T with domain K. A row, or "tuple", of the table is a function r with domain K such that r(k) is an element of T(k) for each key k. So the terminology is misleading in that a "tuple" is really more like an associative array.