Programs & Examples On #Control library

Code for printf function in C

Here's the GNU version of printf... you can see it passing in stdout to vfprintf:

__printf (const char *format, ...)
{
   va_list arg;
   int done;

   va_start (arg, format);
   done = vfprintf (stdout, format, arg);
   va_end (arg);

   return done;
}

See here.

Here's a link to vfprintf... all the formatting 'magic' happens here.

The only thing that's truly 'different' about these functions is that they use varargs to get at arguments in a variable length argument list. Other than that, they're just traditional C. (This is in contrast to Pascal's printf equivalent, which is implemented with specific support in the compiler... at least it was back in the day.)

Why can't I have abstract static methods in C#?

We actually override static methods (in delphi), it's a bit ugly, but it works just fine for our needs.

We use it so the classes can have a list of their available objects without the class instance, for example, we have a method that looks like this:

class function AvailableObjects: string; override;
begin
  Result := 'Object1, Object2';
end; 

It's ugly but necessary, this way we can instantiate just what is needed, instead of having all the classes instantianted just to search for the available objects.

This was a simple example, but the application itself is a client-server application which has all the classes available in just one server, and multiple different clients which might not need everything the server has and will never need an object instance.

So this is much easier to maintain than having one different server application for each client.

Hope the example was clear.

How to Execute SQL Script File in Java?

No, you must read the file, split it into separate queries and then execute them individually (or using the batch API of JDBC).

One of the reasons is that every database defines their own way to separate SQL statements (some use ;, others /, some allow both or even to define your own separator).

How to make div appear in front of another?

I think you're missing something.

http://jsfiddle.net/ZNtKj/

<ul>
 <li style="height:100px;overflow:hidden;">
  <div style="height:500px; background-color:black;">
  </div>
 </li>
</ul>
<ul>
 <li style="height:100px;">
  <div style="height:500px; background-color:red;">
  </div>
 </li>
</ul>

In FF4, this displays a 100px black bar, followed by a 500px red block.

A little bit different example:

http://jsfiddle.net/ZNtKj/1/

<ul>
 <li style="height:100px;overflow:hidden;">
  <div style="height:500px; background-color:black;">
  </div>
 </li>
</ul>
<ul>
 <li style="height:100px;">
  <div style="height:500px; background-color:red;">
  </div>
 </li>
 <li style="height:100px;overflow:hidden;">
  <div style="height:500px; background-color:blue;">
  </div>
 </li>
 <li style="height:100px;overflow:hidden;">
  <div style="height:500px; background-color:green;">
  </div>
 </li>
</ul>

Getting Index of an item in an arraylist;

Rather than a brute force loop through the list (eg 1 to 10000), rather use an iterative search approach : The List needs to be sorted by the element to be tested.

Start search at the middle element size()/2 eg 5000 if search item greater than element at 5000, then test the element at the midpoint between the upper(10000) and midpoint(5000) - 7500

keep doing this until you reach the match (or use a brute force loop through once you get down to a smaller range (eg 20 items)

You can search a list of 10000 in around 13 to 14 tests, rather than potentially 9999 tests.

Add key value pair to all objects in array

Simply use map function:

var arrOfObj = arrOfObj.map(function(element){
   element.active = true;
   return element;
}

Map is pretty decent on compatibility: you can be reasonably safe from IE <= 9.

However, if you are 100% sure your users will use ES6 Compatible browser, you can shorten that function with arrow functions, as @Sergey Panfilov has suggested.

Android Split string

.split method will work, but it uses regular expressions. In this example it would be (to steal from Cristian):

String[] separated = CurrentString.split("\\:");
separated[0]; // this will contain "Fruit"
separated[1]; // this will contain " they taste good"

Also, this came from: Android split not working correctly

Uncaught TypeError: Cannot set property 'value' of null

h_url=document.getElementById("u") is null here

There is no element exist with id as u

ASP MVC href to a controller/view

Try the following:

<a asp-controller="Users" asp-action="Index"></a>

(Valid for ASP.NET 5 and MVC 6)

Printing without newline (print 'a',) prints a space, how to remove?

If you want them to show up one at a time, you can do this:

import time
import sys
for i in range(20):
    sys.stdout.write('a')
    sys.stdout.flush()
    time.sleep(0.5)

sys.stdout.flush() is necessary to force the character to be written each time the loop is run.

Invoking a jQuery function after .each() has completed

I'm using something like this:

$.when(
           $.each(yourArray, function (key, value) {
                // Do Something in loop here
            })
          ).then(function () {
               // After loop ends.
          });

Web scraping with Python

If we think of getting name of items from any specific category then we can do that by specifying the class name of that category using css selector:

import requests ; from bs4 import BeautifulSoup

soup = BeautifulSoup(requests.get('https://www.flipkart.com/').text, "lxml")
for link in soup.select('div._2kSfQ4'):
    print(link.text)

This is the partial search results:

Puma, USPA, Adidas & moreUp to 70% OffMen's Shoes
Shirts, T-Shirts...Under ?599For Men
Nike, UCB, Adidas & moreUnder ?999Men's Sandals, Slippers
Philips & moreStarting ?99LED Bulbs & Emergency Lights

What's the equivalent of Java's Thread.sleep() in JavaScript?

Try with this code. I hope it's useful for you.

function sleep(seconds) 
{
  var e = new Date().getTime() + (seconds * 1000);
  while (new Date().getTime() <= e) {}
}

How to append multiple values to a list in Python

You can use the sequence method list.extend to extend the list by multiple values from any kind of iterable, being it another list or any other thing that provides a sequence of values.

>>> lst = [1, 2]
>>> lst.append(3)
>>> lst.append(4)
>>> lst
[1, 2, 3, 4]

>>> lst.extend([5, 6, 7])
>>> lst.extend((8, 9, 10))
>>> lst
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

>>> lst.extend(range(11, 14))
>>> lst
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]

So you can use list.append() to append a single value, and list.extend() to append multiple values.

How to check if smtp is working from commandline (Linux)

The only thing about using telnet to test postfix, or other SMTP, is that you have to know the commands and syntax. Instead, just use swaks :)

thufir@dur:~$ 
thufir@dur:~$ mail -f Maildir
"/home/thufir/Maildir": 4 messages
>    1 [email protected]                   15/553   test Mon, 30 Dec 2013 10:15:12 -0800
     2 [email protected]                   15/581   test Mon, 30 Dec 2013 10:15:55 -0800
     3 [email protected]                   15/581   test Mon, 30 Dec 2013 10:29:57 -0800
     4 [email protected]                   15/581   test Mon, 30 Dec 2013 11:54:16 -0800
? q
Held 4 messages in /home/thufir/Maildir
thufir@dur:~$ 
thufir@dur:~$ swaks --to [email protected]
=== Trying dur.bounceme.net:25...
=== Connected to dur.bounceme.net.
<-  220 dur.bounceme.net ESMTP Postfix (Ubuntu)
 -> EHLO dur.bounceme.net
<-  250-dur.bounceme.net
<-  250-PIPELINING
<-  250-SIZE 10240000
<-  250-VRFY
<-  250-ETRN
<-  250-STARTTLS
<-  250-ENHANCEDSTATUSCODES
<-  250-8BITMIME
<-  250 DSN
 -> MAIL FROM:<[email protected]>
<-  250 2.1.0 Ok
 -> RCPT TO:<[email protected]>
<-  250 2.1.5 Ok
 -> DATA
<-  354 End data with <CR><LF>.<CR><LF>
 -> Date: Mon, 30 Dec 2013 14:33:17 -0800
 -> To: [email protected]
 -> From: [email protected]
 -> Subject: test Mon, 30 Dec 2013 14:33:17 -0800
 -> X-Mailer: swaks v20130209.0 jetmore.org/john/code/swaks/
 -> 
 -> This is a test mailing
 -> 
 -> .
<-  250 2.0.0 Ok: queued as 52D162C3EFF
 -> QUIT
<-  221 2.0.0 Bye
=== Connection closed with remote host.
thufir@dur:~$ 
thufir@dur:~$ mail -f Maildir
"/home/thufir/Maildir": 5 messages 1 new
     1 [email protected]                   15/553   test Mon, 30 Dec 2013 10:15:12 -0800
     2 [email protected]                   15/581   test Mon, 30 Dec 2013 10:15:55 -0800
     3 [email protected]                   15/581   test Mon, 30 Dec 2013 10:29:57 -0800
     4 [email protected]                   15/581   test Mon, 30 Dec 2013 11:54:16 -0800
>N   5 [email protected]                   15/581   test Mon, 30 Dec 2013 14:33:17 -0800
? 5
Return-Path: <[email protected]>
X-Original-To: [email protected]
Delivered-To: [email protected]
Received: from dur.bounceme.net (localhost [127.0.0.1])
    by dur.bounceme.net (Postfix) with ESMTP id 52D162C3EFF
    for <[email protected]>; Mon, 30 Dec 2013 14:33:17 -0800 (PST)
Date: Mon, 30 Dec 2013 14:33:17 -0800
To: [email protected]
From: [email protected]
Subject: test Mon, 30 Dec 2013 14:33:17 -0800
X-Mailer: swaks v20130209.0 jetmore.org/john/code/swaks/
Message-Id: <[email protected]>

This is a test mailing

New mail has arrived.
? q
Held 5 messages in /home/thufir/Maildir
thufir@dur:~$ 

It's just one easy command.

Android Studio: Add jar as library?

In the project right click

-> new -> module
-> import jar/AAR package
-> import select the jar file to import
-> click ok -> done

Follow the screenshots below:

1:

Step 1

2:

enter image description here

3:

enter image description here

You will see this:

enter image description here

@class vs. #import

Use a forward declaration in the header file if needed, and #import the header files for any classes you're using in the implementation. In other words, you always #import the files you're using in your implementation, and if you need to reference a class in your header file use a forward declaration as well.

The exception to this is that you should #import a class or formal protocol you're inheriting from in your header file (in which case you wouldn't need to import it in the implementation).

Conditional formatting using AND() function

I was having the same problem with the AND() breaking the conditional formatting. I just happened to try treating the AND as multiplication, and it works! Remove the AND() function and just multiply your arguments. Excel will treat the booleans as 1 for true and 0 for false. I just tested this formula and it seems to work.

=(INDIRECT(ADDRESS(4,COLUMN()))>=INDIRECT(ADDRESS(ROW(),4)))*(INDIRECT(ADDRESS(4,COLUMN()))<=INDIRECT(ADDRESS(ROW(),5)))

How to programmatically move, copy and delete files and directories on SD?

/**
     * Copy the local DB file of an application to the root of external storage directory
     * @param context the Context of application
     * @param dbName The name of the DB
     */
    private void copyDbToExternalStorage(Context context , String dbName){

        try {
            File name = context.getDatabasePath(dbName);
            File sdcardFile = new File(Environment.getExternalStorageDirectory() , "test.db");//The name of output file
            sdcardFile.createNewFile();
            InputStream inputStream = null;
            OutputStream outputStream = null;
            inputStream = new FileInputStream(name);
            outputStream = new FileOutputStream(sdcardFile);
            byte[] buffer = new byte[1024];
            int read;
            while ((read = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, read);
            }
            inputStream.close();
            outputStream.flush();
            outputStream.close();
        }
        catch (Exception e) {
            Log.e("Exception" , e.toString());
        }
    }

Project with path ':mypath' could not be found in root project 'myproject'

I got similar error after deleting a subproject, removed

"*compile project(path: ':MySubProject', configuration: 'android-endpoints')*"

in build.gradle (dependencies) under Gradle Scripts

Unable to execute dex: Multiple dex files define

I have also faced this problem in my project. AVD is not able to reload assets,lib,res and etc folder contexts. problem : Dex Loader] Unable to execute dex: Multiple dex files define Landroid/support/v4/accessibilityservice/AccessibilityServiceInfoCompat$AccessibilityServiceInfoVersionImpl.

Then,I created new projects and copied MainActivity.java,activity_main.xml, drawable context. Then delete old project from package explore,restart your Eclipse and AVD. My project is now working properly.... :) I hope this steps will help u little bit folks..!!

Date constructor returns NaN in IE, but works in Firefox and Chrome

Try out using getDate feature of datepicker.

$.datepicker.formatDate('yy-mm-dd',new Date(pField.datepicker("getDate")));

using where and inner join in mysql

You can use as many joins as you want, however, the more you use the more it will impact performance

Using setImageDrawable dynamically to set image in an ImageView

All the answers posted do not apply today. For example, getDrawable() is deprecated. Here is an updated answer, cheers!

ContextCompat.getDrawable(mContext, drawable)

From documented method

public static final android.graphics.drawable.Drawable getDrawable(@NotNull android.content.Context context,
@android.support.annotation.DrawableRes int id

How to hide iOS status bar

You should add this value to plist: "View controller-based status bar appearance" and set it to "NO".

change the date format in laravel view page

There are 3 ways that you can do:

1) Using Laravel Model

$user = \App\User::find(1);

$newDateFormat = $user->created_at->format('d/m/Y');

dd($newDateFormat);

2) Using PHP strtotime

$user = \App\User::find(1);

$newDateFormat2 = date('d/m/Y', strtotime($user->created_at));

dd($newDateFormat2);

3) Using Carbon

$user = \App\User::find(1);

$newDateFormat3 = \Carbon\Carbon::parse($user->created_at)->format('d/m/Y');

dd($newDateFormat3);

Is there a wikipedia API just for retrieve content summary?

If you are just looking for the text which you can then split up but don't want to use the API take a look at en.wikipedia.org/w/index.php?title=Elephant&action=raw

No submodule mapping found in .gitmodule for a path that's not a submodule

Just git rm subdir will be ok. that will remove the subdir as an index.

How do I set the request timeout for one controller action in an asp.net mvc application

I had to add "Current" using .NET 4.5:

HttpContext.Current.Server.ScriptTimeout = 300;

SSIS expression: convert date to string

For SSIS you could go with:

RIGHT("0" + (DT_STR, 2, 1252) DATEPART("dd" , GETDATE()), 2) + "-" + RIGHT("0" + (DT_STR, 2, 1252) DATEPART("mm" , GETDATE()), 2) + "-" +  (DT_STR, 4, 1252) DATEPART("yy" , GETDATE())

Expression builder screen:

Expression builder screen

AES Encryption for an NSString on the iPhone

I waited a bit on @QuinnTaylor to update his answer, but since he didn't, here's the answer a bit more clearly and in a way that it will load on XCode7 (and perhaps greater). I used this in a Cocoa application, but it likely will work okay with an iOS application as well. Has no ARC errors.

Paste before any @implementation section in your AppDelegate.m or AppDelegate.mm file.

#import <CommonCrypto/CommonCryptor.h>

@implementation NSData (AES256)

- (NSData *)AES256EncryptWithKey:(NSString *)key {
    // 'key' should be 32 bytes for AES256, will be null-padded otherwise
    char keyPtr[kCCKeySizeAES256+1]; // room for terminator (unused)
    bzero(keyPtr, sizeof(keyPtr)); // fill with zeroes (for padding)

    // fetch key data
    [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];

    NSUInteger dataLength = [self length];

    //See the doc: For block ciphers, the output size will always be less than or 
    //equal to the input size plus the size of one block.
    //That's why we need to add the size of one block here
    size_t bufferSize = dataLength + kCCBlockSizeAES128;
    void *buffer = malloc(bufferSize);

    size_t numBytesEncrypted = 0;
    CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding,
                                     keyPtr, kCCKeySizeAES256,
                                     NULL /* initialization vector (optional) */,
                                     [self bytes], dataLength, /* input */
                                     buffer, bufferSize, /* output */
                                     &numBytesEncrypted);
    if (cryptStatus == kCCSuccess) {
        //the returned NSData takes ownership of the buffer and will free it on deallocation
        return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
    }

    free(buffer); //free the buffer;
    return nil;
}

- (NSData *)AES256DecryptWithKey:(NSString *)key {
    // 'key' should be 32 bytes for AES256, will be null-padded otherwise
    char keyPtr[kCCKeySizeAES256+1]; // room for terminator (unused)
    bzero(keyPtr, sizeof(keyPtr)); // fill with zeroes (for padding)

    // fetch key data
    [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];

    NSUInteger dataLength = [self length];

    //See the doc: For block ciphers, the output size will always be less than or 
    //equal to the input size plus the size of one block.
    //That's why we need to add the size of one block here
    size_t bufferSize = dataLength + kCCBlockSizeAES128;
    void *buffer = malloc(bufferSize);

    size_t numBytesDecrypted = 0;
    CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding,
                                     keyPtr, kCCKeySizeAES256,
                                     NULL /* initialization vector (optional) */,
                                     [self bytes], dataLength, /* input */
                                     buffer, bufferSize, /* output */
                                     &numBytesDecrypted);

    if (cryptStatus == kCCSuccess) {
        //the returned NSData takes ownership of the buffer and will free it on deallocation
        return [NSData dataWithBytesNoCopy:buffer length:numBytesDecrypted];
    }

    free(buffer); //free the buffer;
    return nil;
}

@end

Paste these two functions in the @implementation class you desire. In my case, I chose @implementation AppDelegate in my AppDelegate.mm or AppDelegate.m file.

- (NSString *) encryptString:(NSString*)plaintext withKey:(NSString*)key {
    NSData *data = [[plaintext dataUsingEncoding:NSUTF8StringEncoding] AES256EncryptWithKey:key];
    return [data base64EncodedStringWithOptions:kNilOptions];
}

- (NSString *) decryptString:(NSString *)ciphertext withKey:(NSString*)key {
    NSData *data = [[NSData alloc] initWithBase64EncodedString:ciphertext options:kNilOptions];
    return [[NSString alloc] initWithData:[data AES256DecryptWithKey:key] encoding:NSUTF8StringEncoding];
}

How to use python numpy.savetxt to write strings and float number to an ASCII file?

The currently accepted answer does not actually address the question, which asks how to save lists that contain both strings and float numbers. For completeness I provide a fully working example, which is based, with some modifications, on the link given in @joris comment.

import numpy as np

names  = np.array(['NAME_1', 'NAME_2', 'NAME_3'])
floats = np.array([ 0.1234 ,  0.5678 ,  0.9123 ])

ab = np.zeros(names.size, dtype=[('var1', 'U6'), ('var2', float)])
ab['var1'] = names
ab['var2'] = floats

np.savetxt('test.txt', ab, fmt="%10s %10.3f")

Update: This example also works properly in Python 3 by using the 'U6' Unicode string dtype, when creating the ab structured array, instead of the 'S6' byte string. The latter dtype would work in Python 2.7, but would write strings like b'NAME_1' in Python 3.

How do I add a library project to Android Studio?

To resolve this problem, you just need to add the abs resource path to your project build file, just like below:

sourceSets {
    main {
        res.srcDirs = ['src/main/res','../../ActionBarSherlock/actionbarsherlock/res']
    }
}

So, I again compile without any errors.

How do I use a Boolean in Python?

Booleans in python are subclass of integer. Constructor of booleans is bool. bool class inherits from int class.

 issubclass(bool,int) // will return True
 isinstance(True,bool) , isinstance(False,bool) //they both True

True and False are singleton objects. they will retain same memory address throughout the lifetime of your app. When you type True, python memory manager will check its address and will pull the value '1'. for False its value is '0'.

Comparisons of any boolean expression to True or False can be performed using either is (identity) or == (equality) operator.

int(True) == 1
int(False) == 0

But note that True and '1' are not the same objects. You can check:

 id(True) == id(1) // will return False

you can also easily see that

  True > False // returns true cause 1>0

any integer operation can work with the booleans.

  True + True + True =3 

All objects in python have an associated truth value. Every object has True value except:

  • None

  • False

  • 0 in any numeric type (0,0.0,0+0j etc)

  • empty sequences (list, tuple, string)

  • empty mapping types (dictionary, set, etc)

  • custom classes that implement __bool__ or __len__ method that returns False or 0.

every class in python has truth values defined by a special instance method:

 __bool__(self)   OR
 __len__

When you call bool(x) python will actually execute

 x.__bool__() 

if instance x does not have this method, then it will execute

 x.__len__()

if this does not exist, by default value is True.

For Example for int class we can define bool as below:

  def __bool__(self):
      return self != 0

for bool(100), 100 !=0 will return True. So

bool(100) == True

you can easily check that bool(0) will be False. with this for instances of int class only 0 will return False.

another example= bool([1,2,3])

[1,2,3] has no __bool__() method defined but it has __len__() and since its length is greater than 0, it will return True. Now you can see why empty lists return False.

Postgres and Indexes on Foreign Keys and Primary Keys

For a PRIMARY KEY, an index will be created with the following message:

NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "index" for table "table" 

For a FOREIGN KEY, the constraint will not be created if there is no index on the referenced table.

An index on referencing table is not required (though desired), and therefore will not be implicitly created.

What does -> mean in Python function definitions?

In the following code:

def f(x) -> int:
    return int(x)

the -> int just tells that f() returns an integer (but it doesn't force the function to return an integer). It is called a return annotation, and can be accessed as f.__annotations__['return'].

Python also supports parameter annotations:

def f(x: float) -> int:
    return int(x)

: float tells people who read the program (and some third-party libraries/programs, e. g. pylint) that x should be a float. It is accessed as f.__annotations__['x'], and doesn't have any meaning by itself. See the documentation for more information:

https://docs.python.org/3/reference/compound_stmts.html#function-definitions https://www.python.org/dev/peps/pep-3107/

pip install: Please check the permissions and owner of that directory

pip install --user <package name> (no sudo needed) worked for me for a very similar problem.

How to set Meld as git mergetool

I think that mergetool.meld.path should point directly to the meld executable. Thus, the command you want is:

git config --global mergetool.meld.path c:/Progra~2/meld/bin/meld

Change Twitter Bootstrap Tooltip content on click

Destroy any pre-existing tooltip so we can repopulate with new tooltip content

$(element).tooltip("destroy");    
$(element).tooltip({
    title: message
});

Javascript format date / time

For the date part:(month is 0-indexed while days are 1-indexed)

var date = new Date('2014-8-20');
console.log((date.getMonth()+1) + '/' + date.getDate() + '/' +  date.getFullYear());

for the time you'll want to create a function to test different situations and convert.

How can I URL encode a string in Excel VBA?

I had problem with encoding cyrillic letters to URF-8.

I modified one of the above scripts to match cyrillic char map. Implmented is the cyrrilic section of

https://en.wikipedia.org/wiki/UTF-8 and http://www.utf8-chartable.de/unicode-utf8-table.pl?start=1024

Other sections development is sample and need verification with real data and calculate the char map offsets

Here is the script:

Public Function UTF8Encode( _
   StringToEncode As String, _
   Optional UsePlusRatherThanHexForSpace As Boolean = False _
) As String

  Dim TempAns As String
  Dim TempChr As Long
  Dim CurChr As Long
  Dim Offset As Long
  Dim TempHex As String
  Dim CharToEncode As Long
  Dim TempAnsShort As String

  CurChr = 1

  Do Until CurChr - 1 = Len(StringToEncode)
    CharToEncode = Asc(Mid(StringToEncode, CurChr, 1))
' http://www.utf8-chartable.de/unicode-utf8-table.pl?start=1024
' as per https://en.wikipedia.org/wiki/UTF-8 specification the engoding is as follows

    Select Case CharToEncode
'   7   U+0000 U+007F 1 0xxxxxxx
      Case 48 To 57, 65 To 90, 97 To 122
        TempAns = TempAns & Mid(StringToEncode, CurChr, 1)
      Case 32
        If UsePlusRatherThanHexForSpace = True Then
          TempAns = TempAns & "+"
        Else
          TempAns = TempAns & "%" & Hex(32)
        End If
      Case 0 To &H7F
            TempAns = TempAns + "%" + Hex(CharToEncode And &H7F)
      Case &H80 To &H7FF
'   11  U+0080 U+07FF 2 110xxxxx 10xxxxxx
' The magic is in offset calculation... there are different offsets between UTF-8 and Windows character maps
' offset 192 = &HC0 = 1100 0000 b  added to start of UTF-8 cyrillic char map at &H410
          CharToEncode = CharToEncode - 192 + &H410
          TempAnsShort = "%" & Right("0" & Hex((CharToEncode And &H3F) Or &H80), 2)
          TempAnsShort = "%" & Right("0" & Hex(((CharToEncode \ &H40) And &H1F) Or &HC0), 2) & TempAnsShort
          TempAns = TempAns + TempAnsShort

'' debug and development version
''          CharToEncode = CharToEncode - 192 + &H410
''          TempChr = (CharToEncode And &H3F) Or &H80
''          TempHex = Hex(TempChr)
''          TempAnsShort = "%" & Right("0" & TempHex, 2)
''          TempChr = ((CharToEncode And &H7C0) / &H40) Or &HC0
''          TempChr = ((CharToEncode \ &H40) And &H1F) Or &HC0
''          TempHex = Hex(TempChr)
''          TempAnsShort = "%" & Right("0" & TempHex, 2) & TempAnsShort
''          TempAns = TempAns + TempAnsShort

      Case &H800 To &HFFFF
'   16 U+0800 U+FFFF 3 1110xxxx 10xxxxxx 10xxxxxx
' not tested . Doesnot match Case condition... very strange
        MsgBox ("Char to encode  matched U+0800 U+FFFF: " & CharToEncode & " = &H" & Hex(CharToEncode))
''          CharToEncode = CharToEncode - 192 + &H410
          TempAnsShort = "%" & Right("0" & Hex((CharToEncode And &H3F) Or &H80), 2)
          TempAnsShort = "%" & Right("0" & Hex(((CharToEncode \ &H40) And &H3F) Or &H80), 2) & TempAnsShort
          TempAnsShort = "%" & Right("0" & Hex(((CharToEncode \ &H1000) And &HF) Or &HE0), 2) & TempAnsShort
          TempAns = TempAns + TempAnsShort

      Case &H10000 To &H1FFFFF
'   21 U+10000 U+1FFFFF 4 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
''        MsgBox ("Char to encode  matched &H10000 &H1FFFFF: " & CharToEncode & " = &H" & Hex(CharToEncode))
' sample offset. tobe verified
          CharToEncode = CharToEncode - 192 + &H410
          TempAnsShort = "%" & Right("0" & Hex((CharToEncode And &H3F) Or &H80), 2)
          TempAnsShort = "%" & Right("0" & Hex(((CharToEncode \ &H40) And &H3F) Or &H80), 2) & TempAnsShort
          TempAnsShort = "%" & Right("0" & Hex(((CharToEncode \ &H1000) And &H3F) Or &H80), 2) & TempAnsShort
          TempAnsShort = "%" & Right("0" & Hex(((CharToEncode \ &H40000) And &H7) Or &HF0), 2) & TempAnsShort
          TempAns = TempAns + TempAnsShort

      Case &H200000 To &H3FFFFFF
'   26  U+200000 U+3FFFFFF 5 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
''        MsgBox ("Char to encode  matched U+200000 U+3FFFFFF: " & CharToEncode & " = &H" & Hex(CharToEncode))
' sample offset. tobe verified
          CharToEncode = CharToEncode - 192 + &H410
          TempAnsShort = "%" & Right("0" & Hex((CharToEncode And &H3F) Or &H80), 2)
          TempAnsShort = "%" & Right("0" & Hex(((CharToEncode \ &H40) And &H3F) Or &H80), 2) & TempAnsShort
          TempAnsShort = "%" & Right("0" & Hex(((CharToEncode \ &H1000) And &H3F) Or &H80), 2) & TempAnsShort
          TempAnsShort = "%" & Right("0" & Hex(((CharToEncode \ &H40000) And &H3F) Or &H80), 2) & TempAnsShort
          TempAnsShort = "%" & Right("0" & Hex(((CharToEncode \ &H1000000) And &H3) Or &HF8), 2) & TempAnsShort
          TempAns = TempAns + TempAnsShort

      Case &H4000000 To &H7FFFFFFF
'   31  U+4000000 U+7FFFFFFF 6 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
''        MsgBox ("Char to encode  matched U+4000000 U+7FFFFFFF: " & CharToEncode & " = &H" & Hex(CharToEncode))
' sample offset. tobe verified
          CharToEncode = CharToEncode - 192 + &H410
          TempAnsShort = "%" & Right("0" & Hex((CharToEncode And &H3F) Or &H80), 2)
          TempAnsShort = "%" & Right("0" & Hex(((CharToEncode \ &H40) And &H3F) Or &H80), 2) & TempAnsShort
          TempAnsShort = "%" & Right("0" & Hex(((CharToEncode \ &H1000) And &H3F) Or &H80), 2) & TempAnsShort
          TempAnsShort = "%" & Right("0" & Hex(((CharToEncode \ &H40000) And &H3F) Or &H80), 2) & TempAnsShort
          TempAnsShort = "%" & Right("0" & Hex(((CharToEncode \ &H1000000) And &H3F) Or &H80), 2) & TempAnsShort
          TempAnsShort = "%" & Right("0" & Hex(((CharToEncode \ &H40000000) And &H1) Or &HFC), 2) & TempAnsShort
          TempAns = TempAns + TempAnsShort

      Case Else
' somethig else
' to be developped
        MsgBox ("Char to encode not matched: " & CharToEncode & " = &H" & Hex(CharToEncode))

    End Select

    CurChr = CurChr + 1
  Loop

  UTF8Encode = TempAns
End Function

Good luck!

What is the => assignment in C# in a property signature

Ok... I made a comment that they were different but couldn't explain exactly how but now I know.

String Property { get; } = "value";

is not the same as

String Property => "value";

Here's the difference...

When you use the auto initializer the property creates the instance of value and uses that value persistently. In the above post there is a broken link to Bill Wagner, that explains this well, and I searched the correct link to understand it myself.

In my situation I had my property auto initialize a command in a ViewModel for a View. I changed the property to use expression bodied initializer and the command CanExecute stopped working.

Here's what it looked like and here's what was happening.

Command MyCommand { get; } = new Command();  //works

here's what I changed it to.

Command MyCommand => new Command();  //doesn't work properly

The difference here is when I use { get; } = I create and reference the SAME command in that property. When I use => I actually create a new command and return it every time the property is called. Therefore, I could never update the CanExecute on my command because I was always telling it to update a new reference of that command.

{ get; } = // same reference
=>         // new reference

All that said, if you are just pointing to a backing field then it works fine. This only happens when the auto or expression body creates the return value.

How to add elements of a Java8 stream into an existing List

I would concatenate the old list and new list as streams and save the results to destination list. Works well in parallel, too.

I will use the example of accepted answer given by Stuart Marks:

List<String> destList = Arrays.asList("foo");
List<String> newList = Arrays.asList("0", "1", "2", "3", "4", "5");

destList = Stream.concat(destList.stream(), newList.stream()).parallel()
            .collect(Collectors.toList());
System.out.println(destList);

//output: [foo, 0, 1, 2, 3, 4, 5]

Hope it helps.

How to search for file names in Visual Studio?

In Visual Studio 2008 (and probably later), the free DevExpress CodeRush Xpress add-in supplies Ctrl+Alt+F, Quick File Navigation, which searches on an exact substring in the file name or on capital letters.

(Unrelated to this answer, but note the rather more useful, Quick Navigation, Ctrl+Shift+Q, which I would have liked to have known about before now :-) )

How to use enums in C++

Enums in C++ are like integers masked by the names you give them, when you declare your enum-values (this is not a definition only a hint how it works).

But there are two errors in your code:

  1. Spell enum all lower case
  2. You don't need the Days. before Saturday.
  3. If this enum is declared in a class, then use if (day == YourClass::Saturday){}

Why is Visual Studio 2013 very slow?

I had a Visual Studio 2013 installed, and it was running smoothly. At some point it started to get sluggish and decided to install Visual Studio 2015. After install, nothing changed and both versions were building the solution very slow (around 10 minutes for 18 projects in solution).

Then I have started thinking of recently installed extensions - the most recent installed was PHP tools for Visual Studio (had it on Visual Studio 2013 only). I am not sure how can an extension affect other versions of Visual Studio, but uninstalling it helped me to solve the problem.

I hope this will help others to realize that it is not always Visual Studio's fault.

ORA-01008: not all variables bound. They are bound

The solution in my situation was similar answer to Charles Burns; and the problem was related to SQL code comments.

I was building (or updating, rather) an already-functioning SSRS report with Oracle datasource. I added some more parameters to the report, tested it in Visual Studio, it works great, so I deployed it to the report server, and then when the report is executed the report on the server I got the error message:

"ORA-01008: not all variables bound"

I tried quite a few different things (TNSNames.ora file installed on the server, Removed single line comments, Validate dataset query mapping). What it came down to was I had to remove a comment block directly after the WHERE keyword. The error message was resolved after moving the comment block after the WHERE CLAUSE conditions. I have other comments in the code also. It was just the one after the WHERE keyword causing the error.

SQL with error: "ORA-01008: not all variables bound"...

WHERE
/*
    OHH.SHIP_DATE BETWEEN TO_DATE('10/1/2018', 'MM/DD/YYYY') AND TO_DATE('10/31/2018', 'MM/DD/YYYY')
    AND OHH.STATUS_CODE<>'DL'
    AND OHH.BILL_COMP_CODE=100
    AND OHH.MASTER_ORDER_NBR IS NULL
*/

    OHH.SHIP_DATE BETWEEN :paramStartDate AND :paramEndDate
    AND OHH.STATUS_CODE<>'DL'
    AND OHH.BILL_COMP_CODE IN (:paramCompany)
    AND LOAD.DEPART_FROM_WHSE_CODE IN (:paramWarehouse) 
    AND OHH.MASTER_ORDER_NBR IS NULL
    AND LOAD.CLASS_CODE IN (:paramClassCode) 
    AND CUST.CUST_CODE || '-' || CUST.CUST_SHIPTO_CODE IN (:paramShipto) 

SQL executes successfully on the report server...

WHERE
    OHH.SHIP_DATE BETWEEN :paramStartDate AND :paramEndDate
    AND OHH.STATUS_CODE<>'DL'
    AND OHH.BILL_COMP_CODE IN (:paramCompany)
    AND LOAD.DEPART_FROM_WHSE_CODE IN (:paramWarehouse) 
    AND OHH.MASTER_ORDER_NBR IS NULL
    AND LOAD.CLASS_CODE IN (:paramClassCode) 
    AND CUST.CUST_CODE || '-' || CUST.CUST_SHIPTO_CODE IN (:paramShipto)   
/*
    OHH.SHIP_DATE BETWEEN TO_DATE('10/1/2018', 'MM/DD/YYYY') AND TO_DATE('10/31/2018', 'MM/DD/YYYY')
    AND OHH.STATUS_CODE<>'DL'
    AND OHH.BILL_COMP_CODE=100
    AND OHH.MASTER_ORDER_NBR IS NULL
*/

Here is what the dataset parameter mapping screen looks like.

enter image description here

How can I use nohup to run process as a background process in linux?

You can write a script and then use nohup ./yourscript & to execute

For example:

vi yourscript

put

#!/bin/bash
script here

you may also need to change permission to run script on server

chmod u+rwx yourscript

finally

nohup ./yourscript &

MySQL: How to allow remote connection to mysql

And for OS X people out there be aware that the bind-address parameter is typically set in the launchd plist and not in the my.ini file. So in my case, I removed <string>--bind-address=127.0.0.1</string> from /Library/LaunchDaemons/homebrew.mxcl.mariadb.plist.

Difference between ref and out parameters in .NET

Ref parameters aren't required to be set in the function, whereas out parameters must be bound to a value before exiting the function. Variables passed as out may also be passed to a function without being initialized.

Java sending and receiving file (byte[]) over sockets

Rookie, if you want to write a file to server by socket, how about using fileoutputstream instead of dataoutputstream? dataoutputstream is more fit for protocol-level read-write. it is not very reasonable for your code in bytes reading and writing. loop to read and write is necessary in java io. and also, you use a buffer way. flush is necessary. here is a code sample: http://www.rgagnon.com/javadetails/java-0542.html

Check if a given time lies between two times regardless of date

I did it this way:

LocalTime time = LocalTime.now();
if (time.isAfter(LocalTime.of(02, 00)) && (time.isBefore(LocalTime.of(04, 00))))
{
    log.info("Checking after 2AM, before 4AM!");                    
}

Edit:

String time1 = "01:00:00";  
String time2 = "15:00:00";  
LocalTime time = LocalTime.parse(time2);  
if ((time.isAfter(LocalTime.of(20,11,13))) || (time.isBefore(LocalTime.of(14,49,0))))  
{  
    System.out.println("true");  
}  
else  
{  
    System.out.println("false");  
}    

What is the difference between buffer and cache memory in Linux?

buffer and cache.

A buffer is something that has yet to be "written" to disk.

A cache is something that has been "read" from the disk and stored for later use.

Call method when home button pressed

The Home button is a very dangerous button to override and, because of that, Android will not let you override its behavior the same way you do the BACK button.

Take a look at this discussion.

You will notice that the home button seems to be implemented as a intent invocation, so you'll end up having to add an intent category to your activity. Then, any time the user hits home, your app will show up as an option. You should consider what it is you are looking to accomplish with the home button. If its not to replace the default home screen of the device, I would be wary of overloading the HOME button, but it is possible (per discussion in above thread.)

How to force a hover state with jQuery?

I think the best solution I have come across is on this stackoverflow. This short jQuery code allows all your hover effects to show on click or touch..
No need to add anything within the function.

$('body').on('touchstart', function() {});

Hope this helps.

How to convert char to int?

What everyone is forgeting is explaining WHY this happens.

A Char, is basically an integer, but with a pointer in the ASCII table. All characters have a corresponding integer value as you can clearly see when trying to parse it.

Pranay has clearly a different character set, thats why HIS code doesnt work. the only way is

int val = '1' - '0';

because this looks up the integer value in the table of '0' which is then the 'base value' subtracting your number in char format from this will give you the original number.

How to increase Java heap space for a tomcat app

  • Open the server tab in eclipse
  • right click open
  • click on open lauch configuration
  • Go to arguments
  • Here you can add in VM arguments after endorsed

    -Xms64m -Xmx256m
    

Filtering Pandas DataFrames on dates

I'm not allowed to write any comments yet, so I'll write an answer, if somebody will read all of them and reach this one.

If the index of the dataset is a datetime and you want to filter that just by (for example) months, you can do following:

df.loc[df.index.month == 3]

That will filter the dataset for you by March.

Laravel migration default value

In Laravel 6 you have to add 'change' to your migrations file as follows:

$table->enum('is_approved', array('0','1'))->default('0')->change();

WebView showing ERR_CLEARTEXT_NOT_PERMITTED although site is HTTPS

Solution:

Add the below line in your application tag:

android:usesCleartextTraffic="true"

As shown below:

<application
    ....
    android:usesCleartextTraffic="true"
    ....>

UPDATE: If you have network security config such as: android:networkSecurityConfig="@xml/network_security_config"

No Need to set clear text traffic to true as shown above, instead use the below code:

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        ....
        ....
    </domain-config>

    <base-config cleartextTrafficPermitted="false"/>
</network-security-config>  

Set the cleartextTrafficPermitted to true

Hope it helps.

How to remove MySQL root password

I have also been through this problem,

First i tried setting my password of root to blank using command :

SET PASSWORD FOR root@localhost=PASSWORD('');

But don't be happy , PHPMYADMIN uses 127.0.0.1 not localhost , i know you would say both are same but that is not the case , use the command mentioned underneath and you are done.

SET PASSWORD FOR [email protected]=PASSWORD('');

Just replace localhost with 127.0.0.1 and you are done .

How to pass values across the pages in ASP.net without using Session

You can pass values from one page to another by followings..

Response.Redirect
Cookies
Application Variables
HttpContext

Response.Redirect

SET :

Response.Redirect("Defaultaspx?Name=Pandian");

GET :

string Name = Request.QueryString["Name"];

Cookies

SET :

HttpCookie cookName = new HttpCookie("Name");
cookName.Value = "Pandian"; 

GET :

string name = Request.Cookies["Name"].Value;

Application Variables

SET :

Application["Name"] = "pandian";

GET :

string Name = Application["Name"].ToString();

Refer the full content here : Pass values from one to another

How does facebook, gmail send the real time notification?

Update

As I continue to recieve upvotes on this, I think it is reasonable to remember that this answer is 4 years old. Web has grown in a really fast pace, so please be mindful about this answer.


I had the same issue recently and researched about the subject.

The solution given is called long polling, and to correctly use it you must be sure that your AJAX request has a "large" timeout and to always make this request after the current ends (timeout, error or success).

Long Polling - Client

Here, to keep code short, I will use jQuery:

function pollTask() { 

    $.ajax({

        url: '/api/Polling',
        async: true,            // by default, it's async, but...
        dataType: 'json',       // or the dataType you are working with
        timeout: 10000,          // IMPORTANT! this is a 10 seconds timeout
        cache: false

    }).done(function (eventList) {  

       // Handle your data here
       var data;
       for (var eventName in eventList) {

            data = eventList[eventName];
            dispatcher.handle(eventName, data); // handle the `eventName` with `data`

       }

    }).always(pollTask);

}

It is important to remember that (from jQuery docs):

In jQuery 1.4.x and below, the XMLHttpRequest object will be in an invalid state if the request times out; accessing any object members may throw an exception. In Firefox 3.0+ only, script and JSONP requests cannot be cancelled by a timeout; the script will run even if it arrives after the timeout period.

Long Polling - Server

It is not in any specific language, but it would be something like this:

function handleRequest () {  

     while (!anythingHappened() || hasTimedOut()) { sleep(2); }

     return events();

} 

Here, hasTimedOut will make sure your code does not wait forever, and anythingHappened, will check if any event happend. The sleep is for releasing your thread to do other stuff while nothing happens. The events will return a dictionary of events (or any other data structure you may prefer) in JSON format (or any other you prefer).

It surely solves the problem, but, if you are concerned about scalability and perfomance as I was when researching, you might consider another solution I found.

Solution

Use sockets!

On client side, to avoid any compatibility issues, use socket.io. It tries to use socket directly, and have fallbacks to other solutions when sockets are not available.

On server side, create a server using NodeJS (example here). The client will subscribe to this channel (observer) created with the server. Whenever a notification has to be sent, it is published in this channel and the subscriptor (client) gets notified.

If you don't like this solution, try APE (Ajax Push Engine).

Hope I helped.

How can I exclude multiple folders using Get-ChildItem -exclude?

#For brevity, I didn't define a function.

#Place the directories you want to exclude in this array.
#Case insensitive and exact match. So 'archive' and
#'ArcHive' will match but 'BuildArchive' will not.
$noDirs = @('archive')

#Build a regex using array of excludes
$excRgx = '^{0}$' -f ($noDirs -join ('$|^'))

#Rather than use the gci -Recurse option, use a more
#performant approach by not processing the match(s) as
#soon as they are located.
$cmd = {
  Param([string]$Path)
  Get-ChildItem $Path -Directory |
  ForEach-Object {
    if ($_.Name -inotmatch $excRgx) {
      #Recurse back into the scriptblock
      Invoke-Command $cmd -ArgumentList $_.FullName;
      #If you want all directory info change to return $_
      return $_.FullName
    }
  }
}

#In this example, start with the current directory
$searchPath = .
#Start the Recursion
Invoke-Command $cmd -ArgumentList $searchPath

How to create permanent PowerShell Aliases

It's not a good idea to add this kind of thing directly to your $env:WINDIR powershell folders.
The recommended way is to add it to your personal profile:

cd $env:USERPROFILE\Documents
md WindowsPowerShell -ErrorAction SilentlyContinue
cd WindowsPowerShell
New-Item Microsoft.PowerShell_profile.ps1 -ItemType "file" -ErrorAction SilentlyContinue
powershell_ise.exe .\Microsoft.PowerShell_profile.ps1

Now add your alias to the Microsoft.PowerShell_profile.ps1 file that is now opened:

function Do-ActualThing {
    # do actual thing
}

Set-Alias MyAlias Do-ActualThing

Then save it, and refresh the current session with:

. $profile

Note: Just in case, if you get permission issue like

CategoryInfo : SecurityError: (:) [], PSSecurityException + FullyQualifiedErrorId : UnauthorizedAccess

Try the below command and refresh the session again.

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned

Recover from git reset --hard?

I did git reset --hard on the wrong project by mistake (I know...). I had just worked on one file and it was still open during and after I ran the command.

Even though I had not committed, I was able to retrieve the old file with the simple COMMAND + Z.

Pandas sum by groupby, but exclude certain columns

If you are looking for a more generalized way to apply to many columns, what you can do is to build a list of column names and pass it as the index of the grouped dataframe. In your case, for example:

columns = ['Y'+str(i) for year in range(1967, 2011)]

df.groupby('Country')[columns].agg('sum')

How to close current tab in a browser window?

This is one way of solving the same, declare a JavaScript function like this

<script>
  function Exit() {
     var x=confirm('Are You sure want to exit:');
     if(x) window.close();
   }
</script>

Add the following line to the HTML to call the function using a <button>

<button name='closeIt' onClick="Exit()" >Click to exit </Button>

Changing the position of Bootstrap popovers based on the popover's X position in relation to window edge?

$scope.popoverPostion = function(event){
    $scope.pos = '';

       if(event.x <= 207 && event.x >= 140){
           $scope.pos = 'top';
           event.x = '';
       }
       else if(event.x < 140){
           $scope.pos = 'top-left';
           event.x = '';
       }
       else if(event.x > 207){
           $scope.pos = 'top-right';
           event.x = '';
       }

};

AlertDialog.Builder with custom layout and EditText; cannot access view

editText is a part of alertDialog layout so Just access editText with reference of alertDialog

EditText editText = (EditText) alertDialog.findViewById(R.id.label_field);

Update:

Because in code line dialogBuilder.setView(inflater.inflate(R.layout.alert_label_editor, null));

inflater is Null.

update your code like below, and try to understand the each code line

AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
// ...Irrelevant code for customizing the buttons and title
LayoutInflater inflater = this.getLayoutInflater();
View dialogView = inflater.inflate(R.layout.alert_label_editor, null);
dialogBuilder.setView(dialogView);

EditText editText = (EditText) dialogView.findViewById(R.id.label_field);
editText.setText("test label");
AlertDialog alertDialog = dialogBuilder.create();
alertDialog.show();

Update 2:

As you are using View object created by Inflater to update UI components else you can directly use setView(int layourResId) method of AlertDialog.Builder class, which is available from API 21 and onwards.

What regex will match every character except comma ',' or semi-colon ';'?

Use character classes. A character class beginning with caret will match anything not in the class.

[^,;]

How to wait for the 'end' of 'resize' event and only then perform an action?

You can store a reference id to any setInterval or setTimeout. Like this:

var loop = setInterval(func, 30);

// some time later clear the interval
clearInterval(loop);

To do this without a "global" variable you can add a local variable to the function itself. Ex:

$(window).resize(function() {
    clearTimeout(this.id);
    this.id = setTimeout(doneResizing, 500);
});

function doneResizing(){
  $("body").append("<br/>done!");   
}

Use Async/Await with Axios in React.js

Async/Await with axios 

  useEffect(() => {     
    const getData = async () => {  
      await axios.get('your_url')  
      .then(res => {  
        console.log(res)  
      })  
      .catch(err => {  
        console.log(err)  
      });  
    }  
    getData()  
  }, [])

Best tool for inspecting PDF files?

The object viewer in Acrobat is good but Windjack Solution's PDF Canopener allows better inspection with an eyedropper for selecting objects on page. Also permits modifications to be made to PDF.

http://www.windjack.com/products/pdfcanopener.html

concat scope variables into string in angular directive expression

I've created a working CodePen example demonstrating how to do this.

Relevant HTML:

<section ng-app="app" ng-controller="MainCtrl">
  <a href="#" ng-click="doSomething('#/path/{{obj.val1}}/{{obj.val2}}')">Click Me</a><br>
  debug: {{debug.val}}
</section>

Relevant javascript:

var app = angular.module('app', []);

app.controller('MainCtrl', function($scope) {
  $scope.obj = {
    val1: 'hello',
    val2: 'world'
  };

  $scope.debug = {
    val: ''
  };

  $scope.doSomething = function(input) {
    $scope.debug.val = input;
  };
});

Import Error: No module named numpy

solution for me - I installed numpy inside a virtual environment, but then running ipython was not inside virtual env:

(venv) ?  which python
/Users/alon/code/google_photos_project/venv/bin/python
(venv) ?  which ipython
/usr/bin/ipython

so I had to install ipython, and run ipython from the venv like this:

python -c 'import IPython; IPython.terminal.ipapp.launch_new_instance()'

How to compare dates in Java?

This code determine today is in some duration.. based on KOREA locale

    Calendar cstart = Calendar.getInstance(Locale.KOREA);
    cstart.clear();
    cstart.set(startyear, startmonth, startday);


    Calendar cend = Calendar.getInstance(Locale.KOREA);
    cend.clear();
    cend.set(endyear, endmonth, endday);

    Calendar c = Calendar.getInstance(Locale.KOREA);

    if(c.after(cstart) && c.before(cend)) {
        // today is in startyear/startmonth/startday ~ endyear/endmonth/endday
    }

How to alter a column's data type in a PostgreSQL table?

See documentation here: http://www.postgresql.org/docs/current/interactive/sql-altertable.html

ALTER TABLE tbl_name ALTER COLUMN col_name TYPE varchar (11);

How to calculate growth with a positive and negative number?

Use this formula:

=100% + (Year 2/Year 1)

The logic is that you recover 100% of the negative in year 1 (hence the initial 100%) plus any excess will be a ratio against year 1.

Twitter Bootstrap - add top space between rows

Bootstrap 4 alpha, for margin-top: shorthand CSS class names mt-1, mt-2 ( mt-lg-5, mt-sm-2) same for the bottom, right, left, and you have also auto class ml-auto

    <div class="mt-lg-1" ...>

Units are from 1 to 5 : in the variables.scss which means if you set mt-1 it gives .25rem of margin top.

$spacers: (
  0: (
    x: 0,
    y: 0
  ),
  1: (
    x: ($spacer-x * .25),
    y: ($spacer-y * .25)
  ),
  2: (
    x: ($spacer-x * .5),
    y: ($spacer-y * .5)
  ),
  3: (
    x: $spacer-x,
    y: $spacer-y
  ),
  4: (
    x: ($spacer-x * 1.5),
    y: ($spacer-y * 1.5)
  ),
  5: (
    x: ($spacer-x * 3),
    y: ($spacer-y * 3)
  )
) !default;

read-more here

https://v4-alpha.getbootstrap.com/utilities/spacing/#horizontal-centering

How to remove item from array by value?

In all values unique, you can:

a = new Set([1,2,3,4,5]) // a = Set(5) {1, 2, 3, 4, 5}
a.delete(3) // a = Set(5) {1, 2, 4, 5} 
[...a] // [1, 2, 4, 5]

Populate a Drop down box from a mySQL table in PHP

At the top first set up database connection as follow:

<?php
$mysqli = new mysqli("localhost", "username", "password", "database") or die($this->mysqli->error);
$query= $mysqli->query("SELECT PcID from PC");
?> 

Then include the following code in HTML inside form

<select name="selected_pcid" id='selected_pcid'>

            <?php 

             while ($rows = $query->fetch_array(MYSQLI_ASSOC)) {
                        $value= $rows['id'];
                ?>
                 <option value="<?= $value?>"><?= $value?></option>
                <?php } ?>
             </select>

However, if you are using materialize css or any other out of the box css, make sure that select field is not hidden or disabled.

Update row values where certain condition is met in pandas

I think you can use loc if you need update two columns to same value:

df1.loc[df1['stream'] == 2, ['feat','another_feat']] = 'aaaa'
print df1
   stream        feat another_feat
a       1  some_value   some_value
b       2        aaaa         aaaa
c       2        aaaa         aaaa
d       3  some_value   some_value

If you need update separate, one option is use:

df1.loc[df1['stream'] == 2, 'feat'] = 10
print df1
   stream        feat another_feat
a       1  some_value   some_value
b       2          10   some_value
c       2          10   some_value
d       3  some_value   some_value

Another common option is use numpy.where:

df1['feat'] = np.where(df1['stream'] == 2, 10,20)
print df1
   stream  feat another_feat
a       1    20   some_value
b       2    10   some_value
c       2    10   some_value
d       3    20   some_value

EDIT: If you need divide all columns without stream where condition is True, use:

print df1
   stream  feat  another_feat
a       1     4             5
b       2     4             5
c       2     2             9
d       3     1             7

#filter columns all without stream
cols = [col for col in df1.columns if col != 'stream']
print cols
['feat', 'another_feat']

df1.loc[df1['stream'] == 2, cols ] = df1 / 2
print df1
   stream  feat  another_feat
a       1   4.0           5.0
b       2   2.0           2.5
c       2   1.0           4.5
d       3   1.0           7.0

If working with multiple conditions is possible use multiple numpy.where or numpy.select:

df0 = pd.DataFrame({'Col':[5,0,-6]})

df0['New Col1'] = np.where((df0['Col'] > 0), 'Increasing', 
                          np.where((df0['Col'] < 0), 'Decreasing', 'No Change'))

df0['New Col2'] = np.select([df0['Col'] > 0, df0['Col'] < 0],
                            ['Increasing',  'Decreasing'], 
                            default='No Change')

print (df0)
   Col    New Col1    New Col2
0    5  Increasing  Increasing
1    0   No Change   No Change
2   -6  Decreasing  Decreasing

How can I edit a view using phpMyAdmin 3.2.4?

Just export you view and you will have all SQL need to make some change on it.

Just need to add your change in SQL query for the view and change :

CREATE for CREATE OR REPLACE

HTML button calling an MVC Controller and Action method

Razor syntax is here:

<input type="button" value="Create" onclick="location.href='@Url.Action("Create", "User")'" />

What's the difference between the atomic and nonatomic attributes?

Atomicity atomic (default)

Atomic is the default: if you don’t type anything, your property is atomic. An atomic property is guaranteed that if you try to read from it, you will get back a valid value. It does not make any guarantees about what that value might be, but you will get back good data, not just junk memory. What this allows you to do is if you have multiple threads or multiple processes pointing at a single variable, one thread can read and another thread can write. If they hit at the same time, the reader thread is guaranteed to get one of the two values: either before the change or after the change. What atomic does not give you is any sort of guarantee about which of those values you might get. Atomic is really commonly confused with being thread-safe, and that is not correct. You need to guarantee your thread safety other ways. However, atomic will guarantee that if you try to read, you get back some kind of value.

nonatomic

On the flip side, non-atomic, as you can probably guess, just means, “don’t do that atomic stuff.” What you lose is that guarantee that you always get back something. If you try to read in the middle of a write, you could get back garbage data. But, on the other hand, you go a little bit faster. Because atomic properties have to do some magic to guarantee that you will get back a value, they are a bit slower. If it is a property that you are accessing a lot, you may want to drop down to nonatomic to make sure that you are not incurring that speed penalty. Access

courtesy https://academy.realm.io/posts/tmi-objective-c-property-attributes/

Atomicity property attributes (atomic and nonatomic) are not reflected in the corresponding Swift property declaration, but the atomicity guarantees of the Objective-C implementation still hold when the imported property is accessed from Swift.

So — if you define an atomic property in Objective-C it will remain atomic when used by Swift.

courtesy https://medium.com/@YogevSitton/atomic-vs-non-atomic-properties-crash-course-d11c23f4366c

SQL Server check case-sensitivity?

You're interested in the collation. You could build something based on this snippet:

SELECT DATABASEPROPERTYEX('master', 'Collation');

Update
Based on your edit — If @test and @TEST can ever refer to two different variables, it's not SQL Server. If you see problems where the same variable is not equal to itself, check if that variable is NULL, because NULL = NULL returns `false.

How to run a Command Prompt command with Visual Basic code?

Here is an example:

Process.Start("CMD", "/C Pause")


/C  Carries out the command specified by string and then terminates
/K  Carries out the command specified by string but remains

And here is a extended function: (Notice the comment-lines using CMD commands.)

#Region " Run Process Function "

' [ Run Process Function ]
'
' // By Elektro H@cker
'
' Examples :
'
' MsgBox(Run_Process("Process.exe")) 
' MsgBox(Run_Process("Process.exe", "Arguments"))
' MsgBox(Run_Process("CMD.exe", "/C Dir /B", True))
' MsgBox(Run_Process("CMD.exe", "/C @Echo OFF & For /L %X in (0,1,50000) Do (Echo %X)", False, False))
' MsgBox(Run_Process("CMD.exe", "/C Dir /B /S %SYSTEMDRIVE%\*", , False, 500))
' If Run_Process("CMD.exe", "/C Dir /B", True).Contains("File.txt") Then MsgBox("File found")

Private Function Run_Process(ByVal Process_Name As String, _
                             Optional Process_Arguments As String = Nothing, _
                             Optional Read_Output As Boolean = False, _
                             Optional Process_Hide As Boolean = False, _
                             Optional Process_TimeOut As Integer = 999999999)

    ' Returns True if "Read_Output" argument is False and Process was finished OK
    ' Returns False if ExitCode is not "0"
    ' Returns Nothing if process can't be found or can't be started
    ' Returns "ErrorOutput" or "StandardOutput" (In that priority) if Read_Output argument is set to True.

    Try

        Dim My_Process As New Process()
        Dim My_Process_Info As New ProcessStartInfo()

        My_Process_Info.FileName = Process_Name ' Process filename
        My_Process_Info.Arguments = Process_Arguments ' Process arguments
        My_Process_Info.CreateNoWindow = Process_Hide ' Show or hide the process Window
        My_Process_Info.UseShellExecute = False ' Don't use system shell to execute the process
        My_Process_Info.RedirectStandardOutput = Read_Output '  Redirect (1) Output
        My_Process_Info.RedirectStandardError = Read_Output ' Redirect non (1) Output
        My_Process.EnableRaisingEvents = True ' Raise events
        My_Process.StartInfo = My_Process_Info
        My_Process.Start() ' Run the process NOW

        My_Process.WaitForExit(Process_TimeOut) ' Wait X ms to kill the process (Default value is 999999999 ms which is 277 Hours)

        Dim ERRORLEVEL = My_Process.ExitCode ' Stores the ExitCode of the process
        If Not ERRORLEVEL = 0 Then Return False ' Returns the Exitcode if is not 0

        If Read_Output = True Then
            Dim Process_ErrorOutput As String = My_Process.StandardOutput.ReadToEnd() ' Stores the Error Output (If any)
            Dim Process_StandardOutput As String = My_Process.StandardOutput.ReadToEnd() ' Stores the Standard Output (If any)
            ' Return output by priority
            If Process_ErrorOutput IsNot Nothing Then Return Process_ErrorOutput ' Returns the ErrorOutput (if any)
            If Process_StandardOutput IsNot Nothing Then Return Process_StandardOutput ' Returns the StandardOutput (if any)
        End If

    Catch ex As Exception
        'MsgBox(ex.Message)
        Return Nothing ' Returns nothing if the process can't be found or started.
    End Try

    Return True ' Returns True if Read_Output argument is set to False and the process finished without errors.

End Function

#End Region

how can I enable scrollbars on the WPF Datagrid?

This worked for me. The key is to use * as Row height.

<Grid x:Name="grid">
        <Grid.RowDefinitions>
            <RowDefinition Height="60"/>
            <RowDefinition Height="*"/>
            <RowDefinition Height="10"/>
        </Grid.RowDefinitions>

        <TabControl  Grid.Row="1" x:Name="tabItem">
                <TabItem x:Name="ta" 
                        Header="List of all Clients">
                        <DataGrid Name="clientsgrid" AutoGenerateColumns="True" Margin="2" 
                         ></DataGrid>
                </TabItem>
        </TabControl>
    
    </Grid>

LEFT INNER JOIN vs. LEFT OUTER JOIN - Why does the OUTER take longer?

Wait -- did you actually mean that "the same number of rows ... are being processed" or that "the same number of rows are being returned"? In general, the outer join would process many more rows, including those for which there is no match, even if it returns the same number of records.

Get difference between 2 dates in JavaScript?

var date1 = new Date("7/11/2010");
var date2 = new Date("8/11/2010");
var diffDays = parseInt((date2 - date1) / (1000 * 60 * 60 * 24), 10); 

alert(diffDays )

How do I get the title of the current active window using c#?

If you were talking about WPF then use:

 Application.Current.Windows.OfType<Window>().SingleOrDefault(w => w.IsActive);

Git push rejected after feature branch rebase

What is wrong with a git merge master on the feature branch? This will preserve the work you had, while keeping it separate from the mainline branch.

A--B--C------F--G
       \         \
        D--E------H

Edit: Ah sorry did not read your problem statement. You will need force as you performed a rebase. All commands that modify the history will need the --force argument. This is a failsafe to prevent you from losing work (the old D and E would be lost).

So you performed a git rebase which made the tree look like (although partially hidden as D and E are no longer in a named branch):

A--B--C------F--G
       \         \
        D--E      D'--E'

So, when trying to push your new feature branch (with D' and E' in it), you would lose D and E.

SQL to find the number of distinct values in a column

select count(distinct(column_name)) AS columndatacount from table_name where somecondition=true

You can use this query, to count different/distinct data. Thanks

How to change the window title of a MATLAB plotting figure?

If you do not want to include that your code script (as advised by others above), then simply you may do the following after generating the figure window:

  1. Go to "Edit" in the figure window

  2. Go to "Figure Properties"

  3. At the bottom, you can type the name you want in "Figure Name" field. You can uncheck "Show Figure Number".

That's all.

Good luck.

javax.servlet.ServletException cannot be resolved to a type in spring web app

As almost anyone said, adding a runtime service will solve the problem. But if there is no runtime services or there is something like Google App Engine which is not your favorite any how, click New button right down the Targeted Runtimes list and add a new runtime server environment. Then check it and click OK and let the compiler to compile your project again.

Hope it helps ;)

rebase in progress. Cannot commit. How to proceed or stop (abort)?

If git rebase --abort doesnt work and you still get

error: could not read '.git/rebase-apply/head-name': No such file or directory

Type:

git rebase --quit

Change border color on <select> HTML form

Replacing the border-color with outline-color should work.

How to switch text case in visual studio code

To have in Visual Studio Code what you can do in Sublime Text ( CTRL+K CTRL+U and CTRL+K CTRL+L ) you could do this:

  • Open "Keyboard Shortcuts" with click on "File -> Preferences -> Keyboard Shortcuts"
  • Click on "keybindings.json" link which appears under "Search keybindings" field
  • Between the [] brackets add:

    {
        "key": "ctrl+k ctrl+u",
        "command": "editor.action.transformToUppercase",
        "when": "editorTextFocus"
    },
    {
        "key": "ctrl+k ctrl+l",
        "command": "editor.action.transformToLowercase",
        "when": "editorTextFocus"
    }
    
  • Save and close "keybindings.json"


Another way:
Microsoft released "Sublime Text Keymap and Settings Importer", an extension which imports keybindings and settings from Sublime Text to VS Code. - https://marketplace.visualstudio.com/items?itemName=ms-vscode.sublime-keybindings

Copy data into another table

Insert Selected column with condition

INSERT INTO where_to_insert (col_1,col_2) SELECT col1, col2 FROM from_table WHERE condition;

Copy all data from one table to another with the same column name.

INSERT INTO where_to_insert 
SELECT * FROM from_table WHERE condition;

ServletException, HttpServletResponse and HttpServletRequest cannot be resolved to a type

As a reason of this problem, some code is broken or undefined.You may see an error in a java class such as "The type javax.servlet.http.HttpSession cannot be resolved. It is indirectly referenced from required .class files". you shuold download " javax.servlet.jar" as mentioned before. Then configure your project build path, add the javax.servlet.jar as an external jar.I hope it fixes the problem.At least it worked for me.

Querying data by joining two tables in two database on different servers

From a practical enterprise perspective, the best practice is to make a mirrored copy of the database table in your database, and then just have a task/proc update it with delta's every hour.

Find index of a value in an array

This solution helped me more, from msdn microsoft:

var result =  query.AsEnumerable().Select((x, index) =>
              new { index,x.Id,x.FirstName});

query is your toList() query.

Rails formatting date

Create an initializer for it:

# config/initializers/time_formats.rb

Add something like this to it:

Time::DATE_FORMATS[:custom_datetime] = "%d.%m.%Y"

And then use it the following way:

post.updated_at.to_s(:custom_datetime)

?? Your have to restart rails server for this to work.

Check the documentation for more information: http://api.rubyonrails.org/v5.1/classes/DateTime.html#method-i-to_formatted_s

Visual Studio Community 2015 expiration date

I also get same issue after I repair vs2015, even I click check license online, still fail. Correct action is: 1. Sign out 2. Check License Status, then it will pop-up login window, after login then it able to successfully get the license info.

What is the difference between a stored procedure and a view?

@Patrick is correct with what he said, but to answer your other questions a View will create itself in Memory, and depending on the type of Joins, Data and if there is any aggregation done, it could be a quite memory hungry View.

Stored procedures do all their processing either using Temp Hash Table e.g #tmpTable1 or in memory using @tmpTable1. Depending on what you want to tell it to do.

A Stored Procedure is like a Function, but is called Directly by its name. instead of Functions which are actually used inside a query itself.

Obviously most of the time Memory tables are faster, if you are not retrieveing alot of data.

How can I include null values in a MIN or MAX?

Assuming you have only one record with null in EndDate column for a given RecordID, something like this should give you desired output :

WITH cte1 AS
(
SELECT recordid, MIN(startdate) as min_start , MAX(enddate) as max_end
FROM tmp 
GROUP BY recordid
)

SELECT a.recordid, a.min_start , 
CASE 
   WHEN b.recordid IS  NULL THEN a.max_end
END as max_end
FROM cte1 a
LEFT JOIN tmp b ON (b.recordid = a.recordid AND b.enddate IS NULL)

"Field has incomplete type" error

You are using a forward declaration for the type MainWindowClass. That's fine, but it also means that you can only declare a pointer or reference to that type. Otherwise the compiler has no idea how to allocate the parent object as it doesn't know the size of the forward declared type (or if it actually has a parameterless constructor, etc.)

So, you either want:

// forward declaration, details unknown
class A;

class B {
  A *a;  // pointer to A, ok
};

Or, if you can't use a pointer or reference....

// declaration of A
#include "A.h"

class B {
  A a;  // ok, declaration of A is known
};

At some point, the compiler needs to know the details of A.

If you are only storing a pointer to A then it doesn't need those details when you declare B. It needs them at some point (whenever you actually dereference the pointer to A), which will likely be in the implementation file, where you will need to include the header which contains the declaration of the class A.

// B.h
// header file

// forward declaration, details unknown
class A;

class B {
public: 
    void foo();
private:
  A *a;  // pointer to A, ok
};

// B.cpp
// implementation file

#include "B.h"
#include "A.h"  // declaration of A

B::foo() {
    // here we need to know the declaration of A
    a->whatever();
}

How to force DNS refresh for a website?

As far as I know, a forced update like this is not directly possible. You might be able to reduce the DNS downtime by reducing the TTL (Time-To-Live) value of the entries before changing them, if your name server service provider allows that.

Here's a guide for less painful DNS changes.

A fair warning, though - not all name servers between your client and the authoritative (origin) name server will enforce your TTL, they might have their own caching time.

Can clearInterval() be called inside setInterval()?

Yes you can. You can even test it:

_x000D_
_x000D_
var i = 0;_x000D_
var timer = setInterval(function() {_x000D_
  console.log(++i);_x000D_
  if (i === 5) clearInterval(timer);_x000D_
  console.log('post-interval'); //this will still run after clearing_x000D_
}, 200);
_x000D_
_x000D_
_x000D_

In this example, this timer clears when i reaches 5.

CSS to line break before/after a particular `inline-block` item

Note sure this will work, depending how you render the page. But how about just starting a new unordered list?

i.e.

_x000D_
_x000D_
<ul>_x000D_
<li>_x000D_
<li>_x000D_
<li>_x000D_
</ul>_x000D_
<!-- start a new ul to line break it -->_x000D_
<ul>
_x000D_
_x000D_
_x000D_

JavaScript - Getting HTML form values

document.forms will contain an array of forms on your page. You can loop through these forms to find the specific form you desire.

var form = false;
var length = document.forms.length;
for(var i = 0; i < length; i++) {
    if(form.id == "wanted_id") {
        form = document.forms[i];
    }
}

Each form has an elements array which you can then loop through to find the data that you want. You should also be able to access them by name

var wanted_value = form.someFieldName.value;
jsFunction(wanted_value);

Can I make 'git diff' only the line numbers AND changed file names?

Shows the file names and amount/nubmer of lines that changed in each file between now and the specified commit:

git diff --stat <commit-hash>

Matplotlib: ValueError: x and y must have same first dimension

You should make x and y numpy arrays, not lists:

x = np.array([0.46,0.59,0.68,0.99,0.39,0.31,1.09,
              0.77,0.72,0.49,0.55,0.62,0.58,0.88,0.78])
y = np.array([0.315,0.383,0.452,0.650,0.279,0.215,0.727,0.512,
              0.478,0.335,0.365,0.424,0.390,0.585,0.511])

With this change, it produces the expect plot. If they are lists, m * x will not produce the result you expect, but an empty list. Note that m is anumpy.float64 scalar, not a standard Python float.

I actually consider this a bit dubious behavior of Numpy. In normal Python, multiplying a list with an integer just repeats the list:

In [42]: 2 * [1, 2, 3]
Out[42]: [1, 2, 3, 1, 2, 3]

while multiplying a list with a float gives an error (as I think it should):

In [43]: 1.5 * [1, 2, 3]
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-43-d710bb467cdd> in <module>()
----> 1 1.5 * [1, 2, 3]
TypeError: can't multiply sequence by non-int of type 'float'

The weird thing is that multiplying a Python list with a Numpy scalar apparently works:

In [45]: np.float64(0.5) * [1, 2, 3]
Out[45]: []

In [46]: np.float64(1.5) * [1, 2, 3]
Out[46]: [1, 2, 3]

In [47]: np.float64(2.5) * [1, 2, 3]
Out[47]: [1, 2, 3, 1, 2, 3]

So it seems that the float gets truncated to an int, after which you get the standard Python behavior of repeating the list, which is quite unexpected behavior. The best thing would have been to raise an error (so that you would have spotted the problem yourself instead of having to ask your question on Stackoverflow) or to just show the expected element-wise multiplication (in which your code would have just worked). Interestingly, addition between a list and a Numpy scalar does work:

In [69]: np.float64(0.123) + [1, 2, 3]
Out[69]: array([ 1.123,  2.123,  3.123])

Adding asterisk to required fields in Bootstrap 3

This works for me:

CSS

.form-group.required.control-label:before{
   content: "*";
   color: red;
}

OR

.form-group.required.control-label:after{
   content: "*";
   color: red;
}

Basic HTML

<div class="form-group required control-label">
  <input class="form-control" />
</div>

What is exactly the base pointer and stack pointer? To what do they point?

esp is as you say it is, the top of the stack.

ebp is usually set to esp at the start of the function. Function parameters and local variables are accessed by adding and subtracting, respectively, a constant offset from ebp. All x86 calling conventions define ebp as being preserved across function calls. ebp itself actually points to the previous frame's base pointer, which enables stack walking in a debugger and viewing other frames local variables to work.

Most function prologs look something like:

push ebp      ; Preserve current frame pointer
mov ebp, esp  ; Create new frame pointer pointing to current stack top
sub esp, 20   ; allocate 20 bytes worth of locals on stack.

Then later in the function you may have code like (presuming both local variables are 4 bytes)

mov [ebp-4], eax    ; Store eax in first local
mov ebx, [ebp - 8]  ; Load ebx from second local

FPO or frame pointer omission optimization which you can enable will actually eliminate this and use ebp as another register and access locals directly off of esp, but this makes debugging a bit more difficult since the debugger can no longer directly access the stack frames of earlier function calls.

EDIT:

For your updated question, the missing two entries in the stack are:

var_C = dword ptr -0Ch
var_8 = dword ptr -8
var_4 = dword ptr -4
*savedFramePointer = dword ptr 0*
*return address = dword ptr 4*
hInstance = dword ptr  8h
PrevInstance = dword ptr  0C
hlpCmdLine = dword ptr  10h
nShowCmd = dword ptr  14h

This is because the flow of the function call is:

  • Push parameters (hInstance, etc.)
  • Call function, which pushes return address
  • Push ebp
  • Allocate space for locals

How to understand nil vs. empty vs. blank in Ruby

I made this useful table with all the cases:

enter image description here

blank?, present? are provided by Rails.

ggplot combining two plots from different data.frames

The only working solution for me, was to define the data object in the geom_line instead of the base object, ggplot.

Like this:

ggplot() + 
geom_line(data=Data1, aes(x=A, y=B), color='green') + 
geom_line(data=Data2, aes(x=C, y=D), color='red')

instead of

ggplot(data=Data1, aes(x=A, y=B), color='green') + 
geom_line() + 
geom_line(data=Data2, aes(x=C, y=D), color='red')

More info here

How to access share folder in virtualbox. Host Win7, Guest Fedora 16?

This thread has some great tips. However....

@GirishB's answer isn't correct - sorry. Jartender's is best.

Also, every post in here seems to assume you're logging in to the Linux guest as root, except for @tomoguisuru. Yuck! Don't use root, use a separate user account and "sudo" when you need root privileges. Then this user (or any other user who needs the shared folder) should have membership in the vboxsf group, and @tomoguisuru's command is perfect, even terser than what I use.

Forget running mount yourself. Set up the shared folder to auto mount and you'll find the shared folder - it's under /media in my OEL (RH and Centos probably the same). If it's not there, just run "mount" with no arguments and look for the mounted directory of type vboxsf.

Terminal showing 'mount' and where to find mounted shared folder

Refreshing data in RecyclerView and keeping its scroll position

Here is an option for people who use DataBinding for RecyclerView. I have var recyclerViewState: Parcelable? in my adapter. And I use a BindingAdapter with a variation of @DawnYu's answer to set and update data in the RecyclerView:

@BindingAdapter("items")
fun setRecyclerViewItems(
    recyclerView: RecyclerView,
    items: List<RecyclerViewItem>?
) {
    var adapter = (recyclerView.adapter as? RecyclerViewAdapter)
    if (adapter == null) {
        adapter = RecyclerViewAdapter()
        recyclerView.adapter = adapter
    }

    adapter.recyclerViewState = recyclerView.layoutManager?.onSaveInstanceState()
    // the main idea is in this call with a lambda. It allows to avoid blinking on data update
    adapter.submitList(items.orEmpty()) {
        adapter.recyclerViewState?.let {
            recyclerView.layoutManager?.onRestoreInstanceState(it)
        }
    }
}

Finally, the XML part looks like:

<androidx.recyclerview.widget.RecyclerView
    android:id="@+id/possible_trips_rv"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    app:items="@{viewState.yourItems}"
    app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"/>

Java - sending HTTP parameters via POST method easily

GET and POST method set like this... Two types for api calling 1)get() and 2) post() . get() method to get value from api json array to get value & post() method use in our data post in url and get response.

 public class HttpClientForExample {

    private final String USER_AGENT = "Mozilla/5.0";

    public static void main(String[] args) throws Exception {

        HttpClientExample http = new HttpClientExample();

        System.out.println("Testing 1 - Send Http GET request");
        http.sendGet();

        System.out.println("\nTesting 2 - Send Http POST request");
        http.sendPost();

    }

    // HTTP GET request
    private void sendGet() throws Exception {

        String url = "http://www.google.com/search?q=developer";

        HttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet(url);

        // add request header
        request.addHeader("User-Agent", USER_AGENT);

        HttpResponse response = client.execute(request);

        System.out.println("\nSending 'GET' request to URL : " + url);
        System.out.println("Response Code : " + 
                       response.getStatusLine().getStatusCode());

        BufferedReader rd = new BufferedReader(
                       new InputStreamReader(response.getEntity().getContent()));

        StringBuffer result = new StringBuffer();
        String line = "";
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }

        System.out.println(result.toString());

    }

    // HTTP POST request
    private void sendPost() throws Exception {

        String url = "https://selfsolve.apple.com/wcResults.do";

        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(url);

        // add header
        post.setHeader("User-Agent", USER_AGENT);

        List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
        urlParameters.add(new BasicNameValuePair("sn", "C02G8416DRJM"));
        urlParameters.add(new BasicNameValuePair("cn", ""));
        urlParameters.add(new BasicNameValuePair("locale", ""));
        urlParameters.add(new BasicNameValuePair("caller", ""));
        urlParameters.add(new BasicNameValuePair("num", "12345"));

        post.setEntity(new UrlEncodedFormEntity(urlParameters));

        HttpResponse response = client.execute(post);
        System.out.println("\nSending 'POST' request to URL : " + url);
        System.out.println("Post parameters : " + post.getEntity());
        System.out.println("Response Code : " + 
                                    response.getStatusLine().getStatusCode());

        BufferedReader rd = new BufferedReader(
                        new InputStreamReader(response.getEntity().getContent()));

        StringBuffer result = new StringBuffer();
        String line = "";
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }

        System.out.println(result.toString());

    }

}

Run jQuery function onclick

There's several things you can improve upon here. To start, there's no reason to use an <a> (anchor) tag since you don't have a link.

Every element can be bound to click and hover events... divs, spans, labels, inputs, etc.

I can't really identify what it is you're trying to do, though. You're mixing the goal with your own implementation and, from what I've seen so far, you're not really sure how to do it. Could you better illustrate what it is you're trying to accomplish?

== EDIT ==

The requirements are still very vague. I've implemented a very quick version of what I'm imagining you're saying ... or something close that illustrates how you might be able to do it. Left me know if I'm on the right track.

http://jsfiddle.net/THEtheChad/j9Ump/

enum - getting value of enum on string conversion

I implemented access using the following

class D(Enum):
    x = 1
    y = 2

    def __str__(self):
        return '%s' % self.value

now I can just do

print(D.x) to get 1 as result.

You can also use self.name in case you wanted to print x instead of 1.

What does O(log n) mean exactly?

In information technology it means that:

  f(n)=O(g(n)) If there is suitable constant C and N0 independent on N, 
  such that
  for all N>N0  "C*g(n) > f(n) > 0" is true.

Ant it seems that this notation was mostly have taken from mathematics.

In this article there is a quote: D.E. Knuth, "BIG OMICRON AND BIG OMEGA AND BIG THETA", 1976:

On the basis of the issues discussed here, I propose that members of SIGACT, and editors of computer science and mathematics journals, adopt notations as defined above, unless a better alternative can be found reasonably soon.

Today is 2016, but we use it still today.


In mathematical analysis it means that:

  lim (f(n)/g(n))=Constant; where n goes to +infinity

But even in mathematical analysis sometimes this symbol was used in meaning "C*g(n) > f(n) > 0".

As I know from university the symbol was intoduced by German mathematician Landau (1877-1938)

What does "select 1 from" do?

SELECT COUNT(*) in EXISTS/NOT EXISTS

EXISTS(SELECT CCOUNT(*) FROM TABLE_NAME WHERE CONDITIONS) - the EXISTS condition will always return true irrespective of CONDITIONS are met or not.

NOT EXISTS(SELECT CCOUNT(*) FROM TABLE_NAME WHERE CONDITIONS) - the NOT EXISTS condition will always return false irrespective of CONDITIONS are met or not.

SELECT COUNT 1 in EXISTS/NOT EXISTS

EXISTS(SELECT CCOUNT 1 FROM TABLE_NAME WHERE CONDITIONS) - the EXISTS condition will return true if CONDITIONS are met. Else false.

NOT EXISTS(SELECT CCOUNT 1 FROM TABLE_NAME WHERE CONDITIONS) - the NOT EXISTS condition will return false if CONDITIONS are met. Else true.

The EntityManager is closed

I found an interesting article about this problem

if (!$entityManager->isOpen()) {
  $entityManager = $entityManager->create(
    $entityManager->getConnection(), $entityManager->getConfiguration());
}

Doctrine 2 Exception EntityManager is closed

Regex for string not ending with given suffix

The question is old but I could not find a better solution I post mine here. Find all USB drives but not listing the partitions, thus removing the "part[0-9]" from the results. I ended up doing two grep, the last negates the result:

ls -1 /dev/disk/by-path/* | grep -P "\-usb\-" | grep -vE "part[0-9]*$"

This results on my system:

pci-0000:00:0b.0-usb-0:1:1.0-scsi-0:0:0:0

If I only want the partitions I could do:

ls -1 /dev/disk/by-path/* | grep -P "\-usb\-" | grep -E "part[0-9]*$"

Where I get:

pci-0000:00:0b.0-usb-0:1:1.0-scsi-0:0:0:0-part1
pci-0000:00:0b.0-usb-0:1:1.0-scsi-0:0:0:0-part2

And when I do:

readlink -f /dev/disk/by-path/pci-0000:00:0b.0-usb-0:1:1.0-scsi-0:0:0:0

I get:

/dev/sdb

How to use MySQL DECIMAL?

There are correct solutions in the comments, but to summarize them into a single answer:

You have to use DECIMAL(6,4).

Then you can have 6 total number of digits, 2 before and 4 after the decimal point (the scale). At least according to this.

PostgreSQL: Modify OWNER on all tables simultaneously in PostgreSQL

If you want to do it in one sql statement, you need to define an exec() function as mentioned in http://wiki.postgresql.org/wiki/Dynamic_DDL

CREATE FUNCTION exec(text) returns text language plpgsql volatile
  AS $f$
    BEGIN
      EXECUTE $1;
      RETURN $1;
    END;
$f$;

Then you can execute this query, it will change the owner of tables, sequences and views:

SELECT exec('ALTER TABLE ' || quote_ident(s.nspname) || '.' ||
            quote_ident(s.relname) || ' OWNER TO $NEWUSER')
  FROM (SELECT nspname, relname
          FROM pg_class c JOIN pg_namespace n ON (c.relnamespace = n.oid) 
         WHERE nspname NOT LIKE E'pg\\_%' AND 
               nspname <> 'information_schema' AND 
               relkind IN ('r','S','v') ORDER BY relkind = 'S') s;

$NEWUSER is the postgresql new name of the new owner.

In most circumstances you need to be superuser to execute this. You can avoid that by changing the owner from your own user to a role group you are a member of.

Thanks to RhodiumToad on #postgresql for helping out with this.

jQuery check if <input> exists and has a value

Just for the heck of it, I tracked this down in the jQuery code. The .val() function currently starts at line 165 of attributes.js. Here's the relevant section, with my annotations:

val: function( value ) {
    var hooks, ret, isFunction,
        elem = this[0];

        /// NO ARGUMENTS, BECAUSE NOT SETTING VALUE
    if ( !arguments.length ) {

        /// IF NOT DEFINED, THIS BLOCK IS NOT ENTERED. HENCE 'UNDEFINED'
        if ( elem ) {
            hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ];

            if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) {
                return ret;
            }

            ret = elem.value;

            /// IF IS DEFINED, JQUERY WILL CHECK TYPE AND RETURN APPROPRIATE 'EMPTY' VALUE
            return typeof ret === "string" ?
                // handle most common string cases
                ret.replace(rreturn, "") :
                // handle cases where value is null/undef or number
                ret == null ? "" : ret;
        }

        return;
    }

So, you'll either get undefined or "" or null -- all of which evaluate as false in if statements.

Escape double quotes in Java

Yes you will have to escape all double quotes by a backslash.

MySQL LEFT JOIN 3 tables

Select 
    p.Name,
    p.SS,
    f.fear
From
    Persons p
left join
        Person_Fear pf
    inner join
        Fears f
    on
        pf.fearID = f.fearID
 on
    p.personID = pf.PersonID

Push Notifications in Android Platform

You can use Pusher

It's a hosted service that makes it super-easy to add real-time data and functionality to web and mobile applications.
Pusher offers libraries to integrate into all the main runtimes and frameworks.

PHP, Ruby, Python, Java, .NET, Go and Node on the server
JavaScript, Objective-C (iOS) and Java (Android) on the client.

setup.py examples?

READ THIS FIRST https://packaging.python.org/en/latest/current.html

Installation Tool Recommendations

  1. Use pip to install Python packages from PyPI.
  2. Use virtualenv, or pyvenv to isolate application specific dependencies from a shared Python installation.
  3. Use pip wheel to create a cache of wheel distributions, for the purpose of > speeding up subsequent installations.
  4. If you’re looking for management of fully integrated cross-platform software stacks, consider buildout (primarily focused on the web development community) or Hashdist, or conda (both primarily focused on the scientific community).

Packaging Tool Recommendations

  1. Use setuptools to define projects and create Source Distributions.
  2. Use the bdist_wheel setuptools extension available from the wheel project to create wheels. This is especially beneficial, if your project contains binary extensions.
  3. Use twine for uploading distributions to PyPI.

This anwser has aged, and indeed there is a rescue plan for python packaging world called

wheels way

I qoute pythonwheels.com here:

What are wheels?

Wheels are the new standard of python distribution and are intended to replace eggs. Support is offered in pip >= 1.4 and setuptools >= 0.8.

Advantages of wheels

  1. Faster installation for pure python and native C extension packages.
  2. Avoids arbitrary code execution for installation. (Avoids setup.py)
  3. Installation of a C extension does not require a compiler on Windows or OS X.
  4. Allows better caching for testing and continuous integration.
  5. Creates .pyc files as part of installation to ensure they match the python interpreter used.
  6. More consistent installs across platforms and machines.

The full story of correct python packaging (and about wheels) is covered at packaging.python.org


conda way

For scientific computing (this is also recommended on packaging.python.org, see above) I would consider using CONDA packaging which can be seen as a 3rd party service build on top of PyPI and pip tools. It also works great on setting up your own version of binstar so I would imagine it can do the trick for sophisticated custom enterprise package management.

Conda can be installed into a user folder (no super user permisssions) and works like magic with

conda install

and powerful virtual env expansion.


eggs way

This option was related to python-distribute.org and is largerly outdated (as well as the site) so let me point you to one of the ready to use yet compact setup.py examples I like:

  • A very practical example/implementation of mixing scripts and single python files into setup.py is giving here
  • Even better one from hyperopt

This quote was taken from the guide on the state of setup.py and still applies:

  • setup.py gone!
  • distutils gone!
  • distribute gone!
  • pip and virtualenv here to stay!
  • eggs ... gone!

I add one more point (from me)

  • wheels!

I would recommend to get some understanding of packaging-ecosystem (from the guide pointed by gotgenes) before attempting mindless copy-pasting.

Most of examples out there in the Internet start with

from distutils.core import setup

but this for example does not support building an egg python setup.py bdist_egg (as well as some other old features), which were available in

from setuptools import setup

And the reason is that they are deprecated.

Now according to the guide

Warning

Please use the Distribute package rather than the Setuptools package because there are problems in this package that can and will not be fixed.

deprecated setuptools are to be replaced by distutils2, which "will be part of the standard library in Python 3.3". I must say I liked setuptools and eggs and have not yet been completely convinced by convenience of distutils2. It requires

pip install Distutils2

and to install

python -m distutils2.run install

PS

Packaging never was trivial (one learns this by trying to develop a new one), so I assume a lot of things have gone for reason. I just hope this time it will be is done correctly.

How do I select an element with its name attribute in jQuery?

$('[name="ElementNameHere"]').doStuff();

jQuery supports CSS3 style selectors, plus some more.

See more

How do I download a package from apt-get without installing it?

There are a least these apt-get extension packages that can help:

apt-offline - offline apt package manager
apt-zip - Update a non-networked computer using apt and removable media

This is specifically for the case of wanting to download where you have network access but to install on another machine where you do not.

Otherwise, the --download-only option to apt-get is your friend:

 -d, --download-only
     Download only; package files are only retrieved, not unpacked or installed.
     Configuration Item: APT::Get::Download-Only.

How to get the path of running java program

You actually do not want to get the path to your main class. According to your example you want to get the current working directory, i.e. directory where your program started. In this case you can just say new File(".").getAbsolutePath()

importing go files in same folder

No import is necessary as long as you declare both a.go and b.go to be in the same package. Then, you can use go run to recognize multiple files with:

$ go run a.go b.go

Error : java.lang.NoSuchMethodError: org.objectweb.asm.ClassWriter.<init>(I)V

Update your pom.xml

<dependency>
  <groupId>asm</groupId>
  <artifactId>asm</artifactId>
  <version>3.1</version>
</dependency>

Scroll to the top of the page after render in react.js

Here's yet another approach that allows you to choose which mounted components you want the window scroll position to reset to without mass duplicating the ComponentDidUpdate/ComponentDidMount.

The example below is wrapping the Blog component with ScrollIntoView(), so that if the route changes when the Blog component is mounted, then the HOC's ComponentDidUpdate will update the window scroll position.

You can just as easily wrap it over the entire app, so that on any route change, it'll trigger a window reset.

ScrollIntoView.js

import React, { Component } from 'react';
import { withRouter } from 'react-router';

export default WrappedComponent => {
  class ResetWindowScroll extends Component {
    componentDidUpdate = (prevProps) => {
      if(this.props.location !== prevProps.location) window.scrollTo(0,0);
    }

    render = () => <WrappedComponent {...this.props} />
  }
  return withRouter(ResetWindowScroll);
}

Routes.js

import React from 'react';
import { Route, IndexRoute } from 'react-router';

import App from '../components/App';
import About from '../components/pages/About';
import Blog from '../components/pages/Blog'
import Index from '../components/Landing';
import NotFound from '../components/navigation/NotFound';
import ScrollIntoView from '../components/navigation/ScrollIntoView';

 export default (
    <Route path="/" component={App}>
        <IndexRoute component={Index} />
        <Route path="/about" component={About} /> 
        <Route path="/blog" component={ScrollIntoView(Blog)} />
        <Route path="*" component={NotFound} />
    </Route>
);

The above example works great, but if you've migrated to react-router-dom, then you can simplify the above by creating a HOC that wraps the component.

Once again, you could also just as easily wrap it over your routes (just change componentDidMount method to the componentDidUpdate method example code written above, as well as wrapping ScrollIntoView with withRouter).

containers/ScrollIntoView.js

import { PureComponent, Fragment } from "react";

class ScrollIntoView extends PureComponent {
  componentDidMount = () => window.scrollTo(0, 0);

  render = () => this.props.children
}

export default ScrollIntoView;

components/Home.js

import React from "react";
import ScrollIntoView from "../containers/ScrollIntoView";

export default () => (
  <ScrollIntoView>
    <div className="container">
      <p>
        Sample Text
      </p>
    </div>
  </ScrollIntoView>
);

Disable browser's back button

<script>
    $(document).ready(function() {
        function disableBack() { window.history.forward() }

        window.onload = disableBack();
        window.onpageshow = function(evt) { if (evt.persisted) disableBack() }
    });
</script>

DB2 SQL error: SQLCODE: -206, SQLSTATE: 42703

That only means that an undefined column or parameter name was detected. The errror that DB2 gives should point what that may be:

DB2 SQL Error: SQLCODE=-206, SQLSTATE=42703, SQLERRMC=[THE_UNDEFINED_COLUMN_OR_PARAMETER_NAME], DRIVER=4.8.87

Double check your table definition. Maybe you just missed adding something.

I also tried google-ing this problem and saw this:

http://www.coderanch.com/t/515475/JDBC/databases/sql-insert-statement-giving-sqlcode

Why can't I reference System.ComponentModel.DataAnnotations?

I also have this problem. That is very stupid when i add a namespace the same with System. I try to remove all references, but it is not resolved. I use "global::System.ComponentModel", it is working as well. When i remove my namespace, this problem has been resolved.

SSL error SSL3_GET_SERVER_CERTIFICATE:certificate verify failed

Add

$mail->SMTPOptions = array(
'ssl' => array(
    'verify_peer' => false,
    'verify_peer_name' => false,
    'allow_self_signed' => true
));

before

mail->send()

and replace

require "mailer/class.phpmailer.php";

with

require "mailer/PHPMailerAutoload.php";

Select all 'tr' except the first one

ideal solution but not supported in IE

tr:not(:first-child) {css}

second solution would be to style all tr's and then override with css for first-child:

tr {css}
tr:first-child {override css above}

How can we store into an NSDictionary? What is the difference between NSDictionary and NSMutableDictionary?

The key difference: NSMutableDictionary can be modified in place, NSDictionary cannot. This is true for all the other NSMutable* classes in Cocoa. NSMutableDictionary is a subclass of NSDictionary, so everything you can do with NSDictionary you can do with both. However, NSMutableDictionary also adds complementary methods to modify things in place, such as the method setObject:forKey:.

You can convert between the two like this:

NSMutableDictionary *mutable = [[dict mutableCopy] autorelease];
NSDictionary *dict = [[mutable copy] autorelease]; 

Presumably you want to store data by writing it to a file. NSDictionary has a method to do this (which also works with NSMutableDictionary):

BOOL success = [dict writeToFile:@"/file/path" atomically:YES];

To read a dictionary from a file, there's a corresponding method:

NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:@"/file/path"];

If you want to read the file as an NSMutableDictionary, simply use:

NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithContentsOfFile:@"/file/path"];

PDO with INSERT INTO through prepared statements

Thanks to Novocaine88's answer to use a try catch loop I have successfully received an error message when I caused one.

    <?php
    $dbhost = "localhost";
    $dbname = "pdo";
    $dbusername = "root";
    $dbpassword = "845625";

    $link = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbusername, $dbpassword);
    $link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    try {
        $statement = $link->prepare("INERT INTO testtable(name, lastname, age)
            VALUES(?,?,?)");

        $statement->execute(array("Bob","Desaunois",18));
    } catch(PDOException $e) {
        echo $e->getMessage();
    }
    ?>

In the following code instead of INSERT INTO it says INERT.

this is the error I got.

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'INERT INTO testtable(name, lastname, age) VALUES('Bob','Desaunoi' at line 1

When I "fix" the issue, it works as it should. Thanks alot everyone!

Maven does not find JUnit tests to run

Check that (for jUnit - 4.12 and Eclipse surefire plugin)

  1. Add required jUnit version in POM.xml in dependencies. Do Maven -> Update project to see required jars exported in project.
  2. Test class is under the folder src/test/java and subdirectories of this folder (or base folder can be specified in POM in config testSourceDirectory). Name of the class should have tailng word 'Test'.
  3. Test Method in the test class should have annotation @Test

Relation between CommonJS, AMD and RequireJS?

It is quite normal to organize JavaScript program modular into several files and to call child-modules from the main js module.

The thing is JavaScript doesn't provide this. Not even today in latest browser versions of Chrome and FF.

But, is there any keyword in JavaScript to call another JavaScript module?

This question may be a total collapse of the world for many because the answer is No.


In ES5 ( released in 2009 ) JavaScript had no keywords like import, include, or require.

ES6 saves the day ( released in 2015 ) proposing the import keyword ( https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/import ), but no browser implements this.

If you use Babel 6.18.0 and transpile with ES2015 option only

import myDefault from "my-module";

you will get require again.

"use strict";
var _myModule = require("my-module");
var _myModule2 = _interopRequireDefault(_myModule);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

This is because require means the module will be loaded from Node.js. Node.js will handle everything from system level file read to wrapping functions into the module.

Because in JavaScript functions are the only wrappers to represent the modules.

I'm a lot confused about CommonJS and AMD?

Both CommonJS and AMD are just two different techniques how to overcome the JavaScript "defect" to load modules smart.

What does "where T : class, new()" mean?

Those are generic type constraints. In your case there are two of them:

where T : class

Means that the type T must be a reference type (not a value type).

where T : new()

Means that the type T must have a parameter-less constructor. Having this constraint will allow you to do something like T field = new T(); in your code which you wouldn't be able to do otherwise.

You then combine the two using a comma to get:

where T : class, new()

Detecting when Iframe content has loaded (Cross browser)

to detect when the iframe has loaded and its document is ready?

It's ideal if you can get the iframe to tell you itself from a script inside the frame. For example it could call a parent function directly to tell it it's ready. Care is always required with cross-frame code execution as things can happen in an order you don't expect. Another alternative is to set ‘var isready= true;’ in its own scope, and have the parent script sniff for ‘contentWindow.isready’ (and add the onload handler if not).

If for some reason it's not practical to have the iframe document co-operate, you've got the traditional load-race problem, namely that even if the elements are right next to each other:

<img id="x" ... />
<script type="text/javascript">
    document.getElementById('x').onload= function() {
        ...
    };
</script>

there is no guarantee that the item won't already have loaded by the time the script executes.

The ways out of load-races are:

  1. on IE, you can use the ‘readyState’ property to see if something's already loaded;

  2. if having the item available only with JavaScript enabled is acceptable, you can create it dynamically, setting the ‘onload’ event function before setting source and appending to the page. In this case it cannot be loaded before the callback is set;

  3. the old-school way of including it in the markup:

    <img onload="callback(this)" ... />

Inline ‘onsomething’ handlers in HTML are almost always the wrong thing and to be avoided, but in this case sometimes it's the least bad option.

C# DataRow Empty-check

You could use this:

if(drEntity.ItemArray.Where(c => IsNotEmpty(c)).ToArray().Length == 0)
{
    // Row is empty
}

IsNotEmpty(cell) would be your own implementation, checking whether the data is null or empty, based on what type of data is in the cell. If it's a simple string, it could end up looking something like this:

if(drEntity.ItemArray.Where(c => c != null && !c.Equals("")).ToArray().Length == 0)
{
    // Row is empty
}
else
{
    // Row is not empty
}

Still, it essentially checks each cell for emptiness, and lets you know whether all cells in the row are empty.

Print to the same line and not a new line?

From python 3.x you can do:

print('bla bla', end='')

(which can also be used in Python 2.6 or 2.7 by putting from __future__ import print_function at the top of your script/module)

Python console progressbar example:

import time

# status generator
def range_with_status(total):
    """ iterate from 0 to total and show progress in console """
    n=0
    while n<total:
        done = '#'*(n+1)
        todo = '-'*(total-n-1)
        s = '<{0}>'.format(done+todo)
        if not todo:
            s+='\n'        
        if n>0:
            s = '\r'+s
        print(s, end='')
        yield n
        n+=1

# example for use of status generator
for i in range_with_status(10):
    time.sleep(0.1)

How to install mscomct2.ocx file from .cab file (Excel User Form and VBA)

You're correct that this is really painful to hand out to others, but if you have to, this is how you do it.

  1. Just extract the .ocx file from the .cab file (it is similar to a zip)
  2. Copy to the system folder (c:\windows\sysWOW64 for 64 bit systems and c:\windows\system32 for 32 bit)
  3. Use regsvr32 through the command prompt to register the file (e.g. "regsvr32 c:\windows\sysWOW64\mscomct2.ocx")

References

Bootstrap 3: how to make head of dropdown link clickable in navbar

This 100% works:

HTML:

<li class="dropdown">
          <a href="https://www.bkweb.co.in/" class="dropdown-toggle" >bkWeb.co.in Dropdown <span class="caret"></span></a>
          <ul class="dropdown-menu">
            <li><a href="#">Action</a></li>
            <li><a href="#">Another action</a></li>
            <li><a href="#">Something else here</a></li>
            <li role="separator" class="divider"></li>
            <li><a href="#">Separated link</a></li>
            <li role="separator" class="divider"></li>
            <li><a href="#">One more separated link</a></li>
          </ul>
        </li>

CSS:

@media (min-width:991px){
  ul.nav li.dropdown:hover ul.dropdown-menu {
    display: block;
  }
}

EXAMPLE in CODEPEN

Make EditText ReadOnly

set in XML

android:inputType="none" 

How to pass parameters or arguments into a gradle task

Its nothing more easy.

run command: ./gradlew clean -PjobId=9999

and

in gradle use: println(project.gradle.startParameter.projectProperties)

You will get clue.

Setting "checked" for a checkbox with jQuery

I'm missing the solution. I'll always use:

if ($('#myCheckBox:checked').val() !== undefined)
{
    //Checked
}
else
{
    //Not checked
}

How do I hide an element when printing a web page?

Bootstrap 3 has its own class for this called:

hidden-print

It is defined like this:

@media print {
  .hidden-print {
    display: none !important;
  }
}

You do not have to define it on your own.


In Bootstrap 4 this has changed to:

.d-print-none

How can I make an "are you sure" prompt in a Windows batchfile?

Here's my go-to method for a yes/no answer.

It's case-insensitive also.

This just checks for the errors given by the input and sets the choice variable to whatever you require so it can be used below in the code.

@echo off
choice /M "[Opt 1]  Do you want to continue [Yes/No]"
if errorlevel 255 (
  echo Error
  ) else if errorlevel 2 (
  set "YourChoice=will not"
  ) else if errorlevel 1 (
  set "YourChoice=will"
  ) else if errorlevel 0 (
  goto :EOF
  )
  echo %YourChoice%
  pause

How to do parallel programming in Python?

You can use joblib library to do parallel computation and multiprocessing.

from joblib import Parallel, delayed

You can simply create a function foo which you want to be run in parallel and based on the following piece of code implement parallel processing:

output = Parallel(n_jobs=num_cores)(delayed(foo)(i) for i in input)

Where num_cores can be obtained from multiprocessing library as followed:

import multiprocessing

num_cores = multiprocessing.cpu_count()

If you have a function with more than one input argument, and you just want to iterate over one of the arguments by a list, you can use the the partial function from functools library as follow:

from joblib import Parallel, delayed
import multiprocessing
from functools import partial
def foo(arg1, arg2, arg3, arg4):
    '''
    body of the function
    '''
    return output
input = [11,32,44,55,23,0,100,...] # arbitrary list
num_cores = multiprocessing.cpu_count()
foo_ = partial(foo, arg2=arg2, arg3=arg3, arg4=arg4)
# arg1 is being fetched from input list
output = Parallel(n_jobs=num_cores)(delayed(foo_)(i) for i in input)

You can find a complete explanation of the python and R multiprocessing with couple of examples here.

How do I check if file exists in Makefile so I can delete it?

It's strange to see so many people using shell scripting for this. I was looking for a way to use native makefile syntax, because I'm writing this outside of any target. You can use the wildcard function to check if file exists:

 ifeq ($(UNAME),Darwin)
     SHELL := /opt/local/bin/bash
     OS_X  := true
 else ifneq (,$(wildcard /etc/redhat-release))
     OS_RHEL := true
 else
     OS_DEB  := true
     SHELL := /bin/bash
 endif 

Update:

I found a way which is really working for me:

ifneq ("$(wildcard $(PATH_TO_FILE))","")
    FILE_EXISTS = 1
else
    FILE_EXISTS = 0
endif

How to disable action bar permanently

  protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   android.support.v7.app.ActionBar actionBar = getSupportActionBar();
    if (actionBar != null) {
        actionBar.hide();
    }
    setContentView(R.layout.activity_main);

Best way to integrate Python and JavaScript?

Many of these projects mentioned above are dead or dying, lacking activity and interest from author side. Interesting to follow how this area develops.

For the record, in era of plugin based implementations, KDE camp had an attempt to solve this with plugin and non-language specific way and created the Kross https://en.wikipedia.org/wiki/Kross_(software) - in my understanding it never took off even inside the community itself.

During this chicken and egg -problem time, javascript-based implementions are definately way to go. Maybe in the future we seee pure and clean, full Python support natively in browsers.

PHP Get Highest Value from Array

Don't sort the array to get the largest value.

Get the max value:

$value = max($array);

Get the corresponding key:

$key = array_search($value, $array);

How do you declare an object array in Java?

vehicle[] car = new vehicle[N];

Transfer data between databases with PostgreSQL

Actually, there is some possibility to send a table data from one PostgreSQL database to another. I use the procedural language plperlu (unsafe Perl procedural language) for it.

Description (all was done on a Linux server):

  1. Create plperlu language in your database A

  2. Then PostgreSQL can join some Perl modules through series of the following commands at the end of postgresql.conf for the database A:

    plperl.on_init='use DBI;'
    plperl.on_init='use DBD::Pg;'
    
  3. You build a function in A like this:

    CREATE OR REPLACE FUNCTION send_data( VARCHAR )
    RETURNS character varying AS
    $BODY$
    my $command = $_[0] || die 'No SQL command!';
    my $connection_string =
    "dbi:Pg:dbname=your_dbase;host=192.168.1.2;port=5432;";
    $dbh = DBI->connect($connection_string,'user','pass',
    {AutoCommit=>0,RaiseError=>1,PrintError=>1,pg_enable_utf8=>1,}
    );
    my $sql = $dbh-> prepare( $command );
    eval { $sql-> execute() };
    my $error = $dbh-> state;
    $sql-> finish;
    if ( $error ) { $dbh-> rollback() } else {  $dbh-> commit() }
    $dbh-> disconnect();
    $BODY$
    LANGUAGE plperlu VOLATILE;
    

And then you can call the function inside database A:

SELECT send_data( 'INSERT INTO jm (jm) VALUES (''zzzzzz'')' );

And the value "zzzzzz" will be added into table "jm" in database B.

jquery - disable click

If you're using jQuery versions 1.4.3+:

$('selector').click(false);

If not:

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

Query to search all packages for table and/or column

You can do this:

select *
from user_source
where upper(text) like upper('%SOMETEXT%');

Alternatively, SQL Developer has a built-in report to do this under:

View > Reports > Data Dictionary Reports > PLSQL > Search Source Code

The 11G docs for USER_SOURCE are here

Getting the thread ID from a thread

The offset under Windows 10 is 0x022C (x64-bit-Application) and 0x0160 (x32-bit-Application):

public static int GetNativeThreadId(Thread thread)
{
    var f = typeof(Thread).GetField("DONT_USE_InternalThread",
        BindingFlags.GetField | BindingFlags.NonPublic | BindingFlags.Instance);

    var pInternalThread = (IntPtr)f.GetValue(thread);
    var nativeId = Marshal.ReadInt32(pInternalThread, (IntPtr.Size == 8) ? 0x022C : 0x0160); // found by analyzing the memory
    return nativeId;
}

How can git be installed on CENTOS 5.5?

I'm sure this question is about to die now that RHEL 5 is nearing end of life, but the answer seems to have gotten a lot simpler now:

sudo yum install epel-release
sudo yum install git

worked for me on a fresh install of CentOS 5.11.

What is the difference between Python and IPython?

There are few differences between Python and IPython but they are only the interpretation of few syntax like the few mentioned by @Ryan Chase but deep inside the true flavor of Python is maintained even in the Ipython.

The best part of the IPython is the IPython notebook. You can put all your work into a notebook like script, image files, etc. But with base Python, you can only make the script in a file and execute it.

At start, you need to understand that the IPython is developed with the intention of supporting rich media and Python script in a single integrated container.

Django download a file

If you hafe upload your file in media than:

media
example-input-file.txt

views.py

def download_csv(request):    
    file_path = os.path.join(settings.MEDIA_ROOT, 'example-input-file.txt')    
    if os.path.exists(file_path):    
        with open(file_path, 'rb') as fh:    
            response = HttpResponse(fh.read(), content_type="application/vnd.ms-excel")    
            response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path)    
            return response

urls.py

path('download_csv/', views.download_csv, name='download_csv'),

download.html

a href="{% url 'download_csv' %}" download=""

What is the difference between bottom-up and top-down?

Dynamic Programming is often called Memoization!

1.Memoization is the top-down technique(start solving the given problem by breaking it down) and dynamic programming is a bottom-up technique(start solving from the trivial sub-problem, up towards the given problem)

2.DP finds the solution by starting from the base case(s) and works its way upwards. DP solves all the sub-problems, because it does it bottom-up

Unlike Memoization, which solves only the needed sub-problems

  1. DP has the potential to transform exponential-time brute-force solutions into polynomial-time algorithms.

  2. DP may be much more efficient because its iterative

On the contrary, Memoization must pay for the (often significant) overhead due to recursion.

To be more simple, Memoization uses the top-down approach to solve the problem i.e. it begin with core(main) problem then breaks it into sub-problems and solve these sub-problems similarly. In this approach same sub-problem can occur multiple times and consume more CPU cycle, hence increase the time complexity. Whereas in Dynamic programming same sub-problem will not be solved multiple times but the prior result will be used to optimize the solution.

vim line numbers - how to have them on by default?

in home directory you will find a file called ".vimrc" in that file add this code "set nu" and save and exit and open new vi file and you will find line numbers on that.

How do I encode/decode HTML entities in Ruby?

To decode characters in Rails use:

<%= raw '<html>' %>

So,

<%= raw '&lt;br&gt;' %>

would output

<br>

String Comparison in Java

Leading from answers from @Bozho and @aioobe, lexicographic comparisons are similar to the ordering that one might find in a dictionary.

The Java String class provides the .compareTo () method in order to lexicographically compare Strings. It is used like this "apple".compareTo ("banana").

The return of this method is an int which can be interpreted as follows:

  • returns < 0 then the String calling the method is lexicographically first (comes first in a dictionary)
  • returns == 0 then the two strings are lexicographically equivalent
  • returns > 0 then the parameter passed to the compareTo method is lexicographically first.

More specifically, the method provides the first non-zero difference in ASCII values.

Thus "computer".compareTo ("comparison") will return a value of (int) 'u' - (int) 'a' (20). Since this is a positive result, the parameter ("comparison") is lexicographically first.

There is also a variant .compareToIgnoreCase () which will return 0 for "a".compareToIgnoreCase ("A"); for example.

Removing underline with href attribute

Add a style with the attribute text-decoration:none;:

There are a number of different ways of doing this.

Inline style:

<a href="xxx.html" style="text-decoration:none;">goto this link</a>

Inline stylesheet:

<html>
<head>
<style type="text/css">
   a {
      text-decoration:none;
   }
</style>
</head>
<body>
<a href="xxx.html">goto this link</a>
</body>
</html>

External stylesheet:

<html>
<head>
<link rel="Stylesheet" href="stylesheet.css" />
</head>
<body>
<a href="xxx.html">goto this link</a>
</body>
</html>

stylesheet.css:

a {
      text-decoration:none;
   }

What does LayoutInflater in Android do?

my customize list hope it illustrate concept

public class second extends ListActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.second);
//  TextView textview=(TextView)findViewById(R.id.textView1);
//  textview.setText(getIntent().getExtras().getString("value"));

    setListAdapter(new MyAdapter(this,R.layout.list_item,R.id.textView1, getResources().getStringArray(R.array.counteries)));
}

private class MyAdapter extends ArrayAdapter<String>{

    public MyAdapter(Context context, int resource, int textViewResourceId,
            String[] objects) {
        super(context, resource, textViewResourceId, objects);
        // TODO Auto-generated constructor stub
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        LayoutInflater inflater=(LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View row=inflater.inflate(R.layout.list_item,parent,false);
        String[]items=getResources().getStringArray(R.array.counteries);

        ImageView iv=(ImageView) row.findViewById(R.id.imageView1);
        TextView tv=(TextView) row.findViewById(R.id.textView1);
        tv.setText(items[position]);

        if(items[position].equals("unitedstates")){
            iv.setImageResource(R.drawable.usa);
        }else   if(items[position].equals("Russia")){
            iv.setImageResource(R.drawable.russia);
        }else   if(items[position].equals("Japan")){
            iv.setImageResource(R.drawable.japan);
        }
        // TODO Auto-generated method stub
        return row;
    }

}

}

Difference between Node object and Element object?

Element inherits from Node, in the same way that Dog inherits from Animal.

An Element object "is-a" Node object, in the same way that a Dog object "is-a" Animal object.

Node is for implementing a tree structure, so its methods are for firstChild, lastChild, childNodes, etc. It is more of a class for a generic tree structure.

And then, some Node objects are also Element objects. Element inherits from Node. Element objects actually represents the objects as specified in the HTML file by the tags such as <div id="content"></div>. The Element class define properties and methods such as attributes, id, innerHTML, clientWidth, blur(), and focus().

Some Node objects are text nodes and they are not Element objects. Each Node object has a nodeType property that indicates what type of node it is, for HTML documents:

1: Element node
3: Text node
8: Comment node
9: the top level node, which is document

We can see some examples in the console:

> document instanceof Node
  true

> document instanceof Element
  false

> document.firstChild
  <html>...</html>

> document.firstChild instanceof Node
  true

> document.firstChild instanceof Element
  true

> document.firstChild.firstChild.nextElementSibling
  <body>...</body>

> document.firstChild.firstChild.nextElementSibling === document.body
  true

> document.firstChild.firstChild.nextSibling
  #text

> document.firstChild.firstChild.nextSibling instanceof Node
  true

> document.firstChild.firstChild.nextSibling instanceof Element
  false

> Element.prototype.__proto__ === Node.prototype
  true

The last line above shows that Element inherits from Node. (that line won't work in IE due to __proto__. Will need to use Chrome, Firefox, or Safari).

By the way, the document object is the top of the node tree, and document is a Document object, and Document inherits from Node as well:

> Document.prototype.__proto__ === Node.prototype
  true

Here are some docs for the Node and Element classes:
https://developer.mozilla.org/en-US/docs/DOM/Node
https://developer.mozilla.org/en-US/docs/DOM/Element

How to install iPhone application in iPhone Simulator

I see you have a problem. Try building your app as Release and then check out your source codes build folder. It may be called Release-iphonesimulator. Inside here will be the app. Then go to (home folder)/Library/Application Support/iPhone Simulator (if you can't find it, try pressing Command - J and choosing arrange by name). Go to an OS that has apps in it in the iPhone sim, like 4.1. In that folder there should be an Applications folder. Open that, and there should be folders with random lettering. Pick any one, and replace it with the app you have. Make sure to delete anything in the little folders!

If it doesn't work, then I'm dumbfounded.

What is the difference between for and foreach?

foreach is useful if you have a array or other IEnumerable Collection of data. but for can be used for access elements of an array that can be accessed by their index.

How to convert BigInteger to String in java

Why don't you use the BigInteger(String) constructor ? That way, round-tripping via toString() should work fine.

(note also that your conversion to bytes doesn't explicitly specify a character-encoding and is platform-dependent - that could be source of grief further down the line)

laravel foreach loop in controller

The view (blade template): Inside the loop you can retrieve whatever column you looking for

 @foreach ($products as $product)
   {{$product->sku}}
 @endforeach

Jackson overcoming underscores in favor of camel-case

You can configure the ObjectMapper to convert camel case to names with an underscore:

objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);

Or annotate a specific model class with this annotation:

@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)

Before Jackson 2.7, the constant was named:

PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES

How do I programmatically change file permissions?

If you want to set 777 permission to your created file than you can use the following method:

public void setPermission(File file) throws IOException{
    Set<PosixFilePermission> perms = new HashSet<>();
    perms.add(PosixFilePermission.OWNER_READ);
    perms.add(PosixFilePermission.OWNER_WRITE);
    perms.add(PosixFilePermission.OWNER_EXECUTE);

    perms.add(PosixFilePermission.OTHERS_READ);
    perms.add(PosixFilePermission.OTHERS_WRITE);
    perms.add(PosixFilePermission.OTHERS_EXECUTE);

    perms.add(PosixFilePermission.GROUP_READ);
    perms.add(PosixFilePermission.GROUP_WRITE);
    perms.add(PosixFilePermission.GROUP_EXECUTE);

    Files.setPosixFilePermissions(file.toPath(), perms);
}

UIButton title text color

use

Objective-C

[headingButton setTitleColor:[UIColor colorWithRed:36/255.0 green:71/255.0 blue:113/255.0 alpha:1.0] forState:UIControlStateNormal];

Swift

headingButton.setTitleColor(.black, for: .normal)

How do I retrieve my MySQL username and password?

While you can't directly recover a MySQL password without bruteforcing, there might be another way - if you've used MySQL Workbench to connect to the database, and have saved the credentials to the "vault", you're golden.

On Windows, the credentials are stored in %APPDATA%\MySQL\Workbench\workbench_user_data.dat - encrypted with CryptProtectData (without any additional entropy). Decrypting is easy peasy:

std::vector<unsigned char> decrypt(BYTE *input, size_t length) {
    DATA_BLOB inblob { length, input };
    DATA_BLOB outblob;

    if (!CryptUnprotectData(&inblob, NULL, NULL, NULL, NULL, CRYPTPROTECT_UI_FORBIDDEN, &outblob)) {
            throw std::runtime_error("Couldn't decrypt");
    }

    std::vector<unsigned char> output(length);
    memcpy(&output[0], outblob.pbData, outblob.cbData);

    return output;
}

Or you can check out this DonationCoder thread for source + executable of a quick-and-dirty implementation.

How to use OpenSSL to encrypt/decrypt files?

Encrypt:

openssl enc -in infile.txt -out encrypted.dat -e -aes256 -k symmetrickey

Decrypt:

openssl enc -in encrypted.dat -out outfile.txt -d -aes256 -k symmetrickey

For details, see the openssl(1) docs.

Effectively use async/await with ASP.NET Web API

I would change your service layer to:

public Task<BackOfficeResponse<List<Country>>> ReturnAllCountries()
{
    return Task.Run(() =>
    {
        return _service.Process<List<Country>>(BackOfficeEndpoint.CountryEndpoint, "returnCountries");
    }      
}

as you have it, you are still running your _service.Process call synchronously, and gaining very little or no benefit from awaiting it.

With this approach, you are wrapping the potentially slow call in a Task, starting it, and returning it to be awaited. Now you get the benefit of awaiting the Task.

Viewing root access files/folders of android on windows

If you have android, you can install free app on phone (Wifi file Transfer) and enable ssl, port and other options for access and send data in both directions just start application and write in pc browser phone ip and port. enjoy!

OpenJDK availability for Windows OS

For Java 12 onwards, official General-Availability (GA) and Early-Access (EA) Windows 64-bit builds of the OpenJDK (GPL2 + Classpath Exception) from Oracle are available as tar.gz/zip from the JDK website.

If you prefer an installer, there are several distributions. There is a public Google Doc and Blog post by the Java Champions community which lists the best-supported OpenJDK distributions. Currently, these are:

android TextView: setting the background color dynamically doesn't work

Just this 1 line of code changed the background programmatically

tv.setBackgroundColor(Color.parseColor("#808080"));

jQuery datepicker to prevent past date

Try this:

$("#datepicker").datepicker({ minDate: 0 });

Remove the quotes from 0.

PHP Curl And Cookies

Here you can find some useful info about cURL & cookies http://docstore.mik.ua/orelly/webprog/pcook/ch11_04.htm .

You can also use this well done method https://github.com/alixaxel/phunction/blob/master/phunction/Net.php#L89 like a function:

function CURL($url, $data = null, $method = 'GET', $cookie = null, $options = null, $retries = 3)
{
    $result = false;

    if ((extension_loaded('curl') === true) && (is_resource($curl = curl_init()) === true))
    {
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_FAILONERROR, true);
        curl_setopt($curl, CURLOPT_AUTOREFERER, true);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);

        if (preg_match('~^(?:DELETE|GET|HEAD|OPTIONS|POST|PUT)$~i', $method) > 0)
        {
            if (preg_match('~^(?:HEAD|OPTIONS)$~i', $method) > 0)
            {
                curl_setopt_array($curl, array(CURLOPT_HEADER => true, CURLOPT_NOBODY => true));
            }

            else if (preg_match('~^(?:POST|PUT)$~i', $method) > 0)
            {
                if (is_array($data) === true)
                {
                    foreach (preg_grep('~^@~', $data) as $key => $value)
                    {
                        $data[$key] = sprintf('@%s', rtrim(str_replace('\\', '/', realpath(ltrim($value, '@'))), '/') . (is_dir(ltrim($value, '@')) ? '/' : ''));
                    }

                    if (count($data) != count($data, COUNT_RECURSIVE))
                    {
                        $data = http_build_query($data, '', '&');
                    }
                }

                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            }

            curl_setopt($curl, CURLOPT_CUSTOMREQUEST, strtoupper($method));

            if (isset($cookie) === true)
            {
                curl_setopt_array($curl, array_fill_keys(array(CURLOPT_COOKIEJAR, CURLOPT_COOKIEFILE), strval($cookie)));
            }

            if ((intval(ini_get('safe_mode')) == 0) && (ini_set('open_basedir', null) !== false))
            {
                curl_setopt_array($curl, array(CURLOPT_MAXREDIRS => 5, CURLOPT_FOLLOWLOCATION => true));
            }

            if (is_array($options) === true)
            {
                curl_setopt_array($curl, $options);
            }

            for ($i = 1; $i <= $retries; ++$i)
            {
                $result = curl_exec($curl);

                if (($i == $retries) || ($result !== false))
                {
                    break;
                }

                usleep(pow(2, $i - 2) * 1000000);
            }
        }

        curl_close($curl);
    }

    return $result;
}

And pass this as $cookie parameter:

$cookie_jar = tempnam('/tmp','cookie');