Programs & Examples On #Tinybutstrong

TinyButStrong is a template engine for PHP.

CSS Grid Layout not working in IE11 even with prefixes

The answer has been given by Faisal Khurshid and Michael_B already.
This is just an attempt to make a possible solution more obvious.

For IE11 and below you need to enable grid's older specification in the parent div e.g. body or like here "grid" like so:

.grid-parent{display:-ms-grid;}

then define the amount and width of the columns and rows like e.g. so:

.grid-parent{
  -ms-grid-columns: 1fr 3fr;
  -ms-grid-rows: 4fr;
}

finally you need to explicitly tell the browser where your element (item) should be placed in e.g. like so:

.grid-item-1{
  -ms-grid-column: 1;
  -ms-grid-row: 1;
}

.grid-item-2{
  -ms-grid-column: 2;
  -ms-grid-row: 1;
}

How do I strip all spaces out of a string in PHP?

If you want to remove all whitespace:

$str = preg_replace('/\s+/', '', $str);

See the 5th example on the preg_replace documentation. (Note I originally copied that here.)

Edit: commenters pointed out, and are correct, that str_replace is better than preg_replace if you really just want to remove the space character. The reason to use preg_replace would be to remove all whitespace (including tabs, etc.).

How does Python return multiple values from a function?

From Python Cookbook v.30

def myfun():
    return 1, 2, 3

a, b, c = myfun()

Although it looks like myfun() returns multiple values, a tuple is actually being created. It looks a bit peculiar, but it’s actually the comma that forms a tuple, not the parentheses

So yes, what's going on in Python is an internal transformation from multiple comma separated values to a tuple and vice-versa.

Though there's no equivalent in you can easily create this behaviour using array's or some Collections like Lists:

private static int[] sumAndRest(int x, int y) {
    int[] toReturn = new int[2];

    toReturn[0] = x + y;
    toReturn[1] = x - y;

    return toReturn;

}

Executed in this way:

public static void main(String[] args) {
    int[] results = sumAndRest(10, 5);

    int sum  = results[0];
    int rest = results[1];

    System.out.println("sum = " + sum + "\nrest = " + rest);

}

result:

sum = 15
rest = 5

Visual Studio loading symbols

In my case Visual Studio was looking for 3rd-party PDBs in paths that, on my machine, referenced an optical drive. Without a disc in the tray it took about Windows about ~30 to fail, which in turn slowed down Visual Studio as it tried to load the PDBs from that location. More detail is available in my complete answer here: https://stackoverflow.com/a/17457581/85196

How to insert table values from one database to another database?

Just Do it.....

( It will create same table structure as from table as to table with same data )

 create table toDatabaseName.toTableName as select * from fromDatabaseName.fromTableName;

git reset --hard HEAD leaves untracked files behind

git reset --hard && git clean -dfx

or, zsh provides a 'gpristine' alias:

alias gpristine='git reset --hard && git clean -dfx'

Which is really handy. (warning: The "-x" will also delete 'git ignored' files, so remove this if it is not what you want)

If working on a forked repo, make sure to fetch and reset from the correct repo/branch, for example:

git fetch upstream && git reset --hard upstream/master && git clean -df

Set an environment variable in git bash

A normal variable is set by simply assigning it a value; note that no whitespace is allowed around the =:

HOME=c

An environment variable is a regular variable that has been marked for export to the environment.

export HOME
HOME=c

You can combine the assignment with the export statement.

export HOME=c

How can I get the UUID of my Android phone in an application?

As of API 26, getDeviceId() is deprecated. If you need to get the IMEI of the device, use the following:

 String deviceId = "";
    if (Build.VERSION.SDK_INT >= 26) {
        deviceId = getSystemService(TelephonyManager.class).getImei();
    }else{
        deviceId = getSystemService(TelephonyManager.class).getDeviceId();
    }

Property 'map' does not exist on type 'Observable<Response>'

for all those linux users that are having this problem, check if the rxjs-compat folder is locked. I had this exact same issue and I went in terminal, used the sudo su to give permission to the whole rxjs-compat folder and it was fixed. Thats assuming you imported

import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch'; 

in the project.ts file where the original .map error occurred.

Displaying a webcam feed using OpenCV and Python

As in the opencv-doc you can get video feed from a camera which is connected to your computer by following code.

import numpy as np
import cv2
cap = cv2.VideoCapture(0)
while(True):
    # Capture frame-by-frame
    ret, frame = cap.read()
    # Our operations on the frame come here
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    # Display the resulting frame
    cv2.imshow('frame',gray)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()

You can change cap = cv2.VideoCapture(0) index from 0 to 1 to access the 2nd camera.
Tested in opencv-3.2.0

IOS 7 Navigation Bar text and arrow color

Vin's answer worked great for me. Here is the same solution for C# developers using Xamarin.iOS/MonoTouch:

var navigationBar = NavigationController.NavigationBar; //or another reference
navigationBar.BarTintColor = UIColor.Blue;
navigationBar.TintColor = UIColor.White;
navigationBar.SetTitleTextAttributes(new UITextAttributes() { TextColor = UIColor.White });
navigationBar.Translucent = false;

C# - How to convert string to char?

For a single string String.ToCharArray should be used

string str = "One";
var charArray = str.ToCharArray();

For an array of strings

string[] arrayStrings = { "One", "Two", "Three" };
var charArrayList = arrayStrings.Select(str => str.ToCharArray()).ToList();

For a single character from a single string:

string str = "One";
var ch = str[0]; // means 'O'

How to set enum to null

I'm assuming c++ here. If you're using c#, the answer is probably the same, but the syntax will be a bit different. The enum is a set of int values. It's not an object, so you shouldn't be setting it to null. Setting something to null means you are pointing a pointer to an object to address zero. You can't really do that with an int. What you want to do with an int is to set it to a value you wouldn't normally have it at so that you can tel if it's a good value or not. So, set your colour to -1

Color color = -1;

Or, you can start your enum at 1 and set it to zero. If you set the colour to zero as it is right now, you will be setting it to "red" because red is zero in your enum.

So,

enum Color {
red =1
blue,
green
}
//red is 1, blue is 2, green is 3
Color mycolour = 0;

Access Session attribute on jstl

You should definitely avoid using <jsp:...> tags. They're relics from the past and should always be avoided now.

Use the JSTL.

Now, wether you use the JSTL or any other tag library, accessing to a bean property needs your bean to have this property. A property is not a private instance variable. It's an information accessible via a public getter (and setter, if the property is writable). To access the questionPaperID property, you thus need to have a

public SomeType getQuestionPaperID() {
    //...
}

method in your bean.

Once you have that, you can display the value of this property using this code :

<c:out value="${Questions.questionPaperID}" />

or, to specifically target the session scoped attributes (in case of conflicts between scopes) :

<c:out value="${sessionScope.Questions.questionPaperID}" />

Finally, I encourage you to name scope attributes as Java variables : starting with a lowercase letter.

Undefined index error PHP

Apparently the index 'productid' is missing from your html form. Inspect your html inputs first. eg <input type="text" name="productid" value=""> But this will handle the current error PHP is raising.

  $rowID = isset($_POST['rowID']) ? $_POST['rowID'] : '';
  $productid = isset($_POST['productid']) ? $_POST['productid'] : '';
  $name = isset($_POST['name']) ? $_POST['name'] : '';
  $price = isset($_POST['price']) ? $_POST['price'] : '';
  $description = isset($_POST['description']) ? $_POST['description'] : '';

how to put image in center of html page?

Put your image in a container div then use the following CSS (changing the dimensions to suit your image.

.imageContainer{
        position: absolute;
        width: 100px; /*the image width*/
        height: 100px; /*the image height*/
        left: 50%;
        top: 50%;
        margin-left: -50px; /*half the image width*/
        margin-top: -50px; /*half the image height*/
    }

"Use the new keyword if hiding was intended" warning

Your class has a base class, and this base class also has a property (which is not virtual or abstract) called Events which is being overridden by your class. If you intend to override it put the "new" keyword after the public modifier. E.G.

public new EventsDataTable Events
{
  ..
}

If you don't wish to override it change your properties' name to something else.

Java FileWriter how to write to next Line

out.write(c.toString());
out.newLine();

here is a simple solution, I hope it works

EDIT: I was using "\n" which was obviously not recommended approach, modified answer.

How to add an image in the title bar using html?

Use the following

1.) Choose the image you want to set in your title bar.
2.) Convert it to ".ico" format. (You can use the following link online) http://image.online-convert.com/convert-to-ico
3.) Save the file as "favicon.ico" in the same folder as your .html file
4.) Add this inside your head tag <link rel="shortcut icon" href="favicon.ico"/>

How can I get LINQ to return the object which has the max value for a given property?

int max = items.Max(i => i.ID);
var item = items.First(x => x.ID == max);

This assumes there are elements in the items collection of course.

How to import module when module name has a '-' dash or hyphen in it?

you can't. foo-bar is not an identifier. rename the file to foo_bar.py

Edit: If import is not your goal (as in: you don't care what happens with sys.modules, you don't need it to import itself), just getting all of the file's globals into your own scope, you can use execfile

# contents of foo-bar.py
baz = 'quux'
>>> execfile('foo-bar.py')
>>> baz
'quux'
>>> 

How to create a batch file to run cmd as administrator

Maybe something like this:

if "%~s0"=="%~s1" ( cd %~sp1 & shift ) else (
  echo CreateObject^("Shell.Application"^).ShellExecute "%~s0","%~0 %*","","runas",1 >"%tmp%%~n0.vbs" & "%tmp%%~n0.vbs" & del /q "%tmp%%~n0.vbs" & goto :eof
)

javascript windows alert with redirect function

Use this if you also want to consider non-javascript users:

echo ("<SCRIPT LANGUAGE='JavaScript'>
           window.alert('Succesfully Updated')
           window.location.href='http://someplace.com';
       </SCRIPT>
       <NOSCRIPT>
           <a href='http://someplace.com'>Successfully Updated. Click here if you are not redirected.</a>
       </NOSCRIPT>");

HMAC-SHA256 Algorithm for signature calculation

If you're using Guava, its latest release now lets you use

 Hashing.hmacSha256()

Further documentation here: https://guava.dev/releases/23.0/api/docs/com/google/common/hash/Hashing.html#hmacSha256-byte:A-

How to turn IDENTITY_INSERT on and off using SQL Server 2008?

This is likely when you have a PRIMARY KEY field and you are inserting a value that is duplicating or you have the INSERT_IDENTITY flag set to on

WPF button click in C# code

You should place below line

btn.Click = btn.Click + btn1_Click;

cmake - find_library - custom library location

There is no way to automatically set CMAKE_PREFIX_PATH in a way you want. I see following ways to solve this problem:

  1. Put all libraries files in the same dir. That is, include/ would contain headers for all libs, lib/ - binaries, etc. FYI, this is common layout for most UNIX-like systems.

  2. Set global environment variable CMAKE_PREFIX_PATH to D:/develop/cmake/libs/libA;D:/develop/cmake/libs/libB;.... When you run CMake, it would aautomatically pick up this env var and populate it's own CMAKE_PREFIX_PATH.

  3. Write a wrapper .bat script, which would call cmake command with -D CMAKE_PREFIX_PATH=... argument.

Reading rather large json files in Python

The issue here is that JSON, as a format, is generally parsed in full and then handled in-memory, which for such a large amount of data is clearly problematic.

The solution to this is to work with the data as a stream - reading part of the file, working with it, and then repeating.

The best option appears to be using something like ijson - a module that will work with JSON as a stream, rather than as a block file.

Edit: Also worth a look - kashif's comment about json-streamer and Henrik Heino's comment about bigjson.

Take screenshots in the iOS simulator

In OSX Captain its a bug to take screenshot of simulator. You have to Update your OSX Sierra first then your are able to take. while taking in OSX Captain use terminal command which is xcrun simctl io booted screenshot.

before running this command u have to select desktop in terminal like:

"cd desktop" then run that command. Happy Coding!!!

'xmlParseEntityRef: no name' warnings while loading xml into a php file

This solve my problème:

$description = strip_tags($value['Description']);
$description=preg_replace('/&(?!#?[a-z0-9]+;)/', '&amp;', $description);
$description= preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", "\n", $description);
$description=str_replace(' & ', ' &amp; ', html_entity_decode((htmlspecialchars_decode($description))));

Call an overridden method from super class in typescript

The key is calling the parent's method using super.methodName();

class A {
    // A protected method
    protected doStuff()
    {
        alert("Called from A");
    }

    // Expose the protected method as a public function
    public callDoStuff()
    {
        this.doStuff();
    }
}

class B extends A {

    // Override the protected method
    protected doStuff()
    {
        // If we want we can still explicitly call the initial method
        super.doStuff();
        alert("Called from B");
    }
}

var a = new A();
a.callDoStuff(); // Will only alert "Called from A"

var b = new B()
b.callDoStuff(); // Will alert "Called from A" then "Called from B"

Try it here

Run chrome in fullscreen mode on Windows

Update 03-Oct-19

new script that displays 10second countdown then launches chrome/chromiumn in fullscreen kiosk mode.

more updates to chrome required script update to allow autoplaying video with audio. Note --overscroll-history-navigation=0 isn't working currently will need to disable this flag by going to chrome://flags/#overscroll-history-navigation in your browser and setting to disabled.

@echo off
echo Countdown to application launch...
timeout /t 10
"C:\Program Files (x86)\chrome-win32\chrome.exe" --chrome --kiosk http://localhost/xxxx --incognito --disable-pinch --no-user-gesture-required --overscroll-history-navigation=0
exit

might need to set chrome://flags/#autoplay-policy if running an older version of chrome (60 below)

Update 11-May-16

There have been many updates to chrome since I posted this and have had to alter the script alot to keep it working as I needed.

Couple of issues with newer versions of chrome:

  • built in pinch to zoom
  • Chrome restore error always showing after forced shutdown
  • auto update popup

Because of the restore error switched out to incognito mode as this launches a clear version all the time and does not save what the user was viewing and so if it crashes there is nothing to restore. Also the auto up in newer versions of chrome being a pain to try and disable I switched out to use chromium as it does not auto update and still gives all the modern features of chrome. Note make sure you download the top version of chromium this comes with all audio and video codecs as the basic version of chromium does not support all codecs.

Chromium download link

@echo off

echo Step 1 of 2: Waiting a few seconds before starting the Kiosk...

"C:\windows\system32\ping" -n 5 -w 1000 127.0.0.1 >NUL

echo Step 2 of 5: Waiting a few more seconds before starting the browser...

"C:\windows\system32\ping" -n 5 -w 1000 127.0.0.1 >NUL

echo Final 'invisible' step: Starting the browser, Finally...

"C:\Program Files (x86)\Google\Chromium\chrome.exe" --chrome --kiosk http://127.0.0.1/xxxx --incognito --disable-pinch --overscroll-history-navigation=0

exit

Outdated

I use this for exhibitions to lock down screens. I think its what your looking for.

  • Start chrome and go to www.google.com drag and drop the url out onto the desktop
  • rename it to something handy for this example google_homepage
  • drop this now into your c directory, click on my computer c: and drop this file in there
  • start chrome again go to settings and under on start up select open a specific page and set your home page here.

Next part is the script that I use to start close and restart chrome again in kiosk mode. The locations is where I have chrome installed so it might be abit different for you depending on your install.

Open your text editor of choice or just notepad and past the below code in, make sure its in the same format/order as below. Save it to your desktop as what ever you like so for this example chrome_startup_script.txt next right click it and rename, remove the txt from the end and put in bat instead. double click this to launch the script to see if its working correctly.

A command line box should appear and run through the script, chrome will start and then close down the reason to do this is to remove any error reports such as if the pc crashed, when chrome starts again without this it would show the yellow error bar at the top saying chrome did not shut down properly would you like to restore it. After a few seconds chrome should start again and in kiosk mode and will point to what ever homepage you have set.

@echo off
echo Step 1 of 5: Waiting a few seconds before starting the Kiosk...
"C:\windows\system32\ping" -n 31 -w 1000 127.0.0.1 >NUL
echo Step 2 of 5: Starting browser as a pre-start to delete error messages...
"C:\google_homepage.url"
echo Step 3 of 5: Waiting a few seconds before killing the browser task...
"C:\windows\system32\ping" -n 11 -w 1000 127.0.0.1 >NUL
echo Step 4 of 5: Killing the browser task gracefully to avoid session restore...
Taskkill /IM chrome.exe
echo Step 5 of 5: Waiting a few seconds before restarting the browser...
"C:\windows\system32\ping" -n 11 -w 1000 127.0.0.1 >NUL
echo Final 'invisible' step: Starting the browser, Finally...
"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --kiosk --overscroll-history-navigation=0"
exit

Note: The number after the -n of the ping is the amount of seconds (minus one second) to wait before starting the link (or application in the next line)

Finally if this is all working then you can drag and drop the .bat file into the startup folder in windows and this script will launch each time windows starts.


Update:

With recent versions of chrome they have really got into enabling touch gestures, this means that swiping left or right on a touchscreen will cause the browser to go forward or backward in history. To prevent this we need to disable the history navigation on the back and forward buttons to do that add the following --overscroll-history-navigation=0 to the end of the script.

Get class name of object as string in Swift

I suggest such an approach (very Swifty):

// Swift 3
func typeName(_ some: Any) -> String {
    return (some is Any.Type) ? "\(some)" : "\(type(of: some))"
}

// Swift 2
func typeName(some: Any) -> String {
    return (some is Any.Type) ? "\(some)" : "\(some.dynamicType)"
}

It doesn't use neither introspection nor manual demangling (no magic!).


Here is a demo:

// Swift 3

import class Foundation.NSObject

func typeName(_ some: Any) -> String {
    return (some is Any.Type) ? "\(some)" : "\(type(of: some))"
}

class GenericClass<T> {
    var x: T? = nil
}

protocol Proto1 {
    func f(x: Int) -> Int
}


@objc(ObjCClass1)
class Class1: NSObject, Proto1 {
    func f(x: Int) -> Int {
        return x
    }
}

struct Struct1 {
    var x: Int
}

enum Enum1 {
    case X
}

print(typeName(GenericClass<Int>.self)) // GenericClass<Int>
print(typeName(GenericClass<Int>()))  // GenericClass<Int>

print(typeName(Proto1.self)) // Proto1

print(typeName(Class1.self))   // Class1
print(typeName(Class1())) // Class1
print(typeName(Class1().f)) // (Int) -> Int

print(typeName(Struct1.self)) // Struct1
print(typeName(Struct1(x: 1))) // Struct1
print(typeName(Enum1.self)) // Enum1
print(typeName(Enum1.X)) // Enum1

How to upload a file to directory in S3 bucket using boto

Try this...

import boto
import boto.s3
import sys
from boto.s3.key import Key

AWS_ACCESS_KEY_ID = ''
AWS_SECRET_ACCESS_KEY = ''

bucket_name = AWS_ACCESS_KEY_ID.lower() + '-dump'
conn = boto.connect_s3(AWS_ACCESS_KEY_ID,
        AWS_SECRET_ACCESS_KEY)


bucket = conn.create_bucket(bucket_name,
    location=boto.s3.connection.Location.DEFAULT)

testfile = "replace this with an actual filename"
print 'Uploading %s to Amazon S3 bucket %s' % \
   (testfile, bucket_name)

def percent_cb(complete, total):
    sys.stdout.write('.')
    sys.stdout.flush()


k = Key(bucket)
k.key = 'my test file'
k.set_contents_from_filename(testfile,
    cb=percent_cb, num_cb=10)

[UPDATE] I am not a pythonist, so thanks for the heads up about the import statements. Also, I'd not recommend placing credentials inside your own source code. If you are running this inside AWS use IAM Credentials with Instance Profiles (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_switch-role-ec2_instance-profiles.html), and to keep the same behaviour in your Dev/Test environment, use something like Hologram from AdRoll (https://github.com/AdRoll/hologram)

SyntaxError: Cannot use import statement outside a module

For those who were as confused as I was when reading the answers, in your package.json file, add "type": "module" in the upper level as show below:

{
  "name": "my-app",
  "version": "0.0.0",
  "type": "module",
  "scripts": { ...
  },
  ...
}

Selenium Finding elements by class name in python

Use nth-child, for example: http://www.w3schools.com/cssref/sel_nth-child.asp

driver.find_element(By.CSS_SELECTOR, 'p.content:nth-child(1)')

or http://www.w3schools.com/cssref/sel_firstchild.asp

driver.find_element(By.CSS_SELECTOR, 'p.content:first-child')

How can I build a recursive function in python?

Recursion in Python works just as recursion in an other language, with the recursive construct defined in terms of itself:

For example a recursive class could be a binary tree (or any tree):

class tree():
    def __init__(self):
        '''Initialise the tree'''
        self.Data = None
        self.Count = 0
        self.LeftSubtree = None
        self.RightSubtree = None

    def Insert(self, data):
        '''Add an item of data to the tree'''
        if self.Data == None:
            self.Data = data
            self.Count += 1
        elif data < self.Data:
            if self.LeftSubtree == None:
                # tree is a recurive class definition
                self.LeftSubtree = tree()
            # Insert is a recursive function
            self.LeftSubtree.Insert(data)
        elif data == self.Data:
            self.Count += 1
        elif data > self.Data:
            if self.RightSubtree == None:
                self.RightSubtree = tree()
            self.RightSubtree.Insert(data)

if __name__ == '__main__':
    T = tree()
    # The root node
    T.Insert('b')
    # Will be put into the left subtree
    T.Insert('a')
    # Will be put into the right subtree
    T.Insert('c')

As already mentioned a recursive structure must have a termination condition. In this class, it is not so obvious because it only recurses if new elements are added, and only does it a single time extra.

Also worth noting, python by default has a limit to the depth of recursion available, to avoid absorbing all of the computer's memory. On my computer this is 1000. I don't know if this changes depending on hardware, etc. To see yours :

import sys
sys.getrecursionlimit()

and to set it :

import sys #(if you haven't already)
sys.setrecursionlimit()

edit: I can't guarentee that my binary tree is the most efficient design ever. If anyone can improve it, I'd be happy to hear how

What is the behavior difference between return-path, reply-to and from?

Let's start with a simple example. Let's say you have an email list, that is going to send out the following RFC2822 content.

From: <[email protected]>
To: <[email protected]>
Subject: Super simple email
Reply-To: <[email protected]>

This is a very simple body.

Now, let's say you are going to send it from a mailing list, that implements VERP (or some other bounce tracking mechanism that uses a different return-path). Lets say it will have a return-path of [email protected]. The SMTP session might look like:

{S}220 workstation1 Microsoft ESMTP MAIL Service
{C}HELO workstation1
{S}250 workstation1 Hello [127.0.0.1]
{C}MAIL FROM:<[email protected]>
{S}250 2.1.0 [email protected] OK
{C}RCPT TO:<[email protected]>
{S}250 2.1.5 [email protected] 
{C}DATA
{S}354 Start mail input; end with <CRLF>.<CRLF>
{C}From: <[email protected]>
To: <[email protected]>
Subject: Super simple email
Reply-To: <[email protected]>

This is a very simple body.
.

{S}250 Queued mail for delivery
{C}QUIT
{S}221 Service closing transmission channel

Where {C} and {S} represent Client and Server commands, respectively.

The recipient's mail would look like:

Return-Path: [email protected]
From: <[email protected]>
To: <[email protected]>
Subject: Super simple email
Reply-To: <[email protected]>

This is a very simple body.

Now, let's describe the different "FROM"s.

  1. The return path (sometimes called the reverse path, envelope sender, or envelope from — all of these terms can be used interchangeably) is the value used in the SMTP session in the MAIL FROM command. As you can see, this does not need to be the same value that is found in the message headers. Only the recipient's mail server is supposed to add a Return-Path header to the top of the email. This records the actual Return-Path sender during the SMTP session. If a Return-Path header already exists in the message, then that header is removed and replaced by the recipient's mail server.

All bounces that occur during the SMTP session should go back to the Return-Path address. Some servers may accept all email, and then queue it locally, until it has a free thread to deliver it to the recipient's mailbox. If the recipient doesn't exist, it should bounce it back to the recorded Return-Path value.

Note, not all mail servers obey this rule; Some mail servers will bounce it back to the FROM address.

  1. The FROM address is the value found in the FROM header. This is supposed to be who the message is FROM. This is what you see as the "FROM" in most mail clients. If an email does not have a Reply-To header, then all human (mail client) replies should go back to the FROM address.

  2. The Reply-To header is added by the sender (or the sender's software). It is where all human replies should be addressed too. Basically, when the user clicks "reply", the Reply-To value should be the value used as the recipient of the newly composed email. The Reply-To value should not be used by any server. It is meant for client-side (MUA) use only.

However, as you can tell, not all mail servers obey the RFC standards or recommendations.

Hopefully this should help clear things up. However, if I missed anything, let me know, and I'll try to answer.

Can you use a trailing comma in a JSON object?

Simple, cheap, easy to read, and always works regardless of the specs.

$delimiter = '';
for ....  {
    print $delimiter.$whatever
    $delimiter = ',';
}

The redundant assignment to $delim is a very small price to pay. Also works just as well if there is no explicit loop but separate code fragments.

dbms_lob.getlength() vs. length() to find blob size in oracle

length and dbms_lob.getlength return the number of characters when applied to a CLOB (Character LOB). When applied to a BLOB (Binary LOB), dbms_lob.getlength will return the number of bytes, which may differ from the number of characters in a multi-byte character set.

As the documentation doesn't specify what happens when you apply length on a BLOB, I would advise against using it in that case. If you want the number of bytes in a BLOB, use dbms_lob.getlength.

How to connect to SQL Server database from JavaScript in the browser?

As stated before it shouldn't be done using client side Javascript but there's a framework for implementing what you want more securely.

Nodejs is a framework that allows you to code server connections in javascript so have a look into Nodejs and you'll probably learn a bit more about communicating with databases and grabbing data you need.

How to extract .war files in java? ZIP vs JAR

If you look at the JarFile API you'll see that it's a subclass of the ZipFile class.

The jar-specific classes mostly just add jar-specific functionality, like direct support for manifest file attributes and so on.

It's OOP "in action"; since jar files are zip files, the jar classes can use zip functionality and provide additional utility.

Location of sqlite database on the device

/data/data/packagename/databases/

ie

/data/data/com.example.program/databases/

How to get milliseconds from LocalDateTime in Java 8

To get the current time in milliseconds (since the epoch), use System.currentTimeMillis().

How do I use regular expressions in bash scripts?

You need spaces around the operator =~

i="test"
if [[ $i =~ "200[78]" ]];
then
  echo "OK"
else
  echo "not OK"
fi

How can I trigger an onchange event manually?

MDN suggests that there's a much cleaner way of doing this in modern browsers:

// Assuming we're listening for e.g. a 'change' event on `element`

// Create a new 'change' event
var event = new Event('change');

// Dispatch it.
element.dispatchEvent(event);

Error message "Unable to install or run the application. The application requires stdole Version 7.0.3300.0 in the GAC"

So it turns out that the .NET files were copied to C:\Program Files\Microsoft.NET\Primary Interop Assemblies\. However, they were never registered in the GAC.

I ended up manually dragging the files in C:\Program Files\Microsoft.NET\Primary Interop Assemblies to C:\windows\assembly and the application worked on that problem machine. You could also do this programmatically with Gacutil.

So it seems that something happened to .NET during the install, but this seems to correct the problem. I hope that helps someone else out!

img onclick call to JavaScript function

You should probably be using a more unobtrusive approach. Here's the benefits

  • Separation of functionality (the "behavior layer") from a Web page's structure/content and presentation
  • Best practices to avoid the problems of traditional JavaScript programming (such as browser inconsistencies and lack of scalability)
  • Progressive enhancement to support user agents that may not support advanced JavaScript functionality

Here's a jsfiddle demo

Your JavaScript

function exportToForm(a, b, c, d, e) {
  console.log(a, b, c, d, e);
}

var images = document.getElementsByTagName("img");

for (var i=0, len=images.length, img; i<len; i++) {
  img = images[i];
  img.addEventListener("click", function() {
    var a = img.getAttribute("data-a"),
        b = img.getAttribute("data-b"),
        c = img.getAttribute("data-c"),
        d = img.getAttribute("data-d"),
        e = img.getAttribute("data-e");

    exportToForm(a, b, c, d, e);
  });
}

Your images will look like this

<img data-a="1" data-b="2" data-c="3" data-d="4" data-e="5" src="image.jpg">

stringstream, string, and char* conversion confusion

What you're doing is creating a temporary. That temporary exists in a scope determined by the compiler, such that it's long enough to satisfy the requirements of where it's going.

As soon as the statement const char* cstr2 = ss.str().c_str(); is complete, the compiler sees no reason to keep the temporary string around, and it's destroyed, and thus your const char * is pointing to free'd memory.

Your statement string str(ss.str()); means that the temporary is used in the constructor for the string variable str that you've put on the local stack, and that stays around as long as you'd expect: until the end of the block, or function you've written. Therefore the const char * within is still good memory when you try the cout.

git am error: "patch does not apply"

I had this error, was able to overcome it by using : patch -p1 < example.patch

I took it from here: https://www.drupal.org/node/1129120

Override element.style using CSS

As per my knowledge Inline sytle comes first so css class should not work.

Use Jquery as

$(document).ready(function(){

   $("#demoFour li").css("display","inline");
  });

You can also try 

#demoFour li { display:inline !important;}

How to add to an existing hash in Ruby

hash {}
hash[:a] = 'a'
hash[:b] = 'b'
hash = {:a => 'a' , :b = > b}

You might get your key and value from user input, so you can use Ruby .to_sym can convert a string to a symbol, and .to_i will convert a string to an integer.
For example:

movies ={}
movie = gets.chomp
rating = gets.chomp
movies[movie.to_sym] = rating.to_int
# movie will convert to a symbol as a key in our hash, and 
# rating will be an integer as a value.

Send a SMS via intent

Hope this is work, this is working in my app

SmsManager.getDefault().sendTextMessage("Phone Number", null, "Message", null, null);

How to combine two lists in R

c can be used on lists (and not only on vectors):

# you have
l1 = list(2, 3)
l2 = list(4)

# you want
list(2, 3, 4)
[[1]]
[1] 2

[[2]]
[1] 3

[[3]]
[1] 4

# you can do
c(l1, l2)
[[1]]
[1] 2

[[2]]
[1] 3

[[3]]
[1] 4

If you have a list of lists, you can do it (perhaps) more comfortably with do.call, eg:

do.call(c, list(l1, l2))

Why extend the Android Application class?

You can access variables to any class without creating objects, if its extended by Application. They can be called globally and their state is maintained till application is not killed.

Finish an activity from another activity

There is one approach that you can use in your case.

Step1: Start Activity B from Activity A

startActivity(new Intent(A.this, B.class));

Step2: If the user clicks on modify button start Activity A using the FLAG_ACTIVITY_CLEAR_TOP.Also, pass the flag in extra.

Intent i = new Intent(B.this, A.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.putExtra("flag", "modify");
startActivity(i);
finish();

Step3: If the user clicks on Add button start Activity A using the FLAG_ACTIVITY_CLEAR_TOP.Also, pass the flag in extra. FLAG_ACTIVITY_CLEAR_TOP will clear all the opened activities up to the target and restart if no launch mode is defined in the target activity

Intent i = new Intent(B.this, A.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.putExtra("flag", "add");
startActivity(i);
finish();

Step4: Now onCreate() method of the Activity A, need to retrieve that flag.

String flag = getIntent().getStringExtra("flag");
if(flag.equals("add")) {
    //Write a code for add
}else {
    //Write a code for modifying
}

How do I make a placeholder for a 'select' box?

Here is a working example how to achieve this with pure JavaScript that handles the options color after the first click:

<!DOCTYPE html>
<html>
  <head>
    <style>
      #myselect {
        color: gray;
      }
    </style>
  </head>

  <body>
    <select id="myselect">
      <option disabled selected>Choose Item
      </option>

      <option>Item 1
      </option>

      <option>Item 2
      </option>

      <option>Item 3
      </option>
    </select>

    <script>
      // Add event listener to change color in the first click
      document.getElementById("myselect").addEventListener("click", setColor)
      function setColor()
      {
        var combo = document.getElementById("myselect");
        combo.style.color = 'red';
        // Remove Event Listener after the color is changed at the first click
        combo.removeEventListener("click", setColor);
      }
    </script>
  </body>
</html>

Prevent scrolling of parent element when inner element scroll position reaches top/bottom?

I was searching for this for MooTools and this was the first that came up. The original MooTools example would work with scrolling up, but not scrolling down so I decided to write this one.


var stopScroll = function (e) {
    var scrollTo = null;
    if (e.event.type === 'mousewheel') {
        scrollTo = (e.event.wheelDelta * -1);
    } else if (e.event.type === 'DOMMouseScroll') {
        scrollTo = 40 * e.event.detail;
    }
    if (scrollTo) {
        e.preventDefault();
        this.scrollTo(0, scrollTo + this.scrollTop);
    }
    return false;
};

Usage:

(function)($){
    window.addEvent('domready', function(){
        $$('.scrollable').addEvents({
             'mousewheel': stopScroll,
             'DOMMouseScroll': stopScroll
        });
    });
})(document.id);

Does MS Access support "CASE WHEN" clause if connect with ODBC?

You could use IIF statement like in the next example:

SELECT
   IIF(test_expression, value_if_true, value_if_false) AS FIELD_NAME
FROM
   TABLE_NAME

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

One way or another you must tell boto3 in which region you wish the kms client to be created. This could be done explicitly using the region_name parameter as in:

kms = boto3.client('kms', region_name='us-west-2')

or you can have a default region associated with your profile in your ~/.aws/config file as in:

[default]
region=us-west-2

or you can use an environment variable as in:

export AWS_DEFAULT_REGION=us-west-2

but you do need to tell boto3 which region to use.

CKEditor automatically strips classes from div

Since CKEditor v4.1, you can do this in config.js of CKEditor:

CKEDITOR.editorConfig = function( config ) {
  config.extraAllowedContent = '*[id](*)';  // remove '[id]', if you don't want IDs for HTML tags
}

You can refer to the official documentation for the detailed syntax of Allowed Content Rules

vagrant primary box defined but commands still run against all boxes

The primary flag seems to only work for vagrant ssh for me.

In the past I have used the following method to hack around the issue.

# stage box intended for configuration closely matching production if ARGV[1] == 'stage'     config.vm.define "stage" do |stage|         box_setup stage, \         "10.9.8.31", "deploy/playbook_full_stack.yml", "deploy/hosts/vagrant_stage.yml"     end end 

How to change navbar/container width? Bootstrap 3

If you are dealing with more dynamic screen resolution/sizes, instead of hardcoding the size in pixels you can change the width to a percentage of the media width as such

@media (min-width: 1200px) {
    .container{
        max-width: 70%;
   }
}

How to remove margin space around body or clear default css styles

I found this problem continued even when setting the BODY MARGIN to zero.

However it turns out there is an easy fix. All you need to do is give your HEADER tag a 1px border, aswell as setting the BODY MARGIN to zero, as shown below.

body { margin:0px; }

header { border:1px black solid; }

If you have any H1, H2, tags within your HEADER you will also need to set the MARGIN for these tags to zero, this will get rid of any extra space which may show up.

Not sure why this works, but I use Chrome browser. Obviously you can also change the colour of the border to match your header colour.

Tab space instead of multiple non-breaking spaces ("nbsp")?

You can use a table and apply a width attribute to the first <td>.

Code:

<table>
    <tr>
        <td width="100">Content1</td>
        <td>Content2</td>
    </tr>
    <tr>
        <td>Content3</td>
        <td>Content4</td>
    </tr>
</table>

Result

Content1       Content2
Content3       Content4

Rollback to last git commit

git reset --hard will force the working directory back to the last commit and delete new/changed files.

How to generate javadoc comments in Android Studio

You can install JavaDoc plugin from Settings->Plugin->Browse repositories.

get plugin documentation from the below link

JavaDoc plugin document

enter image description here

PDO get the last ID inserted

That's because that's an SQL function, not PHP. You can use PDO::lastInsertId().

Like:

$stmt = $db->prepare("...");
$stmt->execute();
$id = $db->lastInsertId();

If you want to do it with SQL instead of the PDO API, you would do it like a normal select query:

$stmt = $db->query("SELECT LAST_INSERT_ID()");
$lastId = $stmt->fetchColumn();

How to include file in a bash shell script

In my situation, in order to include color.sh from the same directory in init.sh, I had to do something as follows.

. ./color.sh

Not sure why the ./ and not color.sh directly. The content of color.sh is as follows.

RED=`tput setaf 1`
GREEN=`tput setaf 2`
BLUE=`tput setaf 4`
BOLD=`tput bold`
RESET=`tput sgr0`

Making use of File color.sh does not error but, the color do not display. I have tested this in Ubuntu 18.04 and the Bash version is:

GNU bash, version 4.4.19(1)-release (x86_64-pc-linux-gnu)

Index inside map() function

  • suppose you have an array like

_x000D_
_x000D_
   const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
    
    
    arr.map((myArr, index) => {
      console.log(`your index is -> ${index} AND value is ${myArr}`);
    })
_x000D_
_x000D_
_x000D_

> output will be
 index is -> 0 AND value is 1
 index is -> 1 AND value is 2
 index is -> 2 AND value is 3
 index is -> 3 AND value is 4
 index is -> 4 AND value is 5
 index is -> 5 AND value is 6
 index is -> 6 AND value is 7
 index is -> 7 AND value is 8
 index is -> 8 AND value is 9

How do I make the method return type generic?

I know this is a completely different thing that the one asked. Another way of resolving this would be reflection. I mean, this does not take the benefit from Generics, but it lets you emulate, in some way, the behavior you want to perform (make a dog bark, make a duck quack, etc.) without taking care of type casting:

import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;

abstract class AnimalExample {
    private Map<String,Class<?>> friends = new HashMap<String,Class<?>>();
    private Map<String,Object> theFriends = new HashMap<String,Object>();

    public void addFriend(String name, Object friend){
        friends.put(name,friend.getClass());
        theFriends.put(name, friend);
    }

    public void makeMyFriendSpeak(String name){
        try {
            friends.get(name).getMethod("speak").invoke(theFriends.get(name));
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
    } 

    public abstract void speak ();
};

class Dog extends Animal {
    public void speak () {
        System.out.println("woof!");
    }
}

class Duck extends Animal {
    public void speak () {
        System.out.println("quack!");
    }
}

class Cat extends Animal {
    public void speak () {
        System.out.println("miauu!");
    }
}

public class AnimalExample {

    public static void main (String [] args) {

        Cat felix = new Cat ();
        felix.addFriend("Spike", new Dog());
        felix.addFriend("Donald", new Duck());
        felix.makeMyFriendSpeak("Spike");
        felix.makeMyFriendSpeak("Donald");

    }

}

How to use \n new line in VB msgbox() ...?

Add a vbNewLine as:

"text1" & vbNewLine & "text2"

How to round a numpy array?

It is worth noting that the accepted answer will round small floats down to zero.

>>> import numpy as np 
>>> arr = np.asarray([2.92290007e+00, -1.57376965e-03, 4.82011728e-08, 1.92896977e-12])
>>> print(arr)
[ 2.92290007e+00 -1.57376965e-03  4.82011728e-08  1.92896977e-12]
>>> np.round(arr, 2)
array([ 2.92, -0.  ,  0.  ,  0.  ]) 

You can use set_printoptions and a custom formatter to fix this and get a more numpy-esque printout with fewer decimal places:

>>> np.set_printoptions(formatter={'float': "{0:0.2e}".format})
>>> print(arr)
[2.92e+00 -1.57e-03 4.82e-08 1.93e-12]  

This way, you get the full versatility of format and maintain the full precision of numpy's datatypes.

Also note that this only affects printing, not the actual precision of the stored values used for computation.

Customize the Authorization HTTP header

In the case of CROSS ORIGIN request read this:

I faced this situation and at first I chose to use the Authorization Header and later removed it after facing the following issue.

Authorization Header is considered a custom header. So if a cross-domain request is made with the Autorization Header set, the browser first sends a preflight request. A preflight request is an HTTP request by the OPTIONS method, this request strips all the parameters from the request. Your server needs to respond with Access-Control-Allow-Headers Header having the value of your custom header (Authorization header).

So for each request the client (browser) sends, an additional HTTP request(OPTIONS) was being sent by the browser. This deteriorated the performance of my API. You should check if adding this degrades your performance. As a workaround I am sending tokens in http parameters, which I know is not the best way of doing it but I couldn't compromise with the performance.

How to simulate a click by using x,y coordinates in JavaScript?

Yes, you can simulate a mouse click by creating an event and dispatching it:

function click(x,y){
    var ev = document.createEvent("MouseEvent");
    var el = document.elementFromPoint(x,y);
    ev.initMouseEvent(
        "click",
        true /* bubble */, true /* cancelable */,
        window, null,
        x, y, 0, 0, /* coordinates */
        false, false, false, false, /* modifier keys */
        0 /*left*/, null
    );
    el.dispatchEvent(ev);
}

Beware of using the click method on an element -- it is widely implemented but not standard and will fail in e.g. PhantomJS. I assume jQuery's implemention of .click() does the right thing but have not confirmed.

How to save a data frame as CSV to a user selected location using tcltk

write.csv([enter name of dataframe here],file = file.choose(new = T))

After running above script this window will open :

enter image description here

Type the new file name with extension in the File name field and click Open, it'll ask you to create a new file to which you should select Yes and the file will be created and saved in the desired location.

Print commit message of a given commit in git

git show is more a plumbing command than git log, and has the same formatting options:

git show -s --format=%B SHA1

How do I show a message in the foreach loop?

You are looking to see if a single value is in an array. Use in_array.

However note that case is important, as are any leading or trailing spaces. Use var_dump to find out the length of the strings too, and see if they fit.

What does 'var that = this;' mean in JavaScript?

Here is an example `

$(document).ready(function() {
        var lastItem = null;
        $(".our-work-group > p > a").click(function(e) {
            e.preventDefault();

            var item = $(this).html(); //Here value of "this" is ".our-work-group > p > a"
            if (item == lastItem) {
                lastItem = null;
                $('.our-work-single-page').show();
            } else {
                lastItem = item;
                $('.our-work-single-page').each(function() {
                    var imgAlt = $(this).find('img').attr('alt'); //Here value of "this" is '.our-work-single-page'. 
                    if (imgAlt != item) {
                        $(this).hide();
                    } else {
                        $(this).show();
                    }
                });
            }

        });
    });`

So you can see that value of this is two different values depending on the DOM element you target but when you add "that" to the code above you change the value of "this" you are targeting.

`$(document).ready(function() {
        var lastItem = null;
        $(".our-work-group > p > a").click(function(e) {
            e.preventDefault();
            var item = $(this).html(); //Here value of "this" is ".our-work-group > p > a"
            if (item == lastItem) {
                lastItem = null;
                var that = this;
                $('.our-work-single-page').show();
            } else {
                lastItem = item;
                $('.our-work-single-page').each(function() {
                   ***$(that).css("background-color", "#ffe700");*** //Here value of "that" is ".our-work-group > p > a"....
                    var imgAlt = $(this).find('img').attr('alt'); 
                    if (imgAlt != item) {
                        $(this).hide();
                    } else {
                        $(this).show();
                    }
                });
            }

        });
    });`

.....$(that).css("background-color", "#ffe700"); //Here value of "that" is ".our-work-group > p > a" because the value of var that = this; so even though we are at "this"= '.our-work-single-page', still we can use "that" to manipulate previous DOM element.

Selecting specific rows and columns from NumPy array

Using np.ix_ is the most convenient way to do it (as answered by others), but here is another interesting way to do it:

>>> rows = [0, 1, 3]
>>> cols = [0, 2]

>>> a[rows].T[cols].T

array([[ 0,  2],
       [ 4,  6],
       [12, 14]])

Two arrays in foreach loop

array_map seems good for this too

$codes = array('tn','us','fr');
$names = array('Tunisia','United States','France');

array_map(function ($code, $name) {
    echo '<option value="' . $code . '">' . $name . '</option>';
}, $codes, $names);

Other benefits are:

  • If one array is shorter than the other, the callback receive null values to fill in the gap.

  • You can use more than 2 arrays to iterate through.

Retrieving a List from a java.util.stream.Stream in Java 8

A little more efficient way (avoid the creating the source List and the auto-unboxing by the filter):

List<Long> targetLongList = LongStream.of(1L, 10L, 50L, 80L, 100L, 120L, 133L, 333L)
    .filter(l -> l > 100)
    .boxed()
    .collect(Collectors.toList());

How to get all Errors from ASP.Net MVC modelState?

foreach (ModelState modelState in ViewData.ModelState.Values) {
    foreach (ModelError error in modelState.Errors) {
        DoSomethingWith(error);
    }
}

See also How do I get the collection of Model State Errors in ASP.NET MVC?.

Why does Git treat this text file as a binary file?

I was having this issue where Git GUI and SourceTree was treating Java/JS files as binary and thus wouldn’t show a diff.

Creating a file named attributes in .git/info with following content solved the problem:

*.java diff
*.js diff
*.pl diff
*.txt diff
*.ts diff
*.html diff
*.sh diff
*.xml diff

If you would like this to apply to all repositories, then you can add the file attributes in $HOME/.config/git/attributes.

Assign output of os.system to a variable and prevent it from being displayed on the screen

from os import system, remove
from uuid import uuid4

def bash_(shell_command: str) -> tuple:
    """

    :param shell_command: your shell command
    :return: ( 1 | 0, stdout)
    """

    logfile: str = '/tmp/%s' % uuid4().hex
    err: int = system('%s &> %s' % (shell_command, logfile))
    out: str = open(logfile, 'r').read()
    remove(logfile)
    return err, out

# Example: 
print(bash_('cat /usr/bin/vi | wc -l'))
>>> (0, '3296\n')```

Angular: Cannot find a differ supporting object '[object Object]'

I received this error in my code because I'd not run JSON.parse(result).

So my result was a string instead of an array of objects.

i.e. I got:

"[{},{}]" 

instead of:

[{},{}]

import { Storage } from '@ionic/storage';
...
private static readonly SERVER = 'server';
...
getStorage(): Promise {
  return this.storage.get(LoginService.SERVER);
}
...
this.getStorage()
  .then((value) => {
     let servers: Server[] = JSON.parse(value) as Server[];
                   }
  );

Correct way to integrate jQuery plugins in AngularJS

Yes, you are correct. If you are using a jQuery plugin, do not put the code in the controller. Instead create a directive and put the code that you would normally have inside the link function of the directive.

There are a couple of points in the documentation that you could take a look at. You can find them here:
Common Pitfalls

Using controllers correctly

Ensure that when you are referencing the script in your view, you refer it last - after the angularjs library, controllers, services and filters are referenced.

EDIT: Rather than using $(element), you can make use of angular.element(element) when using AngularJS with jQuery

How to make sure that string is valid JSON using JSON.NET

Building on Habib's answer, you could write an extension method:

public static bool ValidateJSON(this string s)
{
    try
    {
        JToken.Parse(s);
        return true;
    }
    catch (JsonReaderException ex)
    {
        Trace.WriteLine(ex);
        return false;
    }
}

Which can then be used like this:

if(stringObject.ValidateJSON())
{
    // Valid JSON!
}

Check if a Postgres JSON array contains a string

You could use @> operator to do this something like

SELECT info->>'name'
FROM rabbits
WHERE info->'food' @> '"carrots"';

Loop through an array of strings in Bash?

That is possible, of course.

for databaseName in a b c d e f; do
  # do something like: echo $databaseName
done 

See Bash Loops for, while and until for details.

JUnit assertEquals(double expected, double actual, double epsilon)

Epsilon is your "fuzz factor," since doubles may not be exactly equal. Epsilon lets you describe how close they have to be.

If you were expecting 3.14159 but would take anywhere from 3.14059 to 3.14259 (that is, within 0.001), then you should write something like

double myPi = 22.0d / 7.0d; //Don't use this in real life!
assertEquals(3.14159, myPi, 0.001);

(By the way, 22/7 comes out to 3.1428+, and would fail the assertion. This is a good thing.)

How to format string to money

try

amtf =  amtf.Insert(amtf.Length - 2, ".");

Validation failed for one or more entities. See 'EntityValidationErrors' property for more details

In my case it was because of the length of the database field is less than the length of the input field.

database table

create table user(
  Username nvarchar(5) not  null
);

My input

User newUser = new User()
{
   Username = "123456"
};

the value for Username length is 5 which is lessthan 6

...this may help someone

Convert String to Carbon

Try this

$date = Carbon::parse(date_format($youttimestring,'d/m/Y H:i:s'));
echo $date;

How to fix the error; 'Error: Bootstrap tooltips require Tether (http://github.hubspot.com/tether/)'

Using webpack I used this in webpack.config.js:

var plugins = [

    ...

    new webpack.ProvidePlugin({
        $: "jquery",
        jQuery: "jquery",
        'window.jQuery': 'jquery',
        'window.Tether': 'tether',
        tether: 'tether',
        Tether: 'tether'
    })
];

It seems like Tether was the one it was looking for:

var Tooltip = function ($) {

  /**
   * Check for Tether dependency
   * Tether - http://tether.io/
   */
  if (typeof Tether === 'undefined') {
    throw new Error('Bootstrap tooltips require Tether (http://tether.io/)');
  }

How to install an apk on the emulator in Android Studio?

Run simulator -> drag and drop yourApp.apk into simulator screen. Thats all. No commands.

VBA Date as integer

You can use bellow code example for date string like mdate and Now() like toDay, you can also calculate deference between both date like Aging

Public Sub test(mdate As String)
    Dim toDay As String
    mdate = Round(CDbl(CDate(mdate)), 0)
    toDay = Round(CDbl(Now()), 0)
    Dim Aging as String
    Aging = toDay - mdate
    MsgBox ("So aging is -" & Aging & vbCr & "from the date - " & _
    Format(mdate, "dd-mm-yyyy")) & " to " & Format(toDay, "dd-mm-yyyy"))
End Sub

NB: Used CDate for convert Date String to Valid Date

I am using this in Office 2007 :)

Generic List - moving an item within the list

Insert the item currently at oldIndex to be at newIndex and then remove the original instance.

list.Insert(newIndex, list[oldIndex]);
if (newIndex <= oldIndex) ++oldIndex;
list.RemoveAt(oldIndex);

You have to take into account that the index of the item you want to remove may change due to the insertion.

What is the difference between hg forget and hg remove?

A file can be tracked or not, you use hg add to track a file and hg remove or hg forget to un-track it. Using hg remove without flags will both delete the file and un-track it, hg forget will simply un-track it without deleting it.

Android Studio 3.0 Execution failed for task: unable to merge dex

Go to your module level build.gradle file and add the following lines to the code

    defaultConfig {
        ...
        minSdkVersion 15 
        targetSdkVersion 28
        multiDexEnabled true
    }
    ...
}

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

That solved the problem easily. Check this documentation

How do I redirect to the previous action in ASP.NET MVC?

Pass a returnUrl parameter (url encoded) to the change and login actions and inside redirect to this given returnUrl. Your login action might look something like this:

public ActionResult Login(string returnUrl) 
{
    // Do something...
    return Redirect(returnUrl);
}

How to check whether a variable is a class or not?

class Foo: is called old style class and class X(object): is called new style class.

Check this What is the difference between old style and new style classes in Python? . New style is recommended. Read about "unifying types and classes"

Format numbers in django templates

In case someone stumbles upon this, in Django 2.0.2 you can use this

Thousand separator. Be sure to read format localization as well.

Error while installing json gem 'mkmf.rb can't find header files for ruby'

sudo apt-get --reinstall install ruby

try it for ubuntu 16.04

Python Requests throwing SSLError

I ran into the same issue. Turns out I hadn't installed the intermediate certificate on my server (just append it to the bottom of your certificate as seen below).

https://www.digicert.com/ssl-support/pem-ssl-creation.htm

Make sure you have the ca-certificates package installed:

sudo apt-get install ca-certificates

Updating the time may also resolve this:

sudo apt-get install ntpdate
sudo ntpdate -u ntp.ubuntu.com

If you're using a self-signed certificate, you'll probably have to add it to your system manually.

AWS - Disconnected : No supported authentication methods available (server sent :publickey)

There is another cause that would impact a previously working system. I re-created my instances (using AWS OpsWorks) to use Amazon Linux instead of Ubuntu, and received this error after doing so. Switching to use "ec2-user" as the username instead of "ubuntu" resolved the issue for me.

jQuery document.createElement equivalent?

var mydiv = $('<div />') // also works

Can I have onScrollListener for a ScrollView?

Beside accepted answer, you need to hold a reference of listener and remove when you don't need it. Otherwise you will get a null pointer exception for your ScrollView and memory leak (mentioned in comments of accepted answer).

  1. You can implement OnScrollChangedListener in your activity/fragment.

    MyFragment : ViewTreeObserver.OnScrollChangedListener
    
  2. Add it to scrollView when your view is ready.

    scrollView.viewTreeObserver.addOnScrollChangedListener(this)
    
  3. Remove listener when no longer need (ie. onPause())

    scrollView.viewTreeObserver.removeOnScrollChangedListener(this)
    

Git status ignore line endings / identical files / windows & linux environment / dropbox / mled

I created a script to ignore differences in line endings:

It will display the files which are not added to the commit list and were modified (after ignoring differences in line endings). You can add the argument "add" to add those files to your commit.

#!/usr/bin/perl

# Usage: ./gitdiff.pl [add]
#    add : add modified files to git

use warnings;
use strict;

my ($auto_add) = @ARGV;
if(!defined $auto_add) {
    $auto_add = "";
}

my @mods = `git status --porcelain 2>/dev/null | grep '^ M ' | cut -c4-`;
chomp(@mods);
for my $mod (@mods) {
    my $diff = `git diff -b $mod 2>/dev/null`;
    if($diff) {
        print $mod."\n";
        if($auto_add eq "add") {
            `git add $mod 2>/dev/null`;
        }
    }
}

Source code: https://github.com/lepe/scripts/blob/master/gitdiff.pl

Updates:

  • fix by evandro777 : When the file has space in filename or directory

Rails find_or_create_by more than one attribute?

You can do:

User.find_or_create_by(first_name: 'Penélope', last_name: 'Lopez')
User.where(first_name: 'Penélope', last_name: 'Lopez').first_or_create

Or to just initialize:

User.find_or_initialize_by(first_name: 'Penélope', last_name: 'Lopez')
User.where(first_name: 'Penélope', last_name: 'Lopez').first_or_initialize

MemoryStream - Cannot access a closed Stream

This is because the StreamReader closes the underlying stream automatically when being disposed of. The using statement does this automatically.

However, the StreamWriter you're using is still trying to work on the stream (also, the using statement for the writer is now trying to dispose of the StreamWriter, which is then trying to close the stream).

The best way to fix this is: don't use using and don't dispose of the StreamReader and StreamWriter. See this question.

using (var ms = new MemoryStream())
{
    var sw = new StreamWriter(ms);
    var sr = new StreamReader(ms);

    sw.WriteLine("data");
    sw.WriteLine("data 2");
    ms.Position = 0;

    Console.WriteLine(sr.ReadToEnd());                        
}

If you feel bad about sw and sr being garbage-collected without being disposed of in your code (as recommended), you could do something like that:

StreamWriter sw = null;
StreamReader sr = null;

try
{
    using (var ms = new MemoryStream())
    {
        sw = new StreamWriter(ms);
        sr = new StreamReader(ms);

        sw.WriteLine("data");
        sw.WriteLine("data 2");
        ms.Position = 0;

        Console.WriteLine(sr.ReadToEnd());                        
    }
}
finally
{
    if (sw != null) sw.Dispose();
    if (sr != null) sr.Dispose();
}

How to get the separate digits of an int number?

see bellow my proposal with comments

          int size=i.toString().length(); // the length of the integer (i) we need to split;
           ArrayList<Integer> li = new ArrayList<Integer>(); // an ArrayList in whcih to store the resulting digits

        Boolean b=true; // control variable for the loop in which we will reatrive step by step the digits
        String number="1"; // here we will add the leading zero depending on the size of i
        int temp;  // the resulting digit will be kept by this temp variable

    for (int j=0; j<size; j++){
                        number=number.concat("0");
                    }

Integer multi = Integer.valueOf(number); // the variable used for dividing step by step the number we received 
                while(b){

                    multi=multi/10;
                    temp=i/(multi);
                    li.add(temp);
                    i=i%(multi);
                                        if(i==0){
                                        b=false;
                                        }


                }

                for(Integer in: li){
                    System.out.print(in.intValue()+ " ");
                }

Get Value of Row in Datatable c#

for (int i=0; i<dt_pattern.Rows.Count; i++)
{
    DataRow dr = dt_pattern.Rows[i];
}

In the loop, you can now reference row i+1 (assuming there is an i+1)

How to import a SQL Server .bak file into MySQL?

The .BAK files from SQL server are in Microsoft Tape Format (MTF) ref: http://www.fpns.net/willy/msbackup.htm

The bak file will probably contain the LDF and MDF files that SQL server uses to store the database.

You will need to use SQL server to extract these. SQL Server Express is free and will do the job.

So, install SQL Server Express edition, and open the SQL Server Powershell. There execute sqlcmd -S <COMPUTERNAME>\SQLExpress (whilst logged in as administrator)

then issue the following command.

restore filelistonly from disk='c:\temp\mydbName-2009-09-29-v10.bak';
GO

This will list the contents of the backup - what you need is the first fields that tell you the logical names - one will be the actual database and the other the log file.

RESTORE DATABASE mydbName FROM disk='c:\temp\mydbName-2009-09-29-v10.bak'
WITH 
   MOVE 'mydbName' TO 'c:\temp\mydbName_data.mdf', 
   MOVE 'mydbName_log' TO 'c:\temp\mydbName_data.ldf';
GO

At this point you have extracted the database - then install Microsoft's "Sql Web Data Administrator". together with this export tool and you will have an SQL script that contains the database.

Multi-statement Table Valued Function vs Inline Table Valued Function

Maybe in a very condensed way. ITVF ( inline TVF) : more if u are DB person, is kind of parameterized view, take a single SELECT st

MTVF ( Multi-statement TVF): Developer, creates and load a table variable.

Making a UITableView scroll when text field is selected

Solution for Swift 3-4 with animations and keyboard frame changing:

First, create a Bool:

// MARK: - Private Properties
private var isKeyboardShowing = false

Secondly, add Observers to the System Keyboard Notifications:

// MARK: - Overriding ViewController Life Cycle Methods
override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: .UIKeyboardWillShow, object: nil)

    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: .UIKeyboardWillHide, object: nil)

    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChangeFrame), name: .UIKeyboardWillChangeFrame, object: nil)
}

Thirdly, prepare the animation function:

func adjustTableViewInsets(keyboardHeight: CGFloat, duration: NSNumber, curve: NSNumber){
    var extraHeight: CGFloat = 0
    if keyboardHeight > 0 {
        extraHeight = 20
        isKeyboardShowing = true
    } else {
        isKeyboardShowing = false
    }

    let contentInset = UIEdgeInsets(top: 0, left: 0, bottom: keyboardHeight + extraHeight, right: 0)
    func animateFunc() {
        //refresh constraints
        //self.view.layoutSubviews()
        tableView.contentInset = contentInset
    }

    UIView.animate(withDuration: TimeInterval(duration), delay: 0, options: [UIViewAnimationOptions(rawValue: UInt(curve))], animations: animateFunc, completion: nil)
}

Then add the target/action methods (called by the observers):

// MARK: - Target/Selector Actions
func keyboardWillShow(notification: NSNotification) {
    if !isKeyboardShowing {
        if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
            let keyboardHeight = keyboardSize.height

            let duration = notification.userInfo?[UIKeyboardAnimationDurationUserInfoKey] as! NSNumber
            let curve = notification.userInfo?[UIKeyboardAnimationCurveUserInfoKey] as! NSNumber

            adjustTableViewInsets(keyboardHeight: keyboardHeight, duration: duration, curve: curve)
        }
    }
}

func keyboardWillHide(notification: NSNotification) {
    let duration = notification.userInfo?[UIKeyboardAnimationDurationUserInfoKey] as! NSNumber
    let curve = notification.userInfo?[UIKeyboardAnimationCurveUserInfoKey] as! NSNumber
    adjustTableViewInsets(keyboardHeight: 0, duration: duration, curve: curve)
}

func keyboardWillChangeFrame(notification: NSNotification) {
    if isKeyboardShowing {
        let duration = notification.userInfo?[UIKeyboardAnimationDurationUserInfoKey] as! NSNumber
        let curve = notification.userInfo?[UIKeyboardAnimationCurveUserInfoKey] as! NSNumber

        if let newKeyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
            let keyboardHeight = newKeyboardSize.height
            adjustTableViewInsets(keyboardHeight: keyboardHeight, duration: duration, curve: curve)
        }
    }
}

Lastly, don't forget to remove observers in deinit or in viewWillDisappear:

deinit {
    NotificationCenter.default.removeObserver(self)
}

How to Convert date into MM/DD/YY format in C#

 DateTime.Today.ToString("MM/dd/yy")

Look at the docs for custom date and time format strings for more info.

(Oh, and I hope this app isn't destined for other cultures. That format could really confuse a lot of people... I've never understood the whole month/day/year thing, to be honest. It just seems weird to go "middle/low/high" in terms of scale like that.)

NSNotificationCenter addObserver in Swift

NSNotificationCenter add observer syntax in Swift 4.0 for iOS 11

  NotificationCenter.default.addObserver(self, selector: #selector(keyboardShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)

This is for keyboardWillShow notification name type. Other type can be selected from the available option

the Selector is of type @objc func which handle how the keyboard will show ( this is your user function )

How to load data to hive from HDFS without removing the source file?

An alternative to 'LOAD DATA' is available in which the data will not be moved from your existing source location to hive data warehouse location.

You can use ALTER TABLE command with 'LOCATION' option. Here is below required command

ALTER TABLE table_name ADD PARTITION (date_col='2017-02-07') LOCATION 'hdfs/path/to/location/'

The only condition here is, the location should be a directory instead of file.

Hope this will solve the problem.

Cannot find runtime 'node' on PATH - Visual Studio Code and Node.js

I use /bin/zsh, and I changed vscode to do the same, but somehow vscode still use the path from /bin/bash. So I created a .bash_profile file with node location in the path.

Simply run in terminal:

echo "PATH=$PATH
export \$PATH" >> ~/.bash_profile

Restart vscode, and it will work.

Make TextBox uneditable

Enabled="false" in aspx page

Unit testing with mockito for constructors

Here is the code to mock this functionality using PowerMockito API.

Second mockedSecond = PowerMockito.mock(Second.class);
PowerMockito.whenNew(Second.class).withNoArguments().thenReturn(mockedSecond);

You need to use Powermockito runner and need to add required test classes (comma separated ) which are required to be mocked by powermock API .

@RunWith(PowerMockRunner.class)
@PrepareForTest({First.class,Second.class})
class TestClassName{
    // your testing code
}

How to sort List<Integer>?

To sort in ascending order :

Collections.sort(lList);

And for reverse order :

Collections.reverse(lList);

Restart node upon changing a file

Various NPM packages are available to make this task easy.

For Development

For Production (with extended functionality such as clustering, remote deploy etc.)

Comparison between Forever, pm2 and StrongLoop can be found on StrongLoop's website.

Angular 4 setting selected option in Dropdown

If you want to select a value based on true / false use

[selected]="opt.selected == true"

 <option *ngFor="let opt of question.options" [value]="opt.key" [selected]="opt.selected == true">{{opt.selected+opt.value}}</option>

checkit out

Angular 2 - Setting selected value on dropdown list

Oracle comparing timestamp with date

You can truncate the date part:

select * from table1 where trunc(field1) = to_date('2012-01-01', 'YYYY-MM-DD')

The trouble with this approach is that any index on field1 wouldn't be used due to the function call.

Alternatively (and more index friendly)

select * from table1 
 where field1 >= to_timestamp('2012-01-01', 'YYYY-MM-DD') 
   and field1 < to_timestamp('2012-01-02', 'YYYY-MM-DD')

How to define two angular apps / modules in one page?

You can bootstrap multiple angular applications, but:

1) You need to manually bootstrap them

2) You should not use "document" as the root, but the node where the angular interface is contained to:

var todoRootNode = jQuery('[ng-controller=TodoController]');
angular.bootstrap(todoRootNode, ['TodoApp']);

This would be safe.

AndroidStudio SDK directory does not exists

I think you should go to:

File ->Project Structure->SDK Location->

there select your sdk location.

In Javascript/jQuery what does (e) mean?

DISCLAIMER: This is a very late response to this particular post but as I've been reading through various responses to this question, it struck me that most of the answers use terminology that can only be understood by experienced coders. This answer is an attempt to address the original question with a novice audience in mind.

Intro

The little '(e)' thing is actually part of broader scope of something in Javascript called an event handling function. Every event handling function receives an event object. For the purpose of this discussion, think of an object as a "thing" that holds a bunch of properties (variables) and methods (functions), much like objects in other languages. The handle, the 'e' inside the little (e) thing, is like a variable that allows you to interact with the object (and I use the term variable VERY loosely).

Consider the following jQuery examples:

$("#someLink").on("click", function(e){ // My preferred method
    e.preventDefault();
});

$("#someLink").click(function(e){ // Some use this method too
    e.preventDefault();
});

Explanation

  • "#someLink" is your element selector (which HTML tag will trigger this).
  • "click" is an event (when the selected element is clicked).
  • "function(e)" is the event handling function (on event, object is created).
  • "e" is the object handler (object is made accessible).
  • "preventDefault()" is a method (function) provided by the object.

What's happening?
When a user clicks on the element with the id "#someLink" (probably an anchor tag), call an anonymous function, "function(e)", and assign the resulting object to a handler, "e". Now take that handler and call one of its methods, "e.preventDefault()", which should prevent the browser from performing the default action for that element.

Note: The handle can pretty much be named anything you want (i.e. 'function(billybob)'). The 'e' stands for 'event', which seems to be pretty standard for this type of function.

Although 'e.preventDefault()' is probably the most common use of the event handler, the object itself contains many properties and methods that can be accessed via the event handler.

Some really good information on this topic can be found at jQuery's learning site, http://learn.jquery.com. Pay special attention to the Using jQuery Core and Events sections.

CSS - Overflow: Scroll; - Always show vertical scroll bar?

This will work with iPad on Safari on iOS 7.1.x from my testing, I'm not sure about iOS 6 though. However, it will not work on Firefox. There is a jQuery plugin which aims to be cross browser compliant called jScrollPane.

Also, there is a duplicate post here on Stack Overflow which has some other details.

Before and After Suite execution hook in jUnit 4.x

If you don't want to create a suite and have to list all your test classes you can use reflection to find the number of test classes dynamically and count down in a base class @AfterClass to do the tearDown only once:

public class BaseTestClass
{
    private static int testClassToRun = 0;

    // Counting the classes to run so that we can do the tear down only once
    static {
        try {
            Field field = ClassLoader.class.getDeclaredField("classes");
            field.setAccessible(true);

            @SuppressWarnings({ "unchecked", "rawtypes" })
            Vector<Class> classes = (Vector<Class>) field.get(BlockJUnit4ClassRunner.class.getClassLoader());
            for (Class<?> clazz : classes) {
                if (clazz.getName().endsWith("Test")) {
                    testClassToRun++;
                }
            }
        } catch (Exception ignore) {
        }
    }

    // Setup that needs to be done only once
    static {
        // one time set up
    }

    @AfterClass
    public static void baseTearDown() throws Exception
    {
        if (--testClassToRun == 0) {
            // one time clean up
        }
    }
}

If you prefer to use @BeforeClass instead of the static blocks, you can also use a boolean flag to do the reflection count and test setup only once at the first call. Hope this helps someone, it took me an afternoon to figure out a better way than enumerating all classes in a suite.

Now all you need to do is extend this class for all your test classes. We already had a base class to provide some common stuff for all our tests so this was the best solution for us.

Inspiration comes from this SO answer https://stackoverflow.com/a/37488620/5930242

If you don't want to extend this class everywhere, this last SO answer might do what you want.

npm WARN ... requires a peer of ... but none is installed. You must install peer dependencies yourself

In my case following commands worked for me:

sudo npm cache clean --force
sudo npm install -g npm


sudo apt install libssl1.0-dev
sudo apt install nodejs-dev
sudo apt install node-gyp
sudo apt install npm

After that if you are facing "Cannot find module 'bcrypt' then for that you can resolve this one with below commands:

npm install node-gyp -g
npm install bcrypt -g
npm install bcrypt --save  

Hope it will work for you as well.

Split a String into an array in Swift?

Swift Dev. 4.0 (May 24, 2017)

A new function split in Swift 4 (Beta).

import Foundation
let sayHello = "Hello Swift 4 2017";
let result = sayHello.split(separator: " ")
print(result)

Output:

["Hello", "Swift", "4", "2017"]

Accessing values:

print(result[0]) // Hello
print(result[1]) // Swift
print(result[2]) // 4
print(result[3]) // 2017

Xcode 8.1 / Swift 3.0.1

Here is the way multiple delimiters with array.

import Foundation
let mathString: String = "12-37*2/5"
let numbers = mathString.components(separatedBy: ["-", "*", "/"])
print(numbers)

Output:

["12", "37", "2", "5"]

Jenkins, specifying JAVA_HOME

openjdk-6 is a Java runtime, not a JDK (development kit which contains javac, for example). Install openjdk-6-jdk.

Maven also needs the JDK.

[EDIT] When the JDK is installed, use /usr/lib/jvm/java-6-openjdk for JAVA_HOME (i.e. without the jre part).

How to configure Spring Security to allow Swagger URL to be accessed without authentication

Considering all of your API requests located with a url pattern of /api/.. you can tell spring to secure only this url pattern by using below configuration. Which means that you are telling spring what to secure instead of what to ignore.

@Override
protected void configure(HttpSecurity http) throws Exception {
  http
    .csrf().disable()
     .authorizeRequests()
      .antMatchers("/api/**").authenticated()
      .anyRequest().permitAll()
      .and()
    .httpBasic().and()
    .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}

What does the 'Z' mean in Unix timestamp '120314170138Z'?

Yes. 'Z' stands for Zulu time, which is also GMT and UTC.

From http://en.wikipedia.org/wiki/Coordinated_Universal_Time:

The UTC time zone is sometimes denoted by the letter Z—a reference to the equivalent nautical time zone (GMT), which has been denoted by a Z since about 1950. The letter also refers to the "zone description" of zero hours, which has been used since 1920 (see time zone history). Since the NATO phonetic alphabet and amateur radio word for Z is "Zulu", UTC is sometimes known as Zulu time.

Technically, because the definition of nautical time zones is based on longitudinal position, the Z time is not exactly identical to the actual GMT time 'zone'. However, since it is primarily used as a reference time, it doesn't matter what area of Earth it applies to as long as everyone uses the same reference.

From wikipedia again, http://en.wikipedia.org/wiki/Nautical_time:

Around 1950, a letter suffix was added to the zone description, assigning Z to the zero zone, and A–M (except J) to the east and N–Y to the west (J may be assigned to local time in non-nautical applications; zones M and Y have the same clock time but differ by 24 hours: a full day). These were to be vocalized using a phonetic alphabet which pronounces the letter Z as Zulu, leading sometimes to the use of the term "Zulu Time". The Greenwich time zone runs from 7.5°W to 7.5°E longitude, while zone A runs from 7.5°E to 22.5°E longitude, etc.

Converting NSData to NSString in Objective c

-[NSString initWithData:encoding] will return nil if the specified encoding doesn't match the data's encoding.

Make sure your data is encoded in UTF-8 (or change NSUTF8StringEncoding to whatever encoding that's appropriate for the data).

Declaring a boolean in JavaScript using just var

Variables in Javascript don't have a type. Non-zero, non-null, non-empty and true are "true". Zero, null, undefined, empty string and false are "false".

There's a Boolean type though, as are literals true and false.

Scala best way of turning a Collection into a Map-by-key?

Another solution (might not work for all types)

import scala.collection.breakOut
val m:Map[P, T] = c.map(t => (t.getP, t))(breakOut)

this avoids the creation of the intermediary list, more info here: Scala 2.8 breakOut

GoTo Next Iteration in For Loop in java

If you want to skip current iteration, use continue;.

for(int i = 0; i < 5; i++){
    if (i == 2){
        continue;
    }
 }

Need to break out of the whole loop? Use break;

for(int i = 0; i < 5; i++){
    if (i == 2){
        break;
    }
}

If you need to break out of more than one loop use break someLabel;

outerLoop:                                           // Label the loop
for(int j = 0; j < 5; j++){
     for(int i = 0; i < 5; i++){
        if (i==2){
          break outerLoop;
        }
     }
  }

*Note that in this case you are not marking a point in code to jump to, you are labeling the loop! So after the break the code will continue right after the loop!

When you need to skip one iteration in nested loops use continue someLabel;, but you can also combine them all.

outerLoop:
for(int j = 0; j < 10; j++){
     innerLoop:
     for(int i = 0; i < 10; i++){
        if (i + j == 2){
          continue innerLoop;
        }
        if (i + j == 4){
          continue outerLoop;
        }
        if (i + j == 6){
          break innerLoop;
        }
        if (i + j == 8){
          break outerLoop;
        }
     }
  }

TSQL - Cast string to integer or return default value

I would rather create a function like TryParse or use T-SQL TRY-CATCH block to get what you wanted.

ISNUMERIC doesn't always work as intended. The code given before will fail if you do:

SET @text = '$'

$ sign can be converted to money datatype, so ISNUMERIC() returns true in that case. It will do the same for '-' (minus), ',' (comma) and '.' characters.

How to change font size in Eclipse for Java text editors?

Enter image description here

Menu Window ? Preferences. General ? Appearance ? Colors and Fonts ? Basic ? Text Font

Arduino Tools > Serial Port greyed out

Try to run as an administrator... Run terminal, type sudo arduino, type your root password, and... :)

How to fix Error: this class is not key value coding-compliant for the key tableView.'

Any chance that you changed the name of your table view from "tableView" to "myTableView" at some point?

Generate a random number in the range 1 - 10

This stored procedure inserts a rand number into a table. Look out, it inserts an endless numbers. Stop executing it when u get enough numbers.

create a table for the cursor:

CREATE TABLE [dbo].[SearchIndex](
[ID] [int] IDENTITY(1,1) NOT NULL,
[Cursor] [nvarchar](255) NULL) 

GO

Create a table to contain your numbers:

CREATE TABLE [dbo].[ID](
[IDN] [int] IDENTITY(1,1) NOT NULL,
[ID] [int] NULL)

INSERTING THE SCRIPT :

INSERT INTO [SearchIndex]([Cursor])  SELECT N'INSERT INTO ID  SELECT   FLOOR(rand() * 9 + 1)  SELECT COUNT (ID) FROM ID

CREATING AND EXECUTING THE PROCEDURE:

CREATE PROCEDURE [dbo].[RandNumbers] AS
BEGIN
Declare  CURSE  CURSOR  FOR (SELECT  [Cursor] FROM [dbo].[SearchIndex]  WHERE [Cursor] IS NOT NULL)
DECLARE @RandNoSscript NVARCHAR (250)
OPEN CURSE
FETCH NEXT FROM CURSE
INTO @RandNoSscript 
WHILE @@FETCH_STATUS IS NOT NULL 
BEGIN
Print @RandNoSscript
EXEC SP_EXECUTESQL @RandNoSscript;  
 END
 END
GO

Fill your table:

EXEC RandNumbers

CSS vertical alignment text inside li

line-height is how you vertically align text. It is pretty standard and I don't consider it a "hack". Just add line-height: 100px to your ul.catBlock li and it will be fine.

In this case you may have to add it to ul.catBlock li a instead since all of the text inside the li is also inside of an a. I have seen some weird things happen when you do this, so try both and see which one works.

Select row and element in awk

To expand on Dennis's answer, use awk's -v option to pass the i and j values:

# print the j'th field of the i'th line
awk -v i=5 -v j=3 'FNR == i {print $j}'

Does JavaScript have a built in stringbuilder class?

When I find myself doing a lot of string concatenation in JavaScript, I start looking for templating. Handlebars.js works quite well keeping the HTML and JavaScript more readable. http://handlebarsjs.com

Difference between fprintf, printf and sprintf?

sprintf: Writes formatted data to a character string in memory instead of stdout

Syntax of sprintf is:

#include <stdio.h>
int sprintf (char *string, const char *format
[,item [,item]…]);

Here,

String refers to the pointer to a buffer in memory where the data is to be written.

Format refers to pointer to a character string defining the format.

Each item is a variable or expression specifying the data to write.

The value returned by sprintf is greater than or equal to zero if the operation is successful or in other words the number of characters written, not counting the terminating null character is returned and returns a value less than zero if an error occurred.

printf: Prints to stdout

Syntax for printf is:

printf format [argument]…

The only difference between sprintf() and printf() is that sprintf() writes data into a character array, while printf() writes data to stdout, the standard output device.

JPA or JDBC, how are they different?

JDBC is a much lower-level (and older) specification than JPA. In it's bare essentials, JDBC is an API for interacting with a database using pure SQL - sending queries and retrieving results. It has no notion of objects or hierarchies. When using JDBC, it's up to you to translate a result set (essentially a row/column matrix of values from one or more database tables, returned by your SQL query) into Java objects.

Now, to understand and use JDBC it's essential that you have some understanding and working knowledge of SQL. With that also comes a required insight into what a relational database is, how you work with it and concepts such as tables, columns, keys and relationships. Unless you have at least a basic understanding of databases, SQL and data modelling you will not be able to make much use of JDBC since it's really only a thin abstraction on top of these things.

What is (functional) reactive programming?

The paper Simply efficient functional reactivity by Conal Elliott (direct PDF, 233 KB) is a fairly good introduction. The corresponding library also works.

The paper is now superceded by another paper, Push-pull functional reactive programming (direct PDF, 286 KB).

Simple Android grid example using RecyclerView with GridLayoutManager (like the old GridView)

Although I do like and appreciate Suragch's answer, I would like to leave a note because I found that coding the Adapter (MyRecyclerViewAdapter) to define and expose the Listener method onItemClick isn't the best way to do it, due to not using class encapsulation correctly. So my suggestion is to let the Adapter handle the Listening operations solely (that's his purpose!) and separate those from the Activity that uses the Adapter (MainActivity). So this is how I would set the Adapter class:

MyRecyclerViewAdapter.java

public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.ViewHolder> {

    private String[] mData = new String[0];
    private LayoutInflater mInflater;

    // Data is passed into the constructor
    public MyRecyclerViewAdapter(Context context, String[] data) {
        this.mInflater = LayoutInflater.from(context);
        this.mData = data;
    }

    // Inflates the cell layout from xml when needed
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = mInflater.inflate(R.layout.recyclerview_item, parent, false);
        ViewHolder viewHolder = new ViewHolder(view);
        return viewHolder;
    }

    // Binds the data to the textview in each cell
    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        String animal = mData[position];
        holder.myTextView.setText(animal);
    }

    // Total number of cells
    @Override
    public int getItemCount() {
        return mData.length;
    }

    // Stores and recycles views as they are scrolled off screen
    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        public TextView myTextView;

        public ViewHolder(View itemView) {
            super(itemView);
            myTextView = (TextView) itemView.findViewById(R.id.info_text);
            itemView.setOnClickListener(this);
        }

        @Override
        public void onClick(View view) {
            onItemClick(view, getAdapterPosition());
        }
    }

    // Convenience method for getting data at click position
    public String getItem(int id) {
        return mData[id];
    }

    // Method that executes your code for the action received
    public void onItemClick(View view, int position) {
        Log.i("TAG", "You clicked number " + getItem(position).toString() + ", which is at cell position " + position);
    }
}

Please note the onItemClick method now defined in MyRecyclerViewAdapter that is the place where you would want to code your tasks for the event/action received.

There is only a small change to be done in order to complete this transformation: the Activity doesn't need to implement MyRecyclerViewAdapter.ItemClickListener anymore, because now that is done completely by the Adapter. This would then be the final modification:

MainActivity.java

public class MainActivity extends AppCompatActivity {

    MyRecyclerViewAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // data to populate the RecyclerView with
        String[] data = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48"};

        // set up the RecyclerView
        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.rvNumbers);
        int numberOfColumns = 6;
        recyclerView.setLayoutManager(new GridLayoutManager(this, numberOfColumns));
        adapter = new MyRecyclerViewAdapter(this, data);
        adapter.setClickListener(this);
        recyclerView.setAdapter(adapter);
    }
}

iOS: Compare two dates

NSDate actually represents a time interval in seconds since a reference date (1st Jan 2000 UTC I think). Internally, a double precision floating point number is used so two arbitrary dates are highly unlikely to compare equal even if they are on the same day. If you want to see if a particular date falls on a particular day, you probably need to use NSDateComponents. e.g.

NSDateComponents* dateComponents = [[NSDateComponents alloc] init];
[dateComponents setYear: 2011];
[dateComponents setMonth: 5];
[dateComponents setDay: 24];
/*
 *  Construct two dates that bracket the day you are checking.  
 *  Use the user's current calendar.  I think this takes care of things like daylight saving time.
 */
NSCalendar* calendar = [NSCalendar currentCalendar];
NSDate* startOfDate = [calendar dateFromComponents: dateComponents];
NSDateComponents* oneDay = [[NSDateComponents alloc] init];
[oneDay setDay: 1];
NSDate* endOfDate = [calendar dateByAddingComponents: oneDay toDate: startOfDate options: 0];
/*
 *  Compare the date with the start of the day and the end of the day.
 */
NSComparisonResult startCompare = [startOfDate compare: myDate];
NSComparisonResult endCompare = [endOfDate compare: myDate];

if (startCompare != NSOrderedDescending && endCompare == NSOrderedDescending)
{
    // we are on the right date
} 

Joda DateTime to Timestamp conversion

//This Works just fine
DateTime dt = new DateTime();
Log.d("ts",String.valueOf(dt.now()));               
dt=dt.plusYears(3);
dt=dt.minusDays(7);
Log.d("JODA DateTime",String.valueOf(dt));
Timestamp ts= new Timestamp(dt.getMillis());
Log.d("Coverted to java.sql.Timestamp",String.valueOf(ts));

Can I use DIV class and ID together in CSS?

#y.x should work. And it's convenient too. You can make a page with different kinds of output. You can give a certain element an id, but give it different classes depending on the look you want.

Using pip behind a proxy with CNTLM

With Ubuntu I could not get the proxy option to work as advertised – so following command did not work:

sudo pip --proxy http://web-proxy.mydomain.com install somepackage

But exporting the https_proxy environment variable (note its https_proxy not http_proxy) did the trick:

export https_proxy=http://web-proxy.mydomain.com

then

sudo -E pip install somepackage

'printf' with leading zeros in C

Your format specifier is incorrect. From the printf() man page on my machine:

0 A zero '0' character indicating that zero-padding should be used rather than blank-padding. A '-' overrides a '0' if both are used;

Field Width: An optional digit string specifying a field width; if the output string has fewer characters than the field width it will be blank-padded on the left (or right, if the left-adjustment indicator has been given) to make up the field width (note that a leading zero is a flag, but an embedded zero is part of a field width);

Precision: An optional period, '.', followed by an optional digit string giving a precision which specifies the number of digits to appear after the decimal point, for e and f formats, or the maximum number of characters to be printed from a string; if the digit string is missing, the precision is treated as zero;

For your case, your format would be %09.3f:

#include <stdio.h>

int main(int argc, char **argv)
{
  printf("%09.3f\n", 4917.24);
  return 0;
}

Output:

$ make testapp
cc     testapp.c   -o testapp
$ ./testapp 
04917.240

Note that this answer is conditional on your embedded system having a printf() implementation that is standard-compliant for these details - many embedded environments do not have such an implementation.

Check if value exists in dataTable?

DataRow rw = table.AsEnumerable().FirstOrDefault(tt => tt.Field<string>("Author") == "Name");
if (rw != null)
{
// row exists
}

add to your using clause :

using System.Linq;

and add :

System.Data.DataSetExtensions

to references.

How to Auto-start an Android Application?

Edit your AndroidManifest.xml to add RECEIVE_BOOT_COMPLETED permission

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

Edit your AndroidManifest.xml application-part for below Permission

<receiver android:enabled="true" android:name=".BootUpReceiver"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
</receiver>

Now write below in Activity.

public class BootUpReceiver extends BroadcastReceiver{
    @Override
    public void onReceive(Context context, Intent intent) {
        Intent i = new Intent(context, MyActivity.class);  
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(i);  
    }
}

How do I get which JRadioButton is selected from a ButtonGroup

Use the isSelected() method. It will tell you the state of your radioButton. Using it in combination with a loop(say for loop) you can find which one has been selected.

Get the size of the screen, current web page and browser window

You can get the size of the window or document with jQuery:

// Size of browser viewport.
$(window).height();
$(window).width();

// Size of HTML document (same as pageHeight/pageWidth in screenshot).
$(document).height();
$(document).width();

For screen size you can use the screen object:

window.screen.height;
window.screen.width;

Configuring Hibernate logging using Log4j XML config file?

From http://docs.jboss.org/hibernate/core/3.3/reference/en/html/session-configuration.html#configuration-logging

Here's the list of logger categories:

Category                    Function

org.hibernate.SQL           Log all SQL DML statements as they are executed
org.hibernate.type          Log all JDBC parameters
org.hibernate.tool.hbm2ddl  Log all SQL DDL statements as they are executed
org.hibernate.pretty        Log the state of all entities (max 20 entities) associated with the session at flush time
org.hibernate.cache         Log all second-level cache activity
org.hibernate.transaction   Log transaction related activity
org.hibernate.jdbc          Log all JDBC resource acquisition
org.hibernate.hql.ast.AST   Log HQL and SQL ASTs during query parsing
org.hibernate.secure        Log all JAAS authorization requests
org.hibernate               Log everything (a lot of information, but very useful for troubleshooting) 

Formatted for pasting into a log4j XML configuration file:

<!-- Log all SQL DML statements as they are executed -->
<Logger name="org.hibernate.SQL" level="debug" />
<!-- Log all JDBC parameters -->
<Logger name="org.hibernate.type" level="debug" />
<!-- Log all SQL DDL statements as they are executed -->
<Logger name="org.hibernate.tool.hbm2ddl" level="debug" />
<!-- Log the state of all entities (max 20 entities) associated with the session at flush time -->
<Logger name="org.hibernate.pretty" level="debug" />
<!-- Log all second-level cache activity -->
<Logger name="org.hibernate.cache" level="debug" />
<!-- Log transaction related activity -->
<Logger name="org.hibernate.transaction" level="debug" />
<!-- Log all JDBC resource acquisition -->
<Logger name="org.hibernate.jdbc" level="debug" />
<!-- Log HQL and SQL ASTs during query parsing -->
<Logger name="org.hibernate.hql.ast.AST" level="debug" />
<!-- Log all JAAS authorization requests -->
<Logger name="org.hibernate.secure" level="debug" />
<!-- Log everything (a lot of information, but very useful for troubleshooting) -->
<Logger name="org.hibernate" level="debug" />

NB: Most of the loggers use the DEBUG level, however org.hibernate.type uses TRACE. In previous versions of Hibernate org.hibernate.type also used DEBUG, but as of Hibernate 3 you must set the level to TRACE (or ALL) in order to see the JDBC parameter binding logging.

And a category is specified as such:

<logger name="org.hibernate">
    <level value="ALL" />
    <appender-ref ref="FILE"/>
</logger>

It must be placed before the root element.

Setting a max character length in CSS

That's not possible with CSS, you will have to use the Javascript for that. Although you can set the width of the p to as much as 30 characters and next letters will automatically come down but again this won't be that accurate and will vary if the characters are in capital.

What does file:///android_asset/www/index.html mean?

If someone uses AndroidStudio make sure that the assets folder is placed in

  1. app/src/main/assets

    directory.

Error occurred during initialization of VM Could not reserve enough space for object heap Could not create the Java virtual machine

you can do update the User path as inside _JAVA_OPTIONS : -Xmx512M Path : C:\Program Files (x86)\Java\jdk1.8.0_231\bin;C:\Program Files(x86)\Java\jdk1.8.0_231\jre\bin for now it is working / /

Does dispatch_async(dispatch_get_main_queue(), ^{...}); wait until done?

No it doesn't wait and the way you are doing it in that sample is not good practice.

dispatch_async is always asynchronous. It's just that you are enqueueing all the UI blocks to the same queue so the different blocks will run in sequence but parallel with your data processing code.

If you want the update to wait you can use dispatch_sync instead.

// This will wait to finish
dispatch_sync(dispatch_get_main_queue(), ^{
    // Update the UI on the main thread.
});

Another approach would be to nest enqueueing the block. I wouldn't recommend it for multiple levels though.

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    // Background work

    dispatch_async(dispatch_get_main_queue(), ^{
        // Update UI

        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            // Background work

            dispatch_async(dispatch_get_main_queue(), ^{
                // Update UI
            });
        });
    });
});

If you need the UI updated to wait then you should use the synchronous versions. It's quite okay to have a background thread wait for the main thread. UI updates should be very quick.

How to disable text selection using jQuery?

In jQuery 1.8, this can be done as follows:

(function($){
    $.fn.disableSelection = function() {
        return this
                 .attr('unselectable', 'on')
                 .css('user-select', 'none')
                 .on('selectstart', false);
    };
})(jQuery);

Disable future dates after today in Jquery Ui Datepicker

datepicker doesnot have a maxDate as an option.I used this endDate option.It worked well.

> $('.demo-calendar-default').datepicker({
>                 autoHide: true,
>                 zIndex: 2048,
>                 format: 'dd/mm/yyyy',
>                 endDate: new Date()
>             });

How to use the divide function in the query?

Try something like this

select Cast((SPGI09_EARLY_OVER_T – (SPGI09_OVER_WK_EARLY_ADJUST_T) / (SPGI09_EARLY_OVER_T + SPGR99_LATE_CM_T  + SPGR99_ON_TIME_Q)) as varchar(20) + '%' as percentageAmount
from CSPGI09_OVERSHIPMENT

I presume the value is a representation in percentage - if not convert it to a valid percentage total, then add the % sign and convert the column to varchar.

Spring's overriding bean

Question was more about XML but as annotation are more popular nowadays and it works similarly I'll show by example. Let's create class Foo:

public class Foo {
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

and two Configuration files (you can't create one):

@Configuration
public class Configuration1 {
    @Bean
    public Foo foo() {
        Foo foo = new Foo();
        foo.setName("configuration1");
        return foo;
    }
}

and

@Configuration
public class Configuration2 {
    @Bean
    public Foo foo() {
        Foo foo = new Foo();
        foo.setName("configuration2");
        return foo;
    }
}

and let's see what happens when calling foo.getName():

@SpringBootApplication
public class OverridingBeanDefinitionsApplication {

    public static void main(String[] args) {
        SpringApplication.run(OverridingBeanDefinitionsApplication.class, args);

        AnnotationConfigApplicationContext applicationContext =
                new AnnotationConfigApplicationContext(
                        Configuration1.class, Configuration2.class);

        Foo foo = applicationContext.getBean(Foo.class);
        System.out.println(foo.getName());
    }
}

in this example result is: configuration2. The Spring Container gets all configuration metadata sources and merges bean definitions in those sources. In this example there are two @Beans. Order in which they are fed into ApplicationContext decide. You can flip new AnnotationConfigApplicationContext(Configuration2.class, Configuration1.class); and result will be configuration1.

Is it possible to decompile an Android .apk file?

Sometimes you get broken code, when using dex2jar/apktool, most notably in loops. To avoid this, use jadx, which decompiles dalvik bytecode into java source code, without creating a .jar/.class file first as dex2jar does (apktool uses dex2jar I think). It is also open-source and in active development. It even has a GUI, for GUI-fanatics. Try it!

Cannot push to Git repository on Bitbucket

I found the git command line didnt fancy my pageant generated keys (Windows 10).

See my answer on Serverfault

How do I run a docker instance from a DockerFile?

While other answers were usable, this really helped me, so I am putting it also here.

From the documentation:

Instead of specifying a context, you can pass a single Dockerfile in the URL or pipe the file in via STDIN. To pipe a Dockerfile from STDIN:

$ docker build - < Dockerfile

With Powershell on Windows, you can run:

Get-Content Dockerfile | docker build -

When the build is done, run command:

docker image ls

You will see something like this:

REPOSITORY                 TAG                 IMAGE ID            CREATED             SIZE
<none>                     <none>              123456789        39 seconds ago      422MB

Copy your actual IMAGE ID and then run

docker run 123456789

Where the number at the end is the actual Image ID from previous step

If you do not want to remember the image id, you can tag your image by

docker tag 123456789 pavel/pavel-build

Which will tag your image as pavel/pavel-build

ERROR 2003 (HY000): Can't connect to MySQL server on '127.0.0.1' (111)

i just restart my mysql server and the problem solved in windows net stop MySQL then net start MySQl ubuntu linux sudo service start mysql

XmlDocument - load from string?

XmlDocument doc = new XmlDocument();
doc.LoadXml(str);

Where str is your XML string. See the MSDN article for more info.

Store output of subprocess.Popen call in a string

The accepted answer is still good, just a few remarks on newer features. Since python 3.6, you can handle encoding directly in check_output, see documentation. This returns a string object now:

import subprocess 
out = subprocess.check_output(["ls", "-l"], encoding="utf-8")

In python 3.7, a parameter capture_output was added to subprocess.run(), which does some of the Popen/PIPE handling for us, see the python docs :

import subprocess 
p2 = subprocess.run(["ls", "-l"], capture_output=True, encoding="utf-8")
p2.stdout

Printing with sed or awk a line following a matching pattern

Never use the word "pattern" as is it highly ambiguous. Always use "string" or "regexp" (or in shell "globbing pattern"), whichever it is you really mean.

The specific answer you want is:

awk 'f{print;f=0} /regexp/{f=1}' file

or specializing the more general solution of the Nth record after a regexp (idiom "c" below):

awk 'c&&!--c; /regexp/{c=1}' file

The following idioms describe how to select a range of records given a specific regexp to match:

a) Print all records from some regexp:

awk '/regexp/{f=1}f' file

b) Print all records after some regexp:

awk 'f;/regexp/{f=1}' file

c) Print the Nth record after some regexp:

awk 'c&&!--c;/regexp/{c=N}' file

d) Print every record except the Nth record after some regexp:

awk 'c&&!--c{next}/regexp/{c=N}1' file

e) Print the N records after some regexp:

awk 'c&&c--;/regexp/{c=N}' file

f) Print every record except the N records after some regexp:

awk 'c&&c--{next}/regexp/{c=N}1' file

g) Print the N records from some regexp:

awk '/regexp/{c=N}c&&c--' file

I changed the variable name from "f" for "found" to "c" for "count" where appropriate as that's more expressive of what the variable actually IS.

Pure JavaScript: a function like jQuery's isNumeric()

There is Javascript function isNaN which will do that.

isNaN(90)
=>false

so you can check numeric by

!isNaN(90)
=>true

Initialize value of 'var' in C# to null

var variables still have a type - and the compiler error message says this type must be established during the declaration.

The specific request (assigning an initial null value) can be done, but I don't recommend it. It doesn't provide an advantage here (as the type must still be specified) and it could be viewed as making the code less readable:

var x = (String)null;

Which is still "type inferred" and equivalent to:

String x = null;

The compiler will not accept var x = null because it doesn't associate the null with any type - not even Object. Using the above approach, var x = (Object)null would "work" although it is of questionable usefulness.

Generally, when I can't use var's type inference correctly then

  1. I am at a place where it's best to declare the variable explicitly; or
  2. I should rewrite the code such that a valid value (with an established type) is assigned during the declaration.

The second approach can be done by moving code into methods or functions.

How to check SQL Server version

Following are possible ways to see the version:

Method 1: Connect to the instance of SQL Server, and then run the following query:

Select @@version

An example of the output of this query is as follows:

Microsoft SQL Server 2008 (SP1) - 10.0.2531.0 (X64)   Mar 29 2009 
10:11:52   Copyright (c) 1988-2008 Microsoft Corporation  Express 
Edition (64-bit) on Windows NT 6.1 <X64> (Build 7600: )

Method 2: Connect to the server by using Object Explorer in SQL Server Management Studio. After Object Explorer is connected, it will show the version information in parentheses, together with the user name that is used to connect to the specific instance of SQL Server.

Method 3: Look at the first few lines of the Errorlog file for that instance. By default, the error log is located at Program Files\Microsoft SQL Server\MSSQL.n\MSSQL\LOG\ERRORLOG and ERRORLOG.n files. The entries may resemble the following:

2011-03-27 22:31:33.50 Server      Microsoft SQL Server 2008 (SP1) - 10.0.2531.0 (X64)                 Mar 29 2009 10:11:52                 Copyright (c) 1988-2008 Microsoft Corporation                Express Edition (64-bit) on Windows NT 6.1 <X64> (Build 7600: )

As you can see, this entry gives all the necessary information about the product, such as version, product level, 64-bit versus 32-bit, the edition of SQL Server, and the OS version on which SQL Server is running.

Method 4: Connect to the instance of SQL Server, and then run the following query:

SELECT SERVERPROPERTY('productversion'), SERVERPROPERTY ('productlevel'), SERVERPROPERTY ('edition')

Note This query works with any instance of SQL Server 2000 or of a later version

Post form data using HttpWebRequest

Use this code:

internal void SomeFunction() {
    Dictionary<string, string> formField = new Dictionary<string, string>();
    
    formField.Add("Name", "Henry");
    formField.Add("Age", "21");
    
    string body = GetBodyStringFromDictionary(formField);
    // output : Name=Henry&Age=21
}

internal string GetBodyStringFromDictionary(Dictionary<string, string> formField)
{
    string body = string.Empty;
    foreach (var pair in formField)
    {
        body += $"{pair.Key}={pair.Value}&";   
    }

    // delete last "&"
    body = body.Substring(0, body.Length - 1);

    return body;
}

Get all LI elements in array

After some years have passed, you can do that now with ES6 Array.from (or spread syntax):

_x000D_
_x000D_
const navbar = Array.from(document.querySelectorAll('#navbar>ul>li'));_x000D_
console.log('Get first: ', navbar[0].textContent);_x000D_
_x000D_
// If you need to iterate once over all these nodes, you can use the callback function:_x000D_
console.log('Iterate with Array.from callback argument:');_x000D_
Array.from(document.querySelectorAll('#navbar>ul>li'),li => console.log(li.textContent))_x000D_
_x000D_
// ... or a for...of loop:_x000D_
console.log('Iterate with for...of:');_x000D_
for (const li of document.querySelectorAll('#navbar>ul>li')) {_x000D_
    console.log(li.textContent);_x000D_
}
_x000D_
.as-console-wrapper { max-height: 100% !important; top: 0; }
_x000D_
<div id="navbar">_x000D_
  <ul>_x000D_
    <li id="navbar-One">One</li>_x000D_
    <li id="navbar-Two">Two</li>_x000D_
    <li id="navbar-Three">Three</li>_x000D_
  </ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Save string to the NSUserDefaults?

update for Swift 3

func setObject(value:AnyObject ,key:String)
{
    let pref = UserDefaults.standard
    pref.set(value, forKey: key)
    pref.synchronize()
}

func getObject(key:String) -> AnyObject
{
    let pref = UserDefaults.standard
    return pref.object(forKey: key)! as AnyObject
}

Android SDK Setup under Windows 7 Pro 64 bit

My problem was installing the Android SDK in Eclipse Helios on Windows 7 Enterprise 64bit, I was getting the following error:

Missing requirement: Android Development Tools 0.9.7.v201005071157-36220 (com.android.ide.eclipse.adt.feature.group 0.9.7.v201005071157-36220) requires 'org.eclipse.jdt.junit 0.0.0' but it could not be found

Having followed the advice above to ensure that the JDK was in my PATH variable (it wasn't), installation went smoothly. I guess the error was somewhat spurious (incidentally if you're looking for the JARs that correspond to that class, they were in my profile rather than the Eclipse installation directory)

So, check that PATH variable!

Making a button invisible by clicking another button in HTML

Use this code :

<input type="button" onclick="demoShow()" value="edit" />
<script type="text/javascript"> 
function demoShow()
{document.getElementById("p2").style.visibility="hidden";}
</script>
<input id="p2" type="submit" value="submit" name="submit" />

The real difference between "int" and "unsigned int"

Yes, because in your case they use the same representation.

The bit pattern 0xFFFFFFFF happens to look like -1 when interpreted as a 32b signed integer and as 4294967295 when interpreted as a 32b unsigned integer.

It's the same as char c = 65. If you interpret it as a signed integer, it's 65. If you interpret it as a character it's a.


As R and pmg point out, technically it's undefined behavior to pass arguments that don't match the format specifiers. So the program could do anything (from printing random values to crashing, to printing the "right" thing, etc).

The standard points it out in 7.19.6.1-9

If a conversion speci?cation is invalid, the behavior is unde?ned. If any argument is not the correct type for the corresponding conversion speci?cation, the behavior is unde?ned.

Python argparse: default value or specified value

import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--example', nargs='?', const=1, type=int)
args = parser.parse_args()
print(args)

% test.py 
Namespace(example=None)
% test.py --example
Namespace(example=1)
% test.py --example 2
Namespace(example=2)

  • nargs='?' means 0-or-1 arguments
  • const=1 sets the default when there are 0 arguments
  • type=int converts the argument to int

If you want test.py to set example to 1 even if no --example is specified, then include default=1. That is, with

parser.add_argument('--example', nargs='?', const=1, type=int, default=1)

then

% test.py 
Namespace(example=1)

Javascript - Append HTML to container element without innerHTML

How to fish and while using strict code. There are two prerequisite functions needed at the bottom of this post.

xml_add('before', id_('element_after'), '<span xmlns="http://www.w3.org/1999/xhtml">Some text.</span>');

xml_add('after', id_('element_before'), '<input type="text" xmlns="http://www.w3.org/1999/xhtml" />');

xml_add('inside', id_('element_parent'), '<input type="text" xmlns="http://www.w3.org/1999/xhtml" />');

Add multiple elements (namespace only needs to be on the parent element):

xml_add('inside', id_('element_parent'), '<div xmlns="http://www.w3.org/1999/xhtml"><input type="text" /><input type="button" /></div>');

Dynamic reusable code:

function id_(id) {return (document.getElementById(id)) ? document.getElementById(id) : false;}

function xml_add(pos, e, xml)
{
 e = (typeof e == 'string' && id_(e)) ? id_(e) : e;

 if (e.nodeName)
 {
  if (pos=='after') {e.parentNode.insertBefore(document.importNode(new DOMParser().parseFromString(xml,'application/xml').childNodes[0],true),e.nextSibling);}
  else if (pos=='before') {e.parentNode.insertBefore(document.importNode(new DOMParser().parseFromString(xml,'application/xml').childNodes[0],true),e);}
  else if (pos=='inside') {e.appendChild(document.importNode(new DOMParser().parseFromString(xml,'application/xml').childNodes[0],true));}
  else if (pos=='replace') {e.parentNode.replaceChild(document.importNode(new DOMParser().parseFromString(xml,'application/xml').childNodes[0],true),e);}
  //Add fragment and have it returned.
 }
}

How to convert CSV file to multiline JSON?

Add the indent parameter to json.dumps

 data = {'this': ['has', 'some', 'things'],
         'in': {'it': 'with', 'some': 'more'}}
 print(json.dumps(data, indent=4))

Also note that, you can simply use json.dump with the open jsonfile:

json.dump(data, jsonfile)

SQL Server : Arithmetic overflow error converting expression to data type int

Is the problem with SUM(billableDuration)? To find out, try commenting out that line and see if it works.

It could be that the sum is exceeding the maximum int. If so, try replacing it with SUM(CAST(billableDuration AS BIGINT)).

How to loop through an associative array and get the key?

I use the following loop to get the key and value from an associative array

foreach ($array as $key => $value)
{
  echo "<p>$key = $value</p>";
}

How to import a csv file using python with headers intact, where first column is a non-numerical

You can use pandas library and reference the rows and columns like this:

import pandas as pd

input = pd.read_csv("path_to_file");

#for accessing ith row:
input.iloc[i]

#for accessing column named X
input.X

#for accessing ith row and column named X
input.iloc[i].X