Programs & Examples On #Zseries

Getting mouse position in c#

If you don't want to reference Forms you can use interop to get the cursor position:

using System.Runtime.InteropServices;
using System.Windows; // Or use whatever point class you like for the implicit cast operator

/// <summary>
/// Struct representing a point.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct POINT
{
    public int X;
    public int Y;

    public static implicit operator Point(POINT point)
    {
        return new Point(point.X, point.Y);
    }
}

/// <summary>
/// Retrieves the cursor's position, in screen coordinates.
/// </summary>
/// <see>See MSDN documentation for further information.</see>
[DllImport("user32.dll")]
public static extern bool GetCursorPos(out POINT lpPoint);

public static Point GetCursorPosition()
{
    POINT lpPoint;
    GetCursorPos(out lpPoint);
    // NOTE: If you need error handling
    // bool success = GetCursorPos(out lpPoint);
    // if (!success)
        
    return lpPoint;
}

Content Security Policy "data" not working for base64 Images in Chrome 28

Try this

data to load:

<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 4 5'><path fill='#343a40' d='M2 0L0 2h4zm0 5L0 3h4z'/></svg>

get a utf8 to base64 convertor and convert the "svg" string to:

PHN2ZyB4bWxucz0naHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmcnIHZpZXdCb3g9JzAgMCA0IDUn
PjxwYXRoIGZpbGw9JyMzNDNhNDAnIGQ9J00yIDBMMCAyaDR6bTAgNUwwIDNoNHonLz48L3N2Zz4=

and the CSP is

img-src data: image/svg+xml;base64,PHN2ZyB4bWxucz0naHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmcnIHZpZXdCb3g9JzAgMCA0IDUn
PjxwYXRoIGZpbGw9JyMzNDNhNDAnIGQ9J00yIDBMMCAyaDR6bTAgNUwwIDNoNHonLz48L3N2Zz4=

MySQL - Get row number on select

You can use MySQL variables to do it. Something like this should work (though, it consists of two queries).

SELECT 0 INTO @x;

SELECT itemID, 
       COUNT(*) AS ordercount, 
       (@x:=@x+1) AS rownumber 
FROM orders 
GROUP BY itemID 
ORDER BY ordercount DESC; 

How to access static resources when mapping a global front controller servlet on /*

If you use Tomcat, you can map resources to the default servlet:

<servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>/static/*</url-pattern>
</servlet-mapping>

and access your resources with url http://{context path}/static/res/...

Also works with Jetty, not sure about other servlet containers.

Fastest way to check if a value exists in a list

The original question was:

What is the fastest way to know if a value exists in a list (a list with millions of values in it) and what its index is?

Thus there are two things to find:

  1. is an item in the list, and
  2. what is the index (if in the list).

Towards this, I modified @xslittlegrass code to compute indexes in all cases, and added an additional method.

Results

enter image description here

Methods are:

  1. in--basically if x in b: return b.index(x)
  2. try--try/catch on b.index(x) (skips having to check if x in b)
  3. set--basically if x in set(b): return b.index(x)
  4. bisect--sort b with its index, binary search for x in sorted(b). Note mod from @xslittlegrass who returns the index in the sorted b, rather than the original b)
  5. reverse--form a reverse lookup dictionary d for b; then d[x] provides the index of x.

Results show that method 5 is the fastest.

Interestingly the try and the set methods are equivalent in time.


Test Code

import random
import bisect
import matplotlib.pyplot as plt
import math
import timeit
import itertools

def wrapper(func, *args, **kwargs):
    " Use to produced 0 argument function for call it"
    # Reference https://www.pythoncentral.io/time-a-python-function/
    def wrapped():
        return func(*args, **kwargs)
    return wrapped

def method_in(a,b,c):
    for i,x in enumerate(a):
        if x in b:
            c[i] = b.index(x)
        else:
            c[i] = -1
    return c

def method_try(a,b,c):
    for i, x in enumerate(a):
        try:
            c[i] = b.index(x)
        except ValueError:
            c[i] = -1

def method_set_in(a,b,c):
    s = set(b)
    for i,x in enumerate(a):
        if x in s:
            c[i] = b.index(x)
        else:
            c[i] = -1
    return c

def method_bisect(a,b,c):
    " Finds indexes using bisection "

    # Create a sorted b with its index
    bsorted = sorted([(x, i) for i, x in enumerate(b)], key = lambda t: t[0])

    for i,x in enumerate(a):
        index = bisect.bisect_left(bsorted,(x, ))
        c[i] = -1
        if index < len(a):
            if x == bsorted[index][0]:
                c[i] = bsorted[index][1]  # index in the b array

    return c

def method_reverse_lookup(a, b, c):
    reverse_lookup = {x:i for i, x in enumerate(b)}
    for i, x in enumerate(a):
        c[i] = reverse_lookup.get(x, -1)
    return c

def profile():
    Nls = [x for x in range(1000,20000,1000)]
    number_iterations = 10
    methods = [method_in, method_try, method_set_in, method_bisect, method_reverse_lookup]
    time_methods = [[] for _ in range(len(methods))]

    for N in Nls:
        a = [x for x in range(0,N)]
        random.shuffle(a)
        b = [x for x in range(0,N)]
        random.shuffle(b)
        c = [0 for x in range(0,N)]

        for i, func in enumerate(methods):
            wrapped = wrapper(func, a, b, c)
            time_methods[i].append(math.log(timeit.timeit(wrapped, number=number_iterations)))

    markers = itertools.cycle(('o', '+', '.', '>', '2'))
    colors = itertools.cycle(('r', 'b', 'g', 'y', 'c'))
    labels = itertools.cycle(('in', 'try', 'set', 'bisect', 'reverse'))

    for i in range(len(time_methods)):
        plt.plot(Nls,time_methods[i],marker = next(markers),color=next(colors),linestyle='-',label=next(labels))

    plt.xlabel('list size', fontsize=18)
    plt.ylabel('log(time)', fontsize=18)
    plt.legend(loc = 'upper left')
    plt.show()

profile()

Footnotes for tables in LaTeX

This is a classic difficulty in LaTeX.

The problem is how to do layout with floats (figures and tables, an similar objects) and footnotes. In particular, it is hard to pick a place for a float with certainty that making room for the associated footnotes won't cause trouble. So the standard tabular and figure environments don't even try.

What can you do:

  1. Fake it. Just put a hardcoded vertical skip at the bottom of the caption and then write the footnote yourself (use \footnotesize for the size). You also have to manage the symbols or number yourself with \footnotemark. Simple, but not very attractive, and the footnote does not appear at the bottom of the page.
  2. Use the tabularx, longtable, threeparttable[x] (kudos to Joseph) or ctable which support this behavior.
  3. Manage it by hand. Use [h!] (or [H] with the float package) to control where the float will appear, and \footnotetext on the same page to put the footnote where you want it. Again, use \footnotemark to install the symbol. Fragile and requires hand-tooling every instance.
  4. The footnotes package provides the savenote environment, which can be used to do this.
  5. Minipage it (code stolen outright, and read the disclaimer about long caption texts in that case):
    \begin{figure}
      \begin{minipage}{\textwidth}
        ...
        \caption[Caption for LOF]%
          {Real caption\footnote{blah}}
      \end{minipage}
    \end{figure}

Additional reference: TeX FAQ item Footnotes in tables.

What is the difference between visibility:hidden and display:none?

In addition to all other answers, there's an important difference for IE8: If you use display:none and try to get the element's width or height, IE8 returns 0 (while other browsers will return the actual sizes). IE8 returns correct width or height only for visibility:hidden.

Styling every 3rd item of a list using CSS?

:nth-child is the answer you are looking for.

How do you embed binary data in XML?

I had this problem just last week. I had to serialize a PDF file and send it, inside an XML file, to a server.

If you're using .NET, you can convert a binary file directly to a base64 string and stick it inside an XML element.

string base64 = Convert.ToBase64String(File.ReadAllBytes(fileName));

Or, there is a method built right into the XmlWriter object. In my particular case, I had to include Microsoft's datatype namespace:

StringBuilder sb = new StringBuilder();
System.Xml.XmlWriter xw = XmlWriter.Create(sb);
xw.WriteStartElement("doc");
xw.WriteStartElement("serialized_binary");
xw.WriteAttributeString("types", "dt", "urn:schemas-microsoft-com:datatypes", "bin.base64");
byte[] b = File.ReadAllBytes(fileName);
xw.WriteBase64(b, 0, b.Length);
xw.WriteEndElement();
xw.WriteEndElement();
string abc = sb.ToString();

The string abc looks something that looks like this:

<?xml version="1.0" encoding="utf-16"?>
<doc>
    <serialized_binary types:dt="bin.base64" xmlns:types="urn:schemas-microsoft-com:datatypes">
        JVBERi0xLjMKJaqrrK0KNCAwIG9iago8PCAvVHlwZSAvSW5mbw...(plus lots more)
    </serialized_binary>
</doc>

Completely cancel a rebase

You are lucky that you didn't complete the rebase, so you can still do git rebase --abort. If you had completed the rebase (it rewrites history), things would have been much more complex. Consider tagging the tips of branches before doing potentially damaging operations (particularly history rewriting), that way you can rewind if something blows up.

How to copy part of an array to another array in C#?

In case if you want to implement your own Array.Copy method.

Static method which is of generic type.

 static void MyCopy<T>(T[] sourceArray, long sourceIndex, T[] destinationArray, long destinationIndex, long copyNoOfElements)
 {
  long totaltraversal = sourceIndex + copyNoOfElements;
  long sourceArrayLength = sourceArray.Length;

  //to check all array's length and its indices properties before copying
  CheckBoundaries(sourceArray, sourceIndex, destinationArray, copyNoOfElements, sourceArrayLength);
   for (long i = sourceIndex; i < totaltraversal; i++)
     {
      destinationArray[destinationIndex++] = sourceArray[i]; 
     } 
  }

Boundary method implementation.

private static void CheckBoundaries<T>(T[] sourceArray, long sourceIndex, T[] destinationArray, long copyNoOfElements, long sourceArrayLength)
        {
            if (sourceIndex >= sourceArray.Length)
            {
                throw new IndexOutOfRangeException();
            }
            if (copyNoOfElements > sourceArrayLength)
            {
                throw new IndexOutOfRangeException();
            }
            if (destinationArray.Length < copyNoOfElements)
            {
                throw new IndexOutOfRangeException();
            }
        }

Erase the current printed console line

Usually when you have a '\r' at the end of the string, only carriage return is printed without any newline. If you have the following:

printf("fooooo\r");
printf("bar");

the output will be:

barooo

One thing I can suggest (maybe a workaround) is to have a NULL terminated fixed size string that is initialized to all space characters, ending in a '\r' (every time before printing), and then use strcpy to copy your string into it (without the newline), so every subsequent print will overwrite the previous string. Something like this:

char str[MAX_LENGTH];        
// init str to all spaces, NULL terminated with character as '\r'
strcpy(str, my_string);       // copy my_string into str
str[strlen(my_string)] = ' '; // erase null termination char
str[MAX_LENGTH - 1] = '\r';
printf(str);

You can do error checking so that my_string is always atleast one less in length than str, but you get the basic idea.

is of a type that is invalid for use as a key column in an index

There is a limitation in SQL Server (up till 2008 R2) that varchar(MAX) and nvarchar(MAX) (and several other types like text, ntext ) cannot be used in indices. You have 2 options:
1. Set a limited size on the key field ex. nvarchar(100)
2. Create a check constraint that compares the value with all the keys in the table. The condition is:

([dbo].[CheckKey]([key])=(1))

and [dbo].[CheckKey] is a scalar function defined as:

CREATE FUNCTION [dbo].[CheckKey]
(
    @key nvarchar(max)
)
RETURNS bit
AS
BEGIN
    declare @res bit
    if exists(select * from key_value where [key] = @key)
        set @res = 0
    else
        set @res = 1

    return @res
END

But note that a native index is more performant than a check constraint so unless you really can't specify a length, don't use the check constraint.

Wait until all jQuery Ajax requests are done?

A little workaround is something like this:

// Define how many Ajax calls must be done
var ajaxCalls = 3;
var counter = 0;
var ajaxCallComplete = function() {
    counter++;
    if( counter >= ajaxCalls ) {
            // When all ajax calls has been done
        // Do something like hide waiting images, or any else function call
        $('*').css('cursor', 'auto');
    }
};

var loadPersons = function() {
        // Show waiting image, or something else
    $('*').css('cursor', 'wait');

    var url = global.ctx + '/loadPersons';
    $.getJSON(url, function(data) {
            // Fun things
    })
    .complete(function() { **ajaxCallComplete();** });
};

var loadCountries = function() {
    // Do things
    var url = global.ctx + '/loadCountries';
    $.getJSON(url, function(data) {
            // Travels
    })
    .complete(function() { **ajaxCallComplete();** });
};

var loadCities = function() {
    // Do things
    var url = global.ctx + '/loadCities';
    $.getJSON(url, function(data) {
            // Travels
    })
    .complete(function() { **ajaxCallComplete();** });
};

$(document).ready(function(){
    loadPersons();
    loadCountries();
    loadCities();
});

Hope can be useful...

How to upload a file and JSON data in Postman?

Maybe you could do it this way:

postman_file_upload_with_json

Where does PostgreSQL store the database?

Postgres stores data in files in its data directory. Follow the steps below to go to a database and its files:

The database corresponding to a postgresql table file is a directory. The location of the entire data directory can be obtained by running SHOW data_directory. in a UNIX like OS (eg: Mac) /Library/PostgreSQL/9.4/data Go inside the base folder in the data directory which has all the database folders: /Library/PostgreSQL/9.4/data/base

Find the database folder name by running (Gives an integer. This is the database folder name):

SELECT oid from pg_database WHERE datname = <database_name>;

Find the table file name by running (Gives an integer. This is the file name):

SELECT relname, relfilenode FROM pg_class WHERE relname = <table_name>; 

This is a binary file. File details such as size and creation date time can be obtained as usual. For more info read this SO thread

How to redirect output to a file and stdout

The command you want is named tee:

foo | tee output.file

For example, if you only care about stdout:

ls -a | tee output.file

If you want to include stderr, do:

program [arguments...] 2>&1 | tee outfile

2>&1 redirects channel 2 (stderr/standard error) into channel 1 (stdout/standard output), such that both is written as stdout. It is also directed to the given output file as of the tee command.

Furthermore, if you want to append to the log file, use tee -a as:

program [arguments...] 2>&1 | tee -a outfile

how to remove the bold from a headline?

style is accordingly vis css. An example

<h1 class="mynotsoboldtitle">Im not bold</h1>
<style>
.mynotsoboldtitle { font-weight:normal; }
</style>

Python - Get path of root project structure

There are many answers here but I couldn't find something simple that covers all cases so allow me to suggest my solution too:

_x000D_
_x000D_
import pathlib_x000D_
import os_x000D_
_x000D_
def get_project_root():_x000D_
    """_x000D_
    There is no way in python to get project root. This function uses a trick._x000D_
    We know that the function that is currently running is in the project._x000D_
    We know that the root project path is in the list of PYTHONPATH_x000D_
    look for any path in PYTHONPATH list that is contained in this function's path_x000D_
    Lastly we filter and take the shortest path because we are looking for the root._x000D_
    :return: path to project root_x000D_
    """_x000D_
    apth = str(pathlib.Path().absolute())_x000D_
    ppth = os.environ['PYTHONPATH'].split(':')_x000D_
    matches = [x for x in ppth if x in apth]_x000D_
    project_root = min(matches, key=len)_x000D_
    return project_root
_x000D_
_x000D_
_x000D_

NuGet Package Restore Not Working

If anything else didn't work, try:

  1. Close Project.
  2. Delete packages folder in your solution folder.
  3. Open Project again and restore Nugget Packages again.

Worked for me and it's easy to try.

Iterating over Typescript Map

You could use Map.prototype.forEach((value, key, map) => void, thisArg?) : void instead

Use it like this:

myMap.forEach((value: boolean, key: string) => {
    console.log(key, value);
});

Get file name from URL

String fileName = url.substring( url.lastIndexOf('/')+1, url.length() );

String fileNameWithoutExtn = fileName.substring(0, fileName.lastIndexOf('.'));

Python 3 - ValueError: not enough values to unpack (expected 3, got 2)

You probably want to assign the lastname you are reading out here

lastname = sheet.cell(row=r, column=3).value

to something; currently the program just forgets it

you could do that two lines after, like so

unpaidMembers[name] = lastname, email

your program will still crash at the same place, because .items() still won't give you 3-tuples but rather something that has this structure: (name, (lastname, email))

good news is, python can handle this

for name, (lastname, email) in unpaidMembers.items():

etc.

pypi UserWarning: Unknown distribution option: 'install_requires'

python setup.py uses distutils which doesn't support install_requires. setuptools does, also distribute (its successor), and pip (which uses either) do. But you actually have to use them. I.e. call setuptools through the easy_install command or pip install.

Another way is to import setup from setuptools in your setup.py, but this not standard and makes everybody wanting to use your package have to have setuptools installed.

How to get thread id from a thread pool?

There is the way of current thread getting:

Thread t = Thread.currentThread();

After you have got Thread class object (t) you are able to get information you need using Thread class methods.

Thread ID gettting:

long tId = t.getId(); // e.g. 14291

Thread name gettting:

String tName = t.getName(); // e.g. "pool-29-thread-7"

Changing the selected option of an HTML Select element

I used almost all of the answers posted here but not comfortable with that so i dig one step furter and found easy solution that fits my need and feel worth sharing with you guys.
Instead of iteration all over the options or using JQuery you can do using core JS in simple steps:

Example

<select id="org_list">
  <option value="23">IBM</option>
  <option value="33">DELL</option>
  <option value="25">SONY</option>
  <option value="29">HP</option>
</select>

So you must know the value of the option to select.

function selectOrganization(id){
    org_list=document.getElementById('org_list');
    org_list.selectedIndex=org_list.querySelector('option[value="'+id+'"]').index;
}

How to Use?

selectOrganization(25); //this will select SONY from option List

Your comments are welcome. :) AzmatHunzai.

how do I get a new line, after using float:left?

Another approach that's a little more semantic is to have a UL defined as your total 6 image width, each LI defined as float left and width defined - so that when LI #7 hits, it runs into the boundry of the UL, and is pushed down to the new row. You'll still have an open float that you'll want to clear after the /UL - but that can be done on the next element of the page, or as a clear div. Here's sort of the idea, you may have to mess with actual values, but this should give you the idea. The code is a little cleaner.

 <style type="text/css"> 
ul#imageSet { width: 600px; margin: 0; padding:0; }
ul#imageSet li { float: left; width: 100px;  height: 188px; margin: 0; padding:0; position: relative; list-style-type: none; }
.cornerimage { position: absolute; bottom: 0; right: 0; } 
h3.nextelement { clear: both; }
</style>


<ul id="imageSet">
    <li>
        <img border="0" height="188" src="http://farm3.static.flickr.com/2459/3534790964_5d8bed17c0.jpg" width="100" />
        <img class="cornerimage" height="140" src="http://farm4.static.flickr.com/3310/3514664446_08e9745681.jpg" width="50" />
    </li>
     <li>
        <img border="0" height="188" src="http://farm3.static.flickr.com/2459/3534790964_5d8bed17c0.jpg" width="100" />
        <img class="cornerimage" height="140" src="http://farm4.static.flickr.com/3310/3514664446_08e9745681.jpg" width="50" />
    </li>
    <li>
        <img border="0" height="188" src="http://farm3.static.flickr.com/2459/3534790964_5d8bed17c0.jpg" width="100" />
        <img class="cornerimage" height="140" src="http://farm4.static.flickr.com/3310/3514664446_08e9745681.jpg" width="50" />
    </li>
    <li>
        <img border="0" height="188" src="http://farm3.static.flickr.com/2459/3534790964_5d8bed17c0.jpg" width="100" />
        <img class="cornerimage" height="140" src="http://farm4.static.flickr.com/3310/3514664446_08e9745681.jpg" width="50" />
    </li>
    <li>
        <img border="0" height="188" src="http://farm3.static.flickr.com/2459/3534790964_5d8bed17c0.jpg" width="100" />
        <img class="cornerimage" height="140" src="http://farm4.static.flickr.com/3310/3514664446_08e9745681.jpg" width="50" />
    </li>
    <li>
        <img border="0" height="188" src="http://farm3.static.flickr.com/2459/3534790964_5d8bed17c0.jpg" width="100" />
        <img class="cornerimage" height="140" src="http://farm4.static.flickr.com/3310/3514664446_08e9745681.jpg" width="50" />
    </li>
    <li>
        <img border="0" height="188" src="http://farm3.static.flickr.com/2459/3534790964_5d8bed17c0.jpg" width="100" />
        <img class="cornerimage" height="140" src="http://farm4.static.flickr.com/3310/3514664446_08e9745681.jpg" width="50" />
    </li>
    <li>
        <img border="0" height="188" src="http://farm3.static.flickr.com/2459/3534790964_5d8bed17c0.jpg" width="100" />
        <img class="cornerimage" height="140" src="http://farm4.static.flickr.com/3310/3514664446_08e9745681.jpg" width="50" />
    </li>
</ul>


<h3 class="nextelement">Next Element in Doc</h3>

How do I query for all dates greater than a certain date in SQL Server?

Try enclosing your date into a character string.

 select * 
 from dbo.March2010 A
 where A.Date >= '2010-04-01';

How to convert an Stream into a byte[] in C#?

if you post a file from mobile device or other

    byte[] fileData = null;
    using (var binaryReader = new BinaryReader(Request.Files[0].InputStream))
    {
        fileData = binaryReader.ReadBytes(Request.Files[0].ContentLength);
    }

Properly close mongoose's connection once you're done

You can set the connection to a variable then disconnect it when you are done:

var db = mongoose.connect('mongodb://localhost:27017/somedb');

// Do some stuff

db.disconnect();

How to count check-boxes using jQuery?

Assume that you have a tr row with multiple checkboxes in it, and you want to count only if the first checkbox is checked.

You can do that by giving a class to the first checkbox

For example class='mycxk' and you can count that using the filter, like this

$('.mycxk').filter(':checked').length

Static linking vs dynamic linking

Dynamic linking is the only practical way to meet some license requirements such as the LGPL.

Remove the legend on a matplotlib figure

As of matplotlib v1.4.0rc4, a remove method has been added to the legend object.

Usage:

ax.get_legend().remove()

or

legend = ax.legend(...)
...
legend.remove()

See here for the commit where this was introduced.

Using openssl to get the certificate from a server

While I agree with Ari's answer (and upvoted it :), I needed to do an extra step to get it to work with Java on Windows (where it needed to be deployed):

openssl s_client -showcerts -connect www.example.com:443 < /dev/null | openssl x509 -outform DER > derp.der

Before adding the openssl x509 -outform DER conversion, I was getting an error from keytool on Windows complaining about the certificate's format. Importing the .der file worked fine.

Git commit in terminal opens VIM, but can't get back to terminal

Simply doing the vim "save and quit" command :wq should do the trick.

In order to have Git open it in another editor, you need to change the Git core.editor setting to a command which runs the editor you want.

git config --global core.editor "command to start sublime text 2"

VBA setting the formula for a cell

If you want to make address directly, the worksheet must exist.

Turning off automatic recalculation want help you :)

But... you can get value indirectly...

.FormulaR1C1 = "=INDIRECT(ADDRESS(2,7,1,0,""" & strProjectName & """),FALSE)"

At the time formula is inserted it will return #REF error, because strProjectName sheet does not exist.

But after this worksheet appear Excel will calculate formula again and proper value will be shown.
Disadvantage: there will be no tracking, so if you move the cell or change worksheet name, the formula will not adjust to the changes as in the direct addressing.

How to use XPath contains() here?

You are only looking at the first li child in the query you have instead of looking for any li child element that may contain the text, 'Model'. What you need is a query like the following:

//ul[@class='featureList' and ./li[contains(.,'Model')]]

This query will give you the elements that have a class of featureList with one or more li children that contain the text, 'Model'.

Cannot find vcvarsall.bat when running a Python script

This cryptic error means that you don't have a C compiler installed. There was a discussion to propose a more explanative error (which is continued here, register and comment if you care about it!) but currently it is still not implemented.

To fix this issue you can either install the Visual Studio 2008 SDK which will take about a GB, or you can install the very small VCForPython27.msi but which is not well supported by distutils currently, here's the procedure:

1) install Microsoft Visual C++ Compiler for Python 2.7 from
http://www.microsoft.com/en-us/download/details.aspx?id=44266
2) Enter MSVC for Python command prompt
3) SET DISTUTILS_USE_SDK=1
4) SET MSSdk=1
5) you can then build your C extensions: python.exe setup.py ...

Steps 2 to 4 must be reproduced everytime before building your C extensions. This is because of an issue with the VCForPython27.msi which install the header files and vcvarsall.bat in folders of a different layout than the VS2008 SDK and thus confuse the compiler detection of distutils. This will get fixed in setuptools in Python 2.7.10.

Bug report and workaround by Gregory Szorc: http://bugs.python.org/issue23246

More info and a workaround for using %%cython magic inside IPython: https://github.com/cython/cython/wiki/CythonExtensionsOnWindows

/EDIT: Also, if you have another version of Python, you cannot use Microsoft Visual C++ for Python 2.7, which is a kind of mini-compiler specifically made by Microsoft for Python 2.7. In this case, you need to install the Visual Studio SDK that match your Python version, or a Windows SDK with the correct NET framework version. See here for more infos: https://github.com/cython/cython/wiki/CythonExtensionsOnWindows#using-windows-sdk-cc-compiler-works-for-all-python-versions

Only using @JsonIgnore during serialization, but not deserialization

In my case, I have Jackson automatically (de)serializing objects that I return from a Spring MVC controller (I am using @RestController with Spring 4.1.6). I had to use com.fasterxml.jackson.annotation.JsonIgnore instead of org.codehaus.jackson.annotate.JsonIgnore, as otherwise, it simply did nothing.

How to calculate the width of a text string of a specific font and font-size?

Not sure how efficient this is, but I wrote this function that returns the point size that will fit a string to a given width:

func fontSizeThatFits(targetWidth: CGFloat, maxFontSize: CGFloat, font: UIFont) -> CGFloat {
    var variableFont = font.withSize(maxFontSize)
    var currentWidth = self.size(withAttributes: [NSAttributedString.Key.font:variableFont]).width

    while currentWidth > targetWidth {
        variableFont = variableFont.withSize(variableFont.pointSize - 1)
        currentWidth = self.size(withAttributes: [NSAttributedString.Key.font:variableFont]).width
    }

    return variableFont.pointSize
}

And it would be used like this:

textView.font = textView.font!.withSize(textView.text!.fontSizeThatFits(targetWidth: view.frame.width, maxFontSize: 50, font: textView.font!))

Git - What is the difference between push.default "matching" and "simple"

git push can push all branches or a single one dependent on this configuration:

Push all branches

git config --global push.default matching

It will push all the branches to the remote branch and would merge them. If you don't want to push all branches, you can push the current branch if you fully specify its name, but this is much is not different from default.

Push only the current branch if its named upstream is identical

git config --global push.default simple

So, it's better, in my opinion, to use this option and push your code branch by branch. It's better to push branches manually and individually.

error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘{’ token

AST_NODE* Statement(AST_NODE* node)

is missing a semicolon (a major clue was the error message "In function ‘Statement’: ...") and so is line 24,

   return node

(Once you fix those, you will encounter other problems, some of which are mentioned by others here.)

Python re.sub(): how to substitute all 'u' or 'U's with 'you'

Another possible solution I came up with was:

re.sub(r'([uU]+(.)?\s)',' you ', text)

How to Add a Dotted Underline Beneath HTML Text

If the content has more than 1 line, adding a bottom border won't help. In that case you'll have to use,

text-decoration: underline;
text-decoration-style: dotted;

If you want more breathing space in between the text and the line, simply use,

text-underline-position: under;

What is the difference between `Enum.name()` and `Enum.toString()`?

Use toString when you need to display the name to the user.

Use name when you need the name for your program itself, e.g. to identify and differentiate between different enum values.

How to ssh connect through python Paramiko with ppk public key

To create a valid DSA format private key supported by Paramiko in Puttygen.

Click on Conversions then Export OpenSSH Key

enter image description here

Docker Repository Does Not Have a Release File on Running apt-get update on Ubuntu

On Linux Mint, the official instructions did not work for me. I had to go into /etc/apt/sources.list.d/additional-repositories.list and change serena to xenial.

How do I use a pipe to redirect the output of one command to the input of another?

You can also run exactly same command at Cmd.exe command-line using PowerShell. I'd go with this approach for simplicity...

C:\>PowerShell -Command "temperature | prismcom.exe usb"

Please read up on Understanding the Windows PowerShell Pipeline

You can also type in C:\>PowerShell at the command-line and it'll put you in PS C:\> mode instanctly, where you can directly start writing PS.

What is the difference between declarations, providers, and import in NgModule?

imports are used to import supporting modules like FormsModule, RouterModule, CommonModule, or any other custom-made feature module.

declarations are used to declare components, directives, pipes that belong to the current module. Everyone inside declarations knows each other. For example, if we have a component, say UsernameComponent, which displays a list of the usernames and we also have a pipe, say toupperPipe, which transforms a string to an uppercase letter string. Now If we want to show usernames in uppercase letters in our UsernameComponent then we can use the toupperPipe which we had created before but the question is how UsernameComponent knows that the toupperPipe exists and how it can access and use that. Here come the declarations, we can declare UsernameComponent and toupperPipe.

Providers are used for injecting the services required by components, directives, pipes in the module.

Getting the source of a specific image element with jQuery

To select and element where you know only the attribute value you can use the below jQuery script

var src = $('.conversation_img[alt="example"]').attr('src');

Please refer the jQuery Documentation for attribute equals selectors

Please also refer to the example in Demo

Following is the code incase you are not able to access the demo..

HTML

<div>
    <img alt="example" src="\images\show.jpg" />
    <img  alt="exampleAll" src="\images\showAll.jpg" />  

</div>

SCRIPT JQUERY

var src = $('img[alt="example"]').attr('src');
alert("source of image with alternate text = example - " + src);


var srcAll = $('img[alt="exampleAll"]').attr('src');
alert("source of image with alternate text = exampleAll - " + srcAll );

Output will be

Two Alert messages each having values

  1. source of image with alternate text = example - \images\show.jpg
  2. source of image with alternate text = exampleAll - \images\showAll.jpg

Passing in class names to react components

Just for the reference, for stateless components:

// ParentComponent.js
import React from 'react';
import { ChildComponent } from '../child/ChildComponent';

export const ParentComponent = () =>
  <div className="parent-component">
    <ChildComponent className="parent-component__child">
      ...
    </ChildComponent>
  </div>

// ChildComponent.js
import React from 'react';

export const ChildComponent = ({ className, children }) =>
  <div className={`some-css-className ${className}`}>
    {children}
  </div>

Will render:

<div class="parent-component">
  <div class="some-css-className parent-component__child">
    ...
  </div>
</div>

Converting a JS object to an array using jQuery

After some tests, here is a general object to array function convertor:

You have the object:

var obj = {
    some_key_1: "some_value_1"
    some_key_2: "some_value_2"
};

The function:

function ObjectToArray(o)
{
    var k = Object.getOwnPropertyNames(o);
    var v = Object.values(o);

    var c = function(l)
    {
        this.k = [];
        this.v = [];
        this.length = l;
    };

    var r = new c(k.length);

    for (var i = 0; i < k.length; i++)
    {
        r.k[i] = k[i];
        r.v[i] = v[i];
    }

    return r;
}

Function Use:

var arr = ObjectToArray(obj);

You Get:

arr {
    key: [
        "some_key_1",
        "some_key_2"
    ],
    value: [
        "some_value_1",
        "some_value_2"
    ],
    length: 2
}

So then you can reach all keys & values like:

for (var i = 0; i < arr.length; i++)
{
    console.log(arr.key[i] + " = " + arr.value[i]);
}

Result in console:

some_key_1 = some_value_1
some_key_2 = some_value_2

Edit:

Or in prototype form:

Object.prototype.objectToArray = function()
{
    if (
        typeof this != 'object' ||
        typeof this.length != "undefined"
    ) {
        return false;
    }

    var k = Object.getOwnPropertyNames(this);
    var v = Object.values(this);

    var c = function(l)
    {
        this.k = [];
        this.v = [];
        this.length = l;
    };

    var r = new c(k.length);

    for (var i = 0; i < k.length; i++)
    {
        r.k[i] = k[i];
        r.v[i] = v[i];
    }

    return r;
};

And then use like:

console.log(obj.objectToArray);

Best way to determine user's locale within browser

You can use http or https.

https://ip2c.org/XXX.XXX.XXX.XXX or https://ip2c.org/?ip=XXX.XXX.XXX.XXX |

  • standard IPv4 from 0.0.0.0 to 255.255.255.255

https://ip2c.org/s or https://ip2c.org/self or https://ip2c.org/?self |

  • processes caller's IP
  • faster than ?dec= option but limited to one purpose - give info about yourself

Reference: https://about.ip2c.org/#inputs

Can someone explain mappedBy in JPA and Hibernate?

By specifying the @JoinColumn on both models you don't have a two way relationship. You have two one way relationships, and a very confusing mapping of it at that. You're telling both models that they "own" the IDAIRLINE column. Really only one of them actually should! The 'normal' thing is to take the @JoinColumn off of the @OneToMany side entirely, and instead add mappedBy to the @OneToMany.

@OneToMany(cascade = CascadeType.ALL, mappedBy="airline")
public Set<AirlineFlight> getAirlineFlights() {
    return airlineFlights;
}

That tells Hibernate "Go look over on the bean property named 'airline' on the thing I have a collection of to find the configuration."

ImproperlyConfigured: You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings

If you are using the local server, run Django shell using python manage.py shell. It will take you to the Django python environment and you are good to go.

IOError: [Errno 13] Permission denied

I have a really stupid use case for why I got this error. Originally I was printing my data > file.txt

Then I changed my mind, and decided to use open("file.txt", "w") instead. But when I called python, I left > file.txt .....

Setting a timeout for socket operations

You don't set a timeout for the socket, you set a timeout for the operations you perform on that socket.

For example socket.connect(otherAddress, timeout)

Or socket.setSoTimeout(timeout) for setting a timeout on read() operations.

See: http://docs.oracle.com/javase/7/docs/api/java/net/Socket.html

Random number between 0 and 1 in python

My variation that I find to be more flexible.

str_Key           = ""
str_FullKey       = "" 
str_CharacterPool = "01234ABCDEFfghij~-)"
for int_I in range(64): 
    str_Key = random.choice(str_CharacterPool) 
    str_FullKey = str_FullKey + str_Key 

Launch Pycharm from command line (terminal)

open /Applications/PyCharm\ CE.app/ opens up the primary Pycharm Dialogue box to choose the project..

worked for me with macOS 10.13.6 & Pycharm 2018.1

How to replace a substring of a string

Note that backslashes (\) and dollar signs ($) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string; see Matcher.replaceAll. Use Matcher.quoteReplacement(java.lang.String) to suppress the special meaning of these characters, if desired.

from javadoc.

How to copy a huge table data into another table in SQL Server

Here's another way of transferring large tables. I've just transferred 105 million rows between two servers using this. Quite quick too.

  1. Right-click on the database and choose Tasks/Export Data.
  2. A wizard will take you through the steps but you choosing your SQL server client as the data source and target will allow you to select the database and table(s) you wish to transfer.

For more information, see https://www.mssqltips.com/sqlservertutorial/202/simple-way-to-export-data-from-sql-server/

Why do I get "Exception; must be caught or declared to be thrown" when I try to compile my Java code?

The problem is in this method:

  public static byte[] encrypt(String toEncrypt) throws Exception{

This is the method signature which pretty much says:

  • what the method name is: encrypt
  • what parameter it receives: a String named toEncrypt
  • its access modifier: public static
  • and if it may or not throw an exception when invoked.

In this case the method signature says that when invoked this method "could" potentially throw an exception of type "Exception".

    ....
    concatURL = padString(concatURL, ' ', 16);
    byte[] encrypted = encrypt(concatURL); <-- HERE!!!!!
    String encryptedString = bytesToHex(encrypted);
    content.removeAll();
    ......

So the compilers is saying: Either you surround that with a try/catch construct or you declare the method ( where is being used ) to throw "Exception" it self.

The real problem is the "encrypt" method definition. No method should ever return "Exception", because it is too generic and may hide some other kinds of exception better is to have an specific exception.

Try this:

public static byte[] encrypt(String toEncrypt) {
    try{
      String plaintext = toEncrypt;
      String key = "01234567890abcde";
      String iv = "fedcba9876543210";

      SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
      IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());

      Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
      cipher.init(Cipher.ENCRYPT_MODE,keyspec,ivspec);
      byte[] encrypted = cipher.doFinal(toEncrypt.getBytes());

      return encrypted;
    } catch ( NoSuchAlgorithmException nsae ) { 
        // What can you do if the algorithm doesn't exists??
        // this usually won't happen because you would test 
        // your code before shipping. 
        // So in this case is ok to transform to another kind 
        throw new IllegalStateException( nsae );
    } catch ( NoSuchPaddingException nspe ) { 
       // What can you do when there is no such padding ( whatever that means ) ??
       // I guess not much, in either case you won't be able to encrypt the given string
        throw new IllegalStateException( nsae );
    }
    // line 109 won't say it needs a return anymore.
  }

Basically in this particular case you should make sure the cryptography package is available in the system.

Java needs an extension for the cryptography package, so, the exceptions are declared as "checked" exceptions. For you to handle when they are not present.

In this small program you cannot do anything if the cryptography package is not available, so you check that at "development" time. If those exceptions are thrown when your program is running is because you did something wrong in "development" thus a RuntimeException subclass is more appropriate.

The last line don't need a return statement anymore, in the first version you were catching the exception and doing nothing with it, that's wrong.

try { 
    // risky code ... 
} catch( Exception e ) { 
    // a bomb has just exploited
    // you should NOT ignore it 
} 

// The code continues here, but what should it do???

If the code is to fail, it is better to Fail fast

Here are some related answers:

How to get enum value by string or int

No, you don't want a generic method. This is much easier:

MyEnum myEnum = (MyEnum)myInt;

MyEnum myEnum = (MyEnum)Enum.Parse(typeof(MyEnum), myString);

I think it will also be faster.

PHP Pass by reference in foreach

I think this code show the procedure more clear.

<?php

$a = array ('zero','one','two', 'three');

foreach ($a as &$v) {
}

var_dump($a);

foreach ($a as $v) {
  var_dump($a);
}

Result: (Take attention on the last two array)

array(4) {
  [0]=>
  string(4) "zero"
  [1]=>
  string(3) "one"
  [2]=>
  string(3) "two"
  [3]=>
  &string(5) "three"
}
array(4) {
  [0]=>
  string(4) "zero"
  [1]=>
  string(3) "one"
  [2]=>
  string(3) "two"
  [3]=>
  &string(4) "zero"
}
array(4) {
  [0]=>
  string(4) "zero"
  [1]=>
  string(3) "one"
  [2]=>
  string(3) "two"
  [3]=>
  &string(3) "one"
}
array(4) {
  [0]=>
  string(4) "zero"
  [1]=>
  string(3) "one"
  [2]=>
  string(3) "two"
  [3]=>
  &string(3) "two"
}
array(4) {
  [0]=>
  string(4) "zero"
  [1]=>
  string(3) "one"
  [2]=>
  string(3) "two"
  [3]=>
  &string(3) "two"
}

WPF Data Binding and Validation Rules Best Practices

From MS's Patterns & Practices documentation:

Data Validation and Error Reporting

Your view model or model will often be required to perform data validation and to signal any data validation errors to the view so that the user can act to correct them.

Silverlight and WPF provide support for managing data validation errors that occur when changing individual properties that are bound to controls in the view. For single properties that are data-bound to a control, the view model or model can signal a data validation error within the property setter by rejecting an incoming bad value and throwing an exception. If the ValidatesOnExceptions property on the data binding is true, the data binding engine in WPF and Silverlight will handle the exception and display a visual cue to the user that there is a data validation error.

However, throwing exceptions with properties in this way should be avoided where possible. An alternative approach is to implement the IDataErrorInfo or INotifyDataErrorInfo interfaces on your view model or model classes. These interfaces allow your view model or model to perform data validation for one or more property values and to return an error message to the view so that the user can be notified of the error.

The documentation goes on to explain how to implement IDataErrorInfo and INotifyDataErrorInfo.

Check if table exists without using "select from"

None of the options except SELECT doesn't allow database name as used in SELECT, so I wrote this:

SELECT COUNT(*) AS cnt FROM information_schema.TABLES 
WHERE CONCAT(table_schema,".",table_name)="db_name.table_name";

use current date as default value for a column

You can use:

Insert into Event(Description,Date) values('teste', GETDATE());

Also, you can change your table so that 'Date' has a default, "GETDATE()"

How to convert numpy arrays to standard TensorFlow format?

You can use tf.pack (tf.stack in TensorFlow 1.0.0) method for this purpose. Here is how to pack a random image of type numpy.ndarray into a Tensor:

import numpy as np
import tensorflow as tf
random_image = np.random.randint(0,256, (300,400,3))
random_image_tensor = tf.pack(random_image)
tf.InteractiveSession()
evaluated_tensor = random_image_tensor.eval()

UPDATE: to convert a Python object to a Tensor you can use tf.convert_to_tensor function.

Getting the source HTML of the current page from chrome extension

Here is my solution:

chrome.runtime.onMessage.addListener(function(request, sender) {
        if (request.action == "getSource") {
            this.pageSource = request.source;
            var title = this.pageSource.match(/<title[^>]*>([^<]+)<\/title>/)[1];
            alert(title)
        }
    });

    chrome.tabs.query({ active: true, currentWindow: true }, tabs => {
        chrome.tabs.executeScript(
            tabs[0].id,
            { code: 'var s = document.documentElement.outerHTML; chrome.runtime.sendMessage({action: "getSource", source: s});' }
        );
    });

How to validate GUID is a GUID

if(MyGuid!=Guild.Empty)

{

//Valid Guild

}

else {

// Invalid Guild

}

How to use source: function()... and AJAX in JQuery UI autocomplete

Try this code. You can use $.get instead of $.ajax

$( "input.suggest-user" ).autocomplete({
    source: function( request, response ) {
        $.ajax({
            dataType: "json",
            type : 'Get',
            url: 'yourURL',
            success: function(data) {
                $('input.suggest-user').removeClass('ui-autocomplete-loading');  
                // hide loading image

                response( $.map( data, function(item) {
                    // your operation on data
                }));
            },
            error: function(data) {
                $('input.suggest-user').removeClass('ui-autocomplete-loading');  
            }
        });
    },
    minLength: 3,
    open: function() {},
    close: function() {},
    focus: function(event,ui) {},
    select: function(event, ui) {}
});

Error when checking Java version: could not find java.dll

Reinstall JDK and set system variable JAVA_HOME on your JDK. (e.g. C:\tools\jdk7)
And add JAVA_HOME variable to your PATH system variable

Type in command line

echo %JAVA_HOME%

and

java -version

To verify whether your installation was done successfully.


This problem generally occurs in Windows when your "Java Runtime Environment" registry entry is missing or mismatched with the installed JDK. The mismatch can be due to multiple JDKs.

Steps to resolve:

  1. Open the Run window:

    Press windows+R

  2. Open registry window:

    Type regedit and enter.

  3. Go to: \HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\

  4. If Java Runtime Environment is not present inside JavaSoft, then create a new Key and give the name Java Runtime Environment.

  5. For Java Runtime Environment create "CurrentVersion" String Key and give appropriate version as value:

JRE regedit entry

  1. Create a new subkey of 1.8.

  2. For 1.8 create a String Key with name JavaHome with the value of JRE home:

    JRE regedit entry 2

Ref: https://mybindirectory.blogspot.com/2019/05/error-could-not-find-javadll.html

ImportError: No module named xlsxwriter

I installed it by using a wheel file that can be found at this location: https://pypi.org/project/XlsxWriter/#files

I then ran pip install "XlsxWriter-1.2.8-py2.py3-none-any.whl"

Processing ./XlsxWriter-1.2.8-py2.py3-none-any.whl
Installing collected packages: XlsxWriter
Successfully installed XlsxWriter-1.2.8

Node.js Error: connect ECONNREFUSED

You need to have a server running on port 8080 when you run the code above that simply returns the request back through the response. Copy the code below to a separate file (say 'server.js') and start this server using the node command (node server.js). You can then separately run your code above (node app.js) from a separate command line.

var http = require('http');

http.createServer(function(request, response){

    //The following code will print out the incoming request text
    request.pipe(response);

}).listen(8080, '127.0.0.1');

console.log('Listening on port 8080...');

What is the difference between match_parent and fill_parent?

Google changed the name to avoid confusion.

Problem with the old name fill parent was that it implies its affecting the dimensions of the parent, while match parent better describes the resulting behavior - match the dimension with the parent.

Both constants resolve to -1 in the end, and so result in the identical behavior in the app. Ironically enough, this name change made to clarify things seems to have added confusion rather than eliminating it.

How do I test a website using XAMPP?

The webpages on an online server reside in a location which looks somewhat like this: http://www.somerandomsite.com/index.php

Since xampp is Offline, it sets up a local server whose address is like this http://localhost/

Basically, xampp sets up a server (apache and others) in your system. And all the files such as index.php, somethingelse.php, etc., reside in the xampp\htdocs\ folder.

The browser locates the server in localhost and will search through the above folder for any resources available in there.

So create any number of folders inside the "xampp\htdocs\" each folder thus forming a website (as you build it).

Sometimes apache won't even start. This is due to the clashing of ports with some applications. Some of them I commonly encounter is Skype. See to that it is killed completely and restart apache

Regular expression to remove HTML tags from a string

You should not attempt to parse HTML with regex. HTML is not a regular language, so any regex you come up with will likely fail on some esoteric edge case. Please refer to the seminal answer to this question for specifics. While mostly formatted as a joke, it makes a very good point.


The following examples are Java, but the regex will be similar -- if not identical -- for other languages.


String target = someString.replaceAll("<[^>]*>", "");

Assuming your non-html does not contain any < or > and that your input string is correctly structured.

If you know they're a specific tag -- for example you know the text contains only <td> tags, you could do something like this:

String target = someString.replaceAll("(?i)<td[^>]*>", "");

Edit: Omega brought up a good point in a comment on another post that this would result in multiple results all being squished together if there were multiple tags.

For example, if the input string were <td>Something</td><td>Another Thing</td>, then the above would result in SomethingAnother Thing.

In a situation where multiple tags are expected, we could do something like:

String target = someString.replaceAll("(?i)<td[^>]*>", " ").replaceAll("\\s+", " ").trim();

This replaces the HTML with a single space, then collapses whitespace, and then trims any on the ends.

Hibernate: best practice to pull all lazy collections

You can traverse over the Getters of the Hibernate object in the same transaction to assure all lazy child objects are fetched eagerly with the following generic helper class:

HibernateUtil.initializeObject(myObject, "my.app.model");

package my.app.util;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.Set;

import org.aspectj.org.eclipse.jdt.core.dom.Modifier;
import org.hibernate.Hibernate;

public class HibernateUtil {

public static byte[] hibernateCollectionPackage = "org.hibernate.collection".getBytes();

public static void initializeObject( Object o, String insidePackageName ) {
    Set<Object> seenObjects = new HashSet<Object>();
    initializeObject( o, seenObjects, insidePackageName.getBytes() );
    seenObjects = null;
}

private static void initializeObject( Object o, Set<Object> seenObjects, byte[] insidePackageName ) {

    seenObjects.add( o );

    Method[] methods = o.getClass().getMethods();
    for ( Method method : methods ) {

        String methodName = method.getName();

        // check Getters exclusively
        if ( methodName.length() < 3 || !"get".equals( methodName.substring( 0, 3 ) ) )
            continue;

        // Getters without parameters
        if ( method.getParameterTypes().length > 0 )
            continue;

        int modifiers = method.getModifiers();

        // Getters that are public
        if ( !Modifier.isPublic( modifiers ) )
            continue;

        // but not static
        if ( Modifier.isStatic( modifiers ) )
            continue;

        try {

            // Check result of the Getter
            Object r = method.invoke( o );

            if ( r == null )
                continue;

            // prevent cycles
            if ( seenObjects.contains( r ) )
                continue;

            // ignore simple types, arrays und anonymous classes
            if ( !isIgnoredType( r.getClass() ) && !r.getClass().isPrimitive() && !r.getClass().isArray() && !r.getClass().isAnonymousClass() ) {

                // ignore classes out of the given package and out of the hibernate collection
                // package
                if ( !isClassInPackage( r.getClass(), insidePackageName ) && !isClassInPackage( r.getClass(), hibernateCollectionPackage ) ) {
                    continue;
                }

                // initialize child object
                Hibernate.initialize( r );

                // traverse over the child object
                initializeObject( r, seenObjects, insidePackageName );
            }

        } catch ( InvocationTargetException e ) {
            e.printStackTrace();
            return;
        } catch ( IllegalArgumentException e ) {
            e.printStackTrace();
            return;
        } catch ( IllegalAccessException e ) {
            e.printStackTrace();
            return;
        }
    }

}

private static final Set<Class<?>> IGNORED_TYPES = getIgnoredTypes();

private static boolean isIgnoredType( Class<?> clazz ) {
    return IGNORED_TYPES.contains( clazz );
}

private static Set<Class<?>> getIgnoredTypes() {
    Set<Class<?>> ret = new HashSet<Class<?>>();
    ret.add( Boolean.class );
    ret.add( Character.class );
    ret.add( Byte.class );
    ret.add( Short.class );
    ret.add( Integer.class );
    ret.add( Long.class );
    ret.add( Float.class );
    ret.add( Double.class );
    ret.add( Void.class );
    ret.add( String.class );
    ret.add( Class.class );
    ret.add( Package.class );
    return ret;
}

private static Boolean isClassInPackage( Class<?> clazz, byte[] insidePackageName ) {

    Package p = clazz.getPackage();
    if ( p == null )
        return null;

    byte[] packageName = p.getName().getBytes();

    int lenP = packageName.length;
    int lenI = insidePackageName.length;

    if ( lenP < lenI )
        return false;

    for ( int i = 0; i < lenI; i++ ) {
        if ( packageName[i] != insidePackageName[i] )
            return false;
    }

    return true;
}
}

Converting strings to floats in a DataFrame

Here is an example

                            GHI             Temp  Power Day_Type
2016-03-15 06:00:00 -7.99999952505459e-7    18.3    0   NaN
2016-03-15 06:01:00 -7.99999952505459e-7    18.2    0   NaN
2016-03-15 06:02:00 -7.99999952505459e-7    18.3    0   NaN
2016-03-15 06:03:00 -7.99999952505459e-7    18.3    0   NaN
2016-03-15 06:04:00 -7.99999952505459e-7    18.3    0   NaN

but if this is all string values...as was in my case... Convert the desired columns to floats:

df_inv_29['GHI'] = df_inv_29.GHI.astype(float)
df_inv_29['Temp'] = df_inv_29.Temp.astype(float)
df_inv_29['Power'] = df_inv_29.Power.astype(float)

Your dataframe will now have float values :-)

How can I generate UUID in C#

I have a GitHub Gist with a Java like UUID implementation in C#: https://gist.github.com/rickbeerendonk/13655dd24ec574954366

The UUID can be created from the least and most significant bits, just like in Java. It also exposes them. The implementation has an explicit conversion to a GUID and an implicit conversion from a GUID.

How to convert a byte array to its numeric value (Java)?

Assuming the first byte is the least significant byte:

long value = 0;
for (int i = 0; i < by.length; i++)
{
   value += ((long) by[i] & 0xffL) << (8 * i);
}

Is the first byte the most significant, then it is a little bit different:

long value = 0;
for (int i = 0; i < by.length; i++)
{
   value = (value << 8) + (by[i] & 0xff);
}

Replace long with BigInteger, if you have more than 8 bytes.

Thanks to Aaron Digulla for the correction of my errors.

How to run Unix shell script from Java code?

Here is an example how to run an Unix bash or Windows bat/cmd script from Java. Arguments can be passed on the script and output received from the script. The method accepts arbitrary number of arguments.

public static void runScript(String path, String... args) {
    try {
        String[] cmd = new String[args.length + 1];
        cmd[0] = path;
        int count = 0;
        for (String s : args) {
            cmd[++count] = args[count - 1];
        }
        Process process = Runtime.getRuntime().exec(cmd);
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        try {
            process.waitFor();
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }
        while (bufferedReader.ready()) {
            System.out.println("Received from script: " + bufferedReader.readLine());
        }
    } catch (Exception ex) {
        System.out.println(ex.getMessage());
        System.exit(1);
    }
}

When running on Unix/Linux, the path must be Unix-like (with '/' as separator), when running on Windows - use '\'. Hier is an example of a bash script (test.sh) that receives arbitrary number of arguments and doubles every argument:

#!/bin/bash
counter=0
while [ $# -gt 0 ]
do
  echo argument $((counter +=1)): $1
  echo doubling argument $((counter)): $(($1+$1))
  shift
done

When calling

runScript("path_to_script/test.sh", "1", "2")

on Unix/Linux, the output is:

Received from script: argument 1: 1
Received from script: doubling argument 1: 2
Received from script: argument 2: 2
Received from script: doubling argument 2: 4

Hier is a simple cmd Windows script test.cmd that counts number of input arguments:

@echo off
set a=0
for %%x in (%*) do Set /A a+=1 
echo %a% arguments received

When calling the script on Windows

  runScript("path_to_script\\test.cmd", "1", "2", "3")

The output is

Received from script: 3 arguments received

Shortcut for creating single item list in C#

new[] { "item" }.ToList();

It's shorter than

new List<string> { "item" };

and you don't have to specify the type.

How to set my default shell on Mac?

On macOS Mojave I had to do the following (using zsh as an example):

brew install zsh
sudo sh -c "echo $(which zsh) >> /etc/shells"
chsh -s $(which zsh)

How do I delete from multiple tables using INNER JOIN in SQL server

  1. You can always set up cascading deletes on the relationships of the tables.

  2. You can encapsulate the multiple deletes in one stored procedure.

  3. You can use a transaction to ensure one unit of work.

WHERE Clause to find all records in a specific month

I think the function you're looking for is MONTH(date). You'll probably want to use 'YEAR' too.

Let's assume you have a table named things that looks something like this:

id happend_at
-- ----------------
1  2009-01-01 12:08
2  2009-02-01 12:00
3  2009-01-12 09:40
4  2009-01-29 17:55

And let's say you want to execute to find all the records that have a happened_at during the month 2009/01 (January 2009). The SQL query would be:

SELECT id FROM things 
   WHERE MONTH(happened_at) = 1 AND YEAR(happened_at) = 2009

Which would return:

id
---
1
3
4

pandas: to_numeric for multiple columns

UPDATE: you don't need to convert your values afterwards, you can do it on-the-fly when reading your CSV:

In [165]: df=pd.read_csv(url, index_col=0, na_values=['(NA)']).fillna(0)

In [166]: df.dtypes
Out[166]:
GeoName                    object
ComponentName              object
IndustryId                  int64
IndustryClassification     object
Description                object
2004                        int64
2005                        int64
2006                        int64
2007                        int64
2008                        int64
2009                        int64
2010                        int64
2011                        int64
2012                        int64
2013                        int64
2014                      float64
dtype: object

If you need to convert multiple columns to numeric dtypes - use the following technique:

Sample source DF:

In [271]: df
Out[271]:
     id    a  b  c  d  e    f
0  id_3  AAA  6  3  5  8    1
1  id_9    3  7  5  7  3  BBB
2  id_7    4  2  3  5  4    2
3  id_0    7  3  5  7  9    4
4  id_0    2  4  6  4  0    2

In [272]: df.dtypes
Out[272]:
id    object
a     object
b      int64
c      int64
d      int64
e      int64
f     object
dtype: object

Converting selected columns to numeric dtypes:

In [273]: cols = df.columns.drop('id')

In [274]: df[cols] = df[cols].apply(pd.to_numeric, errors='coerce')

In [275]: df
Out[275]:
     id    a  b  c  d  e    f
0  id_3  NaN  6  3  5  8  1.0
1  id_9  3.0  7  5  7  3  NaN
2  id_7  4.0  2  3  5  4  2.0
3  id_0  7.0  3  5  7  9  4.0
4  id_0  2.0  4  6  4  0  2.0

In [276]: df.dtypes
Out[276]:
id     object
a     float64
b       int64
c       int64
d       int64
e       int64
f     float64
dtype: object

PS if you want to select all string (object) columns use the following simple trick:

cols = df.columns[df.dtypes.eq('object')]

Error: JavaFX runtime components are missing, and are required to run this application with JDK 11

This worked for me:

File >> Project Structure >> Modules >> Dependency >> + (on left-side of window)

clicking the "+" sign will let you designate the directory where you have unpacked JavaFX's "lib" folder.

Scope is Compile (which is the default.) You can then edit this to call it JavaFX by double-clicking on the line.

then in:

Run >> Edit Configurations

Add this line to VM Options:

--module-path /path/to/JavaFX/lib --add-modules=javafx.controls

(oh and don't forget to set the SDK)

Process all arguments except the first one (in a bash script)

If you want a solution that also works in /bin/sh try

first_arg="$1"
shift
echo First argument: "$first_arg"
echo Remaining arguments: "$@"

shift [n] shifts the positional parameters n times. A shift sets the value of $1 to the value of $2, the value of $2 to the value of $3, and so on, decreasing the value of $# by one.

Is there a way to know your current username in mysql?

You can also use : mysql> select user,host from mysql.user;

+---------------+-------------------------------+
| user          | host                          |
+---------------+-------------------------------+
| fkernel       | %                             |
| nagios        | %                             |
| readonly      | %                             |
| replicant     | %                             |
| reporting     | %                             |
| reporting_ro  | %                             |
| nagios        | xx.xx.xx.xx                 |
| haproxy_root  | xx.xx.xx.xx
| root          | 127.0.0.1                     |
| nagios        | localhost                     |
| root          | localhost                     |
+---------------+-------------------------------+

Gson - convert from Json to a typed ArrayList<T>

If you want convert from Json to a typed ArrayList , it's wrong to specify the type of the object contained in the list. The correct syntax is as follows:

 Gson gson = new Gson(); 
 List<MyClass> myList = gson.fromJson(inputString, ArrayList.class);

Is it possible to set a timeout for an SQL query on Microsoft SQL server?

As far as I know, apart from setting the command or connection timeouts in the client, there is no way to change timeouts on a query by query basis in the server.

You can indeed change the default 600 seconds using sp_configure, but these are server scoped.

javascript return true or return false when and how to use it?

Your code makes no sense, maybe because it's out of context.

If you mean code like this:

$('a').click(function () {
    callFunction();
    return false;
});

The return false will return false to the click-event. That tells the browser to stop following events, like follow a link. It has nothing to do with the previous function call. Javascript runs from top to bottom more or less, so a line cannot affect a previous line.

Converting integer to binary in python

Going Old School always works

def intoBinary(number):
binarynumber=""
if (number!=0):
    while (number>=1):
        if (number %2==0):
            binarynumber=binarynumber+"0"
            number=number/2
        else:
            binarynumber=binarynumber+"1"
            number=(number-1)/2

else:
    binarynumber="0"

return "".join(reversed(binarynumber))

Chrome refuses to execute an AJAX script due to wrong MIME type

if application is hosted on IIS, make sure Static Content is installed. Control Panel > Programs > Turn Windows features on or off > Internet Information Services > World Wide Web Services > Common HTTP Features > Static Content.

I faced this problem when trying to run an existing application on a new IIS 10.0 installation

How to get selected value of a dropdown menu in ReactJS

Implement your Dropdown as

<select id = "dropdown" ref = {(input)=> this.menu = input}>
    <option value="N/A">N/A</option>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
</select>

Now, to obtain the selected option value of the dropdown menu just use:

let res = this.menu.value;

Using Python Requests: Sessions, Cookies, and POST

I don't know how stubhub's api works, but generally it should look like this:

s = requests.Session()
data = {"login":"my_login", "password":"my_password"}
url = "http://example.net/login"
r = s.post(url, data=data)

Now your session contains cookies provided by login form. To access cookies of this session simply use

s.cookies

Any further actions like another requests will have this cookie

LaTeX Optional Arguments

I had a similar problem, when I wanted to create a command, \dx, to abbreviate \;\mathrm{d}x (i.e. put an extra space before the differential of the integral and have the "d" upright as well). But then I also wanted to make it flexible enough to include the variable of integration as an optional argument. I put the following code in the preamble.

\usepackage{ifthen}

\newcommand{\dx}[1][]{%
   \ifthenelse{ \equal{#1}{} }
      {\ensuremath{\;\mathrm{d}x}}
      {\ensuremath{\;\mathrm{d}#1}}
}

Then

\begin{document}
   $$\int x\dx$$
   $$\int t\dx[t]$$
\end{document}

gives \dx with optional argument

what innerHTML is doing in javascript?

The innerHTML fetches content depending on the id/name and replaces them.

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
 <title>Learn JavaScript</title>_x000D_
</head>_x000D_
<body>_x000D_
<button type = "button"_x000D_
onclick="document.getElementById('demo').innerHTML = Date()"> <!--fetches the content with id demo and changes the innerHTML content to Date()-->_x000D_
Click for date_x000D_
</button>_x000D_
<h3 id = 'demo'>Before Button is clicked this content will be Displayed the inner content of h3 tag with id demo and once you click the button this will be replaced by the Date() ,which prints the current date and time </h3> _x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

When you click the button,the content in h3 will be replaced by innerHTML assignent i.e Date() .

How to count lines of Java code using IntelliJ IDEA?

Although it is not an IntelliJ option, you could use a simple Bash command (if your operating system is Linux/Unix). Go to your source directory and type:

find . -type f -name '*.java' | xargs cat | wc -l

Basic CSS - how to overlay a DIV with semi-transparent DIV on top

.foo {
   position : relative;
}
.foo .wrapper {
    background-image : url('semi-trans.png');
    z-index : 10;
    position : absolute;
    top : 0;
    left : 0;
}

<div class="foo">
   <img src="example.png" />
   <div class="wrapper">&nbsp;</div>
</div>

How do I negate a test with regular expressions in a bash script?

I like to simplify the code without using conditional operators in such cases:

TEMP=/mnt/silo/bin
[[ ${PATH} =~ ${TEMP} ]] || PATH=$PATH:$TEMP

what is this value means 1.845E-07 in excel?

1.84E-07 is the exact value, represented using scientific notation, also known as exponential notation.

1.845E-07 is the same as 0.0000001845. Excel will display a number very close to 0 as 0, unless you modify the formatting of the cell to display more decimals.

C# however will get the actual value from the cell. The ToString method use the e-notation when converting small numbers to a string.

You can specify a format string if you don't want to use the e-notation.

MySQL "CREATE TABLE IF NOT EXISTS" -> Error 1050

I had a similar Problem as @CraigWalker on debian: My database was in a state where a DROP TABLE failed because it couldn't find the table, but a CREATE TABLE also failed because MySQL thought the table still existed. So the broken table still existed somewhere although it wasn't there when I looked in phpmyadmin.

I created this state by just copying the whole folder that contained a database with some MyISAM and some InnoDB tables

cp -a /var/lib/mysql/sometable /var/lib/mysql/test

(this is not recommended!)

All InnoDB tables where not visible in the new database test in phpmyadmin.

sudo mysqladmin flush-tables didn't help either.

My solution: I had to delete the new test database with drop database test and copy it with mysqldump instead:

mysqldump somedatabase -u username -p -r export.sql
mysql test -u username -p < export.sql

Byte[] to ASCII

Encoding.ASCII.GetString(buf);

How to capitalize the first letter in a String in Ruby

My version:

class String
    def upcase_first
        return self if empty?
        dup.tap {|s| s[0] = s[0].upcase }
    end
    def upcase_first!
        replace upcase_first
    end
end

['NASA title', 'MHz', 'sputnik'].map &:upcase_first  #=> ["NASA title", "MHz", "Sputnik"]

Check also:
https://www.rubydoc.info/gems/activesupport/5.0.0.1/String%3Aupcase_first
https://www.rubydoc.info/gems/activesupport/5.0.0.1/ActiveSupport/Inflector#upcase_first-instance_method

Get array elements from index to end

The [:-1] removes the last element. Instead of

a[3:-1]

write

a[3:]

You can read up on Python slicing notation here: Explain Python's slice notation

NumPy slicing is an extension of that. The NumPy tutorial has some coverage: Indexing, Slicing and Iterating.

How to capture multiple repeated groups?

The key distinction is repeating a captured group instead of capturing a repeated group.

As you have already found out, the difference is that repeating a captured group captures only the last iteration. Capturing a repeated group captures all iterations.

In PCRE (PHP):

((?:\w+)+),?
Match 1, Group 1.    0-5      HELLO
Match 2, Group 1.    6-11     THERE
Match 3, Group 1.    12-20    BRUTALLY
Match 4, Group 1.    21-26    CRUEL
Match 5, Group 1.    27-32    WORLD

Since all captures are in Group 1, you only need $1 for substitution.

I used the following general form of this regular expression:

((?:{{RE}})+)

Example at regex101

Why can't I initialize non-const static member or static array in class?

Why I can't initialize static data members in class?

The C++ standard allows only static constant integral or enumeration types to be initialized inside the class. This is the reason a is allowed to be initialized while others are not.

Reference:
C++03 9.4.2 Static data members
§4

If a static data member is of const integral or const enumeration type, its declaration in the class definition can specify a constant-initializer which shall be an integral constant expression (5.19). In that case, the member can appear in integral constant expressions. The member shall still be defined in a namespace scope if it is used in the program and the namespace scope definition shall not contain an initializer.

What are integral types?

C++03 3.9.1 Fundamental types
§7

Types bool, char, wchar_t, and the signed and unsigned integer types are collectively called integral types.43) A synonym for integral type is integer type.

Footnote:

43) Therefore, enumerations (7.2) are not integral; however, enumerations can be promoted to int, unsigned int, long, or unsigned long, as specified in 4.5.

Workaround:

You could use the enum trick to initialize an array inside your class definition.

class A 
{
    static const int a = 3;
    enum { arrsize = 2 };

    static const int c[arrsize] = { 1, 2 };

};

Why does the Standard does not allow this?

Bjarne explains this aptly here:

A class is typically declared in a header file and a header file is typically included into many translation units. However, to avoid complicated linker rules, C++ requires that every object has a unique definition. That rule would be broken if C++ allowed in-class definition of entities that needed to be stored in memory as objects.

Why are only static const integral types & enums allowed In-class Initialization?

The answer is hidden in Bjarne's quote read it closely,
"C++ requires that every object has a unique definition. That rule would be broken if C++ allowed in-class definition of entities that needed to be stored in memory as objects."

Note that only static const integers can be treated as compile time constants. The compiler knows that the integer value will not change anytime and hence it can apply its own magic and apply optimizations, the compiler simply inlines such class members i.e, they are not stored in memory anymore, As the need of being stored in memory is removed, it gives such variables the exception to rule mentioned by Bjarne.

It is noteworthy to note here that even if static const integral values can have In-Class Initialization, taking address of such variables is not allowed. One can take the address of a static member if (and only if) it has an out-of-class definition.This further validates the reasoning above.

enums are allowed this because values of an enumerated type can be used where ints are expected.see citation above


How does this change in C++11?

C++11 relaxes the restriction to certain extent.

C++11 9.4.2 Static data members
§3

If a static data member is of const literal type, its declaration in the class definition can specify a brace-or-equal-initializer in which every initializer-clause that is an assignment-expression is a constant expression. A static data member of literal type can be declared in the class definition with the constexpr specifier; if so, its declaration shall specify a brace-or-equal-initializer in which every initializer-clause that is an assignment-expression is a constant expression. [ Note: In both these cases, the member may appear in constant expressions. —end note ] The member shall still be defined in a namespace scope if it is used in the program and the namespace scope definition shall not contain an initializer.

Also, C++11 will allow(§12.6.2.8) a non-static data member to be initialized where it is declared(in its class). This will mean much easy user semantics.

Note that these features have not yet been implemented in latest gcc 4.7, So you might still get compilation errors.

Git error when trying to push -- pre-receive hook declined

I'd bet that you are trying a non-fast-forward push and the hook blocks it. If that's the case, simply run git pull --rebase before pushing to rebase your local changes on the newest codebase.

How do a send an HTTPS request through a proxy in Java?

Try the Apache Commons HttpClient library instead of trying to roll your own: http://hc.apache.org/httpclient-3.x/index.html

From their sample code:

  HttpClient httpclient = new HttpClient();
  httpclient.getHostConfiguration().setProxy("myproxyhost", 8080);

  /* Optional if authentication is required.
  httpclient.getState().setProxyCredentials("my-proxy-realm", " myproxyhost",
   new UsernamePasswordCredentials("my-proxy-username", "my-proxy-password"));
  */

  PostMethod post = new PostMethod("https://someurl");
  NameValuePair[] data = {
     new NameValuePair("user", "joe"),
     new NameValuePair("password", "bloggs")
  };
  post.setRequestBody(data);
  // execute method and handle any error responses.
  // ...
  InputStream in = post.getResponseBodyAsStream();
  // handle response.


  /* Example for a GET reqeust
  GetMethod httpget = new GetMethod("https://someurl");
  try { 
    httpclient.executeMethod(httpget);
    System.out.println(httpget.getStatusLine());
  } finally {
    httpget.releaseConnection();
  }
  */

MongoDB vs. Cassandra

Why choose between a traditional database and a NoSQL data store? Use both! The problem with NoSQL solutions (beyond the initial learning curve) is the lack of transactions -- you do all updates to MySQL and have MySQL populate a NoSQL data store for reads -- you then benefit from each technology's strengths. This does add more complexity, but you already have the MySQL side -- just add MongoDB, Cassandra, etc to the mix.

NoSQL datastores generally scale way better than a traditional DB for the same otherwise specs -- there is a reason why Facebook, Twitter, Google, and most start-ups are using NoSQL solutions. It's not just geeks getting high on new tech.

Remove all line breaks from a long string of text

The canonic answer, in Python, would be :

s = ''.join(s.splitlines())

It splits the string into lines (letting Python doing it according to its own best practices). Then you merge it. Two possibilities here:

  • replace the newline by a whitespace (' '.join())
  • or without a whitespace (''.join())

Remove spaces from a string in VB.NET

This will remove spaces only, matches the SQL functionality of rtrim(ltrim(myString))

Dim charstotrim() As Char = {" "c}
myString = myString .Trim(charstotrim) 

Convert HTML Character Back to Text Using Java Standard Library

I think the Apache Commons Lang library's StringEscapeUtils.unescapeHtml3() and unescapeHtml4() methods are what you are looking for. See https://commons.apache.org/proper/commons-text/javadocs/api-release/org/apache/commons/text/StringEscapeUtils.html.

Set an environment variable in git bash

Creating a .bashrc file in your home directory also works. That way you don't have to copy your .bash_profile every time you install a new version of git bash.

How to use the toString method in Java?

the toString() converts the specified object to a string value.

How to get week numbers from dates?

If you want to get the week number with the year, Grant Shannon's solution using strftime works, but you need to make some corrections for the dates around january 1st. For instance, 2016-01-03 (yyyy-mm-dd) is week 53 of year 2015, not 2016. And 2018-12-31 is week 1 of 2019, not of 2018. This codes provides some examples and a solution. In column "yearweek" the years are sometimes wrong, in "yearweek2" they are corrected (rows 2 and 5).

library(dplyr)
library(lubridate)

# create a testset
test <- data.frame(matrix(data = c("2015-12-31",
                                   "2016-01-03",
                                   "2016-01-04",
                                   "2018-12-30",
                                   "2018-12-31",
                                   "2019-01-01") , ncol=1, nrow = 6 ))
# add a colname
colnames(test) <- "date_txt"

# this codes provides correct year-week numbers
test <- test %>%
        mutate(date = as.Date(date_txt, format = "%Y-%m-%d")) %>%
        mutate(yearweek = as.integer(strftime(date, format = "%Y%V"))) %>%
        mutate(yearweek2 = ifelse(test = day(date) > 7 & substr(yearweek, 5, 6) == '01',
                                 yes  = yearweek + 100,
                                 no   = ifelse(test = month(date) == 1 & as.integer(substr(yearweek, 5, 6)) > 51,
                                               yes  = yearweek - 100,
                                               no   = yearweek)))
# print the result
print(test)

    date_txt       date yearweek yearweek2
1 2015-12-31 2015-12-31   201553    201553
2 2016-01-03 2016-01-03   201653    201553
3 2016-01-04 2016-01-04   201601    201601
4 2018-12-30 2018-12-30   201852    201852
5 2018-12-31 2018-12-31   201801    201901
6 2019-01-01 2019-01-01   201901    201901

What is the 'pythonic' equivalent to the 'fold' function from functional programming?

I may be quite late to the party, but we can create custom foldr using simple lambda calculus and curried function. Here is my implementation of foldr in python.

def foldr(func):
    def accumulator(acc):
        def listFunc(l):
            if l:
                x = l[0]
                xs = l[1:]
                return func(x)(foldr(func)(acc)(xs))
            else:
                return acc
        return listFunc
    return accumulator  


def curried_add(x):
    def inner(y):
        return x + y
    return inner

def curried_mult(x):
    def inner(y):
        return x * y
    return inner

print foldr(curried_add)(0)(range(1, 6))
print foldr(curried_mult)(1)(range(1, 6))

Even though the implementation is recursive (might be slow), it will print the values 15 and 120 respectively

Shrink to fit content in flexbox, or flex-basis: content workaround?

I want columns One and Two to shrink/grow to fit rather than being fixed.

Have you tried: flex-basis: auto

or this:

flex: 1 1 auto, which is short for:

  • flex-grow: 1 (grow proportionally)
  • flex-shrink: 1 (shrink proportionally)
  • flex-basis: auto (initial size based on content size)

or this:

main > section:first-child {
    flex: 1 1 auto;
    overflow-y: auto;
}

main > section:nth-child(2) {
    flex: 1 1 auto;
    overflow-y: auto;
}

main > section:last-child {
    flex: 20 1 auto;
    display: flex;
    flex-direction: column;  
}

revised demo

Related:

Remove pandas rows with duplicate indices

Oh my. This is actually so simple!

grouped = df3.groupby(level=0)
df4 = grouped.last()
df4
                      A   B  rownum

2001-01-01 00:00:00   0   0       6
2001-01-01 01:00:00   1   1       7
2001-01-01 02:00:00   2   2       8
2001-01-01 03:00:00   3   3       3
2001-01-01 04:00:00   4   4       4
2001-01-01 05:00:00   5   5       5

Follow up edit 2013-10-29 In the case where I have a fairly complex MultiIndex, I think I prefer the groupby approach. Here's simple example for posterity:

import numpy as np
import pandas

# fake index
idx = pandas.MultiIndex.from_tuples([('a', letter) for letter in list('abcde')])

# random data + naming the index levels
df1 = pandas.DataFrame(np.random.normal(size=(5,2)), index=idx, columns=['colA', 'colB'])
df1.index.names = ['iA', 'iB']

# artificially append some duplicate data
df1 = df1.append(df1.select(lambda idx: idx[1] in ['c', 'e']))
df1
#           colA      colB
#iA iB                    
#a  a  -1.297535  0.691787
#   b  -1.688411  0.404430
#   c   0.275806 -0.078871
#   d  -0.509815 -0.220326
#   e  -0.066680  0.607233
#   c   0.275806 -0.078871  # <--- dup 1
#   e  -0.066680  0.607233  # <--- dup 2

and here's the important part

# group the data, using df1.index.names tells pandas to look at the entire index
groups = df1.groupby(level=df1.index.names)  
groups.last() # or .first()
#           colA      colB
#iA iB                    
#a  a  -1.297535  0.691787
#   b  -1.688411  0.404430
#   c   0.275806 -0.078871
#   d  -0.509815 -0.220326
#   e  -0.066680  0.607233

Insert using LEFT JOIN and INNER JOIN

you can't use VALUES clause when inserting data using another SELECT query. see INSERT SYNTAX

INSERT INTO user
(
 id, name, username, email, opted_in
)
(
    SELECT id, name, username, email, opted_in
    FROM user
         LEFT JOIN user_permission AS userPerm
            ON user.id = userPerm.user_id
);

What is the difference between C++ and Visual C++?

C++ is a general-purpose programming language. It is regarded as a middle-level language, as it comprises a combination of both high-level and low-level language features. It was developed by Bjarne Stroustrup starting in 1979 at Bell Labs as an enhancement to the C programming language and originally named "C with Classes". It was renamed to C++ in 1983.

C++ is widely used in the software industry. Some of its application domains include systems software, application software, device drivers, embedded software, high-performance server and client applications, and entertainment software such as video games. Several groups provide both free and proprietary C++ compiler software, including the GNU Project, Microsoft, Intel, Borland and others.


Microsoft Visual C++ (often abbreviated as MSVC or VC++) is an integrated development environment (IDE) product from Microsoft for the C, C++, and C++/CLI programming languages. MSVC is proprietary software; it was originally a standalone product but later became a part of Visual Studio and made available in both trialware and freeware forms. It features tools for developing and debugging C++ code, especially code written for Windows API, DirectX and .NET Framework.


So the main difference between them is that they are different things. The former is a programming language, while the latter is a commercial integrated development environment (IDE).

Get source JARs from Maven repository

Configuring and running the maven-eclipse plugin, (for example from the command line mvn eclipse:eclipse )

   <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-eclipse-plugin</artifactId>
                <configuration>
                    <downloadSources>true</downloadSources>
                    <downloadJavadocs>true</downloadJavadocs>
                </configuration>
            </plugin>
        </plugins>
    </build>

Git Remote: Error: fatal: protocol error: bad line length character: Unab

Maybe you have a statement in the server's .bashrc that produces output. I, for example had this:

[[ -s "$HOME/.rvm/scripts/rvm" ]] && source "$HOME/.rvm/scripts/rvm"
rvm use ruby-1.9.3-p194@rails32

In this case the output from the rvm use will be (wrongly) interpreted as coming from git. So replace it by:

rvm use ruby-1.9.3-p194@rails32 > /dev/null

Laravel 5.4 ‘cross-env’ Is Not Recognized as an Internal or External Command

Simply try running npm install / yarn etc first before running npm start / yarn start as @only4 mentioned, if you see this problem, as it means your .env is not in sync with your package.json, i.e. you installed a package but not quite configured it or other way around

How to resolve javax.mail.AuthenticationFailedException issue?

When you are trying to sign in to your Google Account from your new device or application you have to unlock the CAPTCHA. To unlock the CAPTCHA go to https://www.google.com/accounts/DisplayUnlockCaptcha and then enter image description here

And also make sure to allow less secure apps on enter image description here

How to delete mysql database through shell command

If you are tired of typing your password, create a (chmod 600) file ~/.my.cnf, and put in it:

[client]
user = "you"
password = "your-password"

For the sake of conversation:

echo 'DROP DATABASE foo;' | mysql

How to upload files in asp.net core?

You can add a new property of type IFormFile to your view model

public class CreatePost
{
   public string ImageCaption { set;get; }
   public string ImageDescription { set;get; }
   public IFormFile MyImage { set; get; }
}

and in your GET action method, we will create an object of this view model and send to the view.

public IActionResult Create()
{
   return View(new CreatePost());
}

Now in your Create view which is strongly typed to our view model, have a form tag which has the enctype attribute set to "multipart/form-data"

@model CreatePost
<form asp-action="Create" enctype="multipart/form-data">   

    <input asp-for="ImageCaption"/>
    <input asp-for="ImageDescription"/>
    <input asp-for="MyImage"/>

    <input type="submit"/>
</form>

And your HttpPost action to handle the form posting

[HttpPost]
public IActionResult Create(CreatePost model)
{
   var img = model.MyImage;
   var imgCaption = model.ImageCaption;

   //Getting file meta data
   var fileName = Path.GetFileName(model.MyImage.FileName);
   var contentType = model.MyImage.ContentType;

   // do something with the above data
   // to do : return something
}

If you want to upload the file to some directory in your app, you should use IHostingEnvironment to get the webroot path. Here is a working sample.

public class HomeController : Controller
{
    private readonly IHostingEnvironment hostingEnvironment;
    public HomeController(IHostingEnvironment environment)
    {
        hostingEnvironment = environment;
    }
    [HttpPost]
    public IActionResult Create(CreatePost model)
    {
        // do other validations on your model as needed
        if (model.MyImage != null)
        {
            var uniqueFileName = GetUniqueFileName(model.MyImage.FileName);
            var uploads = Path.Combine(hostingEnvironment.WebRootPath, "uploads");
            var filePath = Path.Combine(uploads,uniqueFileName);
            model.MyImage.CopyTo(new FileStream(filePath, FileMode.Create)); 

            //to do : Save uniqueFileName  to your db table   
        }
        // to do  : Return something
        return RedirectToAction("Index","Home");
    }
    private string GetUniqueFileName(string fileName)
    {
        fileName = Path.GetFileName(fileName);
        return  Path.GetFileNameWithoutExtension(fileName)
                  + "_" 
                  + Guid.NewGuid().ToString().Substring(0, 4) 
                  + Path.GetExtension(fileName);
    }
}

This will save the file to uploads folder inside wwwwroot directory of your app with a random file name generated using Guids ( to prevent overwriting of files with same name)

Here we are using a very simple GetUniqueName method which will add 4 chars from a guid to the end of the file name to make it somewhat unique. You can update the method to make it more sophisticated as needed.

Should you be storing the full url to the uploaded image in the database ?

No. Do not store the full url to the image in the database. What if tomorrow your business decides to change your company/product name from www.thefacebook.com to www.facebook.com ? Now you have to fix all the urls in the table!

What should you store ?

You should store the unique filename which you generated above(the uniqueFileName varibale we used above) to store the file name. When you want to display the image back, you can use this value (the filename) and build the url to the image.

For example, you can do this in your view.

@{
    var imgFileName = "cats_46df.png";
}
<img src="~/uploads/@imgFileName"  alt="my img"/>

I just hardcoded an image name to imgFileName variable and used that. But you may read the stored file name from your database and set to your view model property and use that. Something like

<img src="~/uploads/@Model.FileName"  alt="my img"/>

Storing the image to table

If you want to save the file as bytearray/varbinary to your database, you may convert the IFormFile object to byte array like this

private byte[] GetByteArrayFromImage(IFormFile file)
{
    using (var target = new MemoryStream())
    {
        file.CopyTo(target);
        return target.ToArray();
    }
}

Now in your http post action method, you can call this method to generate the byte array from IFormFile and use that to save to your table. the below example is trying to save a Post entity object using entity framework.

[HttpPost]
public IActionResult Create(CreatePost model)
{
    //Create an object of your entity class and map property values
    var post=new Post() { ImageCaption = model.ImageCaption };

    if (model.MyImage != null)
    {
       post.Image =  GetByteArrayFromImage(model.MyImage);
    }
    _context.Posts.Add(post);
    _context.SaveChanges();
    return RedirectToAction("Index","Home");
}

How to execute AngularJS controller function on page load?

You can use angular's $window object:

$window.onload = function(e) {
  //your magic here
}

Get epoch for a specific date using Javascript

Some answers does not explain the side effects of variations in the timezone for JavaScript Date object. So you should consider this answer if this is a concern for you.

Method 1: Machine's timezone dependent

By default, JavaScript returns a Date considering the machine's timezone, so getTime() result varies from computer to computer. You can check this behavior running:

new Date(1970, 0, 1, 0, 0, 0, 0).getTime()
    // Since 1970-01-01 is Epoch, you may expect ZERO
    // but in fact the result varies based on computer's timezone

This is not a problem if you really want the time since Epoch considering your timezone. So if you want to get time since Epoch for the current Date or even a specified Date based on the computer's timezone, you're free to continue using this method.

// Seconds since Epoch (Unix timestamp format)

new Date().getTime() / 1000             // local Date/Time since Epoch in seconds
new Date(2020, 11, 1).getTime() / 1000  // time since Epoch to 2020-12-01 00:00 (local timezone) in seconds

// Milliseconds since Epoch (used by some systems, eg. JavaScript itself)

new Date().getTime()                    // local Date/Time since Epoch in milliseconds
new Date(2020,  0, 2).getTime()         // time since Epoch to 2020-01-02 00:00 (local timezone) in milliseconds

// **Warning**: notice that MONTHS in JavaScript Dates starts in zero (0 = January, 11 = December)

Method 2: Machine's timezone independent

However, if you want to get ride of variations in timezone and get time since Epoch for a specified Date in UTC (that is, timezone independent), you need to use Date.UTC method or shift the date from your timezone to UTC:

Date.UTC(1970,  0, 1)
    // should be ZERO in any computer, since it is ZERO the difference from Epoch

    // Alternatively (if, for some reason, you do not want Date.UTC)
    const timezone_diff = new Date(1970, 0, 1).getTime()  // difference in milliseconds between your timezone and UTC
    (new Date(1970,  0, 1).getTime() - timezone_diff)
    // should be ZERO in any computer, since it is ZERO the difference from Epoch

So, using this method (or, alternatively, subtracting the difference), the result should be:

// Seconds since Epoch (Unix timestamp format)

Date.UTC(2020,  0, 1) / 1000  // time since Epoch to 2020-01-01 00:00 UTC in seconds

    // Alternatively (if, for some reason, you do not want Date.UTC)
    const timezone_diff = new Date(1970, 0, 1).getTime()
    (new Date(2020,  0, 1).getTime() - timezone_diff) / 1000  // time since Epoch to 2020-01-01 00:00 UTC in seconds
    (new Date(2020, 11, 1).getTime() - timezone_diff) / 1000  // time since Epoch to 2020-12-01 00:00 UTC in seconds

// Milliseconds since Epoch (used by some systems, eg. JavaScript itself)

Date.UTC(2020,  0, 2)   // time since Epoch to 2020-01-02 00:00 UTC in milliseconds

    // Alternatively (if, for some reason, you do not want Date.UTC)
    const timezone_diff = new Date(1970, 0, 1).getTime()
    (new Date(2020,  0, 2).getTime() - timezone_diff)         // time since Epoch to 2020-01-02 00:00 UTC in milliseconds

// **Warning**: notice that MONTHS in JavaScript Dates starts in zero (0 = January, 11 = December)

IMO, unless you know what you're doing (see note above), you should prefer Method 2, since it is machine independent.


End note

Although the recomendations in this answer, and since Date.UTC does not work without a specified date/time, you may be inclined in using the alternative approach and doing something like this:

const timezone_diff = new Date(1970, 0, 1).getTime()
(new Date().getTime() - timezone_diff)  // <-- !!! new Date() without arguments
    // means "local Date/Time subtracted by timezone since Epoch" (?)

This does not make any sense and it is probably WRONG (you are modifying the date). Be aware of not doing this. If you want to get time since Epoch from the current date AND TIME, you are most probably OK using Method 1.

How to Git stash pop specific stash in 1.8.3?

You need to escape the braces:

git stash pop stash@\{1\}

IntelliJ Organize Imports

ALT+ENTER was far from eclipse habit ,in IDEA for me mouse over did not work , so in setting>IDESetting>Keymap>Show intention actions and quick-fixes I changed it to mouse left click , It did not support mouse over! but mouse left click was OK and closest to my intention.

How to do a Postgresql subquery in select clause with join in from clause like SQL Server?

I'm not sure I understand your intent perfectly, but perhaps the following would be close to what you want:

select n1.name, n1.author_id, count_1, total_count
  from (select id, name, author_id, count(1) as count_1
          from names
          group by id, name, author_id) n1
inner join (select id, author_id, count(1) as total_count
              from names
              group by id, author_id) n2
  on (n2.id = n1.id and n2.author_id = n1.author_id)

Unfortunately this adds the requirement of grouping the first subquery by id as well as name and author_id, which I don't think was wanted. I'm not sure how to work around that, though, as you need to have id available to join in the second subquery. Perhaps someone else will come up with a better solution.

Share and enjoy.

CentOS 64 bit bad ELF interpreter

sudo yum install fontconfig freetype libfreetype.so.6 libfontconfig.so.1 libstdc++.so.6

How can I convert String to Int?

int i = Convert.ToInt32(TextBoxD1.Text);

How to run batch file from network share without "UNC path are not supported" message?

There's a registry setting to avoid this security check (use it at your own risks, though):

Under the registry path

   HKEY_CURRENT_USER
     \Software
       \Microsoft
         \Command Processor

add the value DisableUNCCheck REG_DWORD and set the value to 0 x 1 (Hex).

Note: On Windows 10 version 1803, the setting seems to be located under HKLM: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Command Processor

how to automatically scroll down a html page?

here is the example using Pure JavaScript

_x000D_
_x000D_
function scrollpage() {  _x000D_
 function f() _x000D_
 {_x000D_
  window.scrollTo(0,i);_x000D_
  if(status==0) {_x000D_
      i=i+40;_x000D_
   if(i>=Height){ status=1; } _x000D_
  } else {_x000D_
   i=i-40;_x000D_
   if(i<=1){ status=0; }  // if you don't want continue scroll then remove this line_x000D_
  }_x000D_
 setTimeout( f, 0.01 );_x000D_
 }f();_x000D_
}_x000D_
var Height=document.documentElement.scrollHeight;_x000D_
var i=1,j=Height,status=0;_x000D_
scrollpage();_x000D_
</script>
_x000D_
<style type="text/css">_x000D_
_x000D_
 #top { border: 1px solid black;  height: 20000px; }_x000D_
 #bottom { border: 1px solid red; }_x000D_
_x000D_
</style>
_x000D_
<div id="top">top</div>_x000D_
<div id="bottom">bottom</div>
_x000D_
_x000D_
_x000D_

How to determine if .NET Core is installed

Run this command

dotnet --list-sdks

enter image description here

How to delete history of last 10 commands in shell?

Have you tried editing the history file directly:

~/.bash_history

How can VBA connect to MySQL database in Excel?

Ranjit's code caused the same error message as reported by Tin, but worked after updating Cn.open with the ODBC driver I'm running. Check the Drivers tab in the ODBC Data Source Administrator. Mine said "MySQL ODBC 5.3 Unicode Driver" so I updated accordingly.

update package.json version automatically

To give a more up-to-date approach.

package.json

  "scripts": {
    "eslint": "eslint index.js",
    "pretest": "npm install",
    "test": "npm run eslint",
    "preversion": "npm run test",
    "version": "",
    "postversion": "git push && git push --tags && npm publish"
  }

Then you run it:

npm version minor --force -m "Some message to commit"

Which will:

  1. ... run tests ...

  2. change your package.json to a next minor version (e.g: 1.8.1 to 1.9.0)

  3. push your changes

  4. create a new git tag release and

  5. publish your npm package.

--force is to show who is the boss! Jokes aside see https://github.com/npm/npm/issues/8620

Clear icon inside input text

If you want it like Google, then you should know that the "X" isn't actually inside the <input> -- they're next to each other with the outer container styled to appear like the text box.

HTML:

<form>
    <span class="x-input">
        <input type="text" class="x-input-text" />
        <input type="reset" />
    </span>
</form>

CSS:

.x-input {
    border: 1px solid #ccc;
}

.x-input input.x-input-text {
    border: 0;
    outline: 0;
}

Example: http://jsfiddle.net/VTvNX/

How to set app icon for Electron / Atom Shell App

Below is the solution that i have :

mainWindow = new BrowserWindow({width: 800, height: 600,icon: __dirname + '/Bluetooth.ico'});

Add line break to ::after or ::before pseudo-element content

The content property states:

Authors may include newlines in the generated content by writing the "\A" escape sequence in one of the strings after the 'content' property. This inserted line break is still subject to the 'white-space' property. See "Strings" and "Characters and case" for more information on the "\A" escape sequence.

So you can use:

#headerAgentInfoDetailsPhone:after {
  content:"Office: XXXXX \A Mobile: YYYYY ";
  white-space: pre; /* or pre-wrap */
}

http://jsfiddle.net/XkNxs/

When escaping arbitrary strings, however, it's advisable to use \00000a instead of \A, because any number or [a-f] character followed by the new line may give unpredictable results:

function addTextToStyle(id, text) {
  return `#${id}::after { content: "${text.replace(/"/g, '\\"').replace(/\n/g, '\\00000a')} }"`;
}

android set button background programmatically

Old thread, but learned something new, hope this might help someone.

If you want to change the background color but retain other styles, then below might help.

button.getBackground().setColorFilter(ContextCompat.getColor(this, R.color.colorAccent), PorterDuff.Mode.MULTIPLY);

Automatically deleting related rows in Laravel (Eloquent ORM)

There are 3 approaches to solving this:

1. Using Eloquent Events On Model Boot (ref: https://laravel.com/docs/5.7/eloquent#events)

class User extends Eloquent
{
    public static function boot() {
        parent::boot();

        static::deleting(function($user) {
             $user->photos()->delete();
        });
    }
}

2. Using Eloquent Event Observers (ref: https://laravel.com/docs/5.7/eloquent#observers)

In your AppServiceProvider, register the observer like so:

public function boot()
{
    User::observe(UserObserver::class);
}

Next, add an Observer class like so:

class UserObserver
{
    public function deleting(User $user)
    {
         $user->photos()->delete();
    }
}

3. Using Foreign Key Constraints (ref: https://laravel.com/docs/5.7/migrations#foreign-key-constraints)

$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');

Node.js Best Practice Exception Handling

Catching errors has been very well discussed here, but it's worth remembering to log the errors out somewhere so you can view them and fix stuff up.

?Bunyan is a popular logging framework for NodeJS - it supporst writing out to a bunch of different output places which makes it useful for local debugging, as long as you avoid console.log. ? In your domain's error handler you could spit the error out to a log file.

var log = bunyan.createLogger({
  name: 'myapp',
  streams: [
    {
      level: 'error',
      path: '/var/tmp/myapp-error.log'  // log ERROR to this file
    }
  ]
});

This can get time consuming if you have lots of errors and/or servers to check, so it could be worth looking into a tool like Raygun (disclaimer, I work at Raygun) to group errors together - or use them both together. ? If you decided to use Raygun as a tool, it's pretty easy to setup too

var raygunClient = new raygun.Client().init({ apiKey: 'your API key' });
raygunClient.send(theError);

? Crossed with using a tool like PM2 or forever, your app should be able to crash, log out what happened and reboot without any major issues.

How to use goto statement correctly

Java does not support goto, it is reserved as a keyword in case they wanted to add it to a later version

how do I get the bullet points of a <ul> to center with the text?

Add list-style-position: inside to the ul element. (example)

The default value for the list-style-position property is outside.

_x000D_
_x000D_
ul {_x000D_
    text-align: center;_x000D_
    list-style-position: inside;_x000D_
}
_x000D_
<ul>_x000D_
    <li>one</li>_x000D_
    <li>two</li>_x000D_
    <li>three</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

Another option (which yields slightly different results) would be to center the entire ul element:

_x000D_
_x000D_
.parent {_x000D_
  text-align: center;_x000D_
}_x000D_
.parent > ul {_x000D_
  display: inline-block;_x000D_
}
_x000D_
<div class="parent">_x000D_
  <ul>_x000D_
    <li>one</li>_x000D_
    <li>two</li>_x000D_
    <li>three</li>_x000D_
  </ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Using form input to access camera and immediately upload photos using web app

It's really easy to do this, simply send the file via an XHR request inside of the file input's onchange handler.

<input id="myFileInput" type="file" accept="image/*;capture=camera">

var myInput = document.getElementById('myFileInput');

function sendPic() {
    var file = myInput.files[0];

    // Send file here either by adding it to a `FormData` object 
    // and sending that via XHR, or by simply passing the file into 
    // the `send` method of an XHR instance.
}

myInput.addEventListener('change', sendPic, false);

SQL Server: Make all UPPER case to Proper Case/Title Case

On Server Server 2016 and newer, you can use STRING_SPLIT


with t as (
    select 'GOOFYEAR Tire and Rubber Company' as n
    union all
    select 'THE HAPPY BEAR' as n
    union all
    select 'MONK HOUSE SALES' as n
    union all
    select 'FORUM COMMUNICATIONS' as n
)
select
    n,
    (
        select ' ' + (
            upper(left(value, 1))
            + lower(substring(value, 2, 999))
        )
        from (
            select value
            from string_split(t.n, ' ')
        ) as sq
        for xml path ('')
    ) as title_cased
from t

Example

Using $_POST to get select option value from HTML

You can do it like this, too:

<?php
if(isset($_POST['select1'])){
    $select1 = $_POST['select1'];
    switch ($select1) {
        case 'value1':
            echo 'this is value1<br/>';
            break;
        case 'value2':
            echo 'value2<br/>';
            break;
        default:
            # code...
            break;
    }
}
?>


<form action="" method="post">
    <select name="select1">
        <option value="value1">Value 1</option>
        <option value="value2">Value 2</option>
    </select>
    <input type="submit" name="submit" value="Go"/>
</form>

Escaping ampersand character in SQL string

set escape on
... node_name = 'Geometric Vectors \& Matrices' ...

or alternatively:

set define off
... node_name = 'Geometric Vectors & Matrices' ...

The first allows you to use the backslash to escape the &.

The second turns off & "globally" (no need to add a backslash anywhere). You can turn it on again by set define on and from that line on the ampersands will get their special meaning back, so you can turn it off for some parts of the script and not for others.

How to create large PDF files (10MB, 50MB, 100MB, 200MB, 500MB, 1GB, etc.) for testing purposes?

I had problems using pdftk with the cat parameter had a better success with output.

The following command worked for me:

pdftk file_1.pdf file_1.pdf file_1.pdf file_1.pdf cat output.pdf

Using cat produced the following error:

Error: Unexpected text in page range end, here: 
    output.pdf
    Exiting.
    Acceptable keywords, for example: "even" or "odd".
    To rotate pages, use: "north" "south" "east"
        "west" "left" "right" or "down"
Errors encountered.  No output created.
Done.  Input errors, so no output created.

http://www.pdflabs.com/docs/pdftk-cli-examples/.

I created a 172mb PDF is no time at all.

Is there any way to do HTTP PUT in python

You should have a look at the httplib module. It should let you make whatever sort of HTTP request you want.

reactjs - how to set inline style of backgroundcolor?

If you want more than one style this is the correct full answer. This is div with class and style:

<div className="class-example" style={{width: '300px', height: '150px'}}></div>

Using Node.JS, how do I read a JSON file into (server) memory?

function parseIt(){
    return new Promise(function(res){
        try{
            var fs = require('fs');
            const dirPath = 'K:\\merge-xml-junit\\xml-results\\master.json';
            fs.readFile(dirPath,'utf8',function(err,data){
                if(err) throw err;
                res(data);
        })}
        catch(err){
            res(err);
        }
    });
}

async function test(){
    jsonData = await parseIt();
    var parsedJSON = JSON.parse(jsonData);
    var testSuite = parsedJSON['testsuites']['testsuite'];
    console.log(testSuite);
}

test();

MongoDB/Mongoose querying at a specific date?

That should work if the dates you saved in the DB are without time (just year, month, day).

Chances are that the dates you saved were new Date(), which includes the time components. To query those times you need to create a date range that includes all moments in a day.

db.posts.find({ //query today up to tonight
    created_on: {
        $gte: new Date(2012, 7, 14), 
        $lt: new Date(2012, 7, 15)
    }
})

Android WebView style background-color:transparent ignored on android 2.2

This is how you do it:

First make your project base on 11, but in AndroidManifest set minSdkVersion to 8

android:hardwareAccelerated="false" is unnecessary, and it's incompatible with 8

wv.setBackgroundColor(0x00000000);
if (Build.VERSION.SDK_INT >= 11) wv.setLayerType(WebView.LAYER_TYPE_SOFTWARE, null);

this.wv.setWebViewClient(new WebViewClient()
{
    @Override
    public void onPageFinished(WebView view, String url)
    {
        wv.setBackgroundColor(0x00000000);
        if (Build.VERSION.SDK_INT >= 11) wv.setLayerType(WebView.LAYER_TYPE_SOFTWARE, null);
    }
});

For safety put this in your style:

BODY, HTML {background: transparent}

worked for me on 2.2 and 4

C-like structures in Python

If you don't have a 3.7 for @dataclass and need mutability, the following code might work for you. It's quite self-documenting and IDE-friendly (auto-complete), prevents writing things twice, is easily extendable and it is very simple to test that all instance variables are completely initialized:

class Params():
    def __init__(self):
        self.var1 : int = None
        self.var2 : str = None

    def are_all_defined(self):
        for key, value in self.__dict__.items():
            assert (value is not None), "instance variable {} is still None".format(key)
        return True


params = Params()
params.var1 = 2
params.var2 = 'hello'
assert(params.are_all_defined)

Updating PartialView mvc 4

Controller :

public ActionResult Refresh(string ID)
    {
        DetailsViewModel vm = new DetailsViewModel();  // Model
        vm.productDetails = _product.GetproductDetails(ID); 
        /* "productDetails " is a property in "DetailsViewModel"
        "GetProductDetails" is a method in "Product" class
        "_product" is an interface of "Product" class */

        return PartialView("_Details", vm); // Details is a partial view
    }

In yore index page you should to have refresh link :

     <a href="#" id="refreshItem">Refresh</a>

This Script should be also in your index page:

<script type="text/javascript">

    $(function () {
    $('a[id=refreshItem]:last').click(function (e) {
        e.preventDefault();

        var url = MVC.Url.action('Refresh', 'MyController', { itemId: '@(Model.itemProp.itemId )' }); // Refresh is an Action in controller, MyController is a controller name

        $.ajax({
            type: 'GET',
            url: url,
            cache: false,
            success: function (grid) {
                $('#tabItemDetails').html(grid);
                clientBehaviors.applyPlugins($("#tabProductDetails")); // "tabProductDetails" is an id of div in your "Details partial view"
            }
        });
    });
});

Command line .cmd/.bat script, how to get directory of running script

for /F "eol= delims=~" %%d in ('CD') do set curdir=%%d

pushd %curdir%

Source

MySQL high CPU usage

If this server is visible to the outside world, It's worth checking if it's having lots of requests to connect from the outside world (i.e. people trying to break into it)

DataGridView AutoFit and Fill

Try doing,

 AutoSizeColumnMode = Fill;

PHP Parse error: syntax error, unexpected T_PUBLIC

You can remove public keyword from your functions, because, you have to define a class in order to declare public, private or protected function

Save multiple sheets to .pdf

Similar to Tim's answer - but with a check for 2007 (where the PDF export is not installed by default):

Public Sub subCreatePDF()

    If Not IsPDFLibraryInstalled Then
        'Better show this as a userform with a proper link:
        MsgBox "Please install the Addin to export to PDF. You can find it at http://www.microsoft.com/downloads/details.aspx?familyid=4d951911-3e7e-4ae6-b059-a2e79ed87041". 
        Exit Sub
    End If

    ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
        Filename:=ActiveWorkbook.Path & Application.PathSeparator & _
        ActiveSheet.Name & " für " & Range("SelectedName").Value & ".pdf", _
        Quality:=xlQualityStandard, IncludeDocProperties:=True, _
        IgnorePrintAreas:=False, OpenAfterPublish:=True
End Sub

Private Function IsPDFLibraryInstalled() As Boolean
'Credits go to Ron DeBruin (http://www.rondebruin.nl/pdf.htm)
    IsPDFLibraryInstalled = _
        (Dir(Environ("commonprogramfiles") & _
        "\Microsoft Shared\OFFICE" & _
        Format(Val(Application.Version), "00") & _
        "\EXP_PDF.DLL") <> "")
End Function

INNER JOIN in UPDATE sql for DB2

Just to update only the rows that match the conditions, and avoid updating nulls in the other rows:

update table_one set field_1 = 'ACTIVE' where exists 
(select 1 from table_two where table_one.customer = table_two.customer);

It works in a DB2/AIX64 9.7.8

How can I get relative path of the folders in my android project?

Are you looking for the root folder of the application? Then I would use

 String path = getClass().getClassLoader().getResource(".").getPath();

to actually "find out where I am".

How to convert a String into an array of Strings containing one character each

String x = "stackoverflow";
String [] y = x.split("");

assign headers based on existing row in dataframe in R

The key here is to unlist the row first.

colnames(DF) <- as.character(unlist(DF[1,]))
DF = DF[-1, ]

how to write javascript code inside php

You can put up all your JS like this, so it doesn't execute before your HTML is ready

$(document).ready(function() {
   // some code here
 });

Remember this is jQuery so include it in the head section. Also see Why you should use jQuery and not onload

How do I find the index of a character in a string in Ruby?

index(substring [, offset]) ? fixnum or nil
index(regexp [, offset]) ? fixnum or nil

Returns the index of the first occurrence of the given substring or pattern (regexp) in str. Returns nil if not found. If the second parameter is present, it specifies the position in the string to begin the search.

"hello".index('e')             #=> 1
"hello".index('lo')            #=> 3
"hello".index('a')             #=> nil
"hello".index(?e)              #=> 1
"hello".index(/[aeiou]/, -3)   #=> 4

Check out ruby documents for more information.

iPhone App Minus App Store?

It's worth noting that if you go the jailbroken route, it's possible (likely?) that an iPhone OS update would kill your ability to run these apps. I'd go the official route and pay the $99 to get authorized. In addition to not having to worry about your apps being clobbered, you also get the opportunity (should you choose) to release your apps on the store.

How do I convert a String to an InputStream in Java?

You can try cactoos for that.

final InputStream input = new InputStreamOf("example");

The object is created with new and not a static method for a reason.

Label encoding across multiple columns in scikit-learn

Instead of LabelEncoder we can use OrdinalEncoder from scikit learn, which allows multi-column encoding.

Encode categorical features as an integer array. The input to this transformer should be an array-like of integers or strings, denoting the values taken on by categorical (discrete) features. The features are converted to ordinal integers. This results in a single column of integers (0 to n_categories - 1) per feature.

>>> from sklearn.preprocessing import OrdinalEncoder
>>> enc = OrdinalEncoder()
>>> X = [['Male', 1], ['Female', 3], ['Female', 2]]
>>> enc.fit(X)
OrdinalEncoder()
>>> enc.categories_
[array(['Female', 'Male'], dtype=object), array([1, 2, 3], dtype=object)]
>>> enc.transform([['Female', 3], ['Male', 1]])
array([[0., 2.],
       [1., 0.]])

Both the description and example were copied from its documentation page which you can find here:

https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.OrdinalEncoder.html#sklearn.preprocessing.OrdinalEncoder

Node Express sending image files as API response

a proper solution with streams and error handling is below:

const fs = require('fs')
const stream = require('stream')

app.get('/report/:chart_id/:user_id',(req, res) => {
  const r = fs.createReadStream('path to file') // or any other way to get a readable stream
  const ps = new stream.PassThrough() // <---- this makes a trick with stream error handling
  stream.pipeline(
   r,
   ps, // <---- this makes a trick with stream error handling
   (err) => {
    if (err) {
      console.log(err) // No such file or any other kind of error
      return res.sendStatus(400); 
    }
  })
  ps.pipe(res) // <---- this makes a trick with stream error handling
})

with Node older then 10 you will need to use pump instead of pipeline.

Is there a SELECT ... INTO OUTFILE equivalent in SQL Server Management Studio?

In SQL Management Studio you can:

  1. Right click on the result set grid, select 'Save Result As...' and save in.

  2. On a tool bar toggle 'Result to Text' button. This will prompt for file name on each query run.

If you need to automate it, use bcp tool.

Find the item with maximum occurrences in a list

if you are using numpy in your solution for faster computation use this:

import numpy as np
x = np.array([2,5,77,77,77,77,77,77,77,9,0,3,3,3,3,3])
y = np.bincount(x,minlength = max(x))
y = np.argmax(y)   
print(y)  #outputs 77

Create an array with same element repeated multiple times

No easier way. You need to make a loop and push elements into the array.

What's NSLocalizedString equivalent in Swift?

Created a small helper method for cases, where "comment" is always ignored. Less code is easier to read:

public func NSLocalizedString(key: String) -> String {
    return NSLocalizedString(key, comment: "")
}

Just put it anywhere (outside a class) and Xcode will find this global method.

How to grant "grant create session" privilege?

You can grant system privileges with or without the admin option. The default being without admin option.

GRANT CREATE SESSION TO username

or with admin option:

GRANT CREATE SESSION TO username WITH ADMIN OPTION

The Grantee with the ADMIN OPTION can grant and revoke privileges to other users

django no such table:

sqlall just prints the SQL, it doesn't execute it. syncdb will create tables that aren't already created, but it won't modify existing tables.

How do I connect C# with Postgres?

You want the NPGSQL library. Your only other alternative is ODBC.

What's the best way to join on the same table twice?

First, I would try and refactor these tables to get away from using phone numbers as natural keys. I am not a fan of natural keys and this is a great example why. Natural keys, especially things like phone numbers, can change and frequently so. Updating your database when that change happens will be a HUGE, error-prone headache. *

Method 1 as you describe it is your best bet though. It looks a bit terse due to the naming scheme and the short aliases but... aliasing is your friend when it comes to joining the same table multiple times or using subqueries etc.

I would just clean things up a bit:

SELECT t.PhoneNumber1, t.PhoneNumber2, 
   t1.SomeOtherFieldForPhone1, t2.someOtherFieldForPhone2
FROM Table1 t
JOIN Table2 t1 ON t1.PhoneNumber = t.PhoneNumber1
JOIN Table2 t2 ON t2.PhoneNumber = t.PhoneNumber2

What i did:

  • No need to specify INNER - it's implied by the fact that you don't specify LEFT or RIGHT
  • Don't n-suffix your primary lookup table
  • N-Suffix the table aliases that you will use multiple times to make it obvious

*One way DBAs avoid the headaches of updating natural keys is to not specify primary keys and foreign key constraints which further compounds the issues with poor db design. I've actually seen this more often than not.

Inheriting constructors

How about using a template function to bind all constructors?

template <class... T> Derived(T... t) : Base(t...) {}

Draw line in UIView

One other (and an even shorter) possibility. If you're inside drawRect, something like the following:

[[UIColor blackColor] setFill];
UIRectFill((CGRect){0,200,rect.size.width,1});

How to debug a referenced dll (having pdb)

When you want to set a breakpoint in source code of a referenced dll, first make sure that you have a pdb file available for it. Then you can just open the related source code file and set a breakpoint over there. The source file does not need to be part of your solution. As explained in How can I set a breakpoint in referenced code in Visual Studio?

You can review your breakpoints through the breakpoints window, available via Debug -> Windows -> Breakpoints.

This approach has the benefit that you are not required to add an existing project to your solution just for debugging purposes as leaving it out has saved me a lot of build time. Evidently, building a solution with only one project in it is much faster than building a solution with lots of them.

How to test if a double is zero?

In Java, 0 is the same as 0.0, and doubles default to 0 (though many advise always setting them explicitly for improved readability). I have checked and foo.x == 0 and foo.x == 0.0 are both true if foo.x is zero

Proper way to set response status and JSON content in a REST API made with nodejs and express

You could do it this way:

res.status(400).json(json_response);

This will set the HTTP status code to 400, it works even in express 4.

Loop Through Each HTML Table Column and Get the Data using jQuery

My first post...

I tried this: change 'tr' for 'td' and you will get all HTMLRowElements into an Array, and using textContent will change from Object into String

var dataArray = [];
var data = table.find('td'); //Get All HTML td elements

// Save important data into new Array
for (var i = 0; i <= data.size() - 1; i = i + 4)
{
  dataArray.push(data[i].textContent, data[i + 1].textContent, data[i + 2].textContent);
}

How to check if a Docker image with a specific tag exist locally?

In case you are trying to search for a docker image from a docker registry, I guess the easiest way to check if a docker image is present is by using the Docker V2 REST API Tags list service

Example:-

curl $CURLOPTS -H "Authorization: Bearer $token" "https://hub.docker.com:4443/v2/your-repo-name/tags/list"

if the above result returns 200Ok with a list of image tags, then we know that image exists

{"name":"your-repo-name","tags":["1.0.0.1533677221","1.0.0.1533740305","1.0.0.1535659921","1.0.0.1535665433","latest"]}

else if you see something like

{"errors":[{"code":"NAME_UNKNOWN","message":"repository name not known to registry","detail":{"name":"your-repo-name"}}]} 

then you know for sure that image doesn't exist.

Grab a segment of an array in Java without creating a new array on heap

One option would be to pass the whole array and the start and end indices, and iterate between those instead of iterating over the whole array passed.

void method1(byte[] array) {
    method2(array,4,5);
}
void method2(byte[] smallarray,int start,int end) {
    for ( int i = start; i <= end; i++ ) {
        ....
    }
}

How to specify preference of library path?

If one is used to work with DLL in Windows and would like to skip .so version numbers in linux/QT, adding CONFIG += plugin will take version numbers out. To use absolute path to .so, giving it to linker works fine, as Mr. Klatchko mentioned.

Negative matching using grep (match lines that do not contain foo)

You can also use awk for these purposes, since it allows you to perform more complex checks in a clearer way:

Lines not containing foo:

awk '!/foo/'

Lines containing neither foo nor bar:

awk '!/foo/ && !/bar/'

Lines containing neither foo nor bar which contain either foo2 or bar2:

awk '!/foo/ && !/bar/ && (/foo2/ || /bar2/)'

And so on.

how to convert long date value to mm/dd/yyyy format

Try this example

 String[] formats = new String[] {
   "yyyy-MM-dd",
   "yyyy-MM-dd HH:mm",
   "yyyy-MM-dd HH:mmZ",
   "yyyy-MM-dd HH:mm:ss.SSSZ",
   "yyyy-MM-dd'T'HH:mm:ss.SSSZ",
 };
 for (String format : formats) {
   SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.US);
   System.err.format("%30s %s\n", format, sdf.format(new Date(0)));
   sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
   System.err.format("%30s %s\n", format, sdf.format(new Date(0)));
 }

and read this http://developer.android.com/reference/java/text/SimpleDateFormat.html