Programs & Examples On #Simpledom

A bridge between SimpleXML and the DOM extension, plus a bunch of convenience methods

Eclipse - debugger doesn't stop at breakpoint

To remove the breakpoints:

  1. Debug your class as a junit test
  2. When your debugger stops, click the "breakpoints" tab next to "variables" and "expressions"
  3. At the top right of the breakpoint tab, click the button with two 'X'
  4. Stop the test, replace your breakpoint and run the debugger again

changing default x range in histogram matplotlib

import matplotlib.pyplot as plt


...


plt.xlim(xmin=6.5, xmax = 12.5)

How to post raw body data with curl?

curl's --data will by default send Content-Type: application/x-www-form-urlencoded in the request header. However, when using Postman's raw body mode, Postman sends Content-Type: text/plain in the request header.

So to achieve the same thing as Postman, specify -H "Content-Type: text/plain" for curl:

curl -X POST -H "Content-Type: text/plain" --data "this is raw data" http://78.41.xx.xx:7778/

Note that if you want to watch the full request sent by Postman, you can enable debugging for packed app. Check this link for all instructions. Then you can inspect the app (right-click in Postman) and view all requests sent from Postman in the network tab :

enter image description here

Set markers for individual points on a line in Matplotlib

You can do:

import matplotlib.pyplot as plt
x = [1,2,3,4,5]
y = [2,1,3,6,7]

plt.plot(x, y, style='.-')
plt.show()

This will return a graph with the data points marked with a dot

upgade python version using pip

pip is designed to upgrade python packages and not to upgrade python itself. pip shouldn't try to upgrade python when you ask it to do so.

Don't type pip install python but use an installer instead.

Not Able To Debug App In Android Studio

In my case near any line a red circle appeared with a cross and red line with a message: "No executable code found at line ..." like in Android studio gradle breakpoint No executable code found at line.

A problem appeared after updating of build.gradle. We included Kotlin support, so a number of methods exceeded 64K. Problem lines:

buildTypes {
    debug {
        minifyEnabled true

Change them to:

buildTypes {
    debug {
        minifyEnabled false
        debuggable true

Then sync a gradle with a button "Sync Project with Gradle Files". If after restarting of your application you will get an error: "Error:The number of method references in a .dex file cannot exceed 64K. Learn how to resolve this issue at https://developer.android.com/tools/building/multidex.html", then, like in The number of method references in a .dex file cannot exceed 64k API 17 add the following lines to build.gradle:

android {

    defaultConfig {
        ...

        // Enabling multidex support.
        multiDexEnabled true
    }
    ...
}

dependencies {
    implementation 'com.android.support:multidex:1.0.2'
}

UPDATE

According to https://developer.android.com/studio/build/multidex.html do the following to enable multidex support below Android 5.0. Else it won't start in these devices.

Open AndroidManifest and find tag <application>. Near android:name= is a reference to an Application class. Open this class. Extend Application class with MultiDexApplication so:

public class MyApplication extends MultiDexApplication { ... }

If no Application class set, write so:

<application
        android:name="android.support.multidex.MultiDexApplication" >
    ...
</application>

How to check ASP.NET Version loaded on a system?

open a new command prompt and run the following command: dotnet --info

How to Run Terminal as Administrator on Mac Pro

This is not Windows, you do not "run the Terminal as admin". What you do is you run commands in the terminal as admin, typically using sudo:

$ sudo some command here

How to get a List<string> collection of values from app.config in WPF?

In App.config:

<add key="YOURKEY" value="a,b,c"/>

In C#:

string[] InFormOfStringArray = ConfigurationManager.AppSettings["YOURKEY"].Split(',').Select(s => s.Trim()).ToArray();
List<string> list = new List<string>(InFormOfStringArray);

Get month name from number

import datetime
mydate = datetime.datetime.now()
mydate.strftime("%B") # 'December'
mydate.strftime("%b") # 'dec'

PHP Warning: POST Content-Length of 8978294 bytes exceeds the limit of 8388608 bytes in Unknown on line 0

upload_max_filesize = 8M;
post_max_size = 8M;

Imagine you already changed above values. But what happen when user try to upload large files greater than 8M ?

This is what happen, PHP shows this warning!

Warning: POST Content-Length of x bytes exceeds the limit of y bytes in Unknown on line 0

you can avoid it by adding

ob_get_contents();
ob_end_clean();

How to escape % in String.Format?

To escape %, you will need to double it up: %%.

How do you extract a column from a multi-dimensional array?

If you want to grab more than just one column just use slice:

 a = np.array([[1, 2, 3],[4, 5, 6],[7, 8, 9]])
    print(a[:, [1, 2]])
[[2 3]
[5 6]
[8 9]]

Public class is inaccessible due to its protection level

This error is a result of the protection level of ClassB's constructor, not ClassB itself. Since the name of the constructor is the same as the name of the class* , the error may be interpreted incorrectly. Since you did not specify the protection level of your constructor, it is assumed to be internal by default. Declaring the constructor public will fix this problem:

public ClassB() { } 

* One could also say that constructors have no name, only a type; this does not change the essence of the problem.

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

Asynchronous action methods are useful when an action must perform several independent long running operations.

A typical use for the AsyncController class is long-running Web service calls.

Should my database calls be asynchronous ?

The IIS thread pool can often handle many more simultaneous blocking requests than a database server. If the database is the bottleneck, asynchronous calls will not speed up the database response. Without a throttling mechanism, efficiently dispatching more work to an overwhelmed database server by using asynchronous calls merely shifts more of the burden to the database. If your DB is the bottleneck, asynchronous calls won’t be the magic bullet.

You should have a look at 1 and 2 references

Derived from @PanagiotisKanavos comments:

Moreover, async doesn't mean parallel. Asynchronous execution frees a valuable threadpool thread from blocking for an external resource, for no complexity or performance cost. This means the same IIS machine can handle more concurrent requests, not that it will run faster.

You should also consider that blocking calls start with a CPU-intensive spinwait. During stress times, blocking calls will result in escalating delays and app pool recycling. Asynchronous calls simply avoid this

Microsoft.Jet.OLEDB.4.0' provider is not registered on the local machine

I've the same message, I have a webpage with do on visual studio 2010, I read a file.xls on that page,in my project visual has not any problem, when I put it on my IIS local throw me a 'Microsoft.Jet.OLEDB.4.0' provider is not registered on the local machine' ,I fixed that problem next following this steps,

1.-Open IIS
2.-Change the appPool on Advanced Settings
3.-true to enable to 32-bit application.

and that's all

ps.I changed Configuration Manager to X86 on Active Solution Platform

Writing BMP image in pure c/c++ without other libraries

C++ answer, flexible API, assumes little-endian system to code-golf it a bit. Note this uses the bmp native y-axis (0 at the bottom).

#include <vector>
#include <fstream>

struct image
{   
    image(int width, int height)
    :   w(width), h(height), rgb(w * h * 3)
    {}
    uint8_t & r(int x, int y) { return rgb[(x + y*w)*3 + 2]; }
    uint8_t & g(int x, int y) { return rgb[(x + y*w)*3 + 1]; }
    uint8_t & b(int x, int y) { return rgb[(x + y*w)*3 + 0]; }

    int w, h;
    std::vector<uint8_t> rgb;
};

template<class Stream>
Stream & operator<<(Stream & out, image const& img)
{   
    uint32_t w = img.w, h = img.h;
    uint32_t pad = w * -3 & 3;
    uint32_t total = 54 + 3*w*h + pad*h;
    uint32_t head[13] = {total, 0, 54, 40, w, h, (24<<16)|1};
    char const* rgb = (char const*)img.rgb.data();

    out.write("BM", 2);
    out.write((char*)head, 52);
    for(uint32_t i=0 ; i<h ; i++)
    {   out.write(rgb + (3 * w * i), 3 * w);
        out.write((char*)&pad, pad);
    }
    return out;
}

int main()
{
    image img(100, 100);
    for(int x=0 ; x<100 ; x++)
    {   for(int y=0 ; y<100 ; y++)
        {   img.r(x,y) = x;
            img.g(x,y) = y;
            img.b(x,y) = 100-x;
        }
    }
    std::ofstream("/tmp/out.bmp") << img;
}

TypeScript sorting an array

Numbers

When sorting numbers, you can use the compact comparison:

var numericArray: number[] = [2, 3, 4, 1, 5, 8, 11];

var sortedArray: number[] = numericArray.sort((n1,n2) => n1 - n2);

i.e. - rather than <.

Other Types

If you are comparing anything else, you'll need to convert the comparison into a number.

var stringArray: string[] = ['AB', 'Z', 'A', 'AC'];

var sortedArray: string[] = stringArray.sort((n1,n2) => {
    if (n1 > n2) {
        return 1;
    }

    if (n1 < n2) {
        return -1;
    }

    return 0;
});

Objects

For objects, you can sort based on a property, bear in mind the above information about being able to short-hand number types. The below example works irrespective of the type.

var objectArray: { age: number; }[] = [{ age: 10}, { age: 1 }, {age: 5}];

var sortedArray: { age: number; }[] = objectArray.sort((n1,n2) => {
    if (n1.age > n2.age) {
        return 1;
    }

    if (n1.age < n2.age) {
        return -1;
    }

    return 0;
});

AddTransient, AddScoped and AddSingleton Services Differences

Which one to use

Transient

  • since they are created every time they will use more memory & Resources and can have the negative impact on performance
  • use this for the lightweight service with little or no state.

Scoped

  • better option when you want to maintain state within a request.

Singleton

  • memory leaks in these services will build up over time.
  • also memory efficient as they are created once reused everywhere.

Use Singletons where you need to maintain application wide state. Application configuration or parameters, Logging Service, caching of data is some of the examples where you can use singletons.

Injecting service with different lifetimes into another

  1. Never inject Scoped & Transient services into Singleton service. ( This effectively converts the transient or scoped service into the singleton.)
  2. Never inject Transient services into scoped service ( This converts the transient service into the scoped. )

$(window).scrollTop() vs. $(document).scrollTop()

Cross browser way of doing this is

var top = ($(window).scrollTop() || $("body").scrollTop());

Writing data to a local text file with javascript

Our HTML:

<div id="addnew">
    <input type="text" id="id">
    <input type="text" id="content">
    <input type="button" value="Add" id="submit">
</div>

<div id="check">
    <input type="text" id="input">
    <input type="button" value="Search" id="search">
</div>

JS (writing to the txt file):

function writeToFile(d1, d2){
    var fso = new ActiveXObject("Scripting.FileSystemObject");
    var fh = fso.OpenTextFile("data.txt", 8, false, 0);
    fh.WriteLine(d1 + ',' + d2);
    fh.Close();
}
var submit = document.getElementById("submit");
submit.onclick = function () {
    var id      = document.getElementById("id").value;
    var content = document.getElementById("content").value;
    writeToFile(id, content);
}

checking a particular row:

function readFile(){
    var fso = new ActiveXObject("Scripting.FileSystemObject");
    var fh = fso.OpenTextFile("data.txt", 1, false, 0);
    var lines = "";
    while (!fh.AtEndOfStream) {
        lines += fh.ReadLine() + "\r";
    }
    fh.Close();
    return lines;
}
var search = document.getElementById("search");
search.onclick = function () {
    var input   = document.getElementById("input").value;
    if (input != "") {
        var text    = readFile();
        var lines   = text.split("\r");
        lines.pop();
        var result;
        for (var i = 0; i < lines.length; i++) {
            if (lines[i].match(new RegExp(input))) {
                result = "Found: " + lines[i].split(",")[1];
            }
        }
        if (result) { alert(result); }
        else { alert(input + " not found!"); }
    }
}

Put these inside a .hta file and run it. Tested on W7, IE11. It's working. Also if you want me to explain what's going on, say so.

Sum function in VBA

Place the function value into the cell

Application.Sum often does not work well in my experience (or at least the VBA developer environment does not like it for whatever reason).

The function that works best for me is Excel.WorksheetFunction.Sum()

Example:

Dim Report As Worksheet 'Set up your new worksheet variable.
Set Report = Excel.ActiveSheet 'Assign the active sheet to the variable.

Report.Cells(11, 1).Value = Excel.WorksheetFunction.Sum(Report.Range("A1:A10")) 'Add the function result.

Place the function directly into the cell

The other method which you were looking for I think is to place the function directly into the cell. This can be done by inputting the function string into the cell value. Here is an example that provides the same result as above, except the cell value is given the function and not the result of the function:

    Dim Report As Worksheet 'Set up your new worksheet variable.
    Set Report = Excel.ActiveSheet 'Assign the active sheet to the variable.

    Report.Cells(11, 1).Value = "=Sum(A1:A10)" 'Add the function.

How to force JS to do math instead of putting two strings together

After trying most of the answers here without success for my particular case, I came up with this:

dots = -(-dots - 5);

The + signs are what confuse js, and this eliminates them entirely. Simple to implement, if potentially confusing to understand.

Converting char[] to byte[]

char[] ch = ?
new String(ch).getBytes();

or

new String(ch).getBytes("UTF-8");

to get non-default charset.

Update: Since Java 7: new String(ch).getBytes(StandardCharsets.UTF_8);

Ruby: Can I write multi-line string with no concatenation?

There are multiple syntaxes for multi-line strings as you've already read. My favorite is Perl-style:

conn.exec %q{select attr1, attr2, attr3, attr4, attr5, attr6, attr7
      from table1, table2, table3, etc, etc, etc, etc, etc,
      where etc etc etc etc etc etc etc etc etc etc etc etc etc}

The multi-line string starts with %q, followed by a {, [ or (, and then terminated by the corresponding reversed character. %q does not allow interpolation; %Q does so you can write things like this:

conn.exec %Q{select attr1, attr2, attr3, attr4, attr5, attr6, attr7
      from #{table_names},
      where etc etc etc etc etc etc etc etc etc etc etc etc etc}

I actually have no idea how these kinds of multi-line strings are called so let's just call them Perl multilines.

Note however that whether you use Perl multilines or heredocs as Mark and Peter have suggested, you'll end up with potentially unnecessary whitespaces. Both in my examples and their examples, the "from" and "where" lines contain leading whitespaces because of their indentation in the code. If this whitespace is not desired then you must use concatenated strings as you are doing now.

How to take the nth digit of a number in python

I would recommend adding a boolean check for the magnitude of the number. I'm converting a high milliseconds value to datetime. I have numbers from 2 to 200,000,200 so 0 is a valid output. The function as @Chris Mueller has it will return 0 even if number is smaller than 10**n.

def get_digit(number, n):
    return number // 10**n % 10

get_digit(4231, 5)
# 0

def get_digit(number, n):
    if number - 10**n < 0:
        return False
    return number // 10**n % 10

get_digit(4321, 5)
# False

You do have to be careful when checking the boolean state of this return value. To allow 0 as a valid return value, you cannot just use if get_digit:. You have to use if get_digit is False: to keep 0 from behaving as a false value.

Create an instance of a class from a string

Its pretty simple. Assume that your classname is Car and the namespace is Vehicles, then pass the parameter as Vehicles.Car which returns object of type Car. Like this you can create any instance of any class dynamically.

public object GetInstance(string strFullyQualifiedName)
{         
     Type t = Type.GetType(strFullyQualifiedName); 
     return  Activator.CreateInstance(t);         
}

If your Fully Qualified Name(ie, Vehicles.Car in this case) is in another assembly, the Type.GetType will be null. In such cases, you have loop through all assemblies and find the Type. For that you can use the below code

public object GetInstance(string strFullyQualifiedName)
{
     Type type = Type.GetType(strFullyQualifiedName);
     if (type != null)
         return Activator.CreateInstance(type);
     foreach (var asm in AppDomain.CurrentDomain.GetAssemblies())
     {
         type = asm.GetType(strFullyQualifiedName);
         if (type != null)
             return Activator.CreateInstance(type);
     }
     return null;
 }

Now if you want to call a parameterized constructor do the following

Activator.CreateInstance(t,17); // Incase you are calling a constructor of int type

instead of

Activator.CreateInstance(t);

How to get files in a relative path in C#

As others have said, you can/should prepend the string with @ (though you could also just escape the backslashes), but what they glossed over (that is, didn't bring it up despite making a change related to it) was the fact that, as I recently discovered, using \ at the beginning of a pathname, without . to represent the current directory, refers to the root of the current directory tree.

C:\foo\bar>cd \
C:\>

versus

C:\foo\bar>cd .\
C:\foo\bar>

(Using . by itself has the same effect as using .\ by itself, from my experience. I don't know if there are any specific cases where they somehow would not mean the same thing.)

You could also just leave off the leading .\ , if you want.

C:\foo>cd bar
C:\foo\bar>

In fact, if you really wanted to, you don't even need to use backslashes. Forwardslashes work perfectly well! (Though a single / doesn't alias to the current drive root as \ does.)

C:\>cd foo/bar
C:\foo\bar>

You could even alternate them.

C:\>cd foo/bar\baz
C:\foo\bar\baz>

...I've really gone off-topic here, though, so feel free to ignore all this if you aren't interested.

Lotus Notes email as an attachment to another email

Although probably not exactly what your looking for and you probably don't care at this point since the question was asked 5 years ago, one method is to use "forward".

Go to your inbox or wherever your messages are and select the 2+ messages you want to send than simply click forward... all messages get combined into 1.

jQuery, simple polling example

jQuery.Deferred() can simplify management of asynchronous sequencing and error handling.

polling_active = true // set false to interrupt polling

function initiate_polling()
    {
    $.Deferred().resolve() // optional boilerplate providing the initial 'then()'
    .then( () => $.Deferred( d=>setTimeout(()=>d.resolve(),5000) ) ) // sleep
    .then( () => $.get('/my-api') ) // initiate AJAX
    .then( response =>
        {
        if ( JSON.parse(response).my_result == my_target ) polling_active = false
        if ( ...unhappy... ) return $.Deferred().reject("unhappy") // abort
        if ( polling_active ) initiate_polling() // iterative recursion
        })
    .fail( r => { polling_active=false, alert('failed: '+r) } ) // report errors
    }

This is an elegant approach, but there are some gotchas...

  • If you don't want a then() to fall through immediately, the callback should return another thenable object (probably another Deferred), which the sleep and ajax lines both do.
  • The others are too embarrassing to admit. :)

How to unit test abstract classes: extend with stubs?

I would argue against "abstract" tests. I think a test is a concrete idea and doesn't have an abstraction. If you have common elements, put them in helper methods or classes for everyone to use.

As for testing an abstract test class, make sure you ask yourself what it is you're testing. There are several approaches, and you should find out what works in your scenario. Are you trying to test out a new method in your subclass? Then have your tests only interact with that method. Are you testing the methods in your base class? Then probably have a separate fixture only for that class, and test each method individually with as many tests as necessary.

VBA Print to PDF and Save with Automatic File Name

Hopefully this is self explanatory enough. Use the comments in the code to help understand what is happening. Pass a single cell to this function. The value of that cell will be the base file name. If the cell contains "AwesomeData" then we will try and create a file in the current users desktop called AwesomeData.pdf. If that already exists then try AwesomeData2.pdf and so on. In your code you could just replace the lines filename = Application..... with filename = GetFileName(Range("A1"))

Function GetFileName(rngNamedCell As Range) As String
    Dim strSaveDirectory As String: strSaveDirectory = ""
    Dim strFileName As String: strFileName = ""
    Dim strTestPath As String: strTestPath = ""
    Dim strFileBaseName As String: strFileBaseName = ""
    Dim strFilePath As String: strFilePath = ""
    Dim intFileCounterIndex As Integer: intFileCounterIndex = 1

    ' Get the users desktop directory.
    strSaveDirectory = Environ("USERPROFILE") & "\Desktop\"
    Debug.Print "Saving to: " & strSaveDirectory

    ' Base file name
    strFileBaseName = Trim(rngNamedCell.Value)
    Debug.Print "File Name will contain: " & strFileBaseName

    ' Loop until we find a free file number
    Do
        If intFileCounterIndex > 1 Then
            ' Build test path base on current counter exists.
            strTestPath = strSaveDirectory & strFileBaseName & Trim(Str(intFileCounterIndex)) & ".pdf"
        Else
            ' Build test path base just on base name to see if it exists.
            strTestPath = strSaveDirectory & strFileBaseName & ".pdf"
        End If

        If (Dir(strTestPath) = "") Then
            ' This file path does not currently exist. Use that.
            strFileName = strTestPath
        Else
            ' Increase the counter as we have not found a free file yet.
            intFileCounterIndex = intFileCounterIndex + 1
        End If

    Loop Until strFileName <> ""

    ' Found useable filename
    Debug.Print "Free file name: " & strFileName
    GetFileName = strFileName

End Function

The debug lines will help you figure out what is happening if you need to step through the code. Remove them as you see fit. I went a little crazy with the variables but it was to make this as clear as possible.

In Action

My cell O1 contained the string "FileName" without the quotes. Used this sub to call my function and it saved a file.

Sub Testing()
    Dim filename As String: filename = GetFileName(Range("o1"))

    ActiveWorkbook.Worksheets("Sheet1").Range("A1:N24").ExportAsFixedFormat Type:=xlTypePDF, _
                                              filename:=filename, _
                                              Quality:=xlQualityStandard, _
                                              IncludeDocProperties:=True, _
                                              IgnorePrintAreas:=False, _
                                              OpenAfterPublish:=False
End Sub

Where is your code located in reference to everything else? Perhaps you need to make a module if you have not already and move your existing code into there.

Object creation on the stack/heap?

C++ offers three different ways to create objects:

  1. Stack-based such as temporary objects
  2. Heap-based by using new
  3. Static memory allocation such as global variables and namespace-scope objects

Consider your case,

Object* o;
o = new Object();

and:

Object* o = new Object();

Both forms are the same. This means that a pointer variable o is created on the stack (assume your variables does not belong to the 3 category above) and it points to a memory in the heap, which contains the object.

Is it possible to set ENV variables for rails development environment in my code?

The way I am trying to do this in my question actually works!

# environment/development.rb

ENV['admin_password'] = "secret" 

I just had to restart the server. I thought running reload! in rails console would be enough but I also had to restart the web server.

I am picking my own answer because I feel this is a better place to put and set the ENV variables

Installing TensorFlow on Windows (Python 3.6.x)

For the GPU version, see my answer here.

In short, install Anaconda, then open an anaconda terminal and type conda create --name tf_gpu tensorflow-gpu

You are then free to use the conda environment tf_gpu

How to split a delimited string into an array in awk?

echo "12|23|11" | awk '{split($0,a,"|"); print a[3] a[2] a[1]}'

should work.

Numpy: Creating a complex array from 2 real ones?

If your real and imaginary parts are the slices along the last dimension and your array is contiguous along the last dimension, you can just do

A.view(dtype=np.complex128)

If you are using single precision floats, this would be

A.view(dtype=np.complex64)

Here is a fuller example

import numpy as np
from numpy.random import rand
# Randomly choose real and imaginary parts.
# Treat last axis as the real and imaginary parts.
A = rand(100, 2)
# Cast the array as a complex array
# Note that this will now be a 100x1 array
A_comp = A.view(dtype=np.complex128)
# To get the original array A back from the complex version
A = A.view(dtype=np.float64)

If you want to get rid of the extra dimension that stays around from the casting, you could do something like

A_comp = A.view(dtype=np.complex128)[...,0]

This works because, in memory, a complex number is really just two floating point numbers. The first represents the real part, and the second represents the imaginary part. The view method of the array changes the dtype of the array to reflect that you want to treat two adjacent floating point values as a single complex number and updates the dimension accordingly.

This method does not copy any values in the array or perform any new computations, all it does is create a new array object that views the same block of memory differently. That makes it so that this operation can be performed much faster than anything that involves copying values. It also means that any changes made in the complex-valued array will be reflected in the array with the real and imaginary parts.

It may also be a little trickier to recover the original array if you remove the extra axis that is there immediately after the type cast. Things like A_comp[...,np.newaxis].view(np.float64) do not currently work because, as of this writing, NumPy doesn't detect that the array is still C-contiguous when the new axis is added. See this issue. A_comp.view(np.float64).reshape(A.shape) seems to work in most cases though.

Click a button with XPath containing partial id and title in Selenium IDE

Now that you have provided your HTML sample, we're able to see that your XPath is slightly wrong. While it's valid XPath, it's logically wrong.

You've got:

//*[contains(@id, 'ctl00_btnAircraftMapCell')]//*[contains(@title, 'Select Seat')]

Which translates into:

Get me all the elements that have an ID that contains ctl00_btnAircraftMapCell. Out of these elements, get any child elements that have a title that contains Select Seat.

What you actually want is:

//a[contains(@id, 'ctl00_btnAircraftMapCell') and contains(@title, 'Select Seat')]

Which translates into:

Get me all the anchor elements that have both: an id that contains ctl00_btnAircraftMapCell and a title that contains Select Seat.

Find the item with maximum occurrences in a list

Here is a defaultdict solution that will work with Python versions 2.5 and above:

from collections import defaultdict

L = [1,2,45,55,5,4,4,4,4,4,4,5456,56,6,7,67]
d = defaultdict(int)
for i in L:
    d[i] += 1
result = max(d.iteritems(), key=lambda x: x[1])
print result
# (4, 6)
# The number 4 occurs 6 times

Note if L = [1, 2, 45, 55, 5, 4, 4, 4, 4, 4, 4, 5456, 7, 7, 7, 7, 7, 56, 6, 7, 67] then there are six 4s and six 7s. However, the result will be (4, 6) i.e. six 4s.

Can I make a <button> not submit a form?

Just use good old HTML:

<input type="button" value="Submit" />

Wrap it as the subject of a link, if you so desire:

<a href="http://somewhere.com"><input type="button" value="Submit" /></a>

Or if you decide you want javascript to provide some other functionality:

<input type="button" value="Cancel" onclick="javascript: someFunctionThatCouldIncludeRedirect();"/>

Enter triggers button click

Pressing enter in a form's text field will, by default, submit the form. If you don't want it to work that way you have to capture the enter key press and consume it like you've done. There is no way around this. It will work this way even if there is no button present in the form.

Using CMake with GNU Make: How can I see the exact commands?

I was trying something similar to ensure the -ggdb flag was present.

Call make in a clean directory and grep the flag you are looking for. Looking for debug rather than ggdb I would just write.

make VERBOSE=1 | grep debug

The -ggdb flag was obscure enough that only the compile commands popped up.

S3 limit to objects in a bucket

According to Amazon:

Write, read, and delete objects containing from 0 bytes to 5 terabytes of data each. The number of objects you can store is unlimited.

Source: http://aws.amazon.com/s3/details/ as of Sep 3, 2015.

How do I replace part of a string in PHP?

You can try

$string = "this is the test for string." ;
$string = str_replace(' ', '_', $string);
$string = substr($string,0,10);

var_dump($string);

Output

this_is_th

How to Compare two strings using a if in a stored procedure in sql server 2008?

What you want is a SQL case statement. The form of these is either:

  select case [expression or column]
  when [value] then [result]
  when [value2] then [result2]
  else [value3] end

or:

  select case 
  when [expression or column] = [value] then [result]
  when [expression or column] = [value2] then [result2]
  else [value3] end

In your example you are after:

declare @temp as varchar(100)
set @temp='Measure'

select case @temp 
   when 'Measure' then Measure 
   else OtherMeasure end
from Measuretable

Multiple conditions in WHILE loop

Your condition is wrong. myChar != 'n' || myChar != 'N' will always be true.

Use myChar != 'n' && myChar != 'N' instead

Oracle - Why does the leading zero of a number disappear when converting it TO_CHAR

I was looking for a way to format numbers without leading or trailing spaces, periods, zeros (except one leading zero for numbers less than 1 that should be present).

This is frustrating that such most usual formatting can't be easily achieved in Oracle.

Even Tom Kyte only suggested long complicated workaround like this:

case when trunc(x)=x
    then to_char(x, 'FM999999999999999999')
    else to_char(x, 'FM999999999999999.99')
end x

But I was able to find shorter solution that mentions the value only once:

rtrim(to_char(x, 'FM999999999999990.99'), '.')

This works as expected for all possible values:

select 
    to_char(num, 'FM99.99') wrong_leading_period,
    to_char(num, 'FM90.99') wrong_trailing_period,
    rtrim(to_char(num, 'FM90.99'), '.') correct
from (
  select num from (select 0.25 c1, 0.1 c2, 1.2 c3, 13 c4, -70 c5 from dual)
  unpivot (num for dummy in (c1, c2, c3, c4, c5))
) sampledata;

    | WRONG_LEADING_PERIOD | WRONG_TRAILING_PERIOD | CORRECT |
    |----------------------|-----------------------|---------|
    |                  .25 |                  0.25 |    0.25 |
    |                   .1 |                   0.1 |     0.1 |
    |                  1.2 |                   1.2 |     1.2 |
    |                  13. |                   13. |      13 |
    |                 -70. |                  -70. |     -70 |

Still looking for even shorter solution.

There is a shortening approarch with custom helper function:

create or replace function str(num in number) return varchar2
as
begin
    return rtrim(to_char(num, 'FM999999999999990.99'), '.');
end;

But custom pl/sql functions have significant performace overhead that is not suitable for heavy queries.

How to create a private class method?

As of ruby 2.3.0

class Check
  def self.first_method
    second_method
  end

  private
  def self.second_method
    puts "well I executed"
  end
end

Check.first_method
#=> well I executed

How can I find the version of php that is running on a distinct domain name?

There is a possibility to find the PHP version of other domain by checking "X-Powered-By" response header in the browser through developer tools as other already mentioned it. If it is not exposed through the php.ini configuration there is no way you can get it unless you have access to the server.

How to parse a string into a nullable int

Glenn Slaven: I'm more interested in knowing if there is a built-in framework method that will parse directly into a nullable int?

There is this approach that will parse directly to a nullable int (and not just int) if the value is valid like null or empty string, but does throw an exception for invalid values so you will need to catch the exception and return the default value for those situations:

public static T Parse<T>(object value)
{
    try { return (T)System.ComponentModel.TypeDescriptor.GetConverter(typeof(T)).ConvertFrom(value.ToString()); }
    catch { return default(T); }
}

This approach can still be used for non-nullable parses as well as nullable:

enum Fruit { Orange, Apple }
var res1 = Parse<Fruit>("Apple");
var res2 = Parse<Fruit?>("Banana");
var res3 = Parse<int?>("100") ?? 5; //use this for non-zero default
var res4 = Parse<Unit>("45%");

NB: There is an IsValid method on the converter you can use instead of capturing the exception (thrown exceptions does result in unnecessary overhead if expected). Unfortunately it only works since .NET 4 but there's still an issue where it doesn't check your locale when validating correct DateTime formats, see bug 93559.

AngularJS toggle class using ng-class

<div data-ng-init="featureClass=false" 
     data-ng-click="featureClass=!featureClass" 
     data-ng-class="{'active': featureClass}">
    Click me to toggle my class!
</div>

Analogous to jQuery's toggleClass method, this is a way to toggle the active class on/off when the element is clicked.

Set Matplotlib colorbar size to match graph

You can do this easily with a matplotlib AxisDivider.

The example from the linked page also works without using subplots:

import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
import numpy as np

plt.figure()
ax = plt.gca()
im = ax.imshow(np.arange(100).reshape((10,10)))

# create an axes on the right side of ax. The width of cax will be 5%
# of ax and the padding between cax and ax will be fixed at 0.05 inch.
divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="5%", pad=0.05)

plt.colorbar(im, cax=cax)

enter image description here

Align labels in form next to input

You can also try using flex-box

<head><style>
body {
    color:white;
    font-family:arial;
    font-size:1.2em;
}
form {
    margin:0 auto;
    padding:20px;
    background:#444;
}
.input-group {
    margin-top:10px;
    width:60%;
    display:flex;
    justify-content:space-between;
    flex-wrap:wrap;
}
label, input {
    flex-basis:100px;
}
</style></head>
<body>

<form>
    <div class="wrapper">
        <div class="input-group">
            <label for="user_name">name:</label>
            <input type="text" id="user_name">
        </div>
        <div class="input-group">
            <label for="user_pass">Password:</label>
            <input type="password" id="user_pass">
        </div>
    </div>
</form>

</body>
</html>

HTTP Error 503, the service is unavailable

Actually, in my case https://localhost was working, but http://localhost gave a HTTP 503 Internal server error. Changing the Binding of Default Web Site in IIS to use the hostname localhost instead of a blank host name.

IIS Site bindings for HTTPtname for http binding

Confirm deletion using Bootstrap 3 modal box

Create modal dialog in HTML with id="confirmation" and use function showConfirmation.

Also remember you should to unbind (modal.unbind()) cancel and success buttons after hide modal dialog. If you do not make this you will get double binding. For example: if you open dialog once and press 'Cancel' and then open dialog in second time and press 'Ok' you will get 2 executions of success callback.

showConfirmation = function(title, message, success, cancel) {
    title = title ? title : 'Are you sure?';
    var modal = $("#confirmation");
    modal.find(".modal-title").html(title).end()
        .find(".modal-body").html(message).end()
        .modal({ backdrop: 'static', keyboard: false })
        .on('hidden.bs.modal', function () {
            modal.unbind();
        });
    if (success) {
        modal.one('click', '.modal-footer .btn-primary', success);
    }
    if (cancel) {
        modal.one('click', '.modal-header .close, .modal-footer .btn-default', cancel);
    }
};

// bind confirmation dialog on delete buttons
$(document).on("click", ".delete-event, .delete-all-event", function(event){
    event.preventDefault();
    var self = $(this);
    var url = $(this).data('url');
    var success = function(){
        alert('window.location.href=url');
    }
    var cancel = function(){
        alert('Cancel');
    };
    if (self.data('confirmation')) {
        var title = self.data('confirmation-title') ? self.data('confirmation-title') : undefined;
        var message = self.data('confirmation');
        showConfirmation(title, message, success, cancel);
    } else {
        success();
    }
});

https://jsfiddle.net/yiiBoy/hne9sp6g/

How to comment out a block of Python code in Vim

NERDcommenter is an excellent plugin for commenting which automatically detects a number of filetypes and their associated comment characters. Ridiculously easy to install using Pathogen.

Comment with <leader>cc. Uncomment with <leader>cu. And toggle comments with <leader>c<space>.

(The default <leader> key in vim is \)

Setting up an MS-Access DB for multi-user access

Access is a great multi-user database. It has lots of built in features to handle the multi-user situation. In fact, it is so very popular because it is such a great multi-user database. There is an upper limit on how many users can all use the database at the same time doing updates and edits - depending on how knowledgeable the developer is about access and how the database has been designed - anywhere from 20 users to approx 50 users. Some access databases can be built to handle up to 50 concurrent users, while many others can handle 20 or 25 concurrent users updating the database. These figures have been observed for databases that have been in use for several or more years and have been discussed many times on the access newsgroups.

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

I think the poster meant to say You do not have to allocate everything on theheap rather than the the stack.

Basically objects are allocated on the stack (if the object size allows, of course) because of the cheap cost of stack-allocation, rather than heap-based allocation which involves quite some work by the allocator, and adds verbosity because then you have to manage data allocated on the heap.

What is the difference between an expression and a statement in Python?

Statements represent an action or command e.g print statements, assignment statements.

print 'hello', x = 1

Expression is a combination of variables, operations and values that yields a result value.

5 * 5 # yields 25

Lastly, expression statements

print 5*5

Set variable value to array of strings

declare  @tab table(FirstName  varchar(100))
insert into @tab   values('John'),('Sarah'),('George')

SELECT * 
FROM @tab
WHERE 'John' in (FirstName)

Creating a singleton in Python

How about this:

def singleton(cls):
    instance=cls()
    cls.__new__ = cls.__call__= lambda cls: instance
    cls.__init__ = lambda self: None
    return instance

Use it as a decorator on a class that should be a singleton. Like this:

@singleton
class MySingleton:
    #....

This is similar to the singleton = lambda c: c() decorator in another answer. Like the other solution, the only instance has name of the class (MySingleton). However, with this solution you can still "create" instances (actually get the only instance) from the class, by doing MySingleton(). It also prevents you from creating additional instances by doing type(MySingleton)() (that also returns the same instance).

Convert json to a C# array?

just take the string and use the JavaScriptSerializer to deserialize it into a native object. For example, having this json:

string json = "[{Name:'John Simith',Age:35},{Name:'Pablo Perez',Age:34}]"; 

You'd need to create a C# class called, for example, Person defined as so:

public class Person
{
 public int Age {get;set;}
 public string Name {get;set;}
}

You can now deserialize the JSON string into an array of Person by doing:

JavaScriptSerializer js = new JavaScriptSerializer();
Person [] persons =  js.Deserialize<Person[]>(json);

Here's a link to JavaScriptSerializer documentation.

Note: my code above was not tested but that's the idea Tested it. Unless you are doing something "exotic", you should be fine using the JavascriptSerializer.

Creating a simple login form

Check it - You can try this code for your login form design as you ask thank you.

Explain css -

First, we define property font style and width And after that I have defined form id to set background image and the border And after that I have to define the header text in tag and after that I have added new and define by.New to set background properties and width. Thanks

Create a file index.html

<!DOCTYPE html>
<html>
   <head>
      <link rel="stylesheet" href="style.css">
   </head>
   <body>
      <div id="login_form">
         <div class="new"><span>enter login details</span></div>
         <!-- This is your header text-->
         <form name="f1" method="post" action="login.php" id="f1">
            <table>
               <tr>
                  <td class="f1_label">User Name :</td>
                  <!-- This is your first Input Box Label-->
                  <td>
                     <input type="text" name="username" value="" /><!-- This is your first Input Box-->
                  </td>
               </tr>
               <tr>
                  <td class="f1_label">Password  :</td>
                  <!-- This is your Second Input Box Label-->
                  <td>
                     <input type="password" name="password" value=""  /><!-- This is your Second Input Box -->
                  </td>
               </tr>
               <tr>
                  <td>
                     <input type="submit" name="login" value="Log In" style="font-size:18px; " /><!-- This is your submit button -->
                  </td>
               </tr>
            </table>
         </form>
      </div>
   </body>
</html>

Create css file style.css

body {
    font-style: italic;
    width: 50%;
    margin: 0px auto;
}

#login_form {}

#f1 {
    background-color: #FFF;
    border-style: solid;
    border-width: 1px;
    padding: 23px 1px 20px 114px;
}

.f1_label {
    white-space: nowrap;
}

span {
    color: white;
}

.new {
    background: black;
    text-align: center;
}

failed to find target with hash string 'android-22'

I had similar issue. I updated android studio build tools and my project didn't find "android-22". I looked in android sdk manager and it was installed.

To fix this issue I uninstalled "android-22" and installed again.

Comparing two NumPy arrays for equality, element-wise

The (A==B).all() solution is very neat, but there are some built-in functions for this task. Namely array_equal, allclose and array_equiv.

(Although, some quick testing with timeit seems to indicate that the (A==B).all() method is the fastest, which is a little peculiar, given it has to allocate a whole new array.)

Simple way to find if two different lists contain exactly the same elements?

Sample code:

public static '<'T'>' boolean isListDifferent(List'<'T'>' previousList,
        List'<'T'>' newList) {

    int sizePrevoisList = -1;
    int sizeNewList = -1;

    if (previousList != null && !previousList.isEmpty()) {
        sizePrevoisList = previousList.size();
    }
    if (newList != null && !newList.isEmpty()) {
        sizeNewList = newList.size();
    }

    if ((sizePrevoisList == -1) && (sizeNewList == -1)) {
        return false;
    }

    if (sizeNewList != sizePrevoisList) {
        return true;
    }

    List n_prevois = new ArrayList(previousList);
    List n_new = new ArrayList(newList);

    try {
        Collections.sort(n_prevois);
        Collections.sort(n_new);
    } catch (ClassCastException exp) {
        return true;
    }

    for (int i = 0; i < sizeNewList; i++) {
        Object obj_prevois = n_prevois.get(i);
        Object obj_new = n_new.get(i);
        if (obj_new.equals(obj_prevois)) {
            // Object are same
        } else {
            return true;
        }
    }

    return false;
}

Run reg command in cmd (bat file)?

If memory serves correct, the reg add command will NOT create the entire directory path if it does not exist. Meaning that if any of the parent registry keys do not exist then they must be created manually one by one. It is really annoying, I know! Example:

@echo off
reg add "HKCU\Software\Policies"
reg add "HKCU\Software\Policies\Microsoft"
reg add "HKCU\Software\Policies\Microsoft\Internet Explorer"
reg add "HKCU\Software\Policies\Microsoft\Internet Explorer\Control Panel"
reg add "HKCU\Software\Policies\Microsoft\Internet Explorer\Control Panel" /v HomePage /t REG_DWORD /d 1 /f
pause

Making an image act like a button

You could implement a JavaScript block which contains a function with your needs.

<div style="position: absolute; left: 10px; top: 40px;"> 
    <img src="logg.png" width="114" height="38" onclick="DoSomething();" />
</div>

How to add /usr/local/bin in $PATH on Mac

Try placing $PATH at the end.

export PATH=/usr/local/git/bin:/usr/local/bin:$PATH

Getting the application's directory from a WPF application

I tried this:

    label1.Content = Directory.GetCurrentDirectory();

and get also the directory.

Add ... if string is too long PHP

You can use str_split() for this

$str = "Hello, this is the first example, where I am going to have a string that is over 50 characters and is super long, I don't know how long maybe around 1000 characters. Anyway this should be over 50 characters know...";
$split = str_split($str, 50);
$final = $split[0] . "...";
echo $final;

C# Macro definitions in Preprocessor

Since C# 7.0 supports using static directive and Local functions you don't need preprocessor macros for most cases.

Getting "Skipping JaCoCo execution due to missing execution data file" upon executing JaCoCo

In my case, the prepare agent had a different destFile in configuration, but accordingly the report had to be configured with a dataFile, but this configuration was missing. Once the dataFile was added, it started working fine.

Creating a new ArrayList in Java

You're very close. Use same type on both sides, and include ().

ArrayList<Class> myArray = new ArrayList<Class>();

How to view UTF-8 Characters in VIM or Gvim

If Japanese people come here, please add the following lines to your ~/.vimrc

set encoding=utf-8
set fileencodings=iso-2022-jp,euc-jp,sjis,utf-8
set fileformats=unix,dos,mac

Execute a batch file on a remote PC using a batch file on local PC

While I would recommend against this.

But you can use shutdown as client if the target machine has remote shutdown enabled and is in the same workgroup.

Example:

shutdown.exe /s /m \\<target-computer-name> /t 00

replacing <target-computer-name> with the URI for the target machine,

Otherwise, if you want to trigger this through Apache, you'll need to configure the batch script as a CGI script by putting AddHandler cgi-script .bat and Options +ExecCGI into either a local .htaccess file or in the main configuration for your Apache install.

Then you can just call the .bat file containing the shutdown.exe command from your browser.

Fitting iframe inside a div

Based on the link provided by @better_use_mkstemp, here's a fiddle where nested iframe resizes to fill parent div: http://jsfiddle.net/orlenko/HNyJS/

Html:

<div id="content">
    <iframe src="http://www.microsoft.com" name="frame2" id="frame2" frameborder="0" marginwidth="0" marginheight="0" scrolling="auto" onload="" allowtransparency="false"></iframe>
</div>
<div id="block"></div>
<div id="header"></div>
<div id="footer"></div>

Relevant parts of CSS:

div#content {
    position: fixed;
    top: 80px;
    left: 40px;
    bottom: 25px;
    min-width: 200px;
    width: 40%;
    background: black;
}

div#content iframe {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    height: 100%;
    width: 100%;
}

How to get value of checked item from CheckedListBox?

You can iterate over the CheckedItems property:

foreach(object itemChecked in checkedListBox1.CheckedItems)
{
    MyCompanyClass company = (MyCompanyClass)itemChecked;    
    MessageBox.Show("ID: \"" + company.ID.ToString());
}

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

JVM heap parameters

if you wrote: -Xms512m -Xmx512m when it start, java allocate in those moment 512m of ram for his process and cant increment.

-Xms64m -Xmx512m when it start, java allocate only 64m of ram for his process, but java can be increment his memory occupation while 512m.

I think that second thing is better because you give to java the automatic memory management.

android:layout_height 50% of the screen size

This is my android:layout_height=50% activity:

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

    <LinearLayout
        android:id="@+id/alipay_login"
        style="@style/loginType"
        android:background="#27b" >
    </LinearLayout>

    <LinearLayout
        android:id="@+id/taobao_login"
        style="@style/loginType"
        android:background="#ed6d00" >
    </LinearLayout>

</LinearLayout>

style:

<style name="loginType">
    <item name="android:layout_width">match_parent</item>
    <item name="android:layout_height">match_parent</item>
    <item name="android:layout_weight">0.5</item>
    <item name="android:orientation">vertical</item>
</style>

3D Plotting from X, Y, Z Data, Excel or other Tools

You really can't display 3 columns of data as a 'surface'. Only having one column of 'Z' data will give you a line in 3 dimensional space, not a surface (Or in the case of your data, 3 separate lines). For Excel to be able to work with this data, it needs to be formatted as shown below:

      13    21   29      37    45   
1000  75.2                              
1000       79.21                            
1000             80.02                      
5000             87.9                   
5000                    88.54               
5000                           88.56            
10000            90.11      
10000                   90.79   
10000                          90.87

Then, to get an actual surface, you would need to fill in all the missing cells with the appropriate Z-values. If you don't have those, then you are better off showing this as 3 separate 2D lines, because there isn't enough data for a surface.

The best 3D representation that Excel will give you of the above data is pretty confusing:

enter image description here

Representing this limited dataset as 2D data might be a better choice:

enter image description here

As a note for future reference, these types of questions usually do a little better on superuser.com.

batch to copy files with xcopy

Based on xcopy help, I tried and found that following works perfectly for me (tried on Win 7)

xcopy C:\folder1 C:\folder2\folder1 /E /C /I /Q /G /H /R /K /Y /Z /J

Insert multiple values using INSERT INTO (SQL Server 2005)

You can also use the following syntax:-

INSERT INTO MyTable (FirstCol, SecondCol)
SELECT 'First' ,1
UNION ALL
SELECT 'Second' ,2
UNION ALL
SELECT 'Third' ,3
UNION ALL
SELECT 'Fourth' ,4
UNION ALL
SELECT 'Fifth' ,5
GO

From here

Base64 encoding in SQL Server 2005 T-SQL

No, there is no native function, this method has worked for me in the past: http://www.motobit.com/help/scptutl/sa306.htm
so has this method:
http://www.vbforums.com/showthread.php?t=554886

Unknown SSL protocol error in connection

This error happen to me when push big amount of sources (Nearly 700Mb), then I try to push it partially and it was successfully pushed.

How to access the local Django webserver from outside world

If you are using Docker you need to make sure ports are exposed as well

When and Why to use abstract classes/methods?

At a very high level:

Abstraction of any kind comes down to separating concerns. "Client" code of an abstraction doesn't care how the contract exposed by the abstraction is fulfilled. You usually don't care if a string class uses a null-terminated or buffer-length-tracked internal storage implementation, for example. Encapsulation hides the details, but by making classes/methods/etc. abstract, you allow the implementation to change or for new implementations to be added without affecting the client code.

Using Excel as front end to Access database (with VBA)

I'm sure you'll get a ton of "don't do this" answers, and I must say, there is good reason. This isn't an ideal solution....

That being said, I've gone down this road (and similar ones) before, mostly because the job specified it as a hard requirement and I couldn't talk around it.

Here are a few things to consider with this:

How easy is it to link to Access from Excel using ADO / DAO? Is it quite limited in terms of functionality or can I get creative?

It's fairly straitforward. You're more limited than you would be doing things using other tools, since VBA and Excel forms is a bit more limiting than most full programming languages, but there isn't anything that will be a show stopper. It works - sometimes its a bit ugly, but it does work. In my last company, I often had to do this - and occasionally was pulling data from Access and Oracle via VBA in Excel.

Do I pay a performance penalty (vs.using forms in Access as the UI)?

My experience is that there is definitely a perf. penalty in doing this. I never cared (in my use case, things were small enough that it was reasonable), but going Excel<->Access is a lot slower than just working in Access directly. Part of it depends on what you want to do....

In my case, the thing that seemed to be the absolute slowest (and most painful) was trying to fill in Excel spreadsheets based on Access data. This wasn't fun, and was often very slow. If you have to go down this road, make sure to do everything with Excel hidden/invisible, or the redrawing will absolutely kill you.

Assuming that the database will always be updated using ADO / DAO commands from within Excel VBA, does that mean I can have multiple Excel users using that one single Access database and not run into any concurrency issues etc.?

You're pretty much using Excel as a client - the same way you would use a WinForms application or any other tool. The ADO/DAO clients for Access are pretty good, so you probably won't run into any concurrency issues.

That being said, Access does NOT scale well. This works great if you have 2 or 3 (or even 10) users. If you are going to have 100, you'll probably run into problems. Also, I tended to find that Access needed regular maintenance in order to not have corruption issues. Regular backups of the Access DB are a must. Compacting the access database on a regular basis will help prevent database corruption, in my experience.

Any other things I should be aware of?

You're doing this the hard way. Using Excel to hit Access is going to be a lot more work than just using Access directly.

I'd recommend looking into the Access VBA API - most of it is the same as Excel, so you'll have a small learning curve. The parts that are different just make this easier. You'll also have all of the advantages of Access reporting and Forms, which are much more data-oriented than the ones in Excel. The reporting can be great for things like this, and having the Macros and Reports will make life easier in the long run. If the user's going to be using forms to manage everything, doing the forms in Access will be very, very similar to doing them in Excel, and will look nearly identical, but will make everything faster and smoother.

How to draw a dotted line with css?

Using HTML:

<div class="horizontal_dotted_line"></div>

and in styles.css:

.horizontal_dotted_line{
  border-bottom: 1px dotted [color];
  width: [put your width here]px;
} 

Two dimensional array list

Declaring a two dimensional ArrayList:

ArrayList<ArrayList<String>> rows = new ArrayList<String>();

Or

ArrayList<ArrayList<String>> rows = new ArrayList<>();

Or

ArrayList<ArrayList<String>> rows = new ArrayList<ArrayList<String>>(); 

All the above are valid declarations for a two dimensional ArrayList!

Now, Declaring a one dimensional ArrayList:

ArrayList<String> row = new ArrayList<>();

Inserting values in the two dimensional ArrayList:

for(int i=0; i<5; i++){
    ArrayList<String> row = new ArrayList<>();
    for(int j=0; j<5; j++){
        row.add("Add values here"); 
    }
    rows.add(row); 
}

fetching the values from the two dimensional ArrayList:

for(int i=0; i<5; i++){
    for(int j=0; j<5; j++){
        System.out.print(rows.get(i).get(j)+" ");
     }
     System.out.println("");
}

Looping through a hash, or using an array in PowerShell

I prefer this variant on the enumerator method with a pipeline, because you don't have to refer to the hash table in the foreach (tested in PowerShell 5):

$hash = @{
    'a' = 3
    'b' = 2
    'c' = 1
}
$hash.getEnumerator() | foreach {
    Write-Host ("Key = " + $_.key + " and Value = " + $_.value);
}

Output:

Key = c and Value = 1
Key = b and Value = 2
Key = a and Value = 3

Now, this has not been deliberately sorted on value, the enumerator simply returns the objects in reverse order.

But since this is a pipeline, I now can sort the objects received from the enumerator on value:

$hash.getEnumerator() | sort-object -Property value -Desc | foreach {
  Write-Host ("Key = " + $_.key + " and Value = " + $_.value);
}

Output:

Key = a and Value = 3
Key = b and Value = 2
Key = c and Value = 1

JavaScript - Get Portion of URL Path

If this is the current url use window.location.pathname otherwise use this regular expression:

var reg = /.+?\:\/\/.+?(\/.+?)(?:#|\?|$)/;
var pathname = reg.exec( 'http://www.somedomain.com/account/search?filter=a#top' )[1];

The pipe ' ' could not be found angular2 custom pipe

Suggesting an alternative answer here:

Making a separate module for the Pipe is not required, but is definitely an alternative. Check the official docs footnote: https://angular.io/guide/pipes#custom-pipes

You use your custom pipe the same way you use built-in pipes.
You must include your pipe in the declarations array of the AppModule . If you choose to inject your pipe into a class, you must provide it in the providers array of your NgModule.

All you have to do is add your pipe to the declarations array, and the providers array in the module where you want to use the Pipe.

declarations: [
...
CustomPipe,
...
],
providers: [
...
CustomPipe,
...
]

Hibernate: flush() and commit()

By default flush mode is AUTO which means that: "The Session is sometimes flushed before query execution in order to ensure that queries never return stale state", but most of the time session is flushed when you commit your changes. Manual calling of the flush method is usefull when you use FlushMode=MANUAL or you want to do some kind of optimization. But I have never done this so I can't give you practical advice.

Using StringWriter for XML Serialization

First of all, beware of finding old examples. You've found one that uses XmlTextWriter, which is deprecated as of .NET 2.0. XmlWriter.Create should be used instead.

Here's an example of serializing an object into an XML column:

public void SerializeToXmlColumn(object obj)
{
    using (var outputStream = new MemoryStream())
    {
        using (var writer = XmlWriter.Create(outputStream))
        {
            var serializer = new XmlSerializer(obj.GetType());
            serializer.Serialize(writer, obj);
        }

        outputStream.Position = 0;
        using (var conn = new SqlConnection(Settings.Default.ConnectionString))
        {
            conn.Open();

            const string INSERT_COMMAND = @"INSERT INTO XmlStore (Data) VALUES (@Data)";
            using (var cmd = new SqlCommand(INSERT_COMMAND, conn))
            {
                using (var reader = XmlReader.Create(outputStream))
                {
                    var xml = new SqlXml(reader);

                    cmd.Parameters.Clear();
                    cmd.Parameters.AddWithValue("@Data", xml);
                    cmd.ExecuteNonQuery();
                }
            }
        }
    }
}

Generate Java class from JSON?

As far as I know there is no such tool. Yet.

The main reason is, I suspect, that unlike with XML (which has XML Schema, and then tools like 'xjc' to do what you ask, between XML and POJO definitions), there is no fully features schema language. There is JSON Schema, but it has very little support for actual type definitions (focuses on JSON structures), so it would be tricky to generate Java classes. But probably still possible, esp. if some naming conventions were defined and used to support generation.

However: this is something that has been fairly frequently requested (on mailing lists of JSON tool projects I follow), so I think that someone will write such a tool in near future.

So I don't think it is a bad idea per se (also: it is not a good idea for all use cases, depends on what you want to do ).

Java String new line

you can use <br> tag in your string for show in html pages

difference between variables inside and outside of __init__()

class User(object):
    email = 'none'
    firstname = 'none'
    lastname = 'none'

    def __init__(self, email=None, firstname=None, lastname=None):
        self.email = email
        self.firstname = firstname
        self.lastname = lastname

    @classmethod
    def print_var(cls, obj):
        print ("obj.email obj.firstname obj.lastname")
        print(obj.email, obj.firstname, obj.lastname)
        print("cls.email cls.firstname cls.lastname")
        print(cls.email, cls.firstname, cls.lastname)

u1 = User(email='abc@xyz', firstname='first', lastname='last')
User.print_var(u1)

In the above code, the User class has 3 global variables, each with value 'none'. u1 is the object created by instantiating this class. The method print_var prints the value of class variables of class User and object variables of object u1. In the output shown below, each of the class variables User.email, User.firstname and User.lastname has value 'none', while the object variables u1.email, u1.firstname and u1.lastname have values 'abc@xyz', 'first' and 'last'.

obj.email obj.firstname obj.lastname
('abc@xyz', 'first', 'last')
cls.email cls.firstname cls.lastname
('none', 'none', 'none')

Reset git proxy to default configuration

git config --global --unset http.proxy

What's the right way to pass form element state to sibling/parent elements?

With React >= 16.3 you can use ref and forwardRef, to gain access to child's DOM from its parent. Don't use old way of refs anymore.
Here is the example using your case :

import React, { Component } from 'react';

export default class P extends React.Component {
   constructor (props) {
      super(props)
      this.state = {data: 'test' }
      this.onUpdate = this.onUpdate.bind(this)
      this.ref = React.createRef();
   }

   onUpdate(data) {
      this.setState({data : this.ref.current.value}) 
   }

   render () {
      return (
        <div>
           <C1 ref={this.ref} onUpdate={this.onUpdate}/>
           <C2 data={this.state.data}/>
        </div>
      )
   }
}

const C1 = React.forwardRef((props, ref) => (
    <div>
        <input type='text' ref={ref} onChange={props.onUpdate} />
    </div>
));

class C2 extends React.Component {
    render () {
       return <div>C2 reacts : {this.props.data}</div>
    }
}

See Refs and ForwardRef for detailed info about refs and forwardRef.

Include headers when using SELECT INTO OUTFILE?

The solution provided by Joe Steanelli works, but making a list of columns is inconvenient when dozens or hundreds of columns are involved. Here's how to get column list of table my_table in my_schema.

-- override GROUP_CONCAT limit of 1024 characters to avoid a truncated result
set session group_concat_max_len = 1000000;

select GROUP_CONCAT(CONCAT("'",COLUMN_NAME,"'"))
from INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'my_table'
AND TABLE_SCHEMA = 'my_schema'
order BY ORDINAL_POSITION

Now you can copy & paste the resulting row as first statement in Joe's method.

How to check for an empty object in an AngularJS view

I have met a similar problem when checking emptiness in a component. In this case, the controller must define a method that actually performs the test and the view uses it:

function FormNumericFieldController(/*$scope, $element, $attrs*/ ) {
    var ctrl = this;

    ctrl.isEmptyObject = function(object) {
        return angular.equals(object, {});
    }
}

<!-- any validation error will trigger an error highlight -->
<span ng-class="{'has-error': !$ctrl.isEmptyObject($ctrl.formFieldErrorRef) }">
    <!-- validated control here -->
</span>

undefined reference to WinMain@16 (codeblocks)

Open the project you want to add it.

Right click on the name. Then select, add in the active project. Then the cpp file will get its link to cbp.

How do I increase the contrast of an image in Python OpenCV

Best explanation for X = aY + b (in fact it f(x) = ax + b)) is provided at https://math.stackexchange.com/a/906280/357701

A Simpler one by just adjusting lightness/luma/brightness for contrast as is below:

import cv2

img = cv2.imread('test.jpg')
cv2.imshow('test', img)
cv2.waitKey(1000)
imghsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)


imghsv[:,:,2] = [[max(pixel - 25, 0) if pixel < 190 else min(pixel + 25, 255) for pixel in row] for row in imghsv[:,:,2]]
cv2.imshow('contrast', cv2.cvtColor(imghsv, cv2.COLOR_HSV2BGR))
cv2.waitKey(1000)
raw_input()

Date / Timestamp to record when a record was added to the table?

You can create a non-nullable DATETIME column on your table, and create a DEFAULT constraint on it to auto populate when a row is added.

e.g.

CREATE TABLE Example
(
SomeField INTEGER,
DateCreated DATETIME NOT NULL DEFAULT(GETDATE())
)

cURL error 60: SSL certificate: unable to get local issuer certificate

If you are using PHP 5.6 with Guzzle, Guzzle has switched to using the PHP libraries autodetect for certificates rather than it's process (ref). PHP outlines the changes here.

Finding out Where PHP/Guzzle is Looking for Certificates

You can dump where PHP is looking using the following PHP command:

 var_dump(openssl_get_cert_locations());

Getting a Certificate Bundle

For OS X testing, you can use homebrew to install openssl brew install openssl and then use openssl.cafile=/usr/local/etc/openssl/cert.pem in your php.ini or Zend Server settings (under OpenSSL).

A certificate bundle is also available from curl/Mozilla on the curl website: https://curl.haxx.se/docs/caextract.html

Telling PHP Where the Certificates Are

Once you have a bundle, either place it where PHP is already looking (which you found out above) or update openssl.cafile in php.ini. (Generally, /etc/php.ini or /etc/php/7.0/cli/php.ini or /etc/php/php.ini on Unix.)

Angular - Use pipes in services and components

Yes, it is possible by using a simple custom pipe. Advantage of using custom pipe is if we need to update the date format in future, we can go and update a single file.

import { Pipe, PipeTransform } from '@angular/core';
import { DatePipe } from '@angular/common';

@Pipe({
    name: 'dateFormatPipe',
})
export class dateFormatPipe implements PipeTransform {
    transform(value: string) {
       var datePipe = new DatePipe("en-US");
        value = datePipe.transform(value, 'MMM-dd-yyyy');
        return value;
    }
}

{{currentDate | dateFormatPipe }}

You can always use this pipe anywhere , component, services etc

For example:

export class AppComponent {
  currentDate : any;
  newDate : any;
  constructor(){
    this.currentDate = new Date().getTime();
    let dateFormatPipeFilter = new dateFormatPipe();
    this.newDate = dateFormatPipeFilter.transform(this.currentDate);
    console.log(this.newDate);
}

Don't forget to import dependencies.

import { Component } from '@angular/core';
import {dateFormatPipe} from './pipes'

Custom Pipe examples and more info

How do I install PIL/Pillow for Python 3.6?

Pillow is released with installation wheels on Windows:

We provide Pillow binaries for Windows compiled for the matrix of supported Pythons in both 32 and 64-bit versions in wheel, egg, and executable installers. These binaries have all of the optional libraries included

https://pillow.readthedocs.io/en/3.3.x/installation.html#basic-installation

Update: Python 3.6 is now supported by Pillow. Install with pip install pillow and check https://pillow.readthedocs.io/en/latest/installation.html for more information.


However, Python 3.6 is still in alpha and not officially supported yet, although the tests do all pass for the nightly Python builds (currently 3.6a4).

https://travis-ci.org/python-pillow/Pillow/jobs/155605577

If it's somehow possible to install the 3.5 wheel for 3.6, that's your best bet. Otherwise, zlib notwithstanding, you'll need to build from source, requiring an MS Visual C++ compiler, and which isn't straightforward. For tips see:

https://pillow.readthedocs.io/en/3.3.x/installation.html#building-from-source

And also see how it's built for Windows on AppVeyor CI (but not yet 3.5 or 3.6):

https://github.com/python-pillow/Pillow/tree/master/winbuild

Failing that, downgrade to Python 3.5 or wait until 3.6 is supported by Pillow, probably closer to the 3.6's official release.

DLL load failed error when importing cv2

You can download the latest OpenCV 3.2.0 for Python 3.6 on Windows 32-bit or 64-bit machine, look for file starts withopencv_python-3.2.0-cp36-cp36m, from this unofficial site. Then type below command to install it:

  • pip install opencv_python-3.2.0-cp36-cp36m-win32.whl (32-bit version)
  • pip install opencv_python-3.2.0-cp36-cp36m-win_amd64.whl (64-bit version)

I think it would be easier.

Update on 2017-09-15:

OpenCV 3.3.0 wheel files are now available in the unofficial site and replaced OpenCV 3.2.0.

Update on 2018-02-15:

OpenCV 3.4.0 wheel files are now available in the unofficial site and replaced OpenCV 3.3.0.

Update on 2018-06-19:

OpenCV 3.4.1 wheel files are now available in the unofficial site with CPython 3.5/3.6/3.7 support, and replaced OpenCV 3.4.0.

Update on 2018-10-03:

OpenCV 3.4.3 wheel files are now available in the unofficial site with CPython 3.5/3.6/3.7 support, and replaced OpenCV 3.4.1.

Update on 2019-01-30:

OpenCV 4.0.1 wheel files are now available in the unofficial site with CPython 3.5/3.6/3.7 support.

Update on 2019-06-10:

OpenCV 3.4.6 and OpenCV 4.1.0 wheel files are now available in the unofficial site with CPython 3.5/3.6/3.7 support.

How to use enums as flags in C++?

For lazy people like me, here is templated solution to copy&paste:

template<class T> inline T operator~ (T a) { return (T)~(int)a; }
template<class T> inline T operator| (T a, T b) { return (T)((int)a | (int)b); }
template<class T> inline T operator& (T a, T b) { return (T)((int)a & (int)b); }
template<class T> inline T operator^ (T a, T b) { return (T)((int)a ^ (int)b); }
template<class T> inline T& operator|= (T& a, T b) { return (T&)((int&)a |= (int)b); }
template<class T> inline T& operator&= (T& a, T b) { return (T&)((int&)a &= (int)b); }
template<class T> inline T& operator^= (T& a, T b) { return (T&)((int&)a ^= (int)b); }

expected assignment or function call: no-unused-expressions ReactJS

I encountered the same error, with the below code.

    return this.state.employees.map((employee) => {
      <option value={employee.id}>
        {employee.name}
      </option>
    });

Above issue got resolved, when I changed curly braces to parenthesis, as indicated in the below modified code snippet.

      return this.state.employees.map((employee) => (
          <option value={employee.id}>
            {employee.name}
          </option>
        ));

Show current assembly instruction in GDB

You can do

display/i $pc

and every time GDB stops, it will display the disassembly of the next instruction.

GDB-7.0 also supports set disassemble-next-line on, which will disassemble the entire next line, and give you more of the disassembly context.

How do I evenly add space between a label and the input field regardless of length of text?

This can be accomplished using the brand new CSS display: grid (browser support)

HTML:

<div class='container'>
  <label for="dummy1">title for dummy1:</label>
  <input id="dummy1" name="dummy1" value="dummy1">
  <label for="dummy2">longer title for dummy2:</label>
  <input id="dummy2" name="dummy2" value="dummy2">
  <label for="dummy3">even longer title for dummy3:</label>
  <input id="dummy3" name="dummy3" value="dummy3">
</div>

CSS:

.container {
  display: grid;
  grid-template-columns: 1fr 3fr;
}

When using css grid, by default elements are laid out column by column then row by row. The grid-template-columns rule creates two grid columns, one which takes up 1/4 of the total horizontal space and the other which takes up 3/4 of the horizontal space. This creates the desired effect.

grid

JS-FIDDLE

How to count instances of character in SQL Column

Below solution help to find out no of character present from a string with a limitation:

1) using SELECT LEN(REPLACE(myColumn, 'N', '')), but limitation and wrong output in below condition:

SELECT LEN(REPLACE('YYNYNYYNNNYYNY', 'N', ''));
--8 --Correct

SELECT LEN(REPLACE('123a123a12', 'a', ''));
--8 --Wrong

SELECT LEN(REPLACE('123a123a12', '1', ''));
--7 --Wrong

2) Try with below solution for correct output:

  • Create a function and also modify as per requirement.
  • And call function as per below

select dbo.vj_count_char_from_string('123a123a12','2');
--2 --Correct

select dbo.vj_count_char_from_string('123a123a12','a');
--2 --Correct

-- ================================================
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      VIKRAM JAIN
-- Create date: 20 MARCH 2019
-- Description: Count char from string
-- =============================================
create FUNCTION vj_count_char_from_string
(
    @string nvarchar(500),
    @find_char char(1)  
)
RETURNS integer
AS
BEGIN
    -- Declare the return variable here
    DECLARE @total_char int; DECLARE @position INT;
    SET @total_char=0; set @position = 1;

    -- Add the T-SQL statements to compute the return value here
    if LEN(@string)>0
    BEGIN
        WHILE @position <= LEN(@string) -1
        BEGIN
            if SUBSTRING(@string, @position, 1) = @find_char
            BEGIN
                SET @total_char+= 1;
            END
            SET @position+= 1;
        END
    END;

    -- Return the result of the function
    RETURN @total_char;

END
GO

angularjs getting previous route path

Use the $locationChangeStart or $locationChangeSuccess events, 3rd parameter:

$scope.$on('$locationChangeStart',function(evt, absNewUrl, absOldUrl) {
   console.log('start', evt, absNewUrl, absOldUrl);
});
$scope.$on('$locationChangeSuccess',function(evt, absNewUrl, absOldUrl) {
   console.log('success', evt, absNewUrl, absOldUrl);
});

Is there a constraint that restricts my generic method to numeric types?

I would use a generic one which you could handle externaly...

/// <summary>
/// Generic object copy of the same type
/// </summary>
/// <typeparam name="T">The type of object to copy</typeparam>
/// <param name="ObjectSource">The source object to copy</param>
public T CopyObject<T>(T ObjectSource)
{
    T NewObject = System.Activator.CreateInstance<T>();

    foreach (PropertyInfo p in ObjectSource.GetType().GetProperties())
        NewObject.GetType().GetProperty(p.Name).SetValue(NewObject, p.GetValue(ObjectSource, null), null);

    return NewObject;
}

Concatenate rows of two dataframes in pandas

call concat and pass param axis=1 to concatenate column-wise:

In [5]:

pd.concat([df_a,df_b], axis=1)
Out[5]:
        AAseq Biorep  Techrep Treatment     mz      AAseq1 Biorep1  Techrep1  \
0  ELVISLIVES      A        1         C  500.0  ELVISLIVES       A         1   
1  ELVISLIVES      A        1         C  500.5  ELVISLIVES       A         1   
2  ELVISLIVES      A        1         C  501.0  ELVISLIVES       A         1   

  Treatment1  inte1  
0          C   1100  
1          C   1050  
2          C   1010  

There is a useful guide to the various methods of merging, joining and concatenating online.

For example, as you have no clashing columns you can merge and use the indices as they have the same number of rows:

In [6]:

df_a.merge(df_b, left_index=True, right_index=True)
Out[6]:
        AAseq Biorep  Techrep Treatment     mz      AAseq1 Biorep1  Techrep1  \
0  ELVISLIVES      A        1         C  500.0  ELVISLIVES       A         1   
1  ELVISLIVES      A        1         C  500.5  ELVISLIVES       A         1   
2  ELVISLIVES      A        1         C  501.0  ELVISLIVES       A         1   

  Treatment1  inte1  
0          C   1100  
1          C   1050  
2          C   1010  

And for the same reasons as above a simple join works too:

In [7]:

df_a.join(df_b)
Out[7]:
        AAseq Biorep  Techrep Treatment     mz      AAseq1 Biorep1  Techrep1  \
0  ELVISLIVES      A        1         C  500.0  ELVISLIVES       A         1   
1  ELVISLIVES      A        1         C  500.5  ELVISLIVES       A         1   
2  ELVISLIVES      A        1         C  501.0  ELVISLIVES       A         1   

  Treatment1  inte1  
0          C   1100  
1          C   1050  
2          C   1010  

JavaScript Array to Set

If you start out with:

let array = [
    {name: "malcom", dogType: "four-legged"},
    {name: "peabody", dogType: "three-legged"},
    {name: "pablo", dogType: "two-legged"}
];

And you want a set of, say, names, you would do:

let namesSet = new Set(array.map(item => item.name));

How to change a string into uppercase

>>> s = 'sdsd'
>>> s.upper()
'SDSD'

See String Methods.

Using putty to scp from windows to Linux

You need to tell scp where to send the file. In your command that is not working:

scp C:\Users\Admin\Desktop\WMU\5260\A2.c ~

You have not mentioned a remote server. scp uses : to delimit the host and path, so it thinks you have asked it to download a file at the path \Users\Admin\Desktop\WMU\5260\A2.c from the host C to your local home directory.

The correct upload command, based on your comments, should be something like:

C:\> pscp C:\Users\Admin\Desktop\WMU\5260\A2.c [email protected]:

If you are running the command from your home directory, you can use a relative path:

C:\Users\Admin> pscp Desktop\WMU\5260\A2.c [email protected]:

You can also mention the directory where you want to this folder to be downloaded to at the remote server. i.e by just adding a path to the folder as below:

C:/> pscp C:\Users\Admin\Desktop\WMU\5260\A2.c [email protected]:/home/path_to_the_folder/

Google Maps API Multiple Markers with Infowindows

If you also want to bind closing of infowindow to some event, try something like this

google.maps.event.addListener(marker,'click', (function(marker,content,infowindow){ 
    return function() {
        infowindow.setContent(content);
        infowindow.open(map,marker);
        windows.push(infowindow)
        google.maps.event.addListener(map,'click', function(){ 
            infowindow.close();
        }); 
    };
})(marker,content,infowindow)); 

Adding values to an array in java

You have not one, but many mistakes. It should be:

int[] tall = new int[28123];

for (int j=0;j<28123;j++){
    tall[j] = j+1;
}

Your code is putting a 0 in all the positions of the array.

Morover, it'll throw an exception, because the last index of the array is 28123-1 (arrays in Java start in 0!).

Pandas: ValueError: cannot convert float NaN to integer

I know this has been answered but wanted to provide alternate solution for anyone in the future:

You can use .loc to subset the dataframe by only values that are notnull(), and then subset out the 'x' column only. Take that same vector, and apply(int) to it.

If column x is float:

df.loc[df['x'].notnull(), 'x'] = df.loc[df['x'].notnull(), 'x'].apply(int)

String concatenation in MySQL

That's not the way to concat in MYSQL. Use the CONCAT function Have a look here: http://dev.mysql.com/doc/refman/4.1/en/string-functions.html#function_concat

How to connect android wifi to adhoc wifi?

You are correct, but note that you can do it the other way around - use Android Wifi tethering that sets up the phone as a base station and connect to said base station from the laptop.

Getting the document object of an iframe

For even more robustness:

function getIframeWindow(iframe_object) {
  var doc;

  if (iframe_object.contentWindow) {
    return iframe_object.contentWindow;
  }

  if (iframe_object.window) {
    return iframe_object.window;
  } 

  if (!doc && iframe_object.contentDocument) {
    doc = iframe_object.contentDocument;
  } 

  if (!doc && iframe_object.document) {
    doc = iframe_object.document;
  }

  if (doc && doc.defaultView) {
   return doc.defaultView;
  }

  if (doc && doc.parentWindow) {
    return doc.parentWindow;
  }

  return undefined;
}

and

...
var el = document.getElementById('targetFrame');

var frame_win = getIframeWindow(el);

if (frame_win) {
  frame_win.targetFunction();
  ...
}
...

The OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)"

This is for my reference, as I encountered a variety of SQL error messages while trying to connect with provider. Other answers prescribe "try this, then this, then this". I appreciate the other answers, but I like to pair specific solutions with specific problems


Error

...provider did not give information...Cannot initialize data source object...

Error Numbers

7399, 7303

Error Detail

Msg 7399, Level 16, State 1, Line 2 The OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)" reported an error. 
  The provider did not give any information about the error. 
Msg 7303, Level 16, State 1, Line 2 Cannot initialize the data source object
  of OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)".

Solution

File was open. Close it.

Credit


Error

Access denied...Cannot get the column information...

Error Numbers

7399, 7350

Error Detail

Msg 7399, Level 16, State 1, Line 2 The OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)" reported an error. 
  Access denied.
Msg 7350, Level 16, State 2, Line 2 Cannot get the column information 
  from OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)".

Solution

Give access

Credit


Error

No value given for one or more required parameters....Cannot execute the query ...

Error Numbers

???, 7320

Error Detail

OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)" returned message "No value given for one or more required parameters.".
Msg 7320, Level 16, State 2, Line 2
Cannot execute the query "select [Col A], [Col A] FROM $Sheet" against OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)". 

Solution

Column names might be wrong. Do [Col A] and [Col B] actually exist in your spreadsheet?


Error

"Unspecified error"...Cannot initialize data source object...

Error Numbers

???, 7303

Error Detail

OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)" returned message "Unspecified error".
Msg 7303, Level 16, State 1, Line 2 Cannot initialize the data source object of OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)".

Solution

Run SSMS as admin. See this question.


Other References

Other answers which suggest modifying properties. Not sure how modifying these two properties (checking them or unchecking them) would help.

how to change language for DataTable

There are language files uploaded in a CDN on the dataTables website https://datatables.net/plug-ins/i18n/ So you only have to replace "Spanish" with whatever language you are using in the following example.

https://datatables.net/plug-ins/i18n/Spanish

$('table.dataTable').DataTable( {
    language: {
        url: '//cdn.datatables.net/plug-ins/1.10.15/i18n/Spanish.json'
    }
});

jQuery $(".class").click(); - multiple elements, click event once

_x000D_
_x000D_
$(document).ready(function(){_x000D_
_x000D_
    $(".addproduct").each(function(){_x000D_
          $(this).unbind().click(function(){_x000D_
               console.log('div is clicked, my content => ' + $(this).html());_x000D_
           });_x000D_
     });_x000D_
}); _x000D_
 
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div class="addproduct 151">product info 1</div>_x000D_
<div class="addproduct 151">product info 2</div>_x000D_
<div class="addproduct 151">product info 3</div>_x000D_
<div class="addproduct 151">product info 4</div>_x000D_
<div class="addproduct 151">product info 5</div>
_x000D_
_x000D_
_x000D_

How to copy a collection from one database to another in MongoDB

If RAM is not an issue using insertMany is way faster than forEach loop.

var db1 = connect('<ip_1>:<port_1>/<db_name_1>')
var db2 = connect('<ip_2>:<port_2>/<db_name_2>')

var _list = db1.getCollection('collection_to_copy_from').find({})
db2.collection_to_copy_to.insertMany(_list.toArray())

How to avoid Number Format Exception in java?

I don't know about the runtime disadvantages about the following but you could run a regexp match on your string to make sure it is a number before trying to parse it, thus

cost.matches("-?\\d+\\.?\\d+")

for a float

and

cost.matches("-?\\d+")

for an integer

EDIT

please notices @Voo's comment about max int

When to use setAttribute vs .attribute= in JavaScript?

This is very good discussion. I had one of those moments when I wished or lets say hoped (successfully that I might add) to reinvent the wheel be it a square one. Any ways above is good discussion, so any one coming here looking for what is the difference between Element property and attribute. here is my penny worth and I did have to find it out hard way. I would keep it simple so no extraordinary tech jargon.

suppose we have a variable calls 'A'. what we are used to is as following.

Below will throw an error because simply it put its is kind of object that can only have one property and that is singular left hand side = singular right hand side object. Every thing else is ignored and tossed out in bin.

_x000D_
_x000D_
let A = 'f';
A.b =2;
console.log(A.b);
_x000D_
_x000D_
_x000D_

who has decided that it has to be singular = singular. People who make JavaScript and html standards and thats how engines work.

Lets change the example.

_x000D_
_x000D_
let A = {};
A.b =2;
console.log(A.b);
_x000D_
_x000D_
_x000D_

This time it works ..... because we have explicitly told it so and who decided we can tell it in this case but not in previous case. Again people who make JavaScript and html standards.

I hope we are on this lets complicate it further

_x000D_
_x000D_
let A = {};
A.attribute ={};
A.attribute.b=5;
console.log(A.attribute.b); // will work

console.log(A.b); // will not work
_x000D_
_x000D_
_x000D_

What we have done is tree of sorts level 1 then sub levels of non-singular object. Unless you know what is where and and call it so it will work else no.

This is what goes on with HTMLDOM when its parsed and painted a DOm tree is created for each and every HTML ELEMENT. Each has level of properties per say. Some are predefined and some are not. This is where ID and VALUE bits come on. Behind the scene they are mapped on 1:1 between level 1 property and sun level property aka attributes. Thus changing one changes the other. This is were object getter ans setter scheme of things plays role.

_x000D_
_x000D_
let A = {
attribute :{
id:'',
value:''
},
getAttributes: function (n) {
    return this.attribute[n];
  },
setAttributes: function (n,nn){
this.attribute[n] = nn;
if(this[n]) this[n] = nn;
},
id:'',
value:''
};



A.id = 5;
console.log(A.id);
console.log(A.getAttributes('id'));

A.setAttributes('id',7)
console.log(A.id);
console.log(A.getAttributes('id'));

A.setAttributes('ids',7)
console.log(A.ids);
console.log(A.getAttributes('ids'));

A.idsss=7;
console.log(A.idsss);
console.log(A.getAttributes('idsss'));
_x000D_
_x000D_
_x000D_

This is the point as shown above ELEMENTS has another set of so called property list attributes and it has its own main properties. there some predefined properties between the two and are mapped as 1:1 e.g. ID is common to every one but value is not nor is src. when the parser reaches that point it simply pulls up dictionary as to what to when such and such are present.

All elements have properties and attributes and some of the items between them are common. What is common in one is not common in another.

In old days of HTML3 and what not we worked with html first then on to JS. Now days its other way around and so has using inline onlclick become such an abomination. Things have moved forward in HTML5 where there are many property lists accessible as collection e.g. class, style. In old days color was a property now that is moved to css for handling is no longer valid attribute.

Element.attributes is sub property list with in Element property.

Unless you could change the getter and setter of Element property which is almost high unlikely as it would break hell on all functionality is usually not writable off the bat just because we defined something as A.item does not necessarily mean Js engine will also run another line of function to add it into Element.attributes.item.

I hope this gives some headway clarification as to what is what. Just for the sake of this I tried Element.prototype.setAttribute with custom function it just broke loose whole thing all together, as it overrode native bunch of functions that set attribute function was playing behind the scene.

Error: vector does not name a type

You forgot to add std:: namespace prefix to vector class name.

Android LinearLayout : Add border with shadow around a LinearLayout

Ya Mahdi aj---for RelativeLayout

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="rectangle">
            <gradient
                android:startColor="#7d000000"
                android:endColor="@android:color/transparent"
                android:angle="90" >
            </gradient>
            <corners android:radius="2dp" />
        </shape>
    </item>

    <item
        android:left="0dp"
        android:right="3dp"
        android:top="0dp"
        android:bottom="3dp">
        <shape android:shape="rectangle">
            <padding
                android:bottom="40dp"
                android:top="40dp"
                android:right="10dp"
                android:left="10dp"
                >
            </padding>
            <solid android:color="@color/Whitetransparent"/>
            <corners android:radius="2dp" />
        </shape>
    </item>
</layer-list>

Is there an upper bound to BigInteger?

BigInteger would only be used if you know it will not be a decimal and there is a possibility of the long data type not being large enough. BigInteger has no cap on its max size (as large as the RAM on the computer can hold).

From here.

It is implemented using an int[]:

  110       /**
  111        * The magnitude of this BigInteger, in <i>big-endian</i> order: the
  112        * zeroth element of this array is the most-significant int of the
  113        * magnitude.  The magnitude must be "minimal" in that the most-significant
  114        * int ({@code mag[0]}) must be non-zero.  This is necessary to
  115        * ensure that there is exactly one representation for each BigInteger
  116        * value.  Note that this implies that the BigInteger zero has a
  117        * zero-length mag array.
  118        */
  119       final int[] mag;

From the source

From the Wikipedia article Arbitrary-precision arithmetic:

Several modern programming languages have built-in support for bignums, and others have libraries available for arbitrary-precision integer and floating-point math. Rather than store values as a fixed number of binary bits related to the size of the processor register, these implementations typically use variable-length arrays of digits.

Populate nested array in mongoose

You can populate multiple nested documents like this.

   Project.find(query)
    .populate({ 
      path: 'pages',
      populate: [{
       path: 'components',
       model: 'Component'
      },{
        path: 'AnotherRef',
        model: 'AnotherRef',
        select: 'firstname lastname'
      }] 
   })
   .exec(function(err, docs) {});

Get Request and Session Parameters and Attributes from JSF pages

You can also use a bean (request scoped is suggested) and directly access the context by way of the FacesContext.

You can get the HttpServletRequest and HttpServletResposne objects by using the following code:

HttpServletRequest req = (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
HttpServletResponse res = (HttpServletResponse)FacesContext.getCurrentInstance().getExternalContext().getResponse();

After this, you can access individual parameters via getParameter(paramName) or access the full map via getParameterMap() req object

The reason I suggest a request scoped bean is that you can use these during initialization (worst case scenario being the constructor. Most frameworks give you some place to do code at bean initialization time) and they will be done as your request comes in.

It is, however, a bit of a hack. ;) You may want to look into seeing if there is a JSF Acegi module that will allow you to get access to the variables you need.

Rounding to two decimal places in Python 2.7?

The best, I think, is to use the format() function:

>>> print("financial return of outcome 1 = $ " + format(str(out1), '.2f'))
// Should print: financial return of outcome 1 = $ 752.60

But I have to say: don't use round or format when working with financial values.

How to change style of a default EditText

You have a few options.

  1. Use Android assets studios Android Holo colors generator to generate the resources, styles and themes you need to add to your app to get the holo look across all devices.

  2. Use holo everywhere library.

  3. Use the PNG for the holo text fields and set them as background images yourself. You can get the images from the Android assets studios holo color generator. You'll have to make a drawable and define the normal, selected and disabled states.

UPDATE 2016-01-07

This answer is now outdated. Android has tinting API and ability to theme on controls directly now. A good reference for how to style or theme any element is a site called materialdoc.

Is there a foreach loop in Go?

Following is the example code for how to use foreach in golang

package main

import (
    "fmt"
)

func main() {

    arrayOne := [3]string{"Apple", "Mango", "Banana"}

    for index,element := range arrayOne{

        fmt.Println(index)
        fmt.Println(element)        

    }   

}

This is a running example https://play.golang.org/p/LXptmH4X_0

How to get a resource id with a known resource name?

// image from res/drawable
    int resID = getResources().getIdentifier("my_image", 
            "drawable", getPackageName());
// view
    int resID = getResources().getIdentifier("my_resource", 
            "id", getPackageName());

// string
    int resID = getResources().getIdentifier("my_string", 
            "string", getPackageName());

adb devices command not working

I fixed this issue on my debian GNU/Linux system by overiding system rules that way :

mv  /etc/udev/rules.d/51-android.rules /etc/udev/rules.d/99-android.rules

I used contents from files linked at : http://rootzwiki.com/topic/258-udev-rules-for-any-device-no-more-starting-adb-with-sudo/

Performing Breadth First Search recursively

The following seems pretty natural to me, using Haskell. Iterate recursively over levels of the tree (here I collect names into a big ordered string to show the path through the tree):

data Node = Node {name :: String, children :: [Node]}
aTree = Node "r" [Node "c1" [Node "gc1" [Node "ggc1" []], Node "gc2" []] , Node "c2" [Node "gc3" []], Node "c3" [] ]
breadthFirstOrder x = levelRecurser [x]
    where levelRecurser level = if length level == 0
                                then ""
                                else concat [name node ++ " " | node <- level] ++ levelRecurser (concat [children node | node <- level])

Laravel 5 Application Key

Just as another option if you want to print only the key (doesn't write the .env file) you can use:

php artisan key:generate --show

How to split a comma-separated string?

Remove all white spaces and create an fixed-size or immutable List (See asList API docs)

final String str = "dog, cat, bear, elephant, ..., giraffe";
List<String> list = Arrays.asList(str.replaceAll("\\s", "").split(","));
// result: [dog, cat, bear, elephant, ..., giraffe]

It is possible to also use replaceAll(\\s+", "") but maximum efficiency depends on the use case. (see @GurselKoca answer to Removing whitespace from strings in Java)

What's the best UML diagramming tool?

I advice to use Pacestar UML Diagrammer. It helps you generate UML 2.0 diagrams quickly, easily, flexible AND commonly understood notation.

I used it in many projects and I'm very satisfied. And too it doesn't use much of memory and space just 6 Mo of Hard Disk.

And the most feature that I like it very much is that I can copy diagrams from the editor and paste them in MS Word... so when I need to edit a specific diagram, just I click on and it will be opened in the editor and by closing it, the updates had been done in MS Word document.

Generate your own Error code in swift 3

protocol CustomError : Error {

    var localizedTitle: String
    var localizedDescription: String

}

enum RequestError : Int, CustomError {

    case badRequest         = 400
    case loginFailed        = 401
    case userDisabled       = 403
    case notFound           = 404
    case methodNotAllowed   = 405
    case serverError        = 500
    case noConnection       = -1009
    case timeOutError       = -1001

}

func anything(errorCode: Int) -> CustomError? {

      return RequestError(rawValue: errorCode)
}

Executing "SELECT ... WHERE ... IN ..." using MySQLdb

Maybe we can create a function to do what João proposed? Something like:

def cursor_exec(cursor, query, params):
    expansion_params= []
    real_params = []
    for p in params:
       if isinstance(p, (tuple, list)):
         real_params.extend(p)
         expansion_params.append( ("%s,"*len(p))[:-1] )
       else:
         real_params.append(p)
         expansion_params.append("%s")
    real_query = query % expansion_params
    cursor.execute(real_query, real_params)

Invalidating JSON Web Tokens

An alternative would be to have a middleware script just for critical API endpoints.
This middleware script would check in the database if the token is invalidated by an admin.
This solution may be useful for cases where is not necessary to completely block the access of a user right away.

Cookies on localhost with explicit domain

There seems to be an issue when you use https://<local-domain> and then http://<local-domain>. The http:// site does not send cookies with requests after https:// site sets them. Force reload and clear cache doesn't help. Only manual clearing of cookies works. Also, if I clear them on the https:// page, then http:// page starts working again.

Looks to be related to "Strict secure cookies". Good explanation here. It was released in Chrome 58 on 2017-04-19.

It looks like Chrome does in fact record both secure cookies and non-secure cookies as it will show the correct cookies depending on the page's protocol when clicking the address bar icon.

But Developer tools > Application > Cookies will not show a non-secure cookie when there is a secure cookie of the same name for the same domain, nor will it send the non-secure cookie with any requests. This seems like a Chrome bug, or if this behavior is expected, there should be some way to view the secure cookies when on a http page and an indication that they are being overridden.

Workaround is to use different named cookies depending on if they are for an http site or https site, and to name them specific to your app. A __Secure- prefix indicates that the cookie should be strictly secure, and is also a good practice because secure and non-secure won't collide. There are other benefits to prefixes too.

Using different /etc/hosts domains for https vs. http access would work too, but one accidental https://localhost visit will prevent any cookies of the same names to work on http://localhost sites - so this is not a good workaround.

I have filed a Chrome bug report.

Get full URL and query string in Servlet for both HTTP and HTTPS requests

By design, getRequestURL() gives you the full URL, missing only the query string.

In HttpServletRequest, you can get individual parts of the URI using the methods below:

// Example: http://myhost:8080/people?lastname=Fox&age=30

String uri = request.getScheme() + "://" +   // "http" + "://
             request.getServerName() +       // "myhost"
             ":" +                           // ":"
             request.getServerPort() +       // "8080"
             request.getRequestURI() +       // "/people"
             "?" +                           // "?"
             request.getQueryString();       // "lastname=Fox&age=30"
  • .getScheme() will give you "https" if it was a https://domain request.
  • .getServerName() gives domain on http(s)://domain.
  • .getServerPort() will give you the port.

Use the snippet below:

String uri = request.getScheme() + "://" +
             request.getServerName() + 
             ("http".equals(request.getScheme()) && request.getServerPort() == 80 || "https".equals(request.getScheme()) && request.getServerPort() == 443 ? "" : ":" + request.getServerPort() ) +
             request.getRequestURI() +
            (request.getQueryString() != null ? "?" + request.getQueryString() : "");

This snippet above will get the full URI, hiding the port if the default one was used, and not adding the "?" and the query string if the latter was not provided.


Proxied requests

Note, that if your request passes through a proxy, you need to look at the X-Forwarded-Proto header since the scheme might be altered:

request.getHeader("X-Forwarded-Proto")

Also, a common header is X-Forwarded-For, which show the original request IP instead of the proxys IP.

request.getHeader("X-Forwarded-For")

If you are responsible for the configuration of the proxy/load balancer yourself, you need to ensure that these headers are set upon forwarding.

com.apple.WebKit.WebContent drops 113 error: Could not find specified service

SWIFT

Well I did this in the following order and didn't get any error like Could not signal service com.apple.WebKit.WebContent: 113: Could not find specified service after that, following code might help you too.

webView = WKWebView(frame: self.view.frame)
self.view.addSubview(self.view.webView)
webView.navigationDelegate = self
webView.loadHTMLString(htmlString, baseURL: nil)

Do as order.

Thanks

Converting a double to an int in Javascript without rounding

Use parseInt().

var num = 2.9
console.log(parseInt(num, 10)); // 2

You can also use |.

var num = 2.9
console.log(num | 0); // 2

How to get folder path for ClickOnce application

path is pointing to a subfolder under c:\Documents & Settings

That's right. ClickOnce applications are installed under the profile of the user who installed them. Did you take the path that retrieving the info from the executing assembly gave you, and go check it out?

On windows Vista and Windows 7, you will find the ClickOnce cache here:

c:\users\username\AppData\Local\Apps\2.0\obfuscatedfoldername\obfuscatedfoldername

On Windows XP, you will find it here:

C:\Documents and Settings\username\LocalSettings\Apps\2.0\obfuscatedfoldername\obfuscatedfoldername

Using grep to search for a string that has a dot in it

Escape dot. Sample command will be.

grep '0\.00'

Checking character length in ruby

You could take any of the answers above that use the string.length method and replace it with string.size.

They both work the same way.

if string.size <= 25
  puts "No problem here!"
else
  puts "Sorry too long!"
end

https://ruby-doc.org/core-2.4.0/String.html#method-i-size

How to rebuild docker container in docker-compose.yml?

Maybe these steps are not quite correct, but I do like this:

stop docker compose: $ docker-compose down

remove the container: $ docker system prune -a

start docker compose: $ docker-compose up -d

AssertNull should be used or AssertNotNull

assertNotNull asserts that the object is not null. If it is null the test fails, so you want that.

Maven parent pom vs modules pom

From my experience and Maven best practices there are two kinds of "parent poms"

  • "company" parent pom - this pom contains your company specific information and configuration that inherit every pom and doesn't need to be copied. These informations are:

    • repositories
    • distribution managment sections
    • common plugins configurations (like maven-compiler-plugin source and target versions)
    • organization, developers, etc

    Preparing this parent pom need to be done with caution, because all your company poms will inherit from it, so this pom have to be mature and stable (releasing a version of parent pom should not affect to release all your company projects!)

  • second kind of parent pom is a multimodule parent. I prefer your first solution - this is a default maven convention for multi module projects, very often represents VCS code structure

The intention is to be scalable to a large scale build so should be scalable to a large number of projects and artifacts.

Mutliprojects have structure of trees - so you aren't arrown down to one level of parent pom. Try to find a suitable project struture for your needs - a classic exmample is how to disrtibute mutimodule projects

distibution/
documentation/
myproject/
  myproject-core/
  myproject-api/
  myproject-app/
  pom.xml
pom.xml

A few bonus questions:

  • Where is the best place to define the various shared configuration as in source control, deployment directories, common plugins etc. (I'm assuming the parent but I've often been bitten by this and they've ended up in each project rather than a common one).

This configuration has to be wisely splitted into a "company" parent pom and project parent pom(s). Things related to all you project go to "company" parent and this related to current project go to project one's.

  • How do the maven-release plugin, hudson and nexus deal with how you set up your multi-projects (possibly a giant question, it's more if anyone has been caught out when by how a multi-project build has been set up)?

Company parent pom have to be released first. For multiprojects standard rules applies. CI server need to know all to build the project correctly.

Instantiate and Present a viewController in Swift

Swift 4.2 updated code is

let storyboard = UIStoryboard(name: "StoryboardNameHere", bundle: nil)
let controller = storyboard.instantiateViewController(withIdentifier: "ViewControllerNameHere")
self.present(controller, animated: true, completion: nil)

How do I use dataReceived event of the SerialPort Port Object in C#?

Might very well be the Console.ReadLine blocking your callback's Console.Writeline, in fact. The sample on MSDN looks ALMOST identical, except they use ReadKey (which doesn't lock the console).

Assembly code vs Machine code vs Object code?

Machine code is binary (1's and 0's) code that can be executed directly by the CPU. If you open a machine code file in a text editor you would see garbage, including unprintable characters (no, not those unprintable characters ;) ).

Object code is a portion of machine code not yet linked into a complete program. It's the machine code for one particular library or module that will make up the completed product. It may also contain placeholders or offsets not found in the machine code of a completed program. The linker will use these placeholders and offsets to connect everything together.

Assembly code is plain-text and (somewhat) human read-able source code that mostly has a direct 1:1 analog with machine instructions. This is accomplished using mnemonics for the actual instructions, registers, or other resources. Examples include JMP and MULT for the CPU's jump and multiplication instructions. Unlike machine code, the CPU does not understand assembly code. You convert assembly code to machine code with the use of an assembler or a compiler, though we usually think of compilers in association with high-level programming language that are abstracted further from the CPU instructions.


Building a complete program involves writing source code for the program in either assembly or a higher level language like C++. The source code is assembled (for assembly code) or compiled (for higher level languages) to object code, and individual modules are linked together to become the machine code for the final program. In the case of very simple programs the linking step may not be needed. In other cases, such as with an IDE (integrated development environment) the linker and compiler may be invoked together. In other cases, a complicated make script or solution file may be used to tell the environment how to build the final application.

There are also interpreted languages that behave differently. Interpreted languages rely on the machine code of a special interpreter program. At the basic level, an interpreter parses the source code and immediately converts the commands to new machine code and executes them. Modern interpreters are now much more complicated: evaluating whole sections of source code at a time, caching and optimizing where possible, and handling complex memory management tasks.

One final type of program involves the use of a runtime-environment or virtual machine. In this situation, a program is first pre-compiled to a lower-level intermediate language or byte code. The byte code is then loaded by the virtual machine, which just-in-time compiles it to native code. The advantage here is the virtual machine can take advantage of optimizations available at the time the program runs and for that specific environment. A compiler belongs to the developer, and therefore must produce relatively generic (less-optimized) machine code that could run in many places. The runtime environment or virtual machine, however, is located on the end user's computer and therefore can take advantage of all the features provided by that system.

reading external sql script in python

Your code already contains a beautiful way to execute all statements from a specified sql file

# Open and read the file as a single buffer
fd = open('ZooDatabase.sql', 'r')
sqlFile = fd.read()
fd.close()

# all SQL commands (split on ';')
sqlCommands = sqlFile.split(';')

# Execute every command from the input file
for command in sqlCommands:
    # This will skip and report errors
    # For example, if the tables do not yet exist, this will skip over
    # the DROP TABLE commands
    try:
        c.execute(command)
    except OperationalError, msg:
        print "Command skipped: ", msg

Wrap this in a function and you can reuse it.

def executeScriptsFromFile(filename):
    # Open and read the file as a single buffer
    fd = open(filename, 'r')
    sqlFile = fd.read()
    fd.close()

    # all SQL commands (split on ';')
    sqlCommands = sqlFile.split(';')

    # Execute every command from the input file
    for command in sqlCommands:
        # This will skip and report errors
        # For example, if the tables do not yet exist, this will skip over
        # the DROP TABLE commands
        try:
            c.execute(command)
        except OperationalError, msg:
            print "Command skipped: ", msg

To use it

executeScriptsFromFile('zookeeper.sql')

You said you were confused by

result = c.execute("SELECT * FROM %s;" % table);

In Python, you can add stuff to a string by using something called string formatting.

You have a string "Some string with %s" with %s, that's a placeholder for something else. To replace the placeholder, you add % ("what you want to replace it with") after your string

ex:

a = "Hi, my name is %s and I have a %s hat" % ("Azeirah", "cool")
print(a)
>>> Hi, my name is Azeirah and I have a Cool hat

Bit of a childish example, but it should be clear.

Now, what

result = c.execute("SELECT * FROM %s;" % table);

means, is it replaces %s with the value of the table variable.

(created in)

for table in ['ZooKeeper', 'Animal', 'Handles']:


# for loop example

for fruit in ["apple", "pear", "orange"]:
    print fruit
>>> apple
>>> pear
>>> orange

If you have any additional questions, poke me.

Send multipart/form-data files with angular using $http

Take a look at the FormData object: https://developer.mozilla.org/en/docs/Web/API/FormData

this.uploadFileToUrl = function(file, uploadUrl){
        var fd = new FormData();
        fd.append('file', file);
        $http.post(uploadUrl, fd, {
            transformRequest: angular.identity,
            headers: {'Content-Type': undefined}
        })
        .success(function(){
        })
        .error(function(){
        });
    }

Elegant way to create empty pandas DataFrame with NaN of type float

You could specify the dtype directly when constructing the DataFrame:

>>> df = pd.DataFrame(index=range(0,4),columns=['A'], dtype='float')
>>> df.dtypes
A    float64
dtype: object

Specifying the dtype forces Pandas to try creating the DataFrame with that type, rather than trying to infer it.

Is there a 'foreach' function in Python 3?

If I understood you right, you mean that if you have a function 'func', you want to check for each item in list if func(item) returns true; if you get true for all, then do something.

You can use 'all'.

For example: I want to get all prime numbers in range 0-10 in a list:

from math import sqrt
primes = [x for x in range(10) if x > 2 and all(x % i !=0 for i in range(2, int(sqrt(x)) + 1))]

Installing a pip package from within a Jupyter Notebook not working

conda create -n py27 python=2.7 ipykernel

source activate py27

pip install geocoder

Recursively find files with a specific extension

This q/a shows how to use find with regular expression: How to use regex with find command?

Pattern could be something like

'^Robert\\.\\(h|cgg\\)$'

Is there a conditional ternary operator in VB.NET?

Depends upon the version. The If operator in VB.NET 2008 is a ternary operator (as well as a null coalescence operator). This was just introduced, prior to 2008 this was not available. Here's some more info: Visual Basic If announcement

Example:

Dim foo as String = If(bar = buz, cat, dog)

[EDIT]

Prior to 2008 it was IIf, which worked almost identically to the If operator described Above.

Example:

Dim foo as String = IIf(bar = buz, cat, dog)

Check if array is empty or null

As long as your selector is actually working, I see nothing wrong with your code that checks the length of the array. That should do what you want. There are a lot of ways to clean up your code to be simpler and more readable. Here's a cleaned up version with notes about what I cleaned up.

var album_text = [];

$("input[name='album_text[]']").each(function() {
    var value = $(this).val();
    if (value) {
        album_text.push(value);
    }
});
if (album_text.length === 0) {
    $('#error_message').html("Error");
}

else {
  //send data
}

Some notes on what you were doing and what I changed.

  1. $(this) is always a valid jQuery object so there's no reason to ever check if ($(this)). It may not have any DOM objects inside it, but you can check that with $(this).length if you need to, but that is not necessary here because the .each() loop wouldn't run if there were no items so $(this) inside your .each() loop will always be something.
  2. It's inefficient to use $(this) multiple times in the same function. Much better to get it once into a local variable and then use it from that local variable.
  3. It's recommended to initialize arrays with [] rather than new Array().
  4. if (value) when value is expected to be a string will both protect from value == null, value == undefined and value == "" so you don't have to do if (value && (value != "")). You can just do: if (value) to check for all three empty conditions.
  5. if (album_text.length === 0) will tell you if the array is empty as long as it is a valid, initialized array (which it is here).

What are you trying to do with this selector $("input[name='album_text[]']")?

Convert array to JSON

I made it that way:

if I have:

var jsonArg1 = new Object();
    jsonArg1.name = 'calc this';
    jsonArg1.value = 3.1415;
var jsonArg2 = new Object();
    jsonArg2.name = 'calc this again';
    jsonArg2.value = 2.73;

var pluginArrayArg = new Array();
    pluginArrayArg.push(jsonArg1);
    pluginArrayArg.push(jsonArg2);

to convert pluginArrayArg (which is pure javascript array) into JSON array:

var jsonArray = JSON.parse(JSON.stringify(pluginArrayArg))

Automatic confirmation of deletion in powershell

Try using the -Force parameter on Remove-Item.

How to add onload event to a div element

You could use an interval to check for it until it loads like this: https://codepen.io/pager/pen/MBgGGM

let checkonloadDoSomething = setInterval(() => {
  let onloadDoSomething = document.getElementById("onloadDoSomething");
  if (onloadDoSomething) {
    onloadDoSomething.innerHTML="Loaded"
    clearInterval(checkonloadDoSomething);
  } else {`enter code here`
    console.log("Waiting for onloadDoSomething to load");
  }
}, 100);

Why am I getting "(304) Not Modified" error on some links when using HttpWebRequest?

It is not an issue it is because of caching...

To overcome this add a timestamp to your endpoint call, e.g. axios.get('/api/products').

After timestamp it should be axios.get(/api/products?${Date.now()}.

It will resolve your 304 status code.

How to disable right-click context-menu in JavaScript

Capture the onContextMenu event, and return false in the event handler.

You can also capture the click event and check which mouse button fired the event with event.button, in some browsers anyway.

Bootstrap - dropdown menu not working?

you are missing the "btn btn-navbar" section. For example:

        <a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
        </a>

Take a look to navbar documentation in:

Twitter Bootstrap

Tomcat 8 throwing - org.apache.catalina.webresources.Cache.getResource Unable to add the resource

This isn’t a solution in the sense that it doesn’t resolve the conditions which cause the message to appear in the logs, but the message can be suppressed by appending the following to conf/logging.properties:

org.apache.catalina.webresources.Cache.level = SEVERE

This filters out the “Unable to add the resource” logs, which are at level WARNING.

In my view a WARNING is not necessarily an error that needs to be addressed, but rather can be ignored if desired.

How to write a caption under an image?

Put the image — let's say it's width is 140px — inside of a link:

<a><img src='image link' style='width: 140px'></a>

Next, put the caption in a and give it a width less than your image, while centering it:

<a>
  <img src='image link' style='width: 140px'>
  <div style='width: 130px; text-align: center;'>I just love to visit this most beautiful place in all the world.</div>
</a>

Next, in the link tag, style the link so that it no longer looks like a link. You can give it any color you want, but just remove any text decoration your links may carry.

<a style='text-decoration: none; color: orange;'>
  <img src='image link' style='width: 140px'>
  <div style='width: 130px; text-align: center;'>I just love to visit this most beautiful place in all the world.</div>
</a>

I wrapped the image with it's caption in a link so that no text could push the caption out of the way: The caption is tied to the picture by the link. Here's an example: http://www.alphaeducational.com/p/okay.html

invalid target release: 1.7

When maven is working outside of Eclipse, but giving this error after a JDK change, Go to your Maven Run Configuration, and at the bottom of the Main page, there's a 'Maven Runtime' option. Mine was using the Embedded Maven, so after switching it to use my external maven, it worked.

Monitor network activity in Android Phones

The common approach is to call "cat /proc/net/netstat" as described here:

Android network stats

Adding rows dynamically with jQuery

Building on the other answers, I simplified things a bit. By cloning the last element, we get the "add new" button for free (you have to change the ID to a class because of the cloning) and also reduce DOM operations. I had to use filter() instead of find() to get only the last element.

$('.js-addNew').on('click', function(e) {
   e.preventDefault();
   var $rows   = $('.person'),
       $last   = $rows.filter(':last'),
       $newRow = $last.clone().insertAfter($last);

   $last.find($('.js-addNew')).remove(); // remove old button
   $newRow.hide().find('input').val('');
   $newRow.slideDown(500);
});

Convert 24 Hour time to 12 Hour plus AM/PM indication Oracle SQL

For the 24-hour time, you need to use HH24 instead of HH.

For the 12-hour time, the AM/PM indicator is written as A.M. (if you want periods in the result) or AM (if you don't). For example:

SELECT invoice_date,
       TO_CHAR(invoice_date, 'DD-MM-YYYY HH24:MI:SS') "Date 24Hr",
       TO_CHAR(invoice_date, 'DD-MM-YYYY HH:MI:SS AM') "Date 12Hr"
  FROM invoices
;

For more information on the format models you can use with TO_CHAR on a date, see http://docs.oracle.com/cd/E16655_01/server.121/e17750/ch4datetime.htm#NLSPG004.

How to join on multiple columns in Pyspark?

You should use & / | operators and be careful about operator precedence (== has lower precedence than bitwise AND and OR):

df1 = sqlContext.createDataFrame(
    [(1, "a", 2.0), (2, "b", 3.0), (3, "c", 3.0)],
    ("x1", "x2", "x3"))

df2 = sqlContext.createDataFrame(
    [(1, "f", -1.0), (2, "b", 0.0)], ("x1", "x2", "x3"))

df = df1.join(df2, (df1.x1 == df2.x1) & (df1.x2 == df2.x2))
df.show()

## +---+---+---+---+---+---+
## | x1| x2| x3| x1| x2| x3|
## +---+---+---+---+---+---+
## |  2|  b|3.0|  2|  b|0.0|
## +---+---+---+---+---+---+

currently unable to handle this request HTTP ERROR 500

Have you included the statement include ("fileName.php"); ?

Are you sure that file is in the correct directory?

ASP.NET Bundles how to disable minification

To disable bundling and minification just put this your .aspx file (this will disable optimization even if debug=true in web.config)

vb.net:

System.Web.Optimization.BundleTable.EnableOptimizations = false

c#.net

System.Web.Optimization.BundleTable.EnableOptimizations = false;

If you put EnableOptimizations = true this will bundle and minify even if debug=true in web.config

How to implement a SQL like 'LIKE' operator in java?

public static boolean like(String source, String exp) {
        if (source == null || exp == null) {
            return false;
        }

        int sourceLength = source.length();
        int expLength = exp.length();

        if (sourceLength == 0 || expLength == 0) {
            return false;
        }

        boolean fuzzy = false;
        char lastCharOfExp = 0;
        int positionOfSource = 0;

        for (int i = 0; i < expLength; i++) {
            char ch = exp.charAt(i);

            // ????
            boolean escape = false;
            if (lastCharOfExp == '\\') {
                if (ch == '%' || ch == '_') {
                    escape = true;
                    // System.out.println("escape " + ch);
                }
            }

            if (!escape && ch == '%') {
                fuzzy = true;
            } else if (!escape && ch == '_') {
                if (positionOfSource >= sourceLength) {
                    return false;
                }

                positionOfSource++;// <<<----- ???1
            } else if (ch != '\\') {// ????,?????????
                if (positionOfSource >= sourceLength) {// ?????source????
                    return false;
                }

                if (lastCharOfExp == '%') { // ??????%,?????
                    int tp = source.indexOf(ch);
                    // System.out.println("?????=%,?????=" + ch + ",position=" + position + ",tp=" + tp);

                    if (tp == -1) { // ????????,????
                        return false;
                    }

                    if (tp >= positionOfSource) {
                        positionOfSource = tp + 1;// <<<----- ????

                        if (i == expLength - 1 && positionOfSource < sourceLength) { // exp??????????,????source?????????
                            return false;
                        }
                    } else {
                        return false;
                    }
                } else if (source.charAt(positionOfSource) == ch) {// ????????ch??
                    positionOfSource++;
                } else {
                    return false;
                }
            }

            lastCharOfExp = ch;// <<<----- ??
            // System.out.println("?????=" + ch + ",position=" + position);
        }

        // expr???????,???????,??source???????????source???
        if (!fuzzy && positionOfSource < sourceLength) {
            // System.out.println("?????=" + lastChar + ",position=" + position );

            return false;
        }

        return true;// ????true
    }
Assert.assertEquals(true, like("abc_d", "abc\\_d"));
        Assert.assertEquals(true, like("abc%d", "abc\\%%d"));
        Assert.assertEquals(false, like("abcd", "abc\\_d"));

        String source = "1abcd";
        Assert.assertEquals(true, like(source, "_%d"));
        Assert.assertEquals(false, like(source, "%%a"));
        Assert.assertEquals(false, like(source, "1"));
        Assert.assertEquals(true, like(source, "%d"));
        Assert.assertEquals(true, like(source, "%%%%"));
        Assert.assertEquals(true, like(source, "1%_"));
        Assert.assertEquals(false, like(source, "1%_2"));
        Assert.assertEquals(false, like(source, "1abcdef"));
        Assert.assertEquals(true, like(source, "1abcd"));
        Assert.assertEquals(false, like(source, "1abcde"));

        // ????case?????
        Assert.assertEquals(true, like(source, "_%_"));
        Assert.assertEquals(true, like(source, "_%____"));
        Assert.assertEquals(true, like(source, "_____"));// 5?
        Assert.assertEquals(false, like(source, "___"));// 3?
        Assert.assertEquals(false, like(source, "__%____"));// 6?
        Assert.assertEquals(false, like(source, "1"));

        Assert.assertEquals(false, like(source, "a_%b"));
        Assert.assertEquals(true, like(source, "1%"));
        Assert.assertEquals(false, like(source, "d%"));
        Assert.assertEquals(true, like(source, "_%"));
        Assert.assertEquals(true, like(source, "_abc%"));
        Assert.assertEquals(true, like(source, "%d"));
        Assert.assertEquals(true, like(source, "%abc%"));
        Assert.assertEquals(false, like(source, "ab_%"));

        Assert.assertEquals(true, like(source, "1ab__"));
        Assert.assertEquals(true, like(source, "1ab__%"));
        Assert.assertEquals(false, like(source, "1ab___"));
        Assert.assertEquals(true, like(source, "%"));

        Assert.assertEquals(false, like(null, "1ab___"));
        Assert.assertEquals(false, like(source, null));
        Assert.assertEquals(false, like(source, ""));

Reading multiple Scanner inputs

If every input asks the same question, you should use a for loop and an array of inputs:

Scanner dd = new Scanner(System.in);
int[] vars = new int[3];

for(int i = 0; i < vars.length; i++) {
  System.out.println("Enter next var: ");
  vars[i] = dd.nextInt();
}

Or as Chip suggested, you can parse the input from one line:

Scanner in = new Scanner(System.in);
int[] vars = new int[3];

System.out.println("Enter "+vars.length+" vars: ");
for(int i = 0; i < vars.length; i++)
  vars[i] = in.nextInt();

You were on the right track, and what you did works. This is just a nicer and more flexible way of doing things.

remove inner shadow of text input

This is the solution for mobile safari:

-webkit-appearance: none;

as suggested here: Remove textarea inner shadow on Mobile Safari (iPhone)

How to construct a WebSocket URI relative to the page URI?

Here is my version which adds the tcp port in case it's not 80 or 443:

function url(s) {
    var l = window.location;
    return ((l.protocol === "https:") ? "wss://" : "ws://") + l.hostname + (((l.port != 80) && (l.port != 443)) ? ":" + l.port : "") + l.pathname + s;
}

Edit 1: Improved version as by suggestion of @kanaka :

function url(s) {
    var l = window.location;
    return ((l.protocol === "https:") ? "wss://" : "ws://") + l.host + l.pathname + s;
}

Edit 2: Nowadays I create the WebSocket this:

var s = new WebSocket(((window.location.protocol === "https:") ? "wss://" : "ws://") + window.location.host + "/ws");

Plugin execution not covered by lifecycle configuration (JBossas 7 EAR archetype)

I was able to resolve the same problem with maven-antrun-plugin and jaxb2-maven-plugin in Eclipse Kepler 4.3 by appying this solution: http://wiki.eclipse.org/M2E_plugin_execution_not_covered#Eclipse_4.2_add_default_mapping
So the content of my %elipse_workspace_name%/.metadata/.plugins/org.eclipse.m2e.core/lifecycle-mapping-metadata.xml is as follows:

<?xml version="1.0" encoding="UTF-8"?>
<lifecycleMappingMetadata>
  <pluginExecutions>
    <pluginExecution>
      <pluginExecutionFilter>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-antrun-plugin</artifactId>
        <versionRange>1.3</versionRange>
        <goals>
          <goal>run</goal>
        </goals>
      </pluginExecutionFilter>
      <action>
        <ignore />
      </action>
    </pluginExecution>
    <pluginExecution>
      <pluginExecutionFilter>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>jaxb2-maven-plugin</artifactId>
        <versionRange>1.2</versionRange>
        <goals>
          <goal>xjc</goal>
        </goals>
      </pluginExecutionFilter>
      <action>
        <ignore />
      </action>
    </pluginExecution>
  </pluginExecutions>
</lifecycleMappingMetadata>

*Had to restart Eclipse to see the errors gone.

How to center buttons in Twitter Bootstrap 3?

According to the Twitter Bootstrap documentation: http://getbootstrap.com/css/#helper-classes-center

<!-- Button -->
<div class="form-group">
   <label class="col-md-4 control-label" for="singlebutton"></label>
   <div class="col-md-4 center-block">
      <button id="singlebutton" name="singlebutton" class="btn btn-primary center-block">
          Next Step!
       </button>
   </div>  
</div>

All the class center-block does is to tell the element to have a margin of 0 auto, the auto being the left/right margins. However, unless the class text-center or css text-align:center; is set on the parent, the element does not know the point to work out this auto calculation from so will not center itself as anticipated.

See an example of the code above here: https://jsfiddle.net/Seany84/2j9pxt1z/

Get changes from master into branch in Git

This (from here) worked for me:

git checkout aq
git pull origin master
...
git push

Quoting:

git pull origin master fetches and merges the contents of the master branch with your branch and creates a merge commit. If there are any merge conflicts you'll be notified at this stage and you must resolve the merge commits before proceeding. When you are ready to push your local commits, including your new merge commit, to the remote server, run git push.

How to a convert a date to a number and back again in MATLAB

Use DATESTR

>> datestr(40189)
ans =
12-Jan-0110

Unfortunately, Excel starts counting at 1-Jan-1900. Find out how to convert serial dates from Matlab to Excel by using DATENUM

>> datenum(2010,1,11)
ans =
      734149
>> datenum(2010,1,11)-40189
ans =
      693960
>> datestr(40189+693960)
ans =
11-Jan-2010

In other words, to convert any serial Excel date, call

datestr(excelSerialDate + 693960)

EDIT

To get the date in mm/dd/yyyy format, call datestr with the specified format

excelSerialDate = 40189;
datestr(excelSerialDate + 693960,'mm/dd/yyyy')
ans =
01/11/2010

Also, if you want to get rid of the leading zero for the month, you can use REGEXPREP to fix things

excelSerialDate = 40189;
regexprep(datestr(excelSerialDate + 693960,'mm/dd/yyyy'),'^0','')
ans =
1/11/2010

How to use OpenCV SimpleBlobDetector

You may store the parameters for the blob detector in a file, but this is not necessary. Example:

// set up the parameters (check the defaults in opencv's code in blobdetector.cpp)
cv::SimpleBlobDetector::Params params;
params.minDistBetweenBlobs = 50.0f;
params.filterByInertia = false;
params.filterByConvexity = false;
params.filterByColor = false;
params.filterByCircularity = false;
params.filterByArea = true;
params.minArea = 20.0f;
params.maxArea = 500.0f;
// ... any other params you don't want default value

// set up and create the detector using the parameters
cv::SimpleBlobDetector blob_detector(params);
// or cv::Ptr<cv::SimpleBlobDetector> detector = cv::SimpleBlobDetector::create(params)

// detect!
vector<cv::KeyPoint> keypoints;
blob_detector.detect(image, keypoints);

// extract the x y coordinates of the keypoints: 

for (int i=0; i<keypoints.size(); i++){
    float X = keypoints[i].pt.x; 
    float Y = keypoints[i].pt.y;
}

Showing/Hiding Table Rows with Javascript - can do with ID - how to do with Class?

You can change the class of the entire table and use the cascade in the CSS: http://jsbin.com/oyunuy/1/

Could not find or load main class

Sometimes what might be causing the issue has nothing to do with the main class. I had to find this out the hard way, it was a referenced library that I moved and it gave me the:

Could not find or load main class xxx Linux

I just delete that reference and added again and it worked fine again.

modal View controllers - how to display and dismiss

I think you misunderstood some core concepts about iOS modal view controllers. When you dismiss VC1, any presented view controllers by VC1 are dismissed as well. Apple intended for modal view controllers to flow in a stacked manner - in your case VC2 is presented by VC1. You are dismissing VC1 as soon as you present VC2 from VC1 so it is a total mess. To achieve what you want, buttonPressedFromVC1 should have the mainVC present VC2 immediately after VC1 dismisses itself. And I think this can be achieved without delegates. Something along the lines:

UIViewController presentingVC = [self presentingViewController];
[self dismissViewControllerAnimated:YES completion:
 ^{
    [presentingVC presentViewController:vc2 animated:YES completion:nil];
 }];

Note that self.presentingViewController is stored in some other variable, because after vc1 dismisses itself, you shouldn't make any references to it.