Programs & Examples On #Text decoding

Blurry text after using CSS transform: scale(); in Chrome

I found out, that the problem occures on relative transforms in any way. translateX(50%), scale(1.1) or what ever. providing absolute values always works (does not produce blurry text(ures)).

None of the solutions mentions here worked, and I think there is not solution, yet (using Chrome 62.0.3202.94 while I am writing this).

In my case transform: translateY(-50%) translateX(-50%) causes the blur (I want to center a dialog).

To reach a bit more "absolute" values, I had to set decimal values to transform: translateY(-50.09%) translateX(-50.09%).

NOTE

I am quite sure, that this values vary on different screen sizes. I just wanted to share my experiences, in case it helps someone.

How can I remove a commit on GitHub?

Delete the most recent commit, keeping the work you've done:

git reset --soft HEAD~1

Delete the most recent commit, destroying the work you've done:

git reset --hard HEAD~1

Is there a Python equivalent of the C# null-coalescing operator?

Addionally to @Bothwells answer (which I prefer) for single values, in order to null-checking assingment of function return values, you can use new walrus-operator (since python3.8):

def test():
    return

a = 2 if (x:= test()) is None else x

Thus, test function does not need to be evaluated two times (as in a = 2 if test() is None else test())

Drawing Circle with OpenGL

We will find the value of X and Y from this image. We know, sin?=vertical/hypotenuse and cos?=base/hypotenuse from the image we can say base=X and Y=vertical. Now we can write X=hypotenuse*cos? and Y=hypotenuse*sin?. We will find the value of X and Y from this image. We know, sin?=vertical/hypotenuse and cos?=base/hypotenuse from the image we can say X=base and Y=vertical. Now we can write X=hypotenuse * cos? and Y=hypotenuse * sin?.

Now look at this code

void display(){
float x,y;
glColor3f(1, 1, 0);
for(double i =0; i <= 360;){
    glBegin(GL_TRIANGLES);
    x=5*cos(i);
    y=5*sin(i);
    glVertex2d(x, y);
    i=i+.5;
    x=5*cos(i);
    y=5*sin(i);
    glVertex2d(x, y);
    glVertex2d(0, 0);
    glEnd();
    i=i+.5;
}
glEnd();

glutSwapBuffers();
}

Set Canvas size using javascript

function setWidth(width) {
  var canvas = document.getElementById("myCanvas");  
  canvas.width = width;
}

How to find the path of the local git repository when I am possibly in a subdirectory

git rev-parse --show-toplevel

could be enough if executed within a git repo.
From git rev-parse man page:

--show-toplevel

Show the absolute path of the top-level directory.

For older versions (before 1.7.x), the other options are listed in "Is there a way to get the git root directory in one command?":

git rev-parse --git-dir

That would give the path of the .git directory.


The OP mentions:

git rev-parse --show-prefix

which returns the local path under the git repo root. (empty if you are at the git repo root)


Note: for simply checking if one is in a git repo, I find the following command quite expressive:

git rev-parse --is-inside-work-tree

And yes, if you need to check if you are in a .git git-dir folder:

git rev-parse --is-inside-git-dir

Stacked bar chart

Building on Roland's answer, using tidyr to reshape the data from wide to long:

library(tidyr)
library(ggplot2)

df <- read.table(text="Rank F1     F2     F3
1    500    250    50
2    400    100    30
3    300    155    100
4    200    90     10", header=TRUE)

df %>% 
  gather(variable, value, F1:F3) %>% 
  ggplot(aes(x = Rank, y = value, fill = variable)) + 
  geom_bar(stat = "identity")

enter image description here

How do I parse JSON in Android?

  1. Writing JSON Parser Class

    public class JSONParser {
    
        static InputStream is = null;
        static JSONObject jObj = null;
        static String json = "";
    
        // constructor
        public JSONParser() {}
    
        public JSONObject getJSONFromUrl(String url) {
    
            // Making HTTP request
            try {
                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
    
                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
    
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
    
            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(
                        is, "iso-8859-1"), 8);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
                is.close();
                json = sb.toString();
            } catch (Exception e) {
                Log.e("Buffer Error", "Error converting result " + e.toString());
            }
    
            // try parse the string to a JSON object
            try {
                jObj = new JSONObject(json);
            } catch (JSONException e) {
                Log.e("JSON Parser", "Error parsing data " + e.toString());
            }
    
            // return JSON String
            return jObj;
    
        }
    }
    
  2. Parsing JSON Data
    Once you created parser class next thing is to know how to use that class. Below i am explaining how to parse the json (taken in this example) using the parser class.

    2.1. Store all these node names in variables: In the contacts json we have items like name, email, address, gender and phone numbers. So first thing is to store all these node names in variables. Open your main activity class and declare store all node names in static variables.

    // url to make request
    private static String url = "http://api.9android.net/contacts";
    
    // JSON Node names
    private static final String TAG_CONTACTS = "contacts";
    private static final String TAG_ID = "id";
    private static final String TAG_NAME = "name";
    private static final String TAG_EMAIL = "email";
    private static final String TAG_ADDRESS = "address";
    private static final String TAG_GENDER = "gender";
    private static final String TAG_PHONE = "phone";
    private static final String TAG_PHONE_MOBILE = "mobile";
    private static final String TAG_PHONE_HOME = "home";
    private static final String TAG_PHONE_OFFICE = "office";
    
    // contacts JSONArray
    JSONArray contacts = null;
    

    2.2. Use parser class to get JSONObject and looping through each json item. Below i am creating an instance of JSONParser class and using for loop i am looping through each json item and finally storing each json data in variable.

    // Creating JSON Parser instance
    JSONParser jParser = new JSONParser();
    
    // getting JSON string from URL
    JSONObject json = jParser.getJSONFromUrl(url);
    
        try {
        // Getting Array of Contacts
        contacts = json.getJSONArray(TAG_CONTACTS);
    
        // looping through All Contacts
        for(int i = 0; i < contacts.length(); i++){
            JSONObject c = contacts.getJSONObject(i);
    
            // Storing each json item in variable
            String id = c.getString(TAG_ID);
            String name = c.getString(TAG_NAME);
            String email = c.getString(TAG_EMAIL);
            String address = c.getString(TAG_ADDRESS);
            String gender = c.getString(TAG_GENDER);
    
            // Phone number is agin JSON Object
            JSONObject phone = c.getJSONObject(TAG_PHONE);
            String mobile = phone.getString(TAG_PHONE_MOBILE);
            String home = phone.getString(TAG_PHONE_HOME);
            String office = phone.getString(TAG_PHONE_OFFICE);
    
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
    

Create multiple threads and wait all of them to complete

I don't know if there is a better way, but the following describes how I did it with a counter and background worker thread.

private object _lock = new object();
private int _runningThreads = 0;

private int Counter{
    get{
        lock(_lock)
            return _runningThreads;
    }
    set{
        lock(_lock)
            _runningThreads = value;
    }
}

Now whenever you create a worker thread, increment the counter:

var t = new BackgroundWorker();
// Add RunWorkerCompleted handler

// Start thread
Counter++;

In work completed, decrement the counter:

private void RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    Counter--;
}

Now you can check for the counter anytime to see if any thread is running:

if(Couonter>0){
    // Some thread is yet to finish.
}

SQL Case Expression Syntax?

Here are the CASE statement examples from the PostgreSQL docs (Postgres follows the SQL standard here):

SELECT a,
   CASE WHEN a=1 THEN 'one'
        WHEN a=2 THEN 'two'
        ELSE 'other'
   END
FROM test;

or

SELECT a,
   CASE a WHEN 1 THEN 'one'
          WHEN 2 THEN 'two'
          ELSE 'other'
   END
FROM test;

Obviously the second form is cleaner when you are just checking one field against a list of possible values. The first form allows more complicated expressions.

Round up to Second Decimal Place in Python

Updated answer:
The problem with my original answer, as pointed out in the comments by @jpm, is the behavior at the boundaries. Python 3 makes this even more difficult since it uses "bankers" rounding instead of "old school" rounding. However, in looking into this issue I discovered an even better solution using the decimal library.

import decimal

def round_up(x, place=0):
    context = decimal.getcontext()
    # get the original setting so we can put it back when we're done
    original_rounding = context.rounding
    # change context to act like ceil()
    context.rounding = decimal.ROUND_CEILING

    rounded = round(decimal.Decimal(str(x)), place)
    context.rounding = original_rounding
    return float(rounded)

Or if you really just want a one-liner:

import decimal
decimal.getcontext().rounding = decimal.ROUND_CEILING

# here's the one-liner
float(round(decimal.Decimal(str(0.1111)), ndigits=2))
>> 0.12

# Note: this only affects the rounding of `Decimal`
round(0.1111, ndigits=2)
>> 0.11

Here are some examples:

round_up(0.022499999999999999, 2)
>> 0.03
round_up(0.1111111111111000, 2)
>> 0.12
round_up(0.1111111111111000, 3)
>> 0.112

round_up(3.4)
>> 4.0

# @jpm - boundaries do what we want
round_up(0.1, 2)
>> 0.1
round_up(1.1, 2)
>> 1.1

# Note: this still rounds toward `inf`, not "away from zero"
round_up(2.049, 2)
>> 2.05
round_up(-2.0449, 2)
>> -2.04

We can use it to round to the left of the decimal as well:

round_up(11, -1)
>> 20

We don't multiply by 10, thereby avoiding the overflow mentioned in this answer.

round_up(1.01e308, -307)
>> 1.1e+308

Original Answer (Not recommended):
This depends on the behavior you want when considering positive and negative numbers, but if you want something that always rounds to a larger value (e.g. 2.0449 -> 2.05, -2.0449 -> -2.04) then you can do:

round(x + 0.005, 2)

or a little fancier:

def round_up(x, place):
    return round(x + 5 * 10**(-1 * (place + 1)), place)

This also seems to work as follows:

round(144, -1)
# 140
round_up(144, -1)
# 150
round_up(1e308, -307)
# 1.1e308

Error: Failed to lookup view in Express

I had the same error at first and i was really annoyed. you just need to have ./ before the path to the template

res.render('./index/index');

Hope it works, worked for me.

downloading all the files in a directory with cURL

If you're not bound to curl, you might want to use wget in recursive mode but restricting it to one level of recursion, try the following;

wget --no-verbose --no-parent --recursive --level=1\
--no-directories --user=login --password=pass ftp://ftp.myftpsite.com/
  • --no-parent : Do not ever ascend to the parent directory when retrieving recursively.
  • --level=depth : Specify recursion maximum depth level depth. The default maximum depth is five layers.
  • --no-directories : Do not create a hierarchy of directories when retrieving recursively.

Could not load file or assembly Microsoft.SqlServer.management.sdk.sfc version 11.0.0.0

I am running VS 2012, and SQL Server 2008 R2 SP2, Developer Edition. I ended up having to install items from the Microsoft® SQL Server® 2012 Feature Pack. I think that the install instructions noted that these items work for SQL Server 2005 through 2012. I don't know what the exact requirements are to fix this error, but I installed the three items, and the error stopped appearing.

Microsoft® SQL Server® 2012 Feature Pack Items

  • Microsoft® SQL Server® 2012 Shared Management Objects : x86 , x64
  • Microsoft® System CLR Types for Microsoft® SQL Server® 2012 : x86 , x64
  • Microsoft® SQL Server® 2012 Native Client : x86 , x64

Based on threads elsewhere, you may not end up needing the last item or two. Good luck!

Checking if a website is up via Python

You could try to do this with getcode() from urllib

>>> print urllib.urlopen("http://www.stackoverflow.com").getcode()
>>> 200

EDIT: For more modern python, i.e. python3, use:

import urllib.request
print(urllib.request.urlopen("http://www.stackoverflow.com").getcode())
>>> 200

How to change UIPickerView height

stockPicker = [[UIPickerView alloc] init];
stockPicker.frame = CGRectMake(70.0,155, 180,100);

If You want to set the size of UiPickerView. Above code is surely gonna work for u.

What is the reason for having '//' in Python?

// is unconditionally "flooring division", e.g:

>>> 4.0//1.5
2.0

As you see, even though both operands are floats, // still floors -- so you always know securely what it's going to do.

Single / may or may not floor depending on Python release, future imports, and even flags on which Python's run, e.g.:

$ python2.6 -Qold -c 'print 2/3'
0
$ python2.6 -Qnew -c 'print 2/3'
0.666666666667

As you see, single / may floor, or it may return a float, based on completely non-local issues, up to and including the value of the -Q flag...;-).

So, if and when you know you want flooring, always use //, which guarantees it. If and when you know you don't want flooring, slap a float() around other operand and use /. Any other combination, and you're at the mercy of version, imports, and flags!-)

DropDownList's SelectedIndexChanged event not firing

Set DropDownList AutoPostBack property to true.

Eg:

<asp:DropDownList ID="logList" runat="server" AutoPostBack="True" 
        onselectedindexchanged="itemSelected">
    </asp:DropDownList>

jQuery Button.click() event is triggered twice

Your current code works, you can try it here: http://jsfiddle.net/s4UyH/

You have something outside the example triggering another .click(), check for other handlers that are also triggering a click event on that element.

Best way to generate xml?

Using lxml:

from lxml import etree

# create XML 
root = etree.Element('root')
root.append(etree.Element('child'))
# another child with text
child = etree.Element('child')
child.text = 'some text'
root.append(child)

# pretty string
s = etree.tostring(root, pretty_print=True)
print s

Output:

<root>
  <child/>
  <child>some text</child>
</root>

See the tutorial for more information.

Finding second occurrence of a substring in a string in Java

You can write a function to return array of occurrence positions, Java has String.regionMatches function which is quite handy

public static ArrayList<Integer> occurrencesPos(String str, String substr) {
    final boolean ignoreCase = true;
    int substrLength = substr.length();
    int strLength = str.length();

    ArrayList<Integer> occurrenceArr = new ArrayList<Integer>();

    for(int i = 0; i < strLength - substrLength + 1; i++) {
        if(str.regionMatches(ignoreCase, i, substr, 0, substrLength))  {
            occurrenceArr.add(i);
        }
    }
    return occurrenceArr;
}

oracle.jdbc.driver.OracleDriver ClassNotFoundException

You can add a JAR which having above specified class exist e.g.ojdbc jar which supported by installed java version, also make sure that you have added it into classpath.

Check if a value exists in pandas dataframe index

Multi index works a little different from single index. Here are some methods for multi-indexed dataframe.

df = pd.DataFrame({'col1': ['a', 'b','c', 'd'], 'col2': ['X','X','Y', 'Y'], 'col3': [1, 2, 3, 4]}, columns=['col1', 'col2', 'col3'])
df = df.set_index(['col1', 'col2'])

in df.index works for the first level only when checking single index value.

'a' in df.index     # True
'X' in df.index     # False

Check df.index.levels for other levels.

'a' in df.index.levels[0] # True
'X' in df.index.levels[1] # True

Check in df.index for an index combination tuple.

('a', 'X') in df.index  # True
('a', 'Y') in df.index  # False

Image vs Bitmap class

This is a clarification because I have seen things done in code which are honestly confusing - I think the following example might assist others.

As others have said before - Bitmap inherits from the Abstract Image class

Abstract effectively means you cannot create a New() instance of it.

    Image imgBad1 = new Image();        // Bad - won't compile
    Image imgBad2 = new Image(200,200); // Bad - won't compile

But you can do the following:

    Image imgGood;  // Not instantiated object!
    // Now you can do this
    imgGood = new Bitmap(200, 200);

You can now use imgGood as you would the same bitmap object if you had done the following:

    Bitmap bmpGood = new Bitmap(200,200);

The nice thing here is you can draw the imgGood object using a Graphics object

    Graphics gr = default(Graphics);
    gr = Graphics.FromImage(new Bitmap(1000, 1000));
    Rectangle rect = new Rectangle(50, 50, imgGood.Width, imgGood.Height); // where to draw
    gr.DrawImage(imgGood, rect);

Here imgGood can be any Image object - Bitmap, Metafile, or anything else that inherits from Image!

Windows Forms ProgressBar: Easiest way to start/stop marquee?

To start/stop the animation, you should do this:

To start:

progressBar1.Style = ProgressBarStyle.Marquee;
progressBar1.MarqueeAnimationSpeed = 30;

To stop:

progressBar1.Style = ProgressBarStyle.Continuous;
progressBar1.MarqueeAnimationSpeed = 0;

VSCode: How to Split Editor Vertically

To split vertically:

?+\ Mac

command: workbench.action.splitEditor

To split orthogonal (ie. horizontally in this case):

?+k+?+\ Mac

command: workbench.action.splitEditorOrthogonal

Minimum Hardware requirements for Android development

Firstly, there is an issue with the ADT plugin and Helios which causes lag with looking up Android classes - use Galileo instead (v3.5).

Secondly, the emulators become more resource hungry depending on the version of Android you're developing for. Example, I have a P4 2.4GHz, 1GB RAM PC with Win XP 32-bit and an Android v2.2 emulator takes at least 4-5 minutes to load up. An Android v1.6 emulator on the other hand loads up in less than 1 minute. Remember though that once the emulator is up and running, you can leave it loaded and it will be more responsive than first use.

Also bear in mind that if you give your emulator a 2GB SD card (for example) it will try to create that through virtual memory if there isn't enough physical memory.

How can I print a circular structure in a JSON-like format?

Most of the answers in this thread are catered to use with JSON.stringify specifically -- they do not show how to actually remove circular-references in the original object-tree. (well, short of calling JSON.parse again afterward -- which requires reassignment, and has a higher performance impact)

For removing circular-references from the source object-tree, you can use a function such as this: https://stackoverflow.com/a/63952549/2441655

These general-purpose circular-reference-remover functions can then be used to make subsequent calls to circular-reference-sensitive functions (like JSON.stringify) safe:

const objTree = {normalProp: true};
objTree.selfReference = objTree;
RemoveCircularLinks(objTree); // without this line, the JSON.stringify call errors
console.log(JSON.stringify(objTree));

jQuery Validation plugin: disable validation for specified submit buttons

Other (undocumented) way to do it, is to call:

$("form").validate().cancelSubmit = true;

on the click event of the button (for example).

boto3 client NoRegionError: You must specify a region error only sometimes

you can also set environment variables in the script itself, rather than passing region_name parameter

os.environ['AWS_DEFAULT_REGION'] = 'your_region_name'

case sensitivity may matter.

Is it possible to convert char[] to char* in C?

It sounds like you're confused between pointers and arrays. Pointers and arrays (in this case char * and char []) are not the same thing.

  • An array char a[SIZE] says that the value at the location of a is an array of length SIZE
  • A pointer char *a; says that the value at the location of a is a pointer to a char. This can be combined with pointer arithmetic to behave like an array (eg, a[10] is 10 entries past wherever a points)

In memory, it looks like this (example taken from the FAQ):

 char a[] = "hello";  // array

   +---+---+---+---+---+---+
a: | h | e | l | l | o |\0 |
   +---+---+---+---+---+---+

 char *p = "world"; // pointer

   +-----+     +---+---+---+---+---+---+
p: |  *======> | w | o | r | l | d |\0 |
   +-----+     +---+---+---+---+---+---+

It's easy to be confused about the difference between pointers and arrays, because in many cases, an array reference "decays" to a pointer to it's first element. This means that in many cases (such as when passed to a function call) arrays become pointers. If you'd like to know more, this section of the C FAQ describes the differences in detail.

One major practical difference is that the compiler knows how long an array is. Using the examples above:

char a[] = "hello";  
char *p =  "world";  

sizeof(a); // 6 - one byte for each character in the string,
           // one for the '\0' terminator
sizeof(p); // whatever the size of the pointer is
           // probably 4 or 8 on most machines (depending on whether it's a 
           // 32 or 64 bit machine)

Without seeing your code, it's hard to recommend the best course of action, but I suspect changing to use pointers everywhere will solve the problems you're currently having. Take note that now:

  • You will need to initialise memory wherever the arrays used to be. Eg, char a[10]; will become char *a = malloc(10 * sizeof(char));, followed by a check that a != NULL. Note that you don't actually need to say sizeof(char) in this case, because sizeof(char) is defined to be 1. I left it in for completeness.

  • Anywhere you previously had sizeof(a) for array length will need to be replaced by the length of the memory you allocated (if you're using strings, you could use strlen(), which counts up to the '\0').

  • You will need a make a corresponding call to free() for each call to malloc(). This tells the computer you are done using the memory you asked for with malloc(). If your pointer is a, just write free(a); at a point in the code where you know you no longer need whatever a points to.

As another answer pointed out, if you want to get the address of the start of an array, you can use:

char* p = &a[0] 

You can read this as "char pointer p becomes the address of element [0] of a".

Use C# HttpWebRequest to send json to web service

First of all you missed ScriptService attribute to add in webservice.

[ScriptService]

After then try following method to call webservice via JSON.

        var webAddr = "http://Domain/VBRService.asmx/callJson";
        var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr);
        httpWebRequest.ContentType = "application/json; charset=utf-8";
        httpWebRequest.Method = "POST";            

        using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
        {
            string json = "{\"x\":\"true\"}";

            streamWriter.Write(json);
            streamWriter.Flush();
        }

        var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
        using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
        {
            var result = streamReader.ReadToEnd();
            return result;
        }

The breakpoint will not currently be hit. No symbols have been loaded for this document in a Silverlight application

I've just resolved this issue according to Deploying Silverlight Applications. (This answer is a duplicate of some others but I'll attempt to explain it more thoroughly.)

The problem is most likely that your Silverlight application is not being deployed properly to your web application on build / startup. This is a referencing problem - it's simple to understand but not obvious the first time you encounter it.

Just like any other project reference, the referenced project's output should be copied to the referencing project's bin folder in order to debug. For class libraries this happens when you right click and select 'Add Reference...'. For Silverlight, you should add a reference through Project Properties.

  • Right click your project, and select 'Properties'
  • Select the 'Silverlight Applications' tab on the left
  • Press the 'Add...' button and select your Silverlight project from the dialogue box

This adds a reference to the Silverlight application from your hosting web app, and ensures that the xap file will be copied to the web app on build or deploy. That means that the current Silverlight app and its debug files are inside the application being debugged, and you'll be able to step through the code.

List of tuples to dictionary

Just call dict() on the list of tuples directly

>>> my_list = [('a', 1), ('b', 2)]
>>> dict(my_list)
{'a': 1, 'b': 2}

Checking if a string can be converted to float in Python

I used the function already mentioned, but soon I notice that strings as "Nan", "Inf" and it's variation are considered as number. So I propose you improved version of the function, that will return false on those type of input and will not fail "1e3" variants:

def is_float(text):
    # check for nan/infinity etc.
    if text.isalpha():
        return False
    try:
        float(text)
        return True
    except ValueError:
        return False

Byte[] to InputStream or OutputStream

we can convert byte[] array into input stream by using ByteArrayInputStream

String str = "Welcome to awesome Java World";
    byte[] content = str.getBytes();
    int size = content.length;
    InputStream is = null;
    byte[] b = new byte[size];
    is = new ByteArrayInputStream(content);

For full example please check here http://www.onlinecodegeek.com/2015/09/how-to-convert-byte-into-inputstream.html

How can I position my jQuery dialog to center?

So if anyone hits this page like I did, or for when I forget in 15 minutes, I'm using jqueryui dialog version 1.10.1 and jquery 1.9.1 with ie8 in an iframe(blah), and it needs a within specified or it doesn't work, i.e.

position: {
 my: "center bottom",
 at: "center top",
 of: $("#submitbutton"),
 within: $(".content")
}

Thanks to @vm370 for pointing me in the right direction.

Laravel: Error [PDOException]: Could not Find Driver in PostgreSQL

For PHP 7 in Ubuntu you can also do:

sudo apt-get install php7.0-pgsql

So, now you can do not uncomment lines in php.ini

UPD: I have a same error, so problem was not in driver. I changed my database.ini, but every time I saw an error. And I change database config in .env and errors gone.

Command to list all files in a folder as well as sub-folders in windows

An addition to the answer: when you do not want to list the folders, only the files in the subfolders, use /A-D switch like this:

dir ..\myfolder /b /s /A-D /o:gn>list.txt

Could not resolve '...' from state ''

I had a case where the error was thrown by a

$state.go('');

Which is obvious. I guess this can help someone in future.

Meaning of $? (dollar question mark) in shell scripts

Minimal POSIX C exit status example

To understand $?, you must first understand the concept of process exit status which is defined by POSIX. In Linux:

  • when a process calls the exit system call, the kernel stores the value passed to the system call (an int) even after the process dies.

    The exit system call is called by the exit() ANSI C function, and indirectly when you do return from main.

  • the process that called the exiting child process (Bash), often with fork + exec, can retrieve the exit status of the child with the wait system call

Consider the Bash code:

$ false
$ echo $?
1

The C "equivalent" is:

false.c

#include <stdlib.h> /* exit */

int main(void) {
    exit(1);
}

bash.c

#include <unistd.h> /* execl */
#include <stdlib.h> /* fork */
#include <sys/wait.h> /* wait, WEXITSTATUS */
#include <stdio.h> /* printf */

int main(void) {
    if (fork() == 0) {
        /* Call false. */
        execl("./false", "./false", (char *)NULL);
    }
    int status;
    /* Wait for a child to finish. */
    wait(&status);
    /* Status encodes multiple fields,
     * we need WEXITSTATUS to get the exit status:
     * http://stackoverflow.com/questions/3659616/returning-exit-code-from-child
     **/
    printf("$? = %d\n", WEXITSTATUS(status));
}

Compile and run:

g++ -ggdb3 -O0 -std=c++11 -Wall -Wextra -pedantic -o bash bash.c
g++ -ggdb3 -O0 -std=c++11 -Wall -Wextra -pedantic -o false false.c
./bash

Output:

$? = 1

In Bash, when you hit enter, a fork + exec + wait happens like above, and bash then sets $? to the exit status of the forked process.

Note: for built-in commands like echo, a process need not be spawned, and Bash just sets $? to 0 to simulate an external process.

Standards and documentation

POSIX 7 2.5.2 "Special Parameters" http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_05_02 :

? Expands to the decimal exit status of the most recent pipeline (see Pipelines).

man bash "Special Parameters":

The shell treats several parameters specially. These parameters may only be referenced; assignment to them is not allowed. [...]

? Expands to the exit status of the most recently executed foreground pipeline.

ANSI C and POSIX then recommend that:

  • 0 means the program was successful

  • other values: the program failed somehow.

    The exact value could indicate the type of failure.

    ANSI C does not define the meaning of any vaues, and POSIX specifies values larger than 125: What is the meaning of "POSIX"?

Bash uses exit status for if

In Bash, we often use the exit status $? implicitly to control if statements as in:

if true; then
  :
fi

where true is a program that just returns 0.

The above is equivalent to:

true
result=$?
if [ $result = 0 ]; then
  :
fi

And in:

if [ 1 = 1 ]; then
  :
fi

[ is just an program with a weird name (and Bash built-in that behaves like it), and 1 = 1 ] its arguments, see also: Difference between single and double square brackets in Bash

How to add new line in Markdown presentation?

You could use &nbsp; in R markdown to create a new blank line.

For example, in your .Rmd file:

I want 3 new lines: 

&nbsp;
&nbsp;
&nbsp;

End of file. 

Spring + Web MVC: dispatcher-servlet.xml vs. applicationContext.xml (plus shared security)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:cache="http://www.springframework.org/schema/cache"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd  http://www.springframework.org/schema/cache 
        http://www.springframework.org/schema/cache/spring-cache-3.2.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">

        <mvc:annotation-driven/>
        <context:component-scan base-package="com.testpoc.controller"/>

        <bean id="ViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="ViewClass" value="org.springframework.web.servlet.view.JstlView"></property>
            <property name="prefix">
                <value>/WEB-INF/pages/</value>
            </property>
            <property name="suffix">
                <value>.jsp</value>
            </property>
        </bean>

</beans>

Launch Android application without main Activity and start Service on launching application

The reason to make an App with no activity or service could be making a Homescreen Widget app that doesn't need to be started.
Once you start a project don't create any activities. After you created the project just hit run. Android studio will say No default activity found.

Click Edit Configuration (From the Run menu) and in the Launch option part set the Launch value to Nothing. Then click ok and run the App.

(Since there is no launcher activity, No app will be show in the Apps menu.).

How to create global variables accessible in all views using Express / Node.JS?

One way to do this by updating the app.locals variable for that app in app.js

Set via following

var app = express();
app.locals.appName = "DRC on FHIR";

Get / Access

app.listen(3000, function () {
    console.log('[' + app.locals.appName + '] => app listening on port 3001!');
});

Elaborating with a screenshot from @RamRovi example with slight enhancement.

enter image description here

Close Bootstrap Modal

In some circumstances typing error could be the culprit. For instance, make sure you have:

data-dismiss="modal"

and not

data-dissmiss="modal"

Notice the double "ss" in the second example that will cause the Close button that fail.

Difference between Node object and Element object?

Node is used to represent tags in general. Divided to 3 types:

Attribute Note: is node which inside its has attributes. Exp: <p id=”123”></p>

Text Node: is node which between the opening and closing its have contian text content. Exp: <p>Hello</p>

Element Node : is node which inside its has other tags. Exp: <p><b></b></p>

Each node may be types simultaneously, not necessarily only of a single type.

Element is simply a element node.

Very Simple, Very Smooth, JavaScript Marquee

hiya simple demo from recommendations in above comments: http://jsfiddle.net/FWWEn/

with pause functionality on mouseover: http://jsfiddle.net/zrW5q/

hope this helps, have a nice one, cheers!

html

<h1>Hello World!</h1>
<h2>I'll marquee twice</h2>
<h3>I go fast!</h3>
<h4>Left to right</h4>
<h5>I'll defer that question</h5>?

Jquery code

 (function($) {
        $.fn.textWidth = function(){
             var calc = '<span style="display:none">' + $(this).text() + '</span>';
             $('body').append(calc);
             var width = $('body').find('span:last').width();
             $('body').find('span:last').remove();
            return width;
        };

        $.fn.marquee = function(args) {
            var that = $(this);
            var textWidth = that.textWidth(),
                offset = that.width(),
                width = offset,
                css = {
                    'text-indent' : that.css('text-indent'),
                    'overflow' : that.css('overflow'),
                    'white-space' : that.css('white-space')
                },
                marqueeCss = {
                    'text-indent' : width,
                    'overflow' : 'hidden',
                    'white-space' : 'nowrap'
                },
                args = $.extend(true, { count: -1, speed: 1e1, leftToRight: false }, args),
                i = 0,
                stop = textWidth*-1,
                dfd = $.Deferred();

            function go() {
                if(!that.length) return dfd.reject();
                if(width == stop) {
                    i++;
                    if(i == args.count) {
                        that.css(css);
                        return dfd.resolve();
                    }
                    if(args.leftToRight) {
                        width = textWidth*-1;
                    } else {
                        width = offset;
                    }
                }
                that.css('text-indent', width + 'px');
                if(args.leftToRight) {
                    width++;
                } else {
                    width--;
                }
                setTimeout(go, args.speed);
            };
            if(args.leftToRight) {
                width = textWidth*-1;
                width++;
                stop = offset;
            } else {
                width--;            
            }
            that.css(marqueeCss);
            go();
            return dfd.promise();
        };
    })(jQuery);

$('h1').marquee();
$('h2').marquee({ count: 2 });
$('h3').marquee({ speed: 5 });
$('h4').marquee({ leftToRight: true });
$('h5').marquee({ count: 1, speed: 2 }).done(function() { $('h5').css('color', '#f00'); })?

Date difference in years using C#

I implemented an extension method to get the number of years between two dates, rounded by whole months.

    /// <summary>
    /// Gets the total number of years between two dates, rounded to whole months.
    /// Examples: 
    /// 2011-12-14, 2012-12-15 returns 1.
    /// 2011-12-14, 2012-12-14 returns 1.
    /// 2011-12-14, 2012-12-13 returns 0,9167.
    /// </summary>
    /// <param name="start">
    /// Stardate of time period
    /// </param>
    /// <param name="end">
    /// Enddate of time period
    /// </param>
    /// <returns>
    /// Total Years between the two days
    /// </returns>
    public static double DifferenceTotalYears(this DateTime start, DateTime end)
    {
        // Get difference in total months.
        int months = ((end.Year - start.Year) * 12) + (end.Month - start.Month);

        // substract 1 month if end month is not completed
        if (end.Day < start.Day)
        {
            months--;
        }

        double totalyears = months / 12d;
        return totalyears;
    }

PHPMailer character encoding issues

If you are 100% sure $message contain ISO-8859-1 you can use utf8_encode as David says. Otherwise use mb_detect_encoding and mb_convert_encoding on $message.

Also take note that

$mail -> charSet = "UTF-8"; 

Should be replaced by:

$mail->CharSet = 'UTF-8';

And placed after the instantiation of the class (after the new). The properties are case sensitive! See the PHPMailer doc fot the list & exact spelling.

Also the default encoding of PHPMailer is 8bit which can be problematic with UTF-8 data. To fix this you can do:

$mail->Encoding = 'base64';

Take note that 'quoted-printable' would probably work too in these cases (and maybe even 'binary'). For more details you can read RFC1341 - Content-Transfer-Encoding Header Field.

Initializing multiple variables to the same value in Java

You can declare multiple variables, and initialize multiple variables, but not both at the same time:

 String one,two,three;
 one = two = three = "";

However, this kind of thing (especially the multiple assignments) would be frowned upon by most Java developers, who would consider it the opposite of "visually simple".

Reset all the items in a form

foreach (Control field in container.Controls)
            {
                if (field is TextBox)
                    ((TextBox)field).Clear();
                else if (field is ComboBox)
                    ((ComboBox)field).SelectedIndex=0;
                else
                    dgView.DataSource = null;
                    ClearAllText(field);
            }

How do I set up DNS for an apex domain (no www) pointing to a Heroku app?

To point your apex/root/naked domain at a Heroku-hosted application, you'll need to use a DNS provider who supports CNAME-like records (often referred to as ALIAS or ANAME records). Currently Heroku recommends:

Whichever of those you choose, your record will look like the following:

Record: ALIAS or ANAME

Name: empty or @

Target: example.com.herokudns.com.

That's all you need.


However, it's not good for SEO to have both the www version and non-www version resolve. One should point to the other as the canonical URL. How you decide to do that depends on if you're using HTTPS or not. And if you're not, you probably should be as Heroku now handles SSL certificates for you automatically and for free for all applications running on paid dynos.

If you're not using HTTPS, you can just set up a 301 Redirect record with most DNS providers pointing name www to http://example.com.

If you are using HTTPS, you'll most likely need to handle the redirection at the application level. If you want to know why, check out these short and long explanations but basically since your DNS provider or other URL forwarding service doesn't have, and shouldn't have, your SSL certificate and private key, they can't respond to HTTPS requests for your domain.

To handle the redirects at the application level, you'll need to:

  • Add both your apex and www host names to the Heroku application (heroku domains:add example.com and heroku domains:add www.example.com)
  • Set up your SSL certificates
  • Point your apex domain record at Heroku using an ALIAS or ANAME record as described above
  • Add a CNAME record with name www pointing to www.example.com.herokudns.com.
  • And then in your application, 301 redirect any www requests to the non-www URL (here's an example of how to do it in Django)
  • Also in your application, you should probably redirect any HTTP requests to HTTPS (for example, in Django set SECURE_SSL_REDIRECT to True)

Check out this post from DNSimple for more.

Is there a “not in” operator in JavaScript for checking object properties?

Two quick possibilities:

if(!('foo' in myObj)) { ... }

or

if(myObj['foo'] === undefined) { ... }

Uncaught ReferenceError: $ is not defined

You are calling the ready function before the jQuery JavaScript is included. Reference jQuery first.

How do I iterate over an NSArray?

Do this :-

for (id object in array) 
{
        // statement
}

Is there a way to make Firefox ignore invalid ssl-certificates?

I ran into this issue when trying to get to one of my companies intranet sites. Here is the solution I used:

  1. enter about:config into the firefox address bar and agree to continue.
  2. search for the preference named security.ssl.enable_ocsp_stapling.
  3. double-click this item to change its value to false.

This will lower your security as you will be able to view sites with invalid certs. Firefox will still prompt you that the cert is invalid and you have the choice to proceed forward, so it was worth the risk for me.

Entitlements file do not match those specified in your provisioning profile.(0xE8008016)

In XCode 7.3 I encountered the same question, I 've made the mistake because: Name in (info.plist -->Bundle identifier) is not the same as (target-->build settings -->packaging-->Product bundle identifier). Just make the same, that solved the problem.

How to check if an element of a list is a list (in Python)?

Use isinstance:

if isinstance(e, list):

If you want to check that an object is a list or a tuple, pass several classes to isinstance:

if isinstance(e, (list, tuple)):

How to format DateTime to 24 hours time?

Use upper-case HH for 24h format:

String s = curr.ToString("HH:mm");

See DateTime.ToString Method.

How to display images from a folder using php - PHP

You had a mistake on the statement below. Use . not ,

echo '<img src="', $dir, '/', $file, '" alt="', $file, $

to

echo '<img src="'. $dir. '/'. $file. '" alt="'. $file. $

and

echo 'Directory \'', $dir, '\' not found!';

to

echo 'Directory \''. $dir. '\' not found!';

Override default Spring-Boot application.properties settings in Junit Test

You can also use meta-annotations to externalize the configuration. For example:

@RunWith(SpringJUnit4ClassRunner.class)
@DefaultTestAnnotations
public class ExampleApplicationTests { 
   ...
}

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@SpringApplicationConfiguration(classes = ExampleApplication.class)
@TestPropertySource(locations="classpath:test.properties")
public @interface DefaultTestAnnotations { }

Display/Print one column from a DataFrame of Series in Pandas

Not sure what you are really after but if you want to print exactly what you have you can do:

Option 1

print(df['Item'].to_csv(index=False))

Sweet
Candy
Chocolate

Option 2

for v in df['Item']:
    print(v)

Sweet
Candy
Chocolate

jQuery Combobox/select autocomplete?

[edit] The lovely chosen jQuery plugin has been bought to my attention, looks like a great alternative to me.

Or if you just want to use jQuery autocomplete, I've extended the combobox example to support defaults and remove the tooltips to give what I think is more expected behaviour. Try it out.

(function ($) {
    $.widget("ui.combobox", {
        _create: function () {
            var input,
              that = this,
              wasOpen = false,
              select = this.element.hide(),
              selected = select.children(":selected"),
              defaultValue = selected.text() || "",
              wrapper = this.wrapper = $("<span>")
                .addClass("ui-combobox")
                .insertAfter(select);

            function removeIfInvalid(element) {
                var value = $(element).val(),
                  matcher = new RegExp("^" + $.ui.autocomplete.escapeRegex(value) + "$", "i"),
                  valid = false;
                select.children("option").each(function () {
                    if ($(this).text().match(matcher)) {
                        this.selected = valid = true;
                        return false;
                    }
                });

                if (!valid) {
                    // remove invalid value, as it didn't match anything
                    $(element).val(defaultValue);
                    select.val(defaultValue);
                    input.data("ui-autocomplete").term = "";
                }
            }

            input = $("<input>")
              .appendTo(wrapper)
              .val(defaultValue)
              .attr("title", "")
              .addClass("ui-state-default ui-combobox-input")
              .width(select.width())
              .autocomplete({
                  delay: 0,
                  minLength: 0,
                  autoFocus: true,
                  source: function (request, response) {
                      var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
                      response(select.children("option").map(function () {
                          var text = $(this).text();
                          if (this.value && (!request.term || matcher.test(text)))
                              return {
                                  label: text.replace(
                                    new RegExp(
                                      "(?![^&;]+;)(?!<[^<>]*)(" +
                                      $.ui.autocomplete.escapeRegex(request.term) +
                                      ")(?![^<>]*>)(?![^&;]+;)", "gi"
                                    ), "<strong>$1</strong>"),
                                  value: text,
                                  option: this
                              };
                      }));
                  },
                  select: function (event, ui) {
                      ui.item.option.selected = true;
                      that._trigger("selected", event, {
                          item: ui.item.option
                      });
                  },
                  change: function (event, ui) {
                      if (!ui.item) {
                          removeIfInvalid(this);
                      }
                  }
              })
              .addClass("ui-widget ui-widget-content ui-corner-left");

            input.data("ui-autocomplete")._renderItem = function (ul, item) {
                return $("<li>")
                  .append("<a>" + item.label + "</a>")
                  .appendTo(ul);
            };

            $("<a>")
              .attr("tabIndex", -1)
              .appendTo(wrapper)
              .button({
                  icons: {
                      primary: "ui-icon-triangle-1-s"
                  },
                  text: false
              })
              .removeClass("ui-corner-all")
              .addClass("ui-corner-right ui-combobox-toggle")
              .mousedown(function () {
                  wasOpen = input.autocomplete("widget").is(":visible");
              })
              .click(function () {
                  input.focus();

                  // close if already visible
                  if (wasOpen) {
                      return;
                  }

                  // pass empty string as value to search for, displaying all results
                  input.autocomplete("search", "");
              });
        },

        _destroy: function () {
            this.wrapper.remove();
            this.element.show();
        }
    });
})(jQuery);

How to get week number in Python?

isocalendar() returns incorrect year and weeknumber values for some dates:

Python 2.7.3 (default, Feb 27 2014, 19:58:35) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import datetime as dt
>>> myDateTime = dt.datetime.strptime("20141229T000000.000Z",'%Y%m%dT%H%M%S.%fZ')
>>> yr,weekNumber,weekDay = myDateTime.isocalendar()
>>> print "Year is " + str(yr) + ", weekNumber is " + str(weekNumber)
Year is 2015, weekNumber is 1

Compare with Mark Ransom's approach:

>>> yr = myDateTime.year
>>> weekNumber = ((myDateTime - dt.datetime(yr,1,1)).days/7) + 1
>>> print "Year is " + str(yr) + ", weekNumber is " + str(weekNumber)
Year is 2014, weekNumber is 52

Fastest JavaScript summation

Or you could do it the evil way.

var a = [1,2,3,4,5,6,7,8,9];

sum = eval(a.join("+"));

;)

How to configure logging to syslog in Python?

Piecing things together from here and other places, this is what I came up with that works on unbuntu 12.04 and centOS6

Create an file in /etc/rsyslog.d/ that ends in .conf and add the following text

local6.*        /var/log/my-logfile

Restart rsyslog, reloading did NOT seem to work for the new log files. Maybe it only reloads existing conf files?

sudo restart rsyslog

Then you can use this test program to make sure it actually works.

import logging, sys
from logging import config

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'verbose': {
            'format': '%(levelname)s %(module)s P%(process)d T%(thread)d %(message)s'
            },
        },
    'handlers': {
        'stdout': {
            'class': 'logging.StreamHandler',
            'stream': sys.stdout,
            'formatter': 'verbose',
            },
        'sys-logger6': {
            'class': 'logging.handlers.SysLogHandler',
            'address': '/dev/log',
            'facility': "local6",
            'formatter': 'verbose',
            },
        },
    'loggers': {
        'my-logger': {
            'handlers': ['sys-logger6','stdout'],
            'level': logging.DEBUG,
            'propagate': True,
            },
        }
    }

config.dictConfig(LOGGING)


logger = logging.getLogger("my-logger")

logger.debug("Debug")
logger.info("Info")
logger.warn("Warn")
logger.error("Error")
logger.critical("Critical")

Why is "1000000000000000 in range(1000000000000001)" so fast in Python 3?

Use the source, Luke!

In CPython, range(...).__contains__ (a method wrapper) will eventually delegate to a simple calculation which checks if the value can possibly be in the range. The reason for the speed here is we're using mathematical reasoning about the bounds, rather than a direct iteration of the range object. To explain the logic used:

  1. Check that the number is between start and stop, and
  2. Check that the stride value doesn't "step over" our number.

For example, 994 is in range(4, 1000, 2) because:

  1. 4 <= 994 < 1000, and
  2. (994 - 4) % 2 == 0.

The full C code is included below, which is a bit more verbose because of memory management and reference counting details, but the basic idea is there:

static int
range_contains_long(rangeobject *r, PyObject *ob)
{
    int cmp1, cmp2, cmp3;
    PyObject *tmp1 = NULL;
    PyObject *tmp2 = NULL;
    PyObject *zero = NULL;
    int result = -1;

    zero = PyLong_FromLong(0);
    if (zero == NULL) /* MemoryError in int(0) */
        goto end;

    /* Check if the value can possibly be in the range. */

    cmp1 = PyObject_RichCompareBool(r->step, zero, Py_GT);
    if (cmp1 == -1)
        goto end;
    if (cmp1 == 1) { /* positive steps: start <= ob < stop */
        cmp2 = PyObject_RichCompareBool(r->start, ob, Py_LE);
        cmp3 = PyObject_RichCompareBool(ob, r->stop, Py_LT);
    }
    else { /* negative steps: stop < ob <= start */
        cmp2 = PyObject_RichCompareBool(ob, r->start, Py_LE);
        cmp3 = PyObject_RichCompareBool(r->stop, ob, Py_LT);
    }

    if (cmp2 == -1 || cmp3 == -1) /* TypeError */
        goto end;
    if (cmp2 == 0 || cmp3 == 0) { /* ob outside of range */
        result = 0;
        goto end;
    }

    /* Check that the stride does not invalidate ob's membership. */
    tmp1 = PyNumber_Subtract(ob, r->start);
    if (tmp1 == NULL)
        goto end;
    tmp2 = PyNumber_Remainder(tmp1, r->step);
    if (tmp2 == NULL)
        goto end;
    /* result = ((int(ob) - start) % step) == 0 */
    result = PyObject_RichCompareBool(tmp2, zero, Py_EQ);
  end:
    Py_XDECREF(tmp1);
    Py_XDECREF(tmp2);
    Py_XDECREF(zero);
    return result;
}

static int
range_contains(rangeobject *r, PyObject *ob)
{
    if (PyLong_CheckExact(ob) || PyBool_Check(ob))
        return range_contains_long(r, ob);

    return (int)_PySequence_IterSearch((PyObject*)r, ob,
                                       PY_ITERSEARCH_CONTAINS);
}

The "meat" of the idea is mentioned in the line:

/* result = ((int(ob) - start) % step) == 0 */ 

As a final note - look at the range_contains function at the bottom of the code snippet. If the exact type check fails then we don't use the clever algorithm described, instead falling back to a dumb iteration search of the range using _PySequence_IterSearch! You can check this behaviour in the interpreter (I'm using v3.5.0 here):

>>> x, r = 1000000000000000, range(1000000000000001)
>>> class MyInt(int):
...     pass
... 
>>> x_ = MyInt(x)
>>> x in r  # calculates immediately :) 
True
>>> x_ in r  # iterates for ages.. :( 
^\Quit (core dumped)

How to use the switch statement in R functions?

I hope this example helps. You ca use the curly braces to make sure you've got everything enclosed in the switcher changer guy (sorry don't know the technical term but the term that precedes the = sign that changes what happens). I think of switch as a more controlled bunch of if () {} else {} statements.

Each time the switch function is the same but the command we supply changes.

do.this <- "T1"

switch(do.this,
    T1={X <- t(mtcars)
        colSums(mtcars)%*%X
    },
    T2={X <- colMeans(mtcars)
        outer(X, X)
    },
    stop("Enter something that switches me!")
)
#########################################################
do.this <- "T2"

switch(do.this,
    T1={X <- t(mtcars)
        colSums(mtcars)%*%X
    },
    T2={X <- colMeans(mtcars)
        outer(X, X)
    },
    stop("Enter something that switches me!")
)
########################################################
do.this <- "T3"

switch(do.this,
    T1={X <- t(mtcars)
        colSums(mtcars)%*%X
    },
    T2={X <- colMeans(mtcars)
        outer(X, X)
    },
    stop("Enter something that switches me!")
)

Here it is inside a function:

FUN <- function(df, do.this){
    switch(do.this,
        T1={X <- t(df)
            P <- colSums(df)%*%X
        },
        T2={X <- colMeans(df)
            P <- outer(X, X)
        },
        stop("Enter something that switches me!")
    )
    return(P)
}

FUN(mtcars, "T1")
FUN(mtcars, "T2")
FUN(mtcars, "T3")

Jquery Validate custom error message location

HTML

<form ... id ="GoogleMapsApiKeyForm">
    ...
    <input name="GoogleMapsAPIKey" type="text" class="form-control" placeholder="Enter Google maps API key" />
    ....
    <span class="text-danger" id="GoogleMapsAPIKey-errorMsg"></span>'
    ...
    <button type="submit" class="btn btn-primary">Save</button>
</form>

Javascript

$(function () {
    $("#GoogleMapsApiKeyForm").validate({
      rules: {
          GoogleMapsAPIKey: {
              required: true
          }
        },
        messages: {
            GoogleMapsAPIKey: 'Google maps api key is required',
        },
        errorPlacement: function (error, element) {
            if (element.attr("name") == "GoogleMapsAPIKey")
                $("#GoogleMapsAPIKey-errorMsg").html(error);
        },
        submitHandler: function (form) {
           // form.submit(); //if you need Ajax submit follow for rest of code below
        }
    });

    //If you want to use ajax
    $("#GoogleMapsApiKeyForm").submit(function (e) {
        e.preventDefault();
        if (!$("#GoogleMapsApiKeyForm").valid())
            return;

       //Put your ajax call here
    });
});

Pyinstaller setting icons don't change

That's error of a module in pyinstaller. The stuff would be sth like this, right:

File "c:\users\p-stu\appdata\local\programs\python\python38-32\lib\site-packages\PyInstaller\utils\win32\icon.py", line 234, in CopyIcons
    except win32api.error as W32E:
AttrubuteError: module 'win32ctypes.pywin32.win32api' has no attribute 'error'

Best practices for API versioning?

This is a good and a tricky question. The topic of URI design is at the same time the most prominent part of a REST API and, therefore, a potentially long-term commitment towards the users of that API.

Since evolution of an application and, to a lesser extent, its API is a fact of life and that it's even similar to the evolution of a seemingly complex product like a programming language, the URI design should have less natural constraints and it should be preserved over time. The longer the application's and API's lifespan, the greater the commitment to the users of the application and API.

On the other hand, another fact of life is that it is hard to foresee all the resources and their aspects that would be consumed through the API. Luckily, it is not necessary to design the entire API which will be used until Apocalypse. It is sufficient to correctly define all the resource end-points and the addressing scheme of every resource and resource instance.

Over time you may need to add new resources and new attributes to each particular resource, but the method that API users follow to access a particular resources should not change once a resource addressing scheme becomes public and therefore final.

This method applies to HTTP verb semantics (e.g. PUT should always update/replace) and HTTP status codes that are supported in earlier API versions (they should continue to work so that API clients that have worked without human intervention should be able to continue to work like that).

Furthermore, since embedding of API version into the URI would disrupt the concept of hypermedia as the engine of application state (stated in Roy T. Fieldings PhD dissertation) by having a resource address/URI that would change over time, I would conclude that API versions should not be kept in resource URIs for a long time meaning that resource URIs that API users can depend on should be permalinks.

Sure, it is possible to embed API version in base URI but only for reasonable and restricted uses like debugging a API client that works with the the new API version. Such versioned APIs should be time-limited and available to limited groups of API users (like during closed betas) only. Otherwise, you commit yourself where you shouldn't.

A couple of thoughts regarding maintenance of API versions that have expiration date on them. All programming platforms/languages commonly used to implement web services (Java, .NET, PHP, Perl, Rails, etc.) allow easy binding of web service end-point(s) to a base URI. This way it's easy to gather and keep a collection of files/classes/methods separate across different API versions.

From the API users POV, it's also easier to work with and bind to a particular API version when it's this obvious but only for limited time, i.e. during development.

From the API maintainer's POV, it's easier to maintain different API versions in parallel by using source control systems that predominantly work on files as the smallest unit of (source code) versioning.

However, with API versions clearly visible in URI there's a caveat: one might also object this approach since API history becomes visible/aparent in the URI design and therefore is prone to changes over time which goes against the guidelines of REST. I agree!

The way to go around this reasonable objection, is to implement the latest API version under versionless API base URI. In this case, API client developers can choose to either:

  • develop against the latest one (committing themselves to maintain the application protecting it from eventual API changes that might break their badly designed API client).

  • bind to a specific version of the API (which becomes apparent) but only for a limited time

For example, if API v3.0 is the latest API version, the following two should be aliases (i.e. behave identically to all API requests):

http://shonzilla/api/customers/1234
http://shonzilla/api/v3.0/customers/1234
http://shonzilla/api/v3/customers/1234

In addition, API clients that still try to point to the old API should be informed to use the latest previous API version, if the API version they're using is obsolete or not supported anymore. So accessing any of the obsolete URIs like these:

http://shonzilla/api/v2.2/customers/1234
http://shonzilla/api/v2.0/customers/1234
http://shonzilla/api/v2/customers/1234
http://shonzilla/api/v1.1/customers/1234
http://shonzilla/api/v1/customers/1234

should return any of the 30x HTTP status codes that indicate redirection that are used in conjunction with Location HTTP header that redirects to the appropriate version of resource URI which remain to be this one:

http://shonzilla/api/customers/1234

There are at least two redirection HTTP status codes that are appropriate for API versioning scenarios:

  • 301 Moved permanently indicating that the resource with a requested URI is moved permanently to another URI (which should be a resource instance permalink that does not contain API version info). This status code can be used to indicate an obsolete/unsupported API version, informing API client that a versioned resource URI been replaced by a resource permalink.

  • 302 Found indicating that the requested resource temporarily is located at another location, while requested URI may still supported. This status code may be useful when the version-less URIs are temporarily unavailable and that a request should be repeated using the redirection address (e.g. pointing to the URI with APi version embedded) and we want to tell clients to keep using it (i.e. the permalinks).

  • other scenarios can be found in Redirection 3xx chapter of HTTP 1.1 specification

object==null or null==object?

Because of its commutative property, the only difference between object == null and null == object (the Yoda version) is of cognitive nature: how the code is read and digested by the reader. I don't know the definitive answer though, but I do know I personally prefer comparing the object I'm inspecting to something else, rather than comparing something else to the object I'm inspecting, if that makes any sense. Start with the subject, then the value to compare it to.

In some other languages this comparison style is more useful.

To safe guard against a missing "=" sign in general though, I think writing null == object is a misguided act of defensive programming. The better way around this particular code is by guaranteeing the behavior with a junit test. Remember, the possible mistake of missing an "=" is not dependant on the method's input arguments - you are not dependent on the right use of this API by other people - so a junit test is perfect to safe guard against that instead. Anyway you will want to write junit tests to verify the behavior; a missing "=" naturally falls within scope.

Div 100% height works on Firefox but not in IE

You might have to put one or both of:

html { height:100%; }

or

body { height:100%; }

EDIT: Whoops, didn't notice they were floated. You just need to float the container.

Calling a class method raises a TypeError in Python

You never created an instance.

You've defined average as an instance method, thus, in order to use average you need to create an instance first.

How to get the selected value from RadioButtonList?

string radioListValue = RadioButtonList.Text;

Take a list of numbers and return the average

You want to iterate through the list, sum all the numbers, and then divide the sum by the number of elements in the list. You can use a for loop to accomplish this.

average = 0
sum = 0    
for n in numbers:
    sum = sum + n
average = sum / len(numbers)

The for loop looks at each element in the list, and then adds it to the current sum. You then divide by the length of the list (or the number of elements in the list) to find the average.

I would recommend googling a python reference to find out how to use common programming concepts like loops and conditionals so that you feel comfortable when starting out. There are lots of great resources online that you could look up.

Good luck!

How to negate specific word in regex?

Extracted from this comment by bkDJ:

^(?!bar$).*

The nice property of this solution is that it's possible to clearly negate (exclude) multiple words:

^(?!bar$|foo$|banana$).*

What is the difference between an annotated and unannotated tag?

TL;DR

The difference between the commands is that one provides you with a tag message while the other doesn't. An annotated tag has a message that can be displayed with git-show(1), while a tag without annotations is just a named pointer to a commit.

More About Lightweight Tags

According to the documentation: "To create a lightweight tag, don’t supply any of the -a, -s, or -m options, just provide a tag name". There are also some different options to write a message on annotated tags:

  • When you use git tag <tagname>, Git will create a tag at the current revision but will not prompt you for an annotation. It will be tagged without a message (this is a lightweight tag).
  • When you use git tag -a <tagname>, Git will prompt you for an annotation unless you have also used the -m flag to provide a message.
  • When you use git tag -a -m <msg> <tagname>, Git will tag the commit and annotate it with the provided message.
  • When you use git tag -m <msg> <tagname>, Git will behave as if you passed the -a flag for annotation and use the provided message.

Basically, it just amounts to whether you want the tag to have an annotation and some other information associated with it or not.

How to iterate over a JSONObject?

I made a small recursive function that goes through the entire json object and saves the key path and its value.

// My stored keys and values from the json object
HashMap<String,String> myKeyValues = new HashMap<String,String>();

// Used for constructing the path to the key in the json object
Stack<String> key_path = new Stack<String>();

// Recursive function that goes through a json object and stores 
// its key and values in the hashmap 
private void loadJson(JSONObject json){
    Iterator<?> json_keys = json.keys();

    while( json_keys.hasNext() ){
        String json_key = (String)json_keys.next();

        try{
            key_path.push(json_key);
            loadJson(json.getJSONObject(json_key));
       }catch (JSONException e){
           // Build the path to the key
           String key = "";
           for(String sub_key: key_path){
               key += sub_key+".";
           }
           key = key.substring(0,key.length()-1);

           System.out.println(key+": "+json.getString(json_key));
           key_path.pop();
           myKeyValues.put(key, json.getString(json_key));
        }
    }
    if(key_path.size() > 0){
        key_path.pop();
    }
}

How to display a gif fullscreen for a webpage background?

if you're happy using it as a background image and CSS3 then background-size: cover; would do the trick

SELECT query with CASE condition and SUM()

Use an "Or"

Select SUM(CAmount) as PaymentAmount 
from TableOrderPayment 
where (CPaymentType='Check' Or CPaymentType='Cash')
   and CDate <= case CPaymentType When 'Check' Then SYSDATETIME() else CDate End
   and CStatus='" & "Active" & "'"

or an "IN"

Select SUM(CAmount) as PaymentAmount 
from TableOrderPayment 
where CPaymentType IN ('Check', 'Cash')
   and CDate <= case CPaymentType When 'Check' Then SYSDATETIME() else CDate End
   and CStatus='" & "Active" & "'"

Disable future dates in jQuery UI Datepicker

Try This:

$('#datepicker').datepicker({
    endDate: new Date()
});

It will disable the future date.

How to write super-fast file-streaming code in C#?

Have you considered using the CCR since you are writing to separate files you can do everything in parallel (read and write) and the CCR makes it very easy to do this.

static void Main(string[] args)
    {
        Dispatcher dp = new Dispatcher();
        DispatcherQueue dq = new DispatcherQueue("DQ", dp);

        Port<long> offsetPort = new Port<long>();

        Arbiter.Activate(dq, Arbiter.Receive<long>(true, offsetPort,
            new Handler<long>(Split)));

        FileStream fs = File.Open(file_path, FileMode.Open);
        long size = fs.Length;
        fs.Dispose();

        for (long i = 0; i < size; i += split_size)
        {
            offsetPort.Post(i);
        }
    }

    private static void Split(long offset)
    {
        FileStream reader = new FileStream(file_path, FileMode.Open, 
            FileAccess.Read);
        reader.Seek(offset, SeekOrigin.Begin);
        long toRead = 0;
        if (offset + split_size <= reader.Length)
            toRead = split_size;
        else
            toRead = reader.Length - offset;

        byte[] buff = new byte[toRead];
        reader.Read(buff, 0, (int)toRead);
        reader.Dispose();
        File.WriteAllBytes("c:\\out" + offset + ".txt", buff);
    }

This code posts offsets to a CCR port which causes a Thread to be created to execute the code in the Split method. This causes you to open the file multiple times but gets rid of the need for synchronization. You can make it more memory efficient but you'll have to sacrifice speed.

How to find out the server IP address (using JavaScript) that the browser is connected to?

Not sure how to get the IP address specifically, but the location object provides part of the answer.

e.g. these variables might be helpful:

  • self.location.host - Sets or retrieves the hostname and port number of the location
  • self.location.hostname - Sets or retrieves the host name part of the location or URL.

How to get a path to the desktop for current user in C#?

// Environment.GetFolderPath
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); // Current User's Application Data
Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData); // All User's Application Data
Environment.GetFolderPath(Environment.SpecialFolder.CommonProgramFiles); // Program Files
Environment.GetFolderPath(Environment.SpecialFolder.Cookies); // Internet Cookie
Environment.GetFolderPath(Environment.SpecialFolder.Desktop); // Logical Desktop
Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory); // Physical Desktop
Environment.GetFolderPath(Environment.SpecialFolder.Favorites); // Favorites
Environment.GetFolderPath(Environment.SpecialFolder.History); // Internet History
Environment.GetFolderPath(Environment.SpecialFolder.InternetCache); // Internet Cache
Environment.GetFolderPath(Environment.SpecialFolder.MyComputer); // "My Computer" Folder
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); // "My Documents" Folder
Environment.GetFolderPath(Environment.SpecialFolder.MyMusic); // "My Music" Folder
Environment.GetFolderPath(Environment.SpecialFolder.MyPictures); // "My Pictures" Folder
Environment.GetFolderPath(Environment.SpecialFolder.Personal); // "My Document" Folder
Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles); // Program files Folder
Environment.GetFolderPath(Environment.SpecialFolder.Programs); // Programs Folder
Environment.GetFolderPath(Environment.SpecialFolder.Recent); // Recent Folder
Environment.GetFolderPath(Environment.SpecialFolder.SendTo); // "Sent to" Folder
Environment.GetFolderPath(Environment.SpecialFolder.StartMenu); // Start Menu
Environment.GetFolderPath(Environment.SpecialFolder.Startup); // Startup
Environment.GetFolderPath(Environment.SpecialFolder.System); // System Folder
Environment.GetFolderPath(Environment.SpecialFolder.Templates); // Document Templates

How can I split a text file using PowerShell?

I found this question while trying to split multiple contacts in a single vCard VCF file to separate files. Here's what I did based on Lee's code. I had to look up how to create a new StreamReader object and changed null to $null.

$reader = new-object System.IO.StreamReader("C:\Contacts.vcf")
$count = 1
$filename = "C:\Contacts\{0}.vcf" -f ($count) 

while(($line = $reader.ReadLine()) -ne $null)
{
    Add-Content -path $fileName -value $line

    if($line -eq "END:VCARD")
    {
        ++$count
        $filename = "C:\Contacts\{0}.vcf" -f ($count)
    }
}

$reader.Close()

How to convert DATE to UNIX TIMESTAMP in shell script on MacOS

man date on OSX has this example

date -j -f "%a %b %d %T %Z %Y" "`date`" "+%s"

Which I think does what you want.

You can use this for a specific date

date -j -f "%a %b %d %T %Z %Y" "Tue Sep 28 19:35:15 EDT 2010" "+%s"

Or use whatever format you want.

Python NoneType object is not callable (beginner)

You want to pass the function object hi to your loop() function, not the result of a call to hi() (which is None since hi() doesn't return anything).

So try this:

>>> loop(hi, 5)
hi
hi
hi
hi
hi

Perhaps this will help you understand better:

>>> print hi()
hi
None
>>> print hi
<function hi at 0x0000000002422648>

extract part of a string using bash/cut/split

To extract joebloggs from this string in bash using parameter expansion without any extra processes...

MYVAR="/var/cpanel/users/joebloggs:DNS9=domain.com" 

NAME=${MYVAR%:*}  # retain the part before the colon
NAME=${NAME##*/}  # retain the part after the last slash
echo $NAME

Doesn't depend on joebloggs being at a particular depth in the path.


Summary

An overview of a few parameter expansion modes, for reference...

${MYVAR#pattern}     # delete shortest match of pattern from the beginning
${MYVAR##pattern}    # delete longest match of pattern from the beginning
${MYVAR%pattern}     # delete shortest match of pattern from the end
${MYVAR%%pattern}    # delete longest match of pattern from the end

So # means match from the beginning (think of a comment line) and % means from the end. One instance means shortest and two instances means longest.

You can get substrings based on position using numbers:

${MYVAR:3}   # Remove the first three chars (leaving 4..end)
${MYVAR::3}  # Return the first three characters
${MYVAR:3:5} # The next five characters after removing the first 3 (chars 4-9)

You can also replace particular strings or patterns using:

${MYVAR/search/replace}

The pattern is in the same format as file-name matching, so * (any characters) is common, often followed by a particular symbol like / or .

Examples:

Given a variable like

MYVAR="users/joebloggs/domain.com" 

Remove the path leaving file name (all characters up to a slash):

echo ${MYVAR##*/}
domain.com

Remove the file name, leaving the path (delete shortest match after last /):

echo ${MYVAR%/*}
users/joebloggs

Get just the file extension (remove all before last period):

echo ${MYVAR##*.}
com

NOTE: To do two operations, you can't combine them, but have to assign to an intermediate variable. So to get the file name without path or extension:

NAME=${MYVAR##*/}      # remove part before last slash
echo ${NAME%.*}        # from the new var remove the part after the last period
domain

How to recover Git objects damaged by hard disk failure?

In some previous backups, your bad objects may have been packed in different files or may be loose objects yet. So your objects may be recovered.

It seems there are a few bad objects in your database. So you could do it the manual way.

Because of git hash-object, git mktree and git commit-tree do not write the objects because they are found in the pack, then start doing this:

mv .git/objects/pack/* <somewhere>
for i in <somewhere>/*.pack; do
  git unpack-objects -r < $i
done
rm <somewhere>/*

(Your packs are moved out from the repository, and unpacked again in it; only the good objects are now in the database)

You can do:

git cat-file -t 6c8cae4994b5ec7891ccb1527d30634997a978ee

and check the type of the object.

If the type is blob: retrieve the contents of the file from previous backups (with git show or git cat-file or git unpack-file; then you may git hash-object -w to rewrite the object in your current repository.

If the type is tree: you could use git ls-tree to recover the tree from previous backups; then git mktree to write it again in your current repository.

If the type is commit: the same with git show, git cat-file and git commit-tree.

Of course, I would backup your original working copy before starting this process.

Also, take a look at How to Recover Corrupted Blob Object.

JQuery Validate input file type

Simply use the .rules('add') method immediately after creating the element...

var filenumber = 1;
$("#AddFile").click(function () { //User clicks button #AddFile

    // create the new input element
    $('<li><input type="file" name="FileUpload' + filenumber + '" id="FileUpload' + filenumber + '" /> <a href="#" class="RemoveFileUpload">Remove</a></li>').prependTo("#FileUploader");

    // declare the rule on this newly created input field        
    $('#FileUpload' + filenumber).rules('add', {
        required: true,  // <- with this you would not need 'required' attribute on input
        accept: "image/jpeg, image/pjpeg"
    });

    filenumber++; // increment counter for next time

    return false;
});
  • You'll still need to use .validate() to initialize the plugin within a DOM ready handler.

  • You'll still need to declare rules for your static elements using .validate(). Whatever input elements that are part of the form when the page loads... declare their rules within .validate().

  • You don't need to use .each(), when you're only targeting ONE element with the jQuery selector attached to .rules().

  • You don't need the required attribute on your input element when you're declaring the required rule using .validate() or .rules('add'). For whatever reason, if you still want the HTML5 attribute, at least use a proper format like required="required".

Working DEMO: http://jsfiddle.net/8dAU8/5/

What is difference between XML Schema and DTD?

XML DTD

The purpose of a DTD is to define the structure of an XML document. It defines the structure with a list of legal elements:

<!ATTLIST contact type CDATA #IMPLIED>
<!ELEMENT address1 ( #PCDATA)>
<!ELEMENT city ( #PCDATA)>
<!ELEMENT state ( #PCDATA)>
<!ELEMENT zip ( #PCDATA)>

XML Schema

XML Schema enables schema authors to specify that element quantity’s data must be numeric or, even more specifically, an integer. In the following example I used string:

<xs:element name="note">
<xs:complexType>
  <xs:sequence>
    <xs:element name="address1" type="xs:string"/>
    <xs:element name="city" type="xs:string"/>
    <xs:element name="state" type="xs:string"/>
    <xs:element name="zip" type="xs:string"/>
  </xs:sequence>
</xs:complexType>

Node.js EACCES error when listening on most ports

For me, it was just an error in the .env file. I deleted the comma at the end of each line and it was solved.

Before:

HOST=127.0.0.1,

After:

HOST=127.0.0.1

Can a html button perform a POST request?

This can be done with an input element of a type "submit". This will appear as a button to the user and clicking the button will send the form.

<form action="" method="post">
    <input type="submit" name="upvote" value="Upvote" />
</form>

Android: ProgressDialog.show() crashes with getApplicationContext

This is a common problem. Use this instead of getApplicationContext() That should solve your problem

Documentation for using JavaScript code inside a PDF file

The comprehensive place for Acrobat JavaScript documentation is the Acrobat SDK, which can be downloaded from the Adobe website. In the Documentation section, you will find all the material needed to work with Acrobat JavaScript.

To complete the documentation you may in addition get the specification of the JavaScript Core. My book of choice for that is "JavaScript, the Definitive Guide" by David Flanagan, published by O'Reilly.

Easiest way to use SVG in Android?

You can use Coil library to load svg. Just add these lines in build.gradle

// ... Coil (https://github.com/coil-kt/coil)
implementation("io.coil-kt:coil:0.12.0")
implementation("io.coil-kt:coil-svg:0.12.0")

Then Add an extension function

fun AppCompatImageView.loadSvg(url: String) {
    val imageLoader = ImageLoader.Builder(this.context)
        .componentRegistry { add(SvgDecoder([email protected])) }
        .build()

    val request = ImageRequest.Builder(this.context)
        .crossfade(true)
        .crossfade(500)
        .data(url)
        .target(this)
        .build()

    imageLoader.enqueue(request)
}

Then call this method in your activity or fragment

your_image_view.loadSvg("your_file_name.svg")

Changing route doesn't scroll to top in the new page

After an hour or two of trying every combination of ui-view autoscroll=true, $stateChangeStart, $locationChangeStart, $uiViewScrollProvider.useAnchorScroll(), $provide('$uiViewScroll', ...), and many others, I couldn't get scroll-to-top-on-new-page to work as expected.

This was ultimately what worked for me. It captures pushState and replaceState and only updates scroll position when new pages are navigated to (back/forward button retain their scroll positions):

.run(function($anchorScroll, $window) {
  // hack to scroll to top when navigating to new URLS but not back/forward
  var wrap = function(method) {
    var orig = $window.window.history[method];
    $window.window.history[method] = function() {
      var retval = orig.apply(this, Array.prototype.slice.call(arguments));
      $anchorScroll();
      return retval;
    };
  };
  wrap('pushState');
  wrap('replaceState');
})

gradle build fails on lint task

As for me, it's a bad and quick solution for your problem :

android { 
  lintOptions { 
    abortOnError false 
  }
}

Better solution is solving problem in your code, because lint tool checks your Android project source files for potential bugs and optimization improvements for correctness, security, performance, usability, accessibility, and internationalization.

This problem most frequently occurring when:

  • Layout include unresolved symbols or missing some attribute
  • Other structural issues, such as use of deprecated elements or API calls that are not supported by the target API versions, might lead to code failing to run correctly.

Find your bugs by Inspect Code in Android Studio: Improve Your Code with Lint

How to select bottom most rows?

You can use the OFFSET FETCH clause.

SELECT COUNT(1) FROM COHORT; --Number of results to expect

SELECT * FROM COHORT 
ORDER BY ID
OFFSET 900 ROWS --Assuming you expect 1000 rows
FETCH NEXT 100 ROWS ONLY;

(This is for Microsoft SQL Server)

Official documentation: https://www.sqlservertutorial.net/sql-server-basics/sql-server-offset-fetch/

Servlet for serving static content

I did this by extending the tomcat DefaultServlet (src) and overriding the getRelativePath() method.

package com.example;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import org.apache.catalina.servlets.DefaultServlet;

public class StaticServlet extends DefaultServlet
{
   protected String pathPrefix = "/static";

   public void init(ServletConfig config) throws ServletException
   {
      super.init(config);

      if (config.getInitParameter("pathPrefix") != null)
      {
         pathPrefix = config.getInitParameter("pathPrefix");
      }
   }

   protected String getRelativePath(HttpServletRequest req)
   {
      return pathPrefix + super.getRelativePath(req);
   }
}

... And here are my servlet mappings

<servlet>
    <servlet-name>StaticServlet</servlet-name>
    <servlet-class>com.example.StaticServlet</servlet-class>
    <init-param>
        <param-name>pathPrefix</param-name>
        <param-value>/static</param-value>
    </init-param>       
</servlet>

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

Upload files from Java client to a HTTP server

Here is how you could do it with Java 11's java.net.http package:

    var fileA = new File("a.pdf");
    var fileB = new File("b.pdf");

    var mimeMultipartData = MimeMultipartData.newBuilder()
            .withCharset(StandardCharsets.UTF_8)
            .addFile("file1", fileA.toPath(), Files.probeContentType(fileA.toPath()))
            .addFile("file2", fileB.toPath(), Files.probeContentType(fileB.toPath()))
            .build();

    var request = HttpRequest.newBuilder()
            .header("Content-Type", mimeMultipartData.getContentType())
            .POST(mimeMultipartData.getBodyPublisher())
            .uri(URI.create("http://somehost/upload"))
            .build();

    var httpClient = HttpClient.newBuilder().build();
    var response = httpClient.send(request, BodyHandlers.ofString());

With the following MimeMultipartData:

public class MimeMultipartData {

    public static class Builder {

        private String boundary;
        private Charset charset = StandardCharsets.UTF_8;
        private List<MimedFile> files = new ArrayList<MimedFile>();
        private Map<String, String> texts = new LinkedHashMap<>();

        private Builder() {
            this.boundary = new BigInteger(128, new Random()).toString();
        }

        public Builder withCharset(Charset charset) {
            this.charset = charset;
            return this;
        }

        public Builder withBoundary(String boundary) {
            this.boundary = boundary;
            return this;
        }

        public Builder addFile(String name, Path path, String mimeType) {
            this.files.add(new MimedFile(name, path, mimeType));
            return this;
        }

        public Builder addText(String name, String text) {
            texts.put(name, text);
            return this;
        }

        public MimeMultipartData build() throws IOException {
            MimeMultipartData mimeMultipartData = new MimeMultipartData();
            mimeMultipartData.boundary = boundary;

            var newline = "\r\n".getBytes(charset);
            var byteArrayOutputStream = new ByteArrayOutputStream();
            for (var f : files) {
                byteArrayOutputStream.write(("--" + boundary).getBytes(charset)); 
                byteArrayOutputStream.write(newline);
                byteArrayOutputStream.write(("Content-Disposition: form-data; name=\"" + f.name + "\"; filename=\"" + f.path.getFileName() + "\"").getBytes(charset));
                byteArrayOutputStream.write(newline);
                byteArrayOutputStream.write(("Content-Type: " + f.mimeType).getBytes(charset));
                byteArrayOutputStream.write(newline);
                byteArrayOutputStream.write(newline);
                byteArrayOutputStream.write(Files.readAllBytes(f.path));
                byteArrayOutputStream.write(newline);
            }
            for (var entry: texts.entrySet()) {
                byteArrayOutputStream.write(("--" + boundary).getBytes(charset));
                byteArrayOutputStream.write(newline);
                byteArrayOutputStream.write(("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"").getBytes(charset));
                byteArrayOutputStream.write(newline);
                byteArrayOutputStream.write(newline);
                byteArrayOutputStream.write(entry.getValue().getBytes(charset));
                byteArrayOutputStream.write(newline);
            }
            byteArrayOutputStream.write(("--" + boundary + "--").getBytes(charset));

            mimeMultipartData.bodyPublisher = BodyPublishers.ofByteArray(byteArrayOutputStream.toByteArray());
            return mimeMultipartData;
        }

        public class MimedFile {

            public final String name;
            public final Path path;
            public final String mimeType;

            public MimedFile(String name, Path path, String mimeType) {
                this.name = name;
                this.path = path;
                this.mimeType = mimeType;
            }
        }
    }

    private String boundary;
    private BodyPublisher bodyPublisher;

    private MimeMultipartData() {
    }

    public static Builder newBuilder() {
        return new Builder();
    }

    public BodyPublisher getBodyPublisher() throws IOException {
        return bodyPublisher;
    }

    public String getContentType() {
        return "multipart/form-data; boundary=" + boundary;
    }

}

best way to create object

Decide if you need an immutable object or not.

If you put public properties in your class, the state of every instance can be changed at every time in your code. So your class could be like this:

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
    public Person(){}
    public Person(string name, int age)
    {
        Name = name;
        Age = age;
    }
    //Other properties, methods, events...
}

In that case, having a Person(string name, int age) constructor is not so useful.

The second option is to implement an immutable type. For example:

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

    public Person(string name, int age)
    {
        Name = name;
        Age = age;
    }
    //Other properties, methods, events...
}

Now you have a constructor that sets the state for the instance, once, at creation time. Note that now setters for properties are private, so you can't change the state after your object is instantiated.

A best practice is to define classes as immutable every time if possible. To understand advantages of immutable classes I suggest you read this article.

Adding days to a date in Python

Here is a function of getting from now + specified days

import datetime

def get_date(dateFormat="%d-%m-%Y", addDays=0):

    timeNow = datetime.datetime.now()
    if (addDays!=0):
        anotherTime = timeNow + datetime.timedelta(days=addDays)
    else:
        anotherTime = timeNow

    return anotherTime.strftime(dateFormat)

Usage:

addDays = 3 #days
output_format = '%d-%m-%Y'
output = get_date(output_format, addDays)
print output

macro run-time error '9': subscript out of range

"Subscript out of range" indicates that you've tried to access an element from a collection that doesn't exist. Is there a "Sheet1" in your workbook? If not, you'll need to change that to the name of the worksheet you want to protect.

Must declare the scalar variable

If someone else comes across this question while no solution here made my sql file working, here's what my mistake was:

I have been exporting the contents of my database via the 'Generate Script' command of Microsofts' Server Management Studio and then doing some operations afterwards while inserting the generated data in another instance.

Due to the generated export, there have been a bunch of "GO" statements in the sql file.

What I didn't know was that variables declared at the top of a file aren't accessible as far as a GO statement is executed. Therefore I had to remove the GO statements in my sql file and the error "Must declare the scalar variable xy" was gone!

trying to align html button at the center of the my page

You can center a button without using text-align on the parent div by simple using margin:auto; display:block;

For example:

HTML

<div>
  <button>Submit</button>
</div>

CSS

button {
  margin:auto;
  display:block;
}

SEE IT IN ACTION: CodePen

If list index exists, do X

You can try something like this

list = ["a", "b", "C", "d", "e", "f", "r"]

for i in range(0, len(list), 2):
    print list[i]
    if len(list) % 2 == 1 and  i == len(list)-1:
        break
    print list[i+1];

Android: making a fullscreen application

Simply declare in styles.xml

  <style name="AppTheme.Fullscreen" parent="AppTheme">
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
    <item name="android:windowFullscreen">true</item>
  </style>

Then use in menifest.xml

    <activity
        android:name=".activities.Splash"
        android:theme="@style/AppTheme.Fullscreen">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

Chill Pill :)

How to implement a ViewPager with different Fragments / Layouts

This is also fine:

<android.support.v4.view.ViewPager
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/viewPager"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    />
public class MainActivity extends FragmentActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_activity);

        ViewPager pager = (ViewPager) findViewById(R.id.viewPager);
        pager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));

    }
}


public class FragmentTab1 extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragmenttab1, container, false);
        return rootView;
    }
}

class MyPagerAdapter extends FragmentPagerAdapter{

    public MyPagerAdapter(FragmentManager fragmentManager){
        super(fragmentManager);

    }
    @Override
    public android.support.v4.app.Fragment getItem(int position) {
        switch(position){
            case 0:
                FragmentTab1 fm =   new FragmentTab1();
                return fm;
            case 1: return new FragmentTab2();
            case 2: return new FragmentTab3();
        }
        return null;
    }

    @Override
    public int getCount() {
        return 3;
    }
}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="@string/Fragment1" />

</RelativeLayout>

Oracle sqlldr TRAILING NULLCOLS required, but why?

I had similar issue when I had plenty of extra records in csv file with empty values. If I open csv file in notepad then empty lines looks like this: ,,,, ,,,, ,,,, ,,,,

You can not see those if open in Excel. Please check in Notepad and delete those records

Why are primes important in cryptography?

Because nobody knows a fast algorithm to factorize an integer into its prime factors. Yet, it is very easy to check if a set of prime factors multiply to a certain integer.

syntax error: unexpected token <

I suspect you're getting text/html encoding in response to your request so I believe the issue is:

dataType : 'json',

try changing it to

dataType : 'html',

From http://api.jquery.com/jQuery.get/:

dataType Type: String The type of data expected from the server. Default: Intelligent Guess (xml, json, script, or html).

Find and replace string values in list

words = [w.replace('[br]', '<br />') for w in words]

These are called List Comprehensions.

Server.MapPath - Physical path given, virtual path expected

var files = Directory.GetFiles(@"E:\ftproot\sales");

Seeding the random number generator in Javascript

In PHP, there is function srand(seed) which generate fixed random value for particular seed. But, in JS, there is no such inbuilt function.

However, we can write simple and short function.

Step 1: Choose some Seed (Fix Number).
var seed = 100;
Number should be Positive Integer and greater than 1, further explanation in Step 2.

Step 2: Perform Math.sin() function on Seed, it will give sin value of that number. Store this value in variable x.

var x; 
x = Math.sin(seed); // Will Return Fractional Value between -1 & 1 (ex. 0.4059..)

sin() method returns a Fractional value between -1 and 1.
And we don't need Negative value, therefore, in first step choose number greater than 1.

Step 3: Returned Value is a Fractional value between -1 and 1.
So mulitply this value with 10 for making it more than 1.

x = x * 10; // 10 for Single Digit Number

Step 4: Multiply the value with 10 for additional digits

x = x * 10; // Will Give value between 10 and 99 OR
x = x * 100; // Will Give value between 100 and 999

Multiply as per requirement of digits.

The result will be in decimal.

Step 5: Remove value after Decimal Point by Math's Round (Math.round()) Method.

x = Math.round(x); // This will give Integer Value.

Step 6: Turn Negative Values into Positive (if any) by Math.abs method

x = Math.abs(x); // Convert Negative Values into Positive(if any)

Explanation End.

Final Code

var seed = 111; // Any Number greater than 1
var digit = 10 // 1 => single digit, 10 => 2 Digits, 100 => 3 Digits and so. (Multiple of 10) 

var x; // Initialize the Value to store the result
x = Math.sin(seed); // Perform Mathematical Sin Method on Seed.
x = x * 10; // Convert that number into integer
x = x * digit; // Number of Digits to be included
x = Math.round(x); // Remove Decimals
x = Math.abs(x); // Convert Negative Number into Positive

Clean and Optimized Functional Code

function random_seed(seed, digit = 1) {
    var x = Math.abs(Math.round(Math.sin(seed++) * 10 * digit));
    return x;
}

Then Call this function using
random_seed(any_number, number_of_digits)
any_number is must and should be greater than 1.
number_of_digits is optional parameter and if nothing passed, 1 Digit will return.

random_seed(555); // 1 Digit
random_seed(234, 1); // 1 Digit
random_seed(7895656, 1000); // 4 Digit

Pass a PHP array to a JavaScript function

Use JSON.

In the following example $php_variable can be any PHP variable.

<script type="text/javascript">
    var obj = <?php echo json_encode($php_variable); ?>;
</script>

In your code, you could use like the following:

drawChart(600/50, <?php echo json_encode($day); ?>, ...)

In cases where you need to parse out an object from JSON-string (like in an AJAX request), the safe way is to use JSON.parse(..) like the below:

var s = "<JSON-String>";
var obj = JSON.parse(s);

In Git, what is the difference between origin/master vs origin master?

origin/master is the remote master branch

Usually after doing a git fetch origin to bring all the changes from the server, you would do a git rebase origin/master, to rebase your changes and move the branch to the latest index. Here, origin/master is referring to the remote branch, because you are basically telling GIT to rebase the origin/master branch onto the current branch.

You would use origin master when pushing, for example. git push origin master is simply telling GIT to push to the remote repository the local master branch.

Convert List<T> to ObservableCollection<T> in WP7

Apparently, your project is targeting Windows Phone 7.0. Unfortunately the constructors that accept IEnumerable<T> or List<T> are not available in WP 7.0, only the parameterless constructor. The other constructors are available in Silverlight 4 and above and WP 7.1 and above, just not in WP 7.0.

I guess your only option is to take your list and add the items into a new instance of an ObservableCollection individually as there are no readily available methods to add them in bulk. Though that's not to stop you from putting this into an extension or static method yourself.

var list = new List<SomeType> { /* ... */ };
var oc = new ObservableCollection<SomeType>();
foreach (var item in list)
    oc.Add(item);

But don't do this if you don't have to, if you're targeting framework that provides the overloads, then use them.

Git pull command from different user

This command will help to pull from the repository as the different user:

git pull https://[email protected]/projectfolder/projectname.git master

It is a workaround, when you are using same machine that someone else used before you, and had saved credentials

How to grep, excluding some patterns?

grep -n 'loom' ~/projects/**/trunk/src/**/*.@(h|cpp) | grep -v 'gloom'

How to style CSS role

Accessing it like this should work: #content[role="main"]

NSRange to Range<String.Index>

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {

       let strString = ((textField.text)! as NSString).stringByReplacingCharactersInRange(range, withString: string)

 }

java.security.cert.CertificateException: Certificates does not conform to algorithm constraints

this is more likely happening because somewhere along your certificate chain you have a certificate, more likely an old root, which is still signed with the MD2RSA algorythm.

You need to locate it into your certificate store and delete it.

Then get back to your certification authority and ask them for then new root.

It will more likely be the same root with the same validity period but it has been recertified with SHA1RSA.

Hope this help.

Count number of times a date occurs and make a graph out of it

The simplest is to do a PivotChart. Select your array of dates (with a header) and create a new Pivot Chart (Insert / PivotChart / Ok) Then on the field list window, drag and drop the date column in the Axis list first and then in the value list first.

Step 1:

Step1

Step 2:

Step2

MAC addresses in JavaScript

Nope. The reason ActiveX can do it is because ActiveX is a little application that runs on the client's machine.

I would imagine access to such information via JavaScript would be a security vulnerability.

Use of String.Format in JavaScript?

Here is an solution that allows both prototype and function options.

// --------------------------------------------------------------------
// Add prototype for 'String.format' which is c# equivalent
//
// String.format("{0} i{2}a night{1}", "This", "mare", "s ");
// "{0} i{2}a night{1}".format("This", "mare", "s ");
// --------------------------------------------------------------------

if(!String.format)
    String.format = function(){
        for (var i = 0, args = arguments; i < args.length - 1; i++)
            args[0] = args[0].replace("{" + i + "}", args[i + 1]);
        return args[0];
    };
if(!String.prototype.format && String.format)
    String.prototype.format = function(){
        var args = Array.prototype.slice.call(arguments).reverse();
        args.push(this);
        return String.format.apply(this, args.reverse())
    };

Enjoy.

How do I open a new window using jQuery?

Those are by no means the same. The first will simply send you to whatever URL you have assigned to window.location.href (in the same window you're currently in). The second makes a GET AJAX request.

Try this page: http://www.codebelt.com/jquery/open-new-browser-window-with-jquery-custom-size/

It gives a great example on how to open a new window*.

If you wish to use raw javascript then this is what you're looking for:

window.open(URL,name,specs,replace)

As seen in http://www.w3schools.com/jsref/met_win_open.asp

Java: Replace all ' in a string with \'

You could also try using something like StringEscapeUtils to make your life even easier: http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringEscapeUtils.html

s = StringEscapeUtils.escapeJava(s);

Nginx not running with no error message

Check the daemon option in nginx.conf file. It has to be ON. Or you can simply rip out this line from config file. This option is fully described here http://nginx.org/en/docs/ngx_core_module.html#daemon

How to call a stored procedure from Java and JPA

This answer might be helpful if you have entity manager

I had a stored procedure to create next number and on server side I have seam framework.

Client side

 Object on = entityManager.createNativeQuery("EXEC getNextNmber").executeUpdate();
        log.info("New order id: " + on.toString());

Database Side (SQL server) I have stored procedure named getNextNmber

A Space between Inline-Block List Items

I had the same problem, when I used a inline-block on my menu I had the space between each "li" I found a simple solution, I don't remember where I found it, anyway here is what I did.

<li><a href="index.html" title="home" class="active">Home</a></li><!---->
<li><a href="news.html" title="news">News</a></li><!---->
<li><a href="about.html" title="about">About Us</a></li><!---->
<li><a href="contact.html" title="contact">Contact Us</a></li>

You add a comment sign between each end of, and start of : "li" Then the horizontal space disappear. Hope that answer to the question Thanks

regular expression for DOT

Use String.Replace() if you just want to replace the dots from string. Alternative would be to use Pattern-Matcher with StringBuilder, this gives you more flexibility as you can find groups that are between dots. If using the latter, i would recommend that you ignore empty entries with "\\.+".

public static int count(String str, String regex) {
    int i = 0;
    Pattern p = Pattern.compile(regex);
    Matcher m = p.matcher(str);
    while (m.find()) {
        m.group();
        i++;
    }
    return i;
}

public static void main(String[] args) {
    int i = 0, j = 0, k = 0;
    String str = "-.-..-...-.-.--..-k....k...k..k.k-.-";

    // this will just remove dots
    System.out.println(str.replaceAll("\\.", ""));
    // this will just remove sequences of ".." dots
    System.out.println(str.replaceAll("\\.{2}", ""));
    // this will just remove sequences of dots, and gets
    // multiple of dots as 1
    System.out.println(str.replaceAll("\\.+", ""));

    /* for this to be more obvious, consider following */
    System.out.println(count(str, "\\."));
    System.out.println(count(str, "\\.{2}"));
    System.out.println(count(str, "\\.+"));
}

The output will be:

--------kkkkk--
-.--.-.-.---kk.kk.k-.-
--------kkkkk--
21
7
11

printf %f with only 2 numbers after the decimal point?

Use this:

printf ("%.2f", 3.14159);

Easy way to use variables of enum types as string in C?

There's no built-in solution. The easiest way is with an array of char* where the enum's int value indexes to a string containing the descriptive name of that enum. If you have a sparse enum (one that doesn't start at 0 or has gaps in the numbering) where some of the int mappings are high enough to make an array-based mapping impractical then you could use a hash table instead.

operator << must take exactly one argument

If you define operator<< as a member function it will have a different decomposed syntax than if you used a non-member operator<<. A non-member operator<< is a binary operator, where a member operator<< is a unary operator.

// Declarations
struct MyObj;
std::ostream& operator<<(std::ostream& os, const MyObj& myObj);

struct MyObj
{
    // This is a member unary-operator, hence one argument
    MyObj& operator<<(std::ostream& os) { os << *this; return *this; }

    int value = 8;
};

// This is a non-member binary-operator, 2 arguments
std::ostream& operator<<(std::ostream& os, const MyObj& myObj)
{
    return os << myObj.value;
}

So.... how do you really call them? Operators are odd in some ways, I'll challenge you to write the operator<<(...) syntax in your head to make things make sense.

MyObj mo;

// Calling the unary operator
mo << std::cout;

// which decomposes to...
mo.operator<<(std::cout);

Or you could attempt to call the non-member binary operator:

MyObj mo;

// Calling the binary operator
std::cout << mo;

// which decomposes to...
operator<<(std::cout, mo);

You have no obligation to make these operators behave intuitively when you make them into member functions, you could define operator<<(int) to left shift some member variable if you wanted to, understand that people may be a bit caught off guard, no matter how many comments you may write.

Almost lastly, there may be times where both decompositions for an operator call are valid, you may get into trouble here and we'll defer that conversation.

Lastly, note how odd it might be to write a unary member operator that is supposed to look like a binary operator (as you can make member operators virtual..... also attempting to not devolve and run down this path....)

struct MyObj
{
    // Note that we now return the ostream
    std::ostream& operator<<(std::ostream& os) { os << *this; return os; }

    int value = 8;
};

This syntax will irritate many coders now....

MyObj mo;

mo << std::cout << "Words words words";

// this decomposes to...
mo.operator<<(std::cout) << "Words words words";

// ... or even further ...
operator<<(mo.operator<<(std::cout), "Words words words");

Note how the cout is the second argument in the chain here.... odd right?

Trim last character from a string

In .NET 5 / C# 8:

You can write the code marked as the answer as:

public static class StringExtensions
{
    public static string TrimLastCharacters(this string str) => string.IsNullOrEmpty(str) ? str : str.TrimEnd(str[^1]);
}

However, as mentioned in the answer, this removes all occurrences of that last character. If you only want to remove the last character you should instead do:

    public static string RemoveLastCharacter(this string str) => string.IsNullOrEmpty(str) ? str : str[..^1];

A quick explanation for the new stuff in C# 8:

The ^ is called the "index from end operator". The .. is called the "range operator". ^1 is a shortcut for arr.length - 1. You can get all items after the first character of an array with arr[1..] or all items before the last with arr[..^1]. These are just a few quick examples. For more information, see https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8, "Indices and ranges" section.

How do I pass command line arguments to a Node.js program?

To normalize the arguments like a regular javascript function would receive, I do this in my node.js shell scripts:

var args = process.argv.slice(2);

Note that the first arg is usually the path to nodejs, and the second arg is the location of the script you're executing.

How do I ignore files in a directory in Git?

It would be the former. Go by extensions as well instead of folder structure.

I.e. my example C# development ignore file:

#OS junk files
[Tt]humbs.db
*.DS_Store

#Visual Studio files
*.[Oo]bj
*.user
*.aps
*.pch
*.vspscc
*.vssscc
*_i.c
*_p.c
*.ncb
*.suo
*.tlb
*.tlh
*.bak
*.[Cc]ache
*.ilk
*.log
*.lib
*.sbr
*.sdf
ipch/
obj/
[Bb]in
[Dd]ebug*/
[Rr]elease*/
Ankh.NoLoad

#Tooling
_ReSharper*/
*.resharper
[Tt]est[Rr]esult*

#Project files
[Bb]uild/

#Subversion files
.svn

# Office Temp Files
~$*

Update

I thought I'd provide an update from the comments below. Although not directly answering the OP's question, see the following for more examples of .gitignore syntax.

Community wiki (constantly being updated):

.gitignore for Visual Studio Projects and Solutions

More examples with specific language use can be found here (thanks to Chris McKnight's comment):

https://github.com/github/gitignore

Cast a Double Variable to Decimal

Convert.ToDecimal(the double you are trying to convert);

Fast and simple String encrypt/decrypt in JAVA

If you are using Android then you can use android.util.Base64 class.

Encode:

passwd = Base64.encodeToString( passwd.getBytes(), Base64.DEFAULT );

Decode:

passwd = new String( Base64.decode( passwd, Base64.DEFAULT ) );

A simple and fast single line solution.

change Oracle user account status from EXPIRE(GRACE) to OPEN

Step-1 Need to find user details by using below query

SQL> select username, account_status from dba_users where username='BOB';

USERNAME                       ACCOUNT_STATUS
------------------------------ --------------------------------
BOB                            EXPIRED

Step-2 Get users password by using below query.

SQL>SELECT 'ALTER USER '|| name ||' IDENTIFIED BY VALUES '''|| spare4 ||';'|| password ||''';' FROM sys.user$ WHERE name='BOB';

ALTER USER BOB IDENTIFIED BY VALUES 'S:9BDD17811E21EFEDFB1403AAB1DD86AB481E;T:602E36430C0D8DF7E1E453;2F9933095143F432';

Step -3 Run Above alter query

SQL> ALTER USER BOB IDENTIFIED BY VALUES 'S:9BDD17811E21EFEDFB1403AAB1DD86AB481E;T:602E36430C0D8DF7E1E453;2F9933095143F432';
User altered.

Step-4 :Check users account status

SQL> select username, account_status from dba_users where username='BOB';
USERNAME                       ACCOUNT_STATUS
------------------------------ --------------------------------
BOB                            OPEN

Call a PHP function after onClick HTML event

You don't need javascript for doing so. Just delete the onClick and write the php Admin.php file like this:

<!-- HTML STARTS-->
<?php
//If all the required fields are filled
if (!empty($GET_['fullname'])&&!empty($GET_['email'])&&!empty($GET_['name']))
{
function addNewContact()
    {
    $new = '{';
    $new .= '"fullname":"' . $_GET['fullname'] . '",';
    $new .= '"email":"' . $_GET['email'] . '",';
    $new .= '"phone":"' . $_GET['phone'] . '",';
    $new .= '}';
    return $new;
    }

function saveContact()
    {
    $datafile = fopen ("data/data.json", "a+");
    if(!$datafile){
        echo "<script>alert('Data not existed!')</script>";
        } 
    else{
        $contact_list = $contact_list . addNewContact();
        file_put_contents("data/data.json", $contact_list);
        }
    fclose($datafile);
    }

// Call the function saveContact()
saveContact();
echo "Thank you for joining us";
}
else //If the form is not submited or not all the required fields are filled

{ ?>

<form>
    <fieldset>
        <legend>Add New Contact</legend>
        <input type="text" name="fullname" placeholder="First name and last name" required /> <br />
        <input type="email" name="email" placeholder="[email protected]" required /> <br />
        <input type="text" name="phone" placeholder="Personal phone number: mobile, home phone etc." required /> <br />
        <input type="submit" name="submit" class="button" value="Add Contact"/>
        <input type="button" name="cancel" class="button" value="Reset" />
    </fieldset>
</form>
<?php }
?>
<!-- HTML ENDS -->

Thought I don't like the PHP bit. Do you REALLY want to create a file for contacts? It'd be MUCH better to use a mysql database. Also, adding some breaks to that file would be nice too...

Other thought, IE doesn't support placeholder.

How do I speed up the gwt compiler?

  • Split your application into multiple modules or entry points and re-compile then only when needed.
  • Analyse your application using the trunk version - which provides the Story of your compile. This may or may not be relevant to the 1.6 compiler but it can indicate what's going on.

Passing enum or object through an intent (the best solution)

Don't use enums. Reason #78 to not use enums. :) Use integers, which can easily be remoted through Bundle and Parcelable.

Getting the first index of an object

You could do something like this:

var object = {
    foo:{a:'first'},
    bar:{},
    baz:{}
}


function getAttributeByIndex(obj, index){
  var i = 0;
  for (var attr in obj){
    if (index === i){
      return obj[attr];
    }
    i++;
  }
  return null;
}


var first = getAttributeByIndex(object, 0); // returns the value of the
                                            // first (0 index) attribute
                                            // of the object ( {a:'first'} )

C++: constructor initializer for arrays

There is no way. You need a default constructor for array members and it will be called, afterwards, you can do any initialization you want in the constructor.

Should a retrieval method return 'null' or throw an exception when it can't produce the return value?

Or return an Option

An option is basically a container class that forces the client to handle booth cases. Scala has this concept, look up it's API.

Then you have methods like T getOrElse(T valueIfNull) on this object thet either return the found object, or an allternative the client specifieces.

Detect page change on DataTable

This works form me to scroll to when I click next

$('#myTable').on('draw.dt', function() {
    document.body.scrollTop = 0;
    document.documentElement.scrollTop = 0;
});

how to check for special characters php

preg_match('/'.preg_quote('^\'£$%^&*()}{@#~?><,@|-=-_+-¬', '/').'/', $string);

How to automatically indent source code?

In Visual Studio 2010

Ctrl +k +d indent the complete page.

Ctrl +k +f indent the selected Code.

For more help visit : http://msdn.microsoft.com/en-us/library/da5kh0wa.aspx

every thing is there.

How can I see all the "special" characters permissible in a varchar or char field in SQL Server?

i think that special characters are # and @ only... query will list both.

DECLARE  @str VARCHAR(50) 
SET @str = '[azAB09ram#reddy@wer45' + CHAR(5) + 'a~b$' 
SELECT DISTINCT poschar 
FROM   MASTER..spt_values S 
       CROSS APPLY (SELECT SUBSTRING(@str,NUMBER,1) AS poschar) t 
WHERE  NUMBER > 0 
       AND NUMBER <= LEN(@str) 
       AND NOT (ASCII(t.poschar) BETWEEN 65 AND 90 
                 OR ASCII(t.poschar) BETWEEN 97 AND 122 
                 OR ASCII(t.poschar) BETWEEN 48 AND 57) 

Alternative to iFrames with HTML5

If you want to do this and control the server from which the base page or content is being served, you can use Cross Origin Resource Sharing (http://www.w3.org/TR/access-control/) to allow client-side JavaScript to load data into a <div> via XMLHttpRequest():

// I safely ignore IE 6 and 5 (!) users
// because I do not wish to proliferate
// broken software that will hurt other
// users of the internet, which is what
// you're doing when you write anything
// for old version of IE (5/6)
xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
  if(xhr.readyState == 4 && xhr.status == 200) {
    document.getElementById('displayDiv').innerHTML = xhr.responseText;
  }
};
xhr.open('GET', 'http://api.google.com/thing?request=data', true);
xhr.send();

Now for the lynchpin of this whole operation, you need to write code for your server that will give clients the Access-Control-Allow-Origin header, specifying which domains you want the client-side code to be able to access via XMLHttpRequest(). The following is an example of PHP code you can include at the top of your page in order to send these headers to clients:

<?php
  header('Access-Control-Allow-Origin: http://api.google.com');
  header('Access-Control-Allow-Origin: http://some.example.com');
?>

Running shell command and capturing the output

This is way easier, but only works on Unix (including Cygwin) and Python2.7.

import commands
print commands.getstatusoutput('wc -l file')

It returns a tuple with the (return_value, output).

For a solution that works in both Python2 and Python3, use the subprocess module instead:

from subprocess import Popen, PIPE
output = Popen(["date"],stdout=PIPE)
response = output.communicate()
print response

Delete specified file from document directory

    NSError *error;
    [[NSFileManager defaultManager] removeItemAtPath:new_file_path_str error:&error];
    if (error){
        NSLog(@"%@", error);
    }

How to avoid Sql Query Timeout

Although there is clearly some kind of network instability or something interfering with your connection (15 minutes is possible that you could be crossing a NAT boundary or something in your network is dropping the session), I would think you want such a simple?) query to return well within any anticipated timeoue (like 1s).

I would talk to your DBA and get an index created on the underlying tables on MemberType, Status. If there isn't a single underlying table or these are more complex and created by the view or UDF, and you are running SQL Server 2005 or above, have him consider indexing the view (basically materializing the view in an indexed fashion).

Automatically open default email client and pre-populate content

Try this: It will open the default mail directly.

<a href="mailto:[email protected]"><img src="ICON2.png"></a>

Why am I getting a NoClassDefFoundError in Java?

NoClassDefFoundError can also occur when a static initializer tries to load a resource bundle that is not available in runtime, for example a properties file that the affected class tries to load from the META-INF directory, but isn’t there. If you don’t catch NoClassDefFoundError, sometimes you won’t be able to see the full stack trace; to overcome this you can temporarily use a catch clause for Throwable:

try {
    // Statement(s) that cause(s) the affected class to be loaded
} catch (Throwable t) {
    Logger.getLogger("<logger-name>").info("Loading my class went wrong", t);
}

Default Xmxsize in Java 8 (max heap size)

As of 8, May, 2019:

JVM heap size depends on system configuration, meaning:

a) client jvm vs server jvm

b) 32bit vs 64bit.

Links:

1) updation from J2SE5.0: https://docs.oracle.com/javase/6/docs/technotes/guides/vm/gc-ergonomics.html
2) brief answer: https://docs.oracle.com/javase/8/docs/technotes/guides/vm/gctuning/ergonomics.html
3) detailed answer: https://docs.oracle.com/javase/8/docs/technotes/guides/vm/gctuning/parallel.html#default_heap_size
4) client vs server: https://www.javacodegeeks.com/2011/07/jvm-options-client-vs-server.html

Summary: (Its tough to understand from the above links. So summarizing them here)

1) Default maximum heap size for Client jvm is 256mb (there is an exception, read from links above).

2) Default maximum heap size for Server jvm of 32bit is 1gb and of 64 bit is 32gb (again there are exceptions here too. Kindly read that from the links).

So default maximum jvm heap size is: 256mb or 1gb or 32gb depending on VM, above.

How to upgrade rubygems

Or:

gem update `gem outdated | cut -d ' ' -f 1`

How to create hyperlink to call phone number on mobile devices?

Dashes (-) have no significance other than making the number more readable, so you might as well include them.

Since we never know where our website visitors are coming from, we need to make phone numbers callable from anywhere in the world. For this reason the + sign is always necessary. The + sign is automatically converted by your mobile carrier to your international dialing prefix, also known as "exit code". This code varies by region, country, and sometimes a single country can use multiple codes, depending on the carrier. Fortunately, when it is a local call, dialing it with the international format will still work.

Using your example number, when calling from China, people would need to dial:

00-1-555-555-1212

And from Russia, they would dial

810-1-555-555-1212

The + sign solves this issue by allowing you to omit the international dialing prefix.

After the international dialing prefix comes the country code(pdf), followed by the geographic code (area code), finally the local phone number.

Therefore either of the last two of your examples would work, but my recommendation is to use this format for readability:

<a href="tel:+1-555-555-1212">+1-555-555-1212</a>

Note: For numbers that contain a trunk prefix different from the country code (e.g. if you write it locally with brackets around a 0), you need to omit it because the number must be in international format.

Angular HttpClient "Http failure during parsing"

You should also check you JSON (not in DevTools, but on a backend). Angular HttpClient having a hard time parsing JSON with \0 characters and DevTools will ignore then, so it's quite hard to spot in Chrome.

Based on this article

Merging dictionaries in C#

I would do it like this:

dictionaryFrom.ToList().ForEach(x => dictionaryTo.Add(x.Key, x.Value));

Simple and easy. According to this blog post it's even faster than most loops as its underlying implementation accesses elements by index rather than enumerator (see this answer).

It will of course throw an exception if there are duplicates, so you'll have to check before merging.

Smooth scroll without the use of jQuery

You can also use Scroll Behaviour Property. for example add below line to your css

_x000D_
_x000D_
html{_x000D_
scroll-behavior:smooth;_x000D_
}
_x000D_
_x000D_
_x000D_

and this will result a native smooth scrolling feature . Read More about Scroll behavior

Android EditText Hint

I don't know whether a direct way of doing this is available or not, but you surely there is a workaround via code: listen for onFocus event of EditText, and as soon it gains focus, set the hint to be nothing with something like editText.setHint(""):

This may not be exactly what you have to do, but it may be something like this-

myEditText.setOnFocusListener(new OnFocusListener(){
  public void onFocus(){
    myEditText.setHint("");
  }
});

When and how should I use a ThreadLocal variable?

The ThreadLocal class in Java enables you to create variables that can only be read and written by the same thread. Thus, even if two threads are executing the same code, and the code has a reference to a ThreadLocal variable, then the two threads cannot see each other's ThreadLocal variables.

Read more

Select current date by default in ASP.Net Calendar control

Two ways of doing it.

Late binding

<asp:Calendar ID="planning" runat="server" SelectedDate="<%# DateTime.Now %>"></asp:Calendar>

Code behind way (Page_Load solution)

protected void Page_Load(object sender, EventArgs e)
{
    BindCalendar();
}

private void BindCalendar()
{
    planning.SelectedDate = DateTime.Today;
}

Altough, I strongly recommend to do it from a BindMyStuff way. Single entry point easier to debug. But since you seems to know your game, you're all set.

Rails :include vs. :joins

I was recently reading more on difference between :joins and :includes in rails. Here is an explaination of what I understood (with examples :))

Consider this scenario:

  • A User has_many comments and a comment belongs_to a User.

  • The User model has the following attributes: Name(string), Age(integer). The Comment model has the following attributes:Content, user_id. For a comment a user_id can be null.

Joins:

:joins performs a inner join between two tables. Thus

Comment.joins(:user)

#=> <ActiveRecord::Relation [#<Comment id: 1, content: "Hi I am Aaditi.This is my first   comment!", user_id: 1, created_at: "2014-11-12 18:29:24", updated_at: "2014-11-12 18:29:24">, 
     #<Comment id: 2, content: "Hi I am Ankita.This is my first comment!", user_id: 2, created_at: "2014-11-12 18:29:29", updated_at: "2014-11-12 18:29:29">,    
     #<Comment id: 3, content: "Hi I am John.This is my first comment!", user_id: 3, created_at: "2014-11-12 18:30:25", updated_at: "2014-11-12 18:30:25">]>

will fetch all records where user_id (of comments table) is equal to user.id (users table). Thus if you do

Comment.joins(:user).where("comments.user_id is null")

#=> <ActiveRecord::Relation []>

You will get a empty array as shown.

Moreover joins does not load the joined table in memory. Thus if you do

comment_1 = Comment.joins(:user).first

comment_1.user.age
#=>?[1m?[36mUser Load (0.0ms)?[0m  ?[1mSELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT 1?[0m  [["id", 1]]
#=> 24

As you see, comment_1.user.age will fire a database query again in the background to get the results

Includes:

:includes performs a left outer join between the two tables. Thus

Comment.includes(:user)

#=><ActiveRecord::Relation [#<Comment id: 1, content: "Hi I am Aaditi.This is my first comment!", user_id: 1, created_at: "2014-11-12 18:29:24", updated_at: "2014-11-12 18:29:24">,
   #<Comment id: 2, content: "Hi I am Ankita.This is my first comment!", user_id: 2, created_at: "2014-11-12 18:29:29", updated_at: "2014-11-12 18:29:29">,
   #<Comment id: 3, content: "Hi I am John.This is my first comment!", user_id: 3, created_at: "2014-11-12 18:30:25", updated_at: "2014-11-12 18:30:25">,    
   #<Comment id: 4, content: "Hi This is an anonymous comment!", user_id: nil, created_at: "2014-11-12 18:31:02", updated_at: "2014-11-12 18:31:02">]>

will result in a joined table with all the records from comments table. Thus if you do

Comment.includes(:user).where("comment.user_id is null")
#=> #<ActiveRecord::Relation [#<Comment id: 4, content: "Hi This is an anonymous comment!", user_id: nil, created_at: "2014-11-12 18:31:02", updated_at: "2014-11-12 18:31:02">]>

it will fetch records where comments.user_id is nil as shown.

Moreover includes loads both the tables in the memory. Thus if you do

comment_1 = Comment.includes(:user).first

comment_1.user.age
#=> 24

As you can notice comment_1.user.age simply loads the result from memory without firing a database query in the background.

Set Page Title using PHP

Move the data retrieval at the top of the script, and after that use:

<title>Ultan.me - <?php echo htmlspecialchars($title, ENT_QUOTES, 'UTF-8'); ?></title>

How do I get the YouTube video ID from a URL?

This can get video id from any type of youtube links

var url= 'http://youtu.be/0zM3nApSvMg';
var urlsplit= url.split(/^.*(youtu.be\/|v\/|embed\/|watch\?|youtube.com\/user\/[^#]*#([^\/]*?\/)*)\??v?=?([^#\&\?]*).*/);
console.log(urlsplit[3]);

Column calculated from another column?

You can use generated columns from MYSQL 5.7.

Example Usage:

ALTER TABLE tbl_test
ADD COLUMN calc_val INT 
GENERATED ALWAYS AS (((`column1` - 1) * 16) + `column2`) STORED;

VIRTUAL / STORED

  • Virtual: calculated on the fly when a record is read from a table (default)
  • Stored: calculated when a new record is inserted/updated within the table

Simplest way to download and unzip files in Node.js cross-platform?

I was looking forward this for a long time, and found no simple working example, but based on these answers I created the downloadAndUnzip() function.

The usage is quite simple:

downloadAndUnzip('http://your-domain.com/archive.zip', 'yourfile.xml')
    .then(function (data) {
        console.log(data); // unzipped content of yourfile.xml in root of archive.zip
    })
    .catch(function (err) {
        console.error(err);
    });

And here is the declaration:

var AdmZip = require('adm-zip');
var request = require('request');

var downloadAndUnzip = function (url, fileName) {

    /**
     * Download a file
     * 
     * @param url
     */
    var download = function (url) {
        return new Promise(function (resolve, reject) {
            request({
                url: url,
                method: 'GET',
                encoding: null
            }, function (err, response, body) {
                if (err) {
                    return reject(err);
                }
                resolve(body);
            });
        });
    };

    /**
     * Unzip a Buffer
     * 
     * @param buffer
     * @returns {Promise}
     */
    var unzip = function (buffer) {
        return new Promise(function (resolve, reject) {

            var resolved = false;

            var zip = new AdmZip(buffer);
            var zipEntries = zip.getEntries(); // an array of ZipEntry records

            zipEntries.forEach(function (zipEntry) {
                if (zipEntry.entryName == fileName) {
                    resolved = true;
                    resolve(zipEntry.getData().toString('utf8'));
                }
            });

            if (!resolved) {
                reject(new Error('No file found in archive: ' + fileName));
            }
        });
    };


    return download(url)
        .then(unzip);
};

How do you create a dictionary in Java?

This creates dictionary of text (string):

Map<String, String> dictionary = new HashMap<String, String>();

you then use it as a:

dictionary.put("key", "value");
String value = dictionary.get("key");

Works but gives an error you need to keep the constructor class same as the declaration class. I know it inherits from the parent class but, unfortunately it gives an error on runtime.

Map<String, String> dictionary = new Map<String, String>();

This works properly.

How can I truncate a string to the first 20 words in PHP?

Its not my own creation, its a modification of previous posts. credits goes to karim79.

function limit_text($text, $limit) {
    $strings = $text;
      if (strlen($text) > $limit) {
          $words = str_word_count($text, 2);
          $pos = array_keys($words);
          if(sizeof($pos) >$limit)
          {
            $text = substr($text, 0, $pos[$limit]) . '...';
          }
          return $text;
      }
      return $text;
    }

Unable to begin a distributed transaction

If your Destination server is on another cloud or data-center then need to add host-entry of MSDTC service(Destination Server) in your source server.

Try this one if problem doesn't resolved, After enable the MSDTC settings.

How do I use vim registers?

I think the secret guru register is the expression = register. It can be used for creative mappings.

:inoremap  \d The current date <c-r>=system("date")<cr>

You can use it in conjunction with your system as above or get responses from custom VimL functions etc.

or just ad hoc stuff like

<c-r>=35+7<cr>

Call static methods from regular ES6 class methods

If you are planning on doing any kind of inheritance, then I would recommend this.constructor. This simple example should illustrate why:

class ConstructorSuper {
  constructor(n){
    this.n = n;
  }

  static print(n){
    console.log(this.name, n);
  }

  callPrint(){
    this.constructor.print(this.n);
  }
}

class ConstructorSub extends ConstructorSuper {
  constructor(n){
    this.n = n;
  }
}

let test1 = new ConstructorSuper("Hello ConstructorSuper!");
console.log(test1.callPrint());

let test2 = new ConstructorSub("Hello ConstructorSub!");
console.log(test2.callPrint());
  • test1.callPrint() will log ConstructorSuper Hello ConstructorSuper! to the console
  • test2.callPrint() will log ConstructorSub Hello ConstructorSub! to the console

The named class will not deal with inheritance nicely unless you explicitly redefine every function that makes a reference to the named Class. Here is an example:

class NamedSuper {
  constructor(n){
    this.n = n;
  }

  static print(n){
    console.log(NamedSuper.name, n);
  }

  callPrint(){
    NamedSuper.print(this.n);
  }
}

class NamedSub extends NamedSuper {
  constructor(n){
    this.n = n;
  }
}

let test3 = new NamedSuper("Hello NamedSuper!");
console.log(test3.callPrint());

let test4 = new NamedSub("Hello NamedSub!");
console.log(test4.callPrint());
  • test3.callPrint() will log NamedSuper Hello NamedSuper! to the console
  • test4.callPrint() will log NamedSuper Hello NamedSub! to the console

See all the above running in Babel REPL.

You can see from this that test4 still thinks it's in the super class; in this example it might not seem like a huge deal, but if you are trying to reference member functions that have been overridden or new member variables, you'll find yourself in trouble.

Best way to encode text data for XML in Java?

Here's what I found after searching everywhere looking for a solution:

Get the Jsoup library:

<!-- https://mvnrepository.com/artifact/org.jsoup/jsoup -->
<dependency>
    <groupId>org.jsoup</groupId>
    <artifactId>jsoup</artifactId>
    <version>1.12.1</version>
</dependency>

Then:

import org.jsoup.Jsoup
import org.jsoup.nodes.Document
import org.jsoup.nodes.Entities
import org.jsoup.parser.Parser

String xml = '''<?xml version = "1.0"?>
<SOAP-ENV:Envelope
   xmlns:SOAP-ENV = "http://www.w3.org/2001/12/soap-envelope"
   SOAP-ENV:encodingStyle = "http://www.w3.org/2001/12/soap-encoding">

   <SOAP-ENV:Body xmlns:m = "http://www.example.org/quotations">
      <m:GetQuotation>
         <m:QuotationsName> MiscroSoft@G>>gle.com </m:QuotationsName>
      </m:GetQuotation>
   </SOAP-ENV:Body>
</SOAP-ENV:Envelope>'''



Document doc = Jsoup.parse(new ByteArrayInputStream(xml.getBytes("UTF-8")), "UTF-8", "", Parser.xmlParser())
doc.outputSettings().charset("UTF-8")
doc.outputSettings().escapeMode(Entities.EscapeMode.base)

println doc.toString()

Hope this helps someone

TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined raised when starting react app

If you have ejected, this is the proper way to fix this issue:

find this file config/webpackDevServer.config.js and then inside this file find the following line:

app.use(noopServiceWorkerMiddleware());

You should change it to:

app.use(noopServiceWorkerMiddleware('/'));

For me(and probably most of you) the service worker is served at the root of the project. In case it's different for you, you can pass your base path instead.

Is there a way to rollback my last push to Git?

Since you are the only user:

git reset --hard HEAD@{1}
git push -f
git reset --hard HEAD@{1}

( basically, go back one commit, force push to the repo, then go back again - remove the last step if you don't care about the commit )

Without doing any changes to your local repo, you can also do something like:

git push -f origin <sha_of_previous_commit>:master

Generally, in published repos, it is safer to do git revert and then git push

Invalid column name sql error

You should never write code that concatenates SQL and parameters as string - this opens up your code to SQL injection which is a really serious security problem.

Use bind params - for a nice howto see here...

How to subtract date/time in JavaScript?

If you wish to get difference in wall clock time, for local timezone and with day-light saving awareness.


Date.prototype.diffDays = function (date: Date): number {

    var utcThis = Date.UTC(this.getFullYear(), this.getMonth(), this.getDate(), this.getHours(), this.getMinutes(), this.getSeconds(), this.getMilliseconds());
    var utcOther = Date.UTC(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds(), date.getMilliseconds());

    return (utcThis - utcOther) / 86400000;
};

Test


it('diffDays - Czech DST', function () {
    // expect this to parse as local time
    // with Czech calendar DST change happened 2012-03-25 02:00
    var pre = new Date('2012/03/24 03:04:05');
    var post = new Date('2012/03/27 03:04:05');

    // regardless DST, you still wish to see 3 days
    expect(pre.diffDays(post)).toEqual(-3);
});

Diff minutes or seconds is in same fashion.

How do I convert NSMutableArray to NSArray?

NSArray *array = [mutableArray copy];

Copy makes immutable copies. This is quite useful because Apple can make various optimizations. For example sending copy to a immutable array only retains the object and returns self.

If you don't use garbage collection or ARC remember that -copy retains the object.

Copy a file list as text from Windows Explorer

In Windows 7 and later, this will do the trick for you

  • Select the file/files.
  • Hold the shift key and then right-click on the selected file/files.
  • You will see Copy as Path. Click that.
  • Open a Notepad file and paste and you will be good to go.

The menu item Copy as Path is not available in Windows XP.

Convert string into Date type on Python

from datetime import datetime

a = datetime.strptime(f, "%Y-%m-%d")

How to set up googleTest as a shared library on Linux

This answer from askubuntu is what worked for me. Seems simpler than other options an less error-prone, since it uses package libgtest-dev to get the sources and builds from there: https://askubuntu.com/questions/145887/why-no-library-files-installed-for-google-test?answertab=votes#tab-top

Please refer to that answer, but just as a shortcut I provide the steps here as well:

sudo apt-get install -y libgtest-dev
sudo apt-get install -y cmake
cd /usr/src/gtest
sudo cmake .
sudo make
sudo mv libg* /usr/lib/

After that, I could build my project which depends on gtest with no issues.

Data binding to SelectedItem in a WPF Treeview

This can be accomplished in a 'nicer' way using only binding and the GalaSoft MVVM Light library's EventToCommand. In your VM add a command which will be called when the selected item is changed, and initialize the command to perform whatever action is necessary. In this example I used a RelayCommand and will just set the SelectedCluster property.

public class ViewModel
{
    public ViewModel()
    {
        SelectedClusterChanged = new RelayCommand<Cluster>( c => SelectedCluster = c );
    }

    public RelayCommand<Cluster> SelectedClusterChanged { get; private set; } 

    public Cluster SelectedCluster { get; private set; }
}

Then add the EventToCommand behavior in your xaml. This is really easy using blend.

<TreeView
      x:Name="lstClusters"
      ItemsSource="{Binding Path=Model.Clusters}" 
      ItemTemplate="{StaticResource HoofdCLusterTemplate}">
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="SelectedItemChanged">
            <GalaSoft_MvvmLight_Command:EventToCommand Command="{Binding SelectedClusterChanged}" CommandParameter="{Binding ElementName=lstClusters,Path=SelectedValue}"/>
        </i:EventTrigger>
    </i:Interaction.Triggers>
</TreeView>

How can I generate a random number in a certain range?

You can use If Random. For example, this generates a random number between 75 to 100.

final int random = new Random().nextInt(26) + 75;

Most efficient way to convert an HTMLCollection to an Array

I suppose that calling Array.prototype functions on instances of HTMLCollection is a much better option than converting collections to arrays (e.g.,[...collection] or Array.from(collection)), because in the latter case a collection is unnecessarily implicitly iterated and a new array object is created, and this eats up additional resources. Array.prototype iterating functions can be safely called upon objects with consecutive numeric keys starting from [0] and a length property with a valid number value of such keys' quantity (including, e.g., instances of HTMLCollection and FileList), so it's a reliable way. Also, if there is a frequent need in such operations, an empty array [] can be used for quick access to Array.prototype functions; or a shortcut for Array.prototype can be created instead. A runnable example:

_x000D_
_x000D_
const _ = Array.prototype;
const collection = document.getElementById('ol').children;
alert(_.reduce.call(collection, (acc, { textContent }, i) => {
  return acc += `${i+1}) ${textContent}` + '\n';
}, ''));
_x000D_
<ol id="ol">
    <li>foo</li>
    <li>bar</li>
    <li>bat</li>
    <li>baz</li>
</ol>
_x000D_
_x000D_
_x000D_

Difference between iCalendar (.ics) and the vCalendar (.vcs)

You can try VCS to ICS file converter (Java, works with Windows, Mac, Linux etc.). It has the feature of parsing events and todos. You can convert the VCS generated by your Nokia phone, with bluetooth export or via nbuexplorer.

  • Complete support for UTF-8
  • Quoted-printable encoded strings
  • Completely open source code (GPLv3 and Apache 2.0)
  • Standard iCalendar v2.0 output
  • Encodes multiple files at once (only one event per file)
  • Compatible with Android, iOS, Mozilla Lightning/Sunbird, Google Calendar and others
  • Multiplatform

How do I install PyCrypto on Windows?

So I install MinGW and tack that on the install line as the compiler of choice. But then I get the error "RuntimeError: chmod error".

You need to install msys package under MinGW

enter image description here

and add following entries in your PATH env variable.

  • C:\MinGW\bin
  • C:\MinGW\msys\1.0\bin [This is where you will find chmod executable]

Then run your command from normal windows command prompt.

Serialize JavaScript object into JSON string

You can use a named function on the constructor.

MyClass1 = function foo(id, member) {
    this.id = id;
    this.member = member;
}

var myobject = new MyClass1("5678999", "text");

console.log( myobject.constructor );

//function foo(id, member) {
//    this.id = id;
//    this.member = member;
//}

You could use a regex to parse out 'foo' from myobject.constructor and use that to get the name.

How do you detect the clearing of a "search" HTML5 input?

It doesn't seem like you can access this in browser. The search input is a Webkit HTML wrapper for the Cocoa NSSearchField. The cancel button seems to be contained within the browser client code with no external reference available from the wrapper.

Sources:

Looks like you'll have to figure it out through mouse position on click with something like:

$('input[type=search]').bind('click', function(e) {
  var $earch = $(this);
  var offset = $earch.offset();

  if (e.pageX > offset.left + $earch.width() - 16) { // X button 16px wide?
    // your code here
  }
});

Resizing SVG in html?

Open your .svg file with a text editor (it's just XML), and look for something like this at the top:

<svg ... width="50px" height="50px"...

Erase width and height attributes; the defaults are 100%, so it should stretch to whatever the container allows it.

Docker error cannot delete docker container, conflict: unable to remove repository reference

If you want to cleanup docker images and containers

CAUTION: this will flush everything

stop all containers

docker stop $(docker ps -a -q)

remove all containers

docker rm $(docker ps -a -q)

remove all images

docker rmi -f $(docker images -a -q)

Which selector do I need to select an option by its text?

This will also work.

$('#test').find("select option:contains('B')").filter(":selected");