Programs & Examples On #Nsstring

NSString is the plain-text character-string class in Cocoa and Cocoa Touch. See also NSMutableString, NSData and NSMutableData (for objects that contain bytes rather than human-language characters), and NSAttributedString and NSMutableAttributedString (for rich-text strings).

convert NSDictionary to NSString

You can call [aDictionary description], or anywhere you would need a format string, just use %@ to stand in for the dictionary:

[NSString stringWithFormat:@"my dictionary is %@", aDictionary];

or

NSLog(@"My dictionary is %@", aDictionary);

Split an NSString to access one particular piece

Either of these 2:

NSString *subString = [dateString subStringWithRange:NSMakeRange(0,2)];
NSString *subString = [[dateString componentsSeparatedByString:@"/"] objectAtIndex:0];

Though keep in mind that sometimes a date string is not formatted properly and a day ( or a month for that matter ) is shown as 8, rather than 08 so the first one might be the worst of the 2 solutions.

The latter should be put into a separate array so you can actually check for the length of the thing returned, so you do not get any exceptions thrown in the case of a corrupt or invalid date string from whatever source you have.

Creating NSData from NSString in Swift

// Checking the format
var urlString: NSString = NSString(data: jsonData, encoding: NSUTF8StringEncoding)

// Convert your data and set your request's HTTPBody property
var stringData: NSString = NSString(string: "jsonRequest=\(urlString)")

var requestBodyData: NSData = stringData.dataUsingEncoding(NSUTF8StringEncoding)!

Objective-C and Swift URL encoding

This is not my solution. Someone else wrote in stackoverflow but I have forgotten how.

Somehow this solution works "well". It handles diacritic, chinese characters, and pretty much anything else.

- (NSString *) URLEncodedString {
    NSMutableString * output = [NSMutableString string];
    const char * source = [self UTF8String];
    int sourceLen = strlen(source);
    for (int i = 0; i < sourceLen; ++i) {
        const unsigned char thisChar = (const unsigned char)source[i];
        if (false && thisChar == ' '){
            [output appendString:@"+"];
        } else if (thisChar == '.' || thisChar == '-' || thisChar == '_' || thisChar == '~' ||
                   (thisChar >= 'a' && thisChar <= 'z') ||
                   (thisChar >= 'A' && thisChar <= 'Z') ||
                   (thisChar >= '0' && thisChar <= '9')) {
            [output appendFormat:@"%c", thisChar];
        } else {
            [output appendFormat:@"%%%02X", thisChar];
        }
    }
    return output;
}

If someone would tell me who wrote this code, I'll really appreciate it. Basically he has some explanation why this encoded string will decode exactly as it wish.

I modified his solution a little. I like space to be represented with %20 rather than +. That's all.

Convert NSDate to NSString

In Swift:

var formatter = NSDateFormatter()
formatter.dateFormat = "yyyy"
var dateString = formatter.stringFromDate(YourNSDateInstanceHERE)

Constants in Objective-C

If you want something like global constants; a quick an dirty way is to put the constant declarations into the pch file.

NSRange to Range<String.Index>

The Swift 3.0 beta official documentation has provided its standard solution for this situation under the title String.UTF16View in section UTF16View Elements Match NSString Characters title

Objective-C: Reading a file line by line

This should do the trick:

#include <stdio.h>

NSString *readLineAsNSString(FILE *file)
{
    char buffer[4096];

    // tune this capacity to your liking -- larger buffer sizes will be faster, but
    // use more memory
    NSMutableString *result = [NSMutableString stringWithCapacity:256];

    // Read up to 4095 non-newline characters, then read and discard the newline
    int charsRead;
    do
    {
        if(fscanf(file, "%4095[^\n]%n%*c", buffer, &charsRead) == 1)
            [result appendFormat:@"%s", buffer];
        else
            break;
    } while(charsRead == 4095);

    return result;
}

Use as follows:

FILE *file = fopen("myfile", "r");
// check for NULL
while(!feof(file))
{
    NSString *line = readLineAsNSString(file);
    // do stuff with line; line is autoreleased, so you should NOT release it (unless you also retain it beforehand)
}
fclose(file);

This code reads non-newline characters from the file, up to 4095 at a time. If you have a line that is longer than 4095 characters, it keeps reading until it hits a newline or end-of-file.

Note: I have not tested this code. Please test it before using it.

How do I convert NSInteger to NSString datatype?

Easy way to do:

NSInteger value = x;
NSString *string = [@(value) stringValue];

Here the @(value) converts the given NSInteger to an NSNumber object for which you can call the required function, stringValue.

Remove all whitespaces from NSString

Use below marco and remove the space.

#define TRIMWHITESPACE(string) [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]

in other file call TRIM :

    NSString *strEmail;
    strEmail = TRIM(@"     this is the test.");

May it will help you...

Converting NSString to NSDate (and back again)

using "10" for representing a year is not good, because it can be 1910, 1810, etc. You probably should use 4 digits for that.

If you can change the date to something like

yyyymmdd

Then you can use:

// Convert string to date object
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyyMMdd"];
NSDate *date = [dateFormat dateFromString:dateStr];  

// Convert date object to desired output format
[dateFormat setDateFormat:@"EEEE MMMM d, YYYY"];
dateStr = [dateFormat stringFromDate:date];  
[dateFormat release];

How to check if NSString begins with a certain character

This nice little bit of code I found by chance, and I have yet to see it suggested on Stack. It only works if the characters you want to remove or alter exist, which is convenient in many scenarios. If the character/s does not exist, it won't alter your NSString:

NSString = [yourString stringByReplacingOccurrencesOfString:@"YOUR CHARACTERS YOU WANT TO REMOVE" withString:@"CAN either be EMPTY or WITH TEXT REPLACEMENT"];

This is how I use it:

//declare what to look for
NSString * suffixTorRemove = @"&lt;/p&gt;";
NSString * prefixToRemove = @"&lt;p&gt;";
NSString * randomCharacter = @"&lt;/strong&gt;";
NSString * moreRandom = @"&lt;strong&gt;";
NSString * makeAndSign = @"&amp;amp;";

//I AM INSERTING A VALUE FROM A DATABASE AND HAVE ASSIGNED IT TO returnStr
returnStr = [returnStr stringByReplacingOccurrencesOfString:suffixTorRemove withString:@""];
returnStr = [returnStr stringByReplacingOccurrencesOfString:prefixToRemove withString:@""];
returnStr = [returnStr stringByReplacingOccurrencesOfString:randomCharacter withString:@""];
returnStr = [returnStr stringByReplacingOccurrencesOfString:moreRandom withString:@""];
returnStr = [returnStr stringByReplacingOccurrencesOfString:makeAndSign withString:@"&"];

//check the output
NSLog(@"returnStr IS NOW: %@", returnStr);

This one line is super easy to perform three actions in one:

  1. Checks your string for the character/s you do not want
  2. Can replaces them with whatever you like
  3. Does not affect surrounding code

Remove HTML Tags from an NSString on the iPhone

use this

NSString *myregex = @"<[^>]*>"; //regex to remove any html tag

NSString *htmlString = @"<html>bla bla</html>";
NSString *stringWithoutHTML = [hstmString stringByReplacingOccurrencesOfRegex:myregex withString:@""];

don't forget to include this in your code : #import "RegexKitLite.h" here is the link to download this API : http://regexkit.sourceforge.net/#Downloads

Case insensitive comparison NSString

An alternative if you want more control than just case insensitivity is:

[someString compare:otherString options:NSCaseInsensitiveSearch];

Numeric search and diacritical insensitivity are two handy options.

Capitalize or change case of an NSString in Objective-C

Here ya go:

viewNoteDateMonth.text  = [[displayDate objectAtIndex:2] uppercaseString];

Btw:
"april" is lowercase ? [NSString lowercaseString]
"APRIL" is UPPERCASE ? [NSString uppercaseString]
"April May" is Capitalized/Word Caps ? [NSString capitalizedString]
"April may" is Sentence caps ? (method missing; see workaround below)

Hence what you want is called "uppercase", not "capitalized". ;)

As for "Sentence Caps" one has to keep in mind that usually "Sentence" means "entire string". If you wish for real sentences use the second method, below, otherwise the first:

@interface NSString ()

- (NSString *)sentenceCapitalizedString; // sentence == entire string
- (NSString *)realSentenceCapitalizedString; // sentence == real sentences

@end

@implementation NSString

- (NSString *)sentenceCapitalizedString {
    if (![self length]) {
        return [NSString string];
    }
    NSString *uppercase = [[self substringToIndex:1] uppercaseString];
    NSString *lowercase = [[self substringFromIndex:1] lowercaseString];
    return [uppercase stringByAppendingString:lowercase];
}

- (NSString *)realSentenceCapitalizedString {
    __block NSMutableString *mutableSelf = [NSMutableString stringWithString:self];
    [self enumerateSubstringsInRange:NSMakeRange(0, [self length])
                             options:NSStringEnumerationBySentences
                          usingBlock:^(NSString *sentence, NSRange sentenceRange, NSRange enclosingRange, BOOL *stop) {
        [mutableSelf replaceCharactersInRange:sentenceRange withString:[sentence sentenceCapitalizedString]];
    }];
    return [NSString stringWithString:mutableSelf]; // or just return mutableSelf.
}

@end

Converting NSString to NSDictionary / JSON

I believe you are misinterpreting the JSON format for key values. You should store your string as

NSString *jsonString = @"{\"ID\":{\"Content\":268,\"type\":\"text\"},\"ContractTemplateID\":{\"Content\":65,\"type\":\"text\"}}";
NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];

Now if you do following NSLog statement

NSLog(@"%@",[json objectForKey:@"ID"]);

Result would be another NSDictionary.

{
    Content = 268;
    type = text;
}

Hope this helps to get clear understanding.

How do I test if a string is empty in Objective-C?

if(str.length == 0 || [str isKindOfClass: [NSNull class]]){
    NSLog(@"String is empty");
}
else{
    NSLog(@"String is not empty");
}    

AES Encryption for an NSString on the iPhone

@owlstead, regarding your request for "a cryptographically secure variant of one of the given answers," please see RNCryptor. It was designed to do exactly what you're requesting (and was built in response to the problems with the code listed here).

RNCryptor uses PBKDF2 with salt, provides a random IV, and attaches HMAC (also generated from PBKDF2 with its own salt. It support synchronous and asynchronous operation.

Shortcuts in Objective-C to concatenate NSStrings

Let's imagine that u don't know how many strings there.

NSMutableArray *arrForStrings = [[NSMutableArray alloc] init];
for (int i=0; i<[allMyStrings count]; i++) {
    NSString *str = [allMyStrings objectAtIndex:i];
    [arrForStrings addObject:str];
}
NSString *readyString = [[arrForStrings mutableCopy] componentsJoinedByString:@", "];

How to get substring of NSString?

Here's a slightly less complicated answer:

NSString *myString = @"abcdefg";
NSString *mySmallerString = [myString substringToIndex:4];

See also substringWithRange and substringFromIndex

Check that a input to UITextField is numeric only

#pragma mark - UItextfield Delegate

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if ([string isEqualToString:@"("]||[string isEqualToString:@")"]) {
        return TRUE;
    }

    NSLog(@"Range ==%d  ,%d",range.length,range.location);
    //NSRange *CURRANGE = [NSString  rangeOfString:string];

    if (range.location == 0 && range.length == 0) {
        if ([string isEqualToString:@"+"]) {
            return TRUE;
        }
    }
    return [self isNumeric:string];
}

-(BOOL)isNumeric:(NSString*)inputString{
    BOOL isValid = NO;
    NSCharacterSet *alphaNumbersSet = [NSCharacterSet decimalDigitCharacterSet];
    NSCharacterSet *stringSet = [NSCharacterSet characterSetWithCharactersInString:inputString];
    isValid = [alphaNumbersSet isSupersetOfSet:stringSet];
    return isValid;
}

String comparison in Objective-C

You can use case-sensitive or case-insensitive comparison, depending what you need. Case-sensitive is like this:

if ([category isEqualToString:@"Some String"])
{
   // Both strings are equal without respect to their case.
}

Case-insensitive is like this:

if ([category compare:@"Some String" options:NSCaseInsensitiveSearch] == NSOrderedSame)
{
   // Both strings are equal with respect to their case.
}

Remove characters from NSString?

All above will works fine. But the right method is this:

yourString = [yourString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];

It will work like a TRIM method. It will remove all front and back spaces.

Thanks

Trim spaces from end of a NSString

Here you go...

- (NSString *)removeEndSpaceFrom:(NSString *)strtoremove{
    NSUInteger location = 0;
    unichar charBuffer[[strtoremove length]];
    [strtoremove getCharacters:charBuffer];
    int i = 0;
    for(i = [strtoremove length]; i >0; i--) {
        NSCharacterSet* charSet = [NSCharacterSet whitespaceCharacterSet];
        if(![charSet characterIsMember:charBuffer[i - 1]]) {
            break;
        }
    }
    return [strtoremove substringWithRange:NSMakeRange(location, i  - location)];
}

So now just call it. Supposing you have a string that has spaces on the front and spaces on the end and you just want to remove the spaces on the end, you can call it like this:

NSString *oneTwoThree = @"  TestString   ";
NSString *resultString;
resultString = [self removeEndSpaceFrom:oneTwoThree];

resultString will then have no spaces at the end.

How to add percent sign to NSString

The accepted answer doesn't work for UILocalNotification. For some reason, %%%% (4 percent signs) or the unicode character '\uFF05' only work for this.

So to recap, when formatting your string you may use %%. However, if your string is part of a UILocalNotification, use %%%% or \uFF05.

String replacement in Objective-C

NSString *stringreplace=[yourString stringByReplacingOccurrencesOfString:@"search" withString:@"new_string"];

Convert UTF-8 encoded NSData to NSString

Just to summarize, here's a complete answer, that worked for me.

My problem was that when I used

[NSString stringWithUTF8String:(char *)data.bytes];

The string I got was unpredictable: Around 70% it did contain the expected value, but too often it resulted with Null or even worse: garbaged at the end of the string.

After some digging I switched to

[[NSString alloc] initWithBytes:(char *)data.bytes length:data.length encoding:NSUTF8StringEncoding];

And got the expected result every time.

enum Values to NSString (iOS)

The solution below uses the preprocessor's stringize operator, allowing for a more elegant solution. It lets you define the enum terms in just one place for greater resilience against typos.

First, define your enum in the following way.

#define ENUM_TABLE \
X(ENUM_ONE),    \
X(ENUM_TWO)    \

#define X(a)    a
typedef enum Foo {
    ENUM_TABLE
} MyFooEnum;
#undef X

#define X(a)    @#a
NSString * const enumAsString[] = {
    ENUM_TABLE
};
#undef X

Now, use it in the following way:

// Usage
MyFooEnum t = ENUM_ONE;
NSLog(@"Enum test - t is: %@", enumAsString[t]);

t = ENUM_TWO;
NSLog(@"Enum test - t is now: %@", enumAsString[t]);

which outputs:

2014-10-22 13:36:21.344 FooProg[367:60b] Enum test - t is: ENUM_ONE
2014-10-22 13:36:21.344 FooProg[367:60b] Enum test - t is now: ENUM_TWO

@pixel's answer pointed me in the right direction.

How do I URL encode a string

In swift 3:

// exclude alpha and numeric == "full" encoding
stringUrl = stringUrl.addingPercentEncoding(withAllowedCharacters: .alphanumerics)!;

// exclude hostname and symbols &,/ and etc
stringUrl = stringUrl.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!;

How to convert NSNumber to NSString

//An example of implementation :
// we set the score of one player to a value
[Game getCurrent].scorePlayer1 = [NSNumber numberWithInteger:1];
// We copy the value in a NSNumber
NSNumber *aNumber = [Game getCurrent].scorePlayer1;
// Conversion of the NSNumber aNumber to a String with stringValue
NSString *StringScorePlayer1 = [aNumber stringValue];

How do I convert an NSString value to NSData?

For Swift 3, you will mostly be converting from String to Data.

let myString = "test"
let myData = myString.data(using: .utf8)
print(myData) // Optional(Data)

Convert NSArray to NSString in Objective-C

NSString * str = [componentsJoinedByString:@""];

and you have dic or multiple array then used bellow

NSString * result = [[array valueForKey:@"description"] componentsJoinedByString:@""];   

How to convert an NSString into an NSNumber

What about C's standard atoi?

int num = atoi([scannedNumber cStringUsingEncoding:NSUTF8StringEncoding]);

Do you think there are any caveats?

How to convert from int to string in objective c: example code

Simply convert int to NSString use :

  int x=10;

  NSString *strX=[NSString stringWithFormat:@"%d",x];

NSString with \n or line break

I just ran into the same issue when overloading -description for a subclass of NSObject. In this situation I was able to use carriage return (\r) instead of newline (\n) to create a line break.

[NSString stringWithFormat:@"%@\r%@", mystring1,mystring2];

How do I deserialize a JSON string into an NSDictionary? (For iOS 5+)

It looks like you are passing an NSString parameter where you should be passing an NSData parameter:

NSError *jsonError;
NSData *objectData = [@"{\"2\":\"3\"}" dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData
                                      options:NSJSONReadingMutableContainers 
                                        error:&jsonError];

Convert an NSURL to an NSString

If you're interested in the pure string:

[myUrl absoluteString];

If you're interested in the path represented by the URL (and to be used with NSFileManager methods for example):

[myUrl path];

How do I check if a string contains another string in Swift?

Here you go! Ready for Xcode 8 and Swift 3.

import UIKit

let mString = "This is a String that contains something to search."
let stringToSearchUpperCase = "String"
let stringToSearchLowerCase = "string"

mString.contains(stringToSearchUpperCase) //true
mString.contains(stringToSearchLowerCase) //false
mString.lowercased().contains(stringToSearchUpperCase) //false
mString.lowercased().contains(stringToSearchLowerCase) //true

Preventing twitter bootstrap carousel from auto sliding on page load

For Bootstrap 4 simply remove the 'data-ride="carousel"' from the carousel div. This removes auto play at load time.

To enable the auto play again you would still have to use the "play" call in javascript.

How can I display two div in one line via css inline property

use inline-block instead of inline. Read more information here about the difference between inline and inline-block.

.inline { 
display: inline-block; 
border: 1px solid red; 
margin:10px;
}

DEMO

Spark - SELECT WHERE or filtering?

As Yaron mentioned, there isn't any difference between where and filter.

filter is an overloaded method that takes a column or string argument. The performance is the same, regardless of the syntax you use.

filter overloaded method

We can use explain() to see that all the different filtering syntaxes generate the same Physical Plan. Suppose you have a dataset with person_name and person_country columns. All of the following code snippets will return the same Physical Plan below:

df.where("person_country = 'Cuba'").explain()
df.where($"person_country" === "Cuba").explain()
df.where('person_country === "Cuba").explain()
df.filter("person_country = 'Cuba'").explain()

These all return this Physical Plan:

== Physical Plan ==
*(1) Project [person_name#152, person_country#153]
+- *(1) Filter (isnotnull(person_country#153) && (person_country#153 = Cuba))
   +- *(1) FileScan csv [person_name#152,person_country#153] Batched: false, Format: CSV, Location: InMemoryFileIndex[file:/Users/matthewpowers/Documents/code/my_apps/mungingdata/spark2/src/test/re..., PartitionFilters: [], PushedFilters: [IsNotNull(person_country), EqualTo(person_country,Cuba)], ReadSchema: struct<person_name:string,person_country:string>

The syntax doesn't change how filters are executed under the hood, but the file format / database that a query is executed on does. Spark will execute the same query differently on Postgres (predicate pushdown filtering is supported), Parquet (column pruning), and CSV files. See here for more details.

Regex Letters, Numbers, Dashes, and Underscores

Just escape the dashes to prevent them from being interpreted (I don't think underscore needs escaping, but it can't hurt). You don't say which regex you are using.

([A-Za-z0-9\-\_]+)

List of IP Space used by Facebook

Updated list as of 6/11/2013

204.15.20.0/22
69.63.176.0/20

66.220.144.0/20
66.220.144.0/21
69.63.184.0/21
69.63.176.0/21
74.119.76.0/22
69.171.255.0/24
173.252.64.0/18
69.171.224.0/19
69.171.224.0/20
103.4.96.0/22
69.63.176.0/24
173.252.64.0/19
173.252.70.0/24
31.13.64.0/18
31.13.24.0/21
66.220.152.0/21
66.220.159.0/24
69.171.239.0/24
69.171.240.0/20
31.13.64.0/19
31.13.64.0/24
31.13.65.0/24
31.13.67.0/24
31.13.68.0/24
31.13.69.0/24
31.13.70.0/24
31.13.71.0/24
31.13.72.0/24
31.13.73.0/24
31.13.74.0/24
31.13.75.0/24
31.13.76.0/24
31.13.77.0/24
31.13.96.0/19
31.13.66.0/24
173.252.96.0/19
69.63.178.0/24
31.13.78.0/24
31.13.79.0/24
31.13.80.0/24
31.13.82.0/24
31.13.83.0/24
31.13.84.0/24
31.13.85.0/24
31.13.87.0/24
31.13.88.0/24
31.13.89.0/24
31.13.90.0/24
31.13.91.0/24
31.13.92.0/24
31.13.93.0/24
31.13.94.0/24
31.13.95.0/24
69.171.253.0/24
69.63.186.0/24
204.15.20.0/22
69.63.176.0/20
69.63.176.0/21
69.63.184.0/21
66.220.144.0/20
69.63.176.0/20

Installing lxml module in python

If you are encountering this issue on an Alpine based image try this :

apk add --update --no-cache g++ gcc libxml2-dev libxslt-dev python-dev libffi-dev openssl-dev make

// pip install -r requirements.txt

How to convert array to SimpleXML

You can use Mustache Template Engine and make a Template like:

{{#RECEIVER}}
<RECEIVER>
    <COMPANY>{{{COMPANY}}}</COMPANY>
    <CONTACT>{{{CONTACT}}}</CONTACT>
    <ADDRESS>{{{ADDRESS}}}</ADDRESS>
    <ZIP>{{ZIP}}</ZIP>
    <CITY>{{{CITY}}}</CITY>
</RECEIVER>
{{/RECEIVER}}
{{#DOC}}
<DOC>
    <TEXT>{{{TEXT}}}</TEXT>
    <NUMBER>{{{NUMBER}}}</NUMBER>
</DOC>
{{/DOC}}

Use it like this in PHP:

require_once( __DIR__ .'/../controls/Mustache/Autoloader.php' );
Mustache_Autoloader::register();
$oMustache = new Mustache_Engine();
$sTemplate = implode( '', file( __DIR__ ."/xml.tpl" ));
$return = $oMustache->render($sTemplate, $res);
echo($return);

Activity restart on rotation Android

What you describe is the default behavior. You have to detect and handle these events yourself by adding:

android:configChanges

to your manifest and then the changes that you want to handle. So for orientation, you would use:

android:configChanges="orientation"

and for the keyboard being opened or closed you would use:

android:configChanges="keyboardHidden"

If you want to handle both you can just separate them with the pipe command like:

android:configChanges="keyboardHidden|orientation"

This will trigger the onConfigurationChanged method in whatever Activity you call. If you override the method you can pass in the new values.

Hope this helps.

How to determine the Schemas inside an Oracle Data Pump Export file

impdp exports the DDL of a dmp backup to a file if you use the SQLFILE parameter. For example, put this into a text file

impdp '/ as sysdba' dumpfile=<your .dmp file> logfile=import_log.txt sqlfile=ddl_dump.txt

Then check ddl_dump.txt for the tablespaces, users, and schemas in the backup.

According to the documentation, this does not actually modify the database:

The SQL is not actually executed, and the target system remains unchanged.

Send parameter to Bootstrap modal window?

There is a better solution than the accepted answer, specifically using data-* attributes. Setting the id to 1 will cause you issues if any other element on the page has id=1. Instead, you can do:

<button class="btn btn-primary" data-toggle="modal" data-target="#yourModalID" data-yourparameter="whateverYouWant">Load</button>

<script>
$('#yourModalID').on('show.bs.modal', function(e) {
  var yourparameter = e.relatedTarget.dataset.yourparameter;
  // Do some stuff w/ it.
});
</script>

Show MySQL host via SQL Command

To get current host name :-

select @@hostname;
show variables where Variable_name like '%host%';

To get hosts for all incoming requests :-

select host from information_schema.processlist;

Based on your last comment,
I don't think you can resolve IP for the hostname using pure mysql function,
as it require a network lookup, which could be taking long time.

However, mysql document mention this :-

resolveip google.com.sg

docs :- http://dev.mysql.com/doc/refman/5.0/en/resolveip.html

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

What is the problem here is that you somehow installed into virtualenv using sudo. Probably by accident. This means root user will rewrite Python package data, making all file owned by root and your normal user cannot write those files anymore. Usually virtualenv should be used and owned by your normal UNIX user only.

You can fix the issue by changing UNIX file permissions pack to your user. Try:

$ sudo chown -R USERNAME /Users/USERNAME/Library/Logs/pip
$ sudo chown -R USERNAME /Users/USERNAME/Library/Caches/pip

then pip should be able to write those files again.

More information about UNIX file permission management

PHP session lost after redirect

I was having the same problem and I went nuts searching in my code for the answer. Finally I found my hosting recently updated the PHP version on my server and didn't correctly set up the session_save_path parameter on the php.ini file.

So, if someone reads this, please check php.ini config before anything else.

How do I preserve line breaks when getting text from a textarea?

You could set width of div using Javascript and add white-space:pre-wrap to p tag, this break your textarea content at end of each line.

_x000D_
_x000D_
document.querySelector("button").onclick = function gt(){_x000D_
var card = document.createElement('div');_x000D_
card.style.width = "160px";_x000D_
card.style.background = "#eee";_x000D_
var post = document.createElement('p');_x000D_
var postText = document.getElementById('post-text').value;_x000D_
post.style.whiteSpace = "pre-wrap";_x000D_
card.append(post);_x000D_
post.append(postText);_x000D_
document.body.append(card);_x000D_
}
_x000D_
<textarea id="post-text" class="form-control" rows="3" placeholder="What's up?" required>_x000D_
Group Schedule:_x000D_
_x000D_
Tuesday practice @ 5th floor (8pm - 11 pm)_x000D_
_x000D_
Thursday practice @ 5th floor (8pm - 11 pm)_x000D_
_x000D_
Sunday practice @ (9pm - 12 am)</textarea>_x000D_
<br><br>_x000D_
<button>Copy!!</button>
_x000D_
_x000D_
_x000D_

How can I access iframe elements with Javascript?

If you have the HTML

<form name="formname" .... id="form-first">
    <iframe id="one" src="iframe2.html">
    </iframe>
</form>

and JavaScript

function iframeRef( frameRef ) {
    return frameRef.contentWindow
        ? frameRef.contentWindow.document
        : frameRef.contentDocument
}

var inside = iframeRef( document.getElementById('one') )

inside is now a reference to the document, so you can do getElementsByTagName('textarea') and whatever you like, depending on what's inside the iframe src.

What is the preferred syntax for defining enums in JavaScript?

var DaysEnum = Object.freeze ({ monday: {}, tuesday: {}, ... });

You don't need to specify an id, you can just use an empty object to compare enums.

if (incommingEnum === DaysEnum.monday) //incommingEnum is monday

EDIT: If you are going to serialize the object (to JSON for instance) you'll the id again.

How to find out when a particular table was created in Oracle?

You can query the data dictionary/catalog views to find out when an object was created as well as the time of last DDL involving the object (example: alter table)

select * 
  from all_objects 
 where owner = '<name of schema owner>'
   and object_name = '<name of table>'

The column "CREATED" tells you when the object was created. The column "LAST_DDL_TIME" tells you when the last DDL was performed against the object.

As for when a particular row was inserted/updated, you can use audit columns like an "insert_timestamp" column or use a trigger and populate an audit table

Application Error - The connection to the server was unsuccessful. (file:///android_asset/www/index.html)

For my case, the problem was due to losing of the internet connection in my WiFi.

Powershell equivalent of bash ampersand (&) for forking/running background processes

I've used the solution described here http://jtruher.spaces.live.com/blog/cns!7143DA6E51A2628D!130.entry successfully in PowerShell v1.0. It definitely will be easier in PowerShell v2.0.

Decode HTML entities in Python string?

Python 3.4+

Use html.unescape():

import html
print(html.unescape('&pound;682m'))

FYI html.parser.HTMLParser.unescape is deprecated, and was supposed to be removed in 3.5, although it was left in by mistake. It will be removed from the language soon.


Python 2.6-3.3

You can use HTMLParser.unescape() from the standard library:

>>> try:
...     # Python 2.6-2.7 
...     from HTMLParser import HTMLParser
... except ImportError:
...     # Python 3
...     from html.parser import HTMLParser
... 
>>> h = HTMLParser()
>>> print(h.unescape('&pound;682m'))
£682m

You can also use the six compatibility library to simplify the import:

>>> from six.moves.html_parser import HTMLParser
>>> h = HTMLParser()
>>> print(h.unescape('&pound;682m'))
£682m

Changing text of UIButton programmatically swift

In Swift 3, 4, 5:

button.setTitle("Button Title", for: .normal)

Otherwise:

button.setTitle("Button Title", forState: UIControlState.Normal)

Also an @IBOutlet has to declared for the button.

HashMap allows duplicates?

m.put(null,null); // here key=null, value=null
m.put(null,a);    // here also key=null, and value=a

Duplicate keys are not allowed in hashmap.
However,value can be duplicated.

How can I copy data from one column to another in the same table?

UPDATE table_name SET
    destination_column_name=orig_column_name
WHERE condition_if_necessary

How do I show a message in the foreach loop?

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

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

How to add headers to OkHttp request interceptor?

client = new OkHttpClient();

        Request request = new Request.Builder().header("authorization", token).url(url).build();
        MyWebSocketListener wsListener = new MyWebSocketListener(LudoRoomActivity.this);
        client.newWebSocket(request, wsListener);
        client.dispatcher().executorService().shutdown();

Visual Studio Code Search and Replace with Regular Expressions

If you want ex. change all country codes in .json file from uppercase to lowercase:

ctrl+h
alt+r
alt+c

Find: ([A-Z]{2,})
Replace: $1

alt+enter
F1
type: lower -> select toLoweCase
ctrl+alt+enter

ex file:

[
 {"id": "PL", "name": "Poland"},
 {"id": "NZ", "name": "New Zealand"},
 ...
]

How to set-up a favicon?

With the introduction of (i|android|windows)phones, things have changed, and to get a correct and complete solution that works on any device is really time-consuming.

You can have a peek at https://realfavicongenerator.net/favicon_compatibility or http://caniuse.com/#search=favicon to get an idea on the best way to get something that works on any device.

You should have a look at http://realfavicongenerator.net/ to automate a large part of this work, and probably at https://github.com/audreyr/favicon-cheat-sheet to understand how it works (even if this latter resource hasn't been updated in a loooong time).

One complete solution requires to add to you header the following (with the corresponding pictures and files, of course) :

<link rel="shortcut icon" href="favicon.ico">
<link rel="apple-touch-icon" sizes="57x57" href="apple-touch-icon-57x57.png">
<link rel="apple-touch-icon" sizes="114x114" href="apple-touch-icon-114x114.png">
<link rel="apple-touch-icon" sizes="72x72" href="apple-touch-icon-72x72.png">
<link rel="apple-touch-icon" sizes="144x144" href="apple-touch-icon-144x144.png">
<link rel="apple-touch-icon" sizes="60x60" href="apple-touch-icon-60x60.png">
<link rel="apple-touch-icon" sizes="120x120" href="apple-touch-icon-120x120.png">
<link rel="apple-touch-icon" sizes="76x76" href="apple-touch-icon-76x76.png">
<link rel="apple-touch-icon" sizes="152x152" href="apple-touch-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="apple-touch-icon-180x180.png">
<link rel="icon" type="image/png" href="favicon-192x192.png" sizes="192x192">
<link rel="icon" type="image/png" href="favicon-160x160.png" sizes="160x160">
<link rel="icon" type="image/png" href="favicon-96x96.png" sizes="96x96">
<link rel="icon" type="image/png" href="favicon-16x16.png" sizes="16x16">
<link rel="icon" type="image/png" href="favicon-32x32.png" sizes="32x32">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="mstile-144x144.png">
<meta name="msapplication-config" content="browserconfig.xml">

In June 2016, RealFaviconGenerator claimed that the following 5 lines of code were supporting as many devices as the previous 18 lines:

<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png">
<link rel="icon" type="image/png" href="/favicon-32x32.png" sizes="32x32">
<link rel="icon" type="image/png" href="/favicon-16x16.png" sizes="16x16">
<link rel="manifest" href="/manifest.json">
<link rel="mask-icon" href="/safari-pinned-tab.svg" color="#5bbad5">
<meta name="theme-color" content="#ffffff">

Symfony2 Setting a default choice field selection

Setting default choice for symfony2 radio button

            $builder->add('range_options', 'choice', array(
                'choices' => array('day'=>'Day', 'week'=>'Week', 'month'=>'Month'),
                'data'=>'day', //set default value 
                'required'=>true,
                'empty_data'=>null,
                'multiple'=>false,
                'expanded'=> true                   
        ))

jQuery: Adding two attributes via the .attr(); method

Multiple Attribute

var tag = "tag name";
createNode(tag, target, attribute);

createNode: function(tag, target, attribute){
    var tag = jQuery("<" + tag + ">");
    jQuery.each(attribute, function(i,v){
        tag.attr(v);
    });
    target.append(tag);
    tag.appendTo(target);
}
var attribute = [
    {"data-level": "3"},
];

Getting the IP address of the current machine using Java

When you are looking for your "local" address, you should note that each machine has not only a single network interface, and each interface could has its own local address. Which means your machine is always owning several "local" addresses.

Different "local" addresses will be automatically chosen to use when you are connecting to different endpoints. For example, when you connect to google.com, you are using an "outside" local address; but when you connect to your localhost, your local address is always localhost itself, because localhost is just a loopback.

Below is showing how to find out your local address when you are communicating with google.com:

Socket socket = new Socket();
socket.connect(new InetSocketAddress("google.com", 80));
System.out.println(socket.getLocalAddress());
socket.close();

How to dockerize maven project? and how many ways to accomplish it?

Working example.

This is not a spring boot tutorial. It's the updated answer to a question on how to run a Maven build within a Docker container.

Question originally posted 4 years ago.

1. Generate an application

Use the spring initializer to generate a demo app

https://start.spring.io/

enter image description here

Extract the zip archive locally

2. Create a Dockerfile

#
# Build stage
#
FROM maven:3.6.0-jdk-11-slim AS build
COPY src /home/app/src
COPY pom.xml /home/app
RUN mvn -f /home/app/pom.xml clean package

#
# Package stage
#
FROM openjdk:11-jre-slim
COPY --from=build /home/app/target/demo-0.0.1-SNAPSHOT.jar /usr/local/lib/demo.jar
EXPOSE 8080
ENTRYPOINT ["java","-jar","/usr/local/lib/demo.jar"]

Note

  • This example uses a multi-stage build. The first stage is used to build the code. The second stage only contains the built jar and a JRE to run it (note how jar is copied between stages).

3. Build the image

docker build -t demo .

4. Run the image

$ docker run --rm -it demo:latest

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.3.RELEASE)

2019-02-22 17:18:57.835  INFO 1 --- [           main] com.example.demo.DemoApplication         : Starting DemoApplication v0.0.1-SNAPSHOT on f4e67677c9a9 with PID 1 (/usr/local/bin/demo.jar started by root in /)
2019-02-22 17:18:57.837  INFO 1 --- [           main] com.example.demo.DemoApplication         : No active profile set, falling back to default profiles: default
2019-02-22 17:18:58.294  INFO 1 --- [           main] com.example.demo.DemoApplication         : Started DemoApplication in 0.711 seconds (JVM running for 1.035)

Misc

Read the Docker hub documentation on how the Maven build can be optimized to use a local repository to cache jars.

Update (2019-02-07)

This question is now 4 years old and in that time it's fair to say building application using Docker has undergone significant change.

Option 1: Multi-stage build

This new style enables you to create more light-weight images that don't encapsulate your build tools and source code.

The example here again uses the official maven base image to run first stage of the build using a desired version of Maven. The second part of the file defines how the built jar is assembled into the final output image.

FROM maven:3.5-jdk-8 AS build  
COPY src /usr/src/app/src  
COPY pom.xml /usr/src/app  
RUN mvn -f /usr/src/app/pom.xml clean package

FROM gcr.io/distroless/java  
COPY --from=build /usr/src/app/target/helloworld-1.0.0-SNAPSHOT.jar /usr/app/helloworld-1.0.0-SNAPSHOT.jar  
EXPOSE 8080  
ENTRYPOINT ["java","-jar","/usr/app/helloworld-1.0.0-SNAPSHOT.jar"]  

Note:

  • I'm using Google's distroless base image, which strives to provide just enough run-time for a java app.

Option 2: Jib

I haven't used this approach but seems worthy of investigation as it enables you to build images without having to create nasty things like Dockerfiles :-)

https://github.com/GoogleContainerTools/jib

The project has a Maven plugin which integrates the packaging of your code directly into your Maven workflow.


Original answer (Included for completeness, but written ages ago)

Try using the new official images, there's one for Maven

https://registry.hub.docker.com/_/maven/

The image can be used to run Maven at build time to create a compiled application or, as in the following examples, to run a Maven build within a container.

Example 1 - Maven running within a container

The following command runs your Maven build inside a container:

docker run -it --rm \
       -v "$(pwd)":/opt/maven \
       -w /opt/maven \
       maven:3.2-jdk-7 \
       mvn clean install

Notes:

  • The neat thing about this approach is that all software is installed and running within the container. Only need docker on the host machine.
  • See Dockerfile for this version

Example 2 - Use Nexus to cache files

Run the Nexus container

docker run -d -p 8081:8081 --name nexus sonatype/nexus

Create a "settings.xml" file:

<settings>
  <mirrors>
    <mirror>
      <id>nexus</id>
      <mirrorOf>*</mirrorOf>
      <url>http://nexus:8081/content/groups/public/</url>
    </mirror>
  </mirrors>
</settings>

Now run Maven linking to the nexus container, so that dependencies will be cached

docker run -it --rm \
       -v "$(pwd)":/opt/maven \
       -w /opt/maven \
       --link nexus:nexus \
       maven:3.2-jdk-7 \
       mvn -s settings.xml clean install

Notes:

  • An advantage of running Nexus in the background is that other 3rd party repositories can be managed via the admin URL transparently to the Maven builds running in local containers.

Generating combinations in c++

A simple way using std::next_permutation:

#include <iostream>
#include <algorithm>
#include <vector>

int main() {
    int n, r;
    std::cin >> n;
    std::cin >> r;

    std::vector<bool> v(n);
    std::fill(v.end() - r, v.end(), true);

    do {
        for (int i = 0; i < n; ++i) {
            if (v[i]) {
                std::cout << (i + 1) << " ";
            }
        }
        std::cout << "\n";
    } while (std::next_permutation(v.begin(), v.end()));
    return 0;
}

or a slight variation that outputs the results in an easier to follow order:

#include <iostream>
#include <algorithm>
#include <vector>

int main() {
   int n, r;
   std::cin >> n;
   std::cin >> r;

   std::vector<bool> v(n);
   std::fill(v.begin(), v.begin() + r, true);

   do {
       for (int i = 0; i < n; ++i) {
           if (v[i]) {
               std::cout << (i + 1) << " ";
           }
       }
       std::cout << "\n";
   } while (std::prev_permutation(v.begin(), v.end()));
   return 0;
}

A bit of explanation:

It works by creating a "selection array" (v), where we place r selectors, then we create all permutations of these selectors, and print the corresponding set member if it is selected in in the current permutation of v.


You can implement it if you note that for each level r you select a number from 1 to n.

In C++, we need to 'manually' keep the state between calls that produces results (a combination): so, we build a class that on construction initialize the state, and has a member that on each call returns the combination while there are solutions: for instance

#include <iostream>
#include <iterator>
#include <vector>
#include <cstdlib>

using namespace std;

struct combinations
{
    typedef vector<int> combination_t;

    // initialize status
   combinations(int N, int R) :
       completed(N < 1 || R > N),
       generated(0),
       N(N), R(R)
   {
       for (int c = 1; c <= R; ++c)
           curr.push_back(c);
   }

   // true while there are more solutions
   bool completed;

   // count how many generated
   int generated;

   // get current and compute next combination
   combination_t next()
   {
       combination_t ret = curr;

       // find what to increment
       completed = true;
       for (int i = R - 1; i >= 0; --i)
           if (curr[i] < N - R + i + 1)
           {
               int j = curr[i] + 1;
               while (i <= R-1)
                   curr[i++] = j++;
               completed = false;
               ++generated;
               break;
           }

       return ret;
   }

private:

   int N, R;
   combination_t curr;
};

int main(int argc, char **argv)
{
    int N = argc >= 2 ? atoi(argv[1]) : 5;
    int R = argc >= 3 ? atoi(argv[2]) : 2;
    combinations cs(N, R);
    while (!cs.completed)
    {
        combinations::combination_t c = cs.next();
        copy(c.begin(), c.end(), ostream_iterator<int>(cout, ","));
        cout << endl;
    }
    return cs.generated;
}

test output:

1,2,
1,3,
1,4,
1,5,
2,3,
2,4,
2,5,
3,4,
3,5,
4,5,

How can I do a case insensitive string comparison?

You can (although controverse) extend System.String to provide a case insensitive comparison extension method:

public static bool CIEquals(this String a, String b) {
    return a.Equals(b, StringComparison.CurrentCultureIgnoreCase);
}

and use as such:

x.Username.CIEquals((string)drUser["Username"]);

C# allows you to create extension methods that can serve as syntax suggar in your project, quite useful I'd say.

It's not the answer and I know this question is old and solved, I just wanted to add these bits.

What is @ModelAttribute in Spring MVC?

@ModelAttribute will create a attribute with the name specified by you (@ModelAttribute("Testing") Test test) as Testing in the given example ,Test being the bean test being the reference to the bean and Testing will be available in model so that you can further use it on jsp pages for retrieval of values that you stored in you ModelAttribute.

Find the host name and port using PSQL commands

service postgresql status

returns: 10/main (port 5432): online

I'm running Ubuntu 18.04

Form Google Maps URL that searches for a specific places near specific coordinates

additional info:

http://maps.google.com/maps?q=loc: put in latitude and longitude after, example:

http://maps.google.com/maps?q=loc:51.03841,-114.01679

this will show pointer on map, but will suppress geocoding of the address, best for a location without an address, or for a location where google maps shows the incorrect address.

Using PUT method in HTML form

To set methods PUT and DELETE I perform as following:

<form
  method="PUT"
  action="domain/route/param?query=value"
>
  <input type="hidden" name="delete_id" value="1" />
  <input type="hidden" name="put_id" value="1" />
  <input type="text" name="put_name" value="content_or_not" />
  <div>
    <button name="update_data">Save changes</button>
    <button name="remove_data">Remove</button>
  </div>
</form>
<hr>
<form
  method="DELETE"
  action="domain/route/param?query=value"
>
  <input type="hidden" name="delete_id" value="1" />
  <input type="text" name="delete_name" value="content_or_not" />
  <button name="delete_data">Remove item</button>
</form>

Then JS acts to perform the desired methods:

<script>
   var putMethod = ( event ) => {
     // Prevent redirection of Form Click
     event.preventDefault();
     var target = event.target;
     while ( target.tagName != "FORM" ) {
       target = target.parentElement;
     } // While the target is not te FORM tag, it looks for the parent element
     // The action attribute provides the request URL
     var url = target.getAttribute( "action" );

     // Collect Form Data by prefix "put_" on name attribute
     var bodyForm = target.querySelectorAll( "[name^=put_]");
     var body = {};
     bodyForm.forEach( element => {
       // I used split to separate prefix from worth name attribute
       var nameArray = element.getAttribute( "name" ).split( "_" );
       var name = nameArray[ nameArray.length - 1 ];
       if ( element.tagName != "TEXTAREA" ) {
         var value = element.getAttribute( "value" );
       } else {
       // if element is textarea, value attribute may return null or undefined
         var value = element.innerHTML;
       }
       // all elements with name="put_*" has value registered in body object
       body[ name ] = value;
     } );
     var xhr = new XMLHttpRequest();
     xhr.open( "PUT", url );
     xhr.setRequestHeader( "Content-Type", "application/json" );
     xhr.onload = () => {
       if ( xhr.status === 200 ) {
       // reload() uses cache, reload( true ) force no-cache. I reload the page to make "redirects normal effect" of HTML form when submit. You can manipulate DOM instead.
         location.reload( true );
       } else {
         console.log( xhr.status, xhr.responseText );
       }
     }
     xhr.send( body );
   }

   var deleteMethod = ( event ) => {
     event.preventDefault();
     var confirm = window.confirm( "Certeza em deletar este conteúdo?" );
     if ( confirm ) {
       var target = event.target;
       while ( target.tagName != "FORM" ) {
         target = target.parentElement;
       }
       var url = target.getAttribute( "action" );
       var xhr = new XMLHttpRequest();
       xhr.open( "DELETE", url );
       xhr.setRequestHeader( "Content-Type", "application/json" );
       xhr.onload = () => {
         if ( xhr.status === 200 ) {
           location.reload( true );
           console.log( xhr.responseText );
         } else {
           console.log( xhr.status, xhr.responseText );
         }
       }
       xhr.send();
     }
   }
</script>

With these functions defined, I add a event listener to the buttons which make the form method request:

<script>
  document.querySelectorAll( "[name=update_data], [name=delete_data]" ).forEach( element => {
    var button = element;
    var form = element;
    while ( form.tagName != "FORM" ) {
      form = form.parentElement;
    }
    var method = form.getAttribute( "method" );
    if ( method == "PUT" ) {
      button.addEventListener( "click", putMethod );
    }
    if ( method == "DELETE" ) {
      button.addEventListener( "click", deleteMethod );
    }
  } );
</script>

And for the remove button on the PUT form:

<script>
  document.querySelectorAll( "[name=remove_data]" ).forEach( element => {
    var button = element;
    button.addEventListener( "click", deleteMethod );
</script>

_ - - - - - - - - - - -

This article https://blog.garstasio.com/you-dont-need-jquery/ajax/ helps me a lot!

Beyond this, you can set postMethod function and getMethod to handle POST and GET submit methods as you like instead browser default behavior. You can do whatever you want instead use location.reload(), like show message of successful changes or successful deletion.

=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

JSFiddle: https://jsfiddle.net/enriquerene/d6jvw52t/53/

Spring Boot + JPA : Column name annotation ignored

I also tried all the above and nothing works. I got field called "gunName" in DB and i couldn't handle this, till i used example below:

@Column(name="\"gunName\"")
public String gunName;

with properties:

spring.jpa.hibernate.naming.implicit-strategy=org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyJpaImpl
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl

also see this: https://stackoverflow.com/a/35708531

Get current URL from IFRAME

I had an issue with blob url hrefs. So, with a reference to the iframe, I just produced an url from the iframe's src attribute:

    const iframeReference = document.getElementById("iframe_id");
    const iframeUrl = iframeReference ? new URL(iframeReference.src) : undefined;
    if (iframeUrl) {
        console.log("Voila: " + iframeUrl);
    } else {
        console.warn("iframe with id iframe_id not found");
    }

Fastest way to convert string to integer in PHP

Run a test.

   string coerce:          7.42296099663
   string cast:            8.05654597282
   string fail coerce:     7.14159703255
   string fail cast:       7.87444186211

This was a test that ran each scenario 10,000,000 times. :-)

Co-ercion is 0 + "123"

Casting is (integer)"123"

I think Co-ercion is a tiny bit faster. Oh, and trying 0 + array('123') is a fatal error in PHP. You might want your code to check the type of the supplied value.

My test code is below.


function test_string_coerce($s) {
    return 0 + $s;
}

function test_string_cast($s) {
    return (integer)$s;
}

$iter = 10000000;

print "-- running each text $iter times.\n";

// string co-erce
$string_coerce = new Timer;
$string_coerce->Start();

print "String Coerce test\n";
for( $i = 0; $i < $iter ; $i++ ) {
    test_string_coerce('123');
}

$string_coerce->Stop();

// string cast
$string_cast = new Timer;
$string_cast->Start();

print "String Cast test\n";
for( $i = 0; $i < $iter ; $i++ ) {
    test_string_cast('123');
}

$string_cast->Stop();

// string co-erce fail.
$string_coerce_fail = new Timer;
$string_coerce_fail->Start();

print "String Coerce fail test\n";
for( $i = 0; $i < $iter ; $i++ ) {
    test_string_coerce('hello');
}

$string_coerce_fail->Stop();

// string cast fail
$string_cast_fail = new Timer;
$string_cast_fail->Start();

print "String Cast fail test\n";
for( $i = 0; $i < $iter ; $i++ ) {
    test_string_cast('hello');
}

$string_cast_fail->Stop();

// -----------------
print "\n";
print "string coerce:          ".$string_coerce->Elapsed()."\n";
print "string cast:            ".$string_cast->Elapsed()."\n";
print "string fail coerce:     ".$string_coerce_fail->Elapsed()."\n";
print "string fail cast:       ".$string_cast_fail->Elapsed()."\n";


class Timer {
    var $ticking = null;
    var $started_at = false;
    var $elapsed = 0;

    function Timer() {
        $this->ticking = null;
    }

    function Start() {
        $this->ticking = true;
        $this->started_at = microtime(TRUE);
    }

    function Stop() {
        if( $this->ticking )
            $this->elapsed = microtime(TRUE) - $this->started_at;
        $this->ticking = false;
    }

    function Elapsed() {
        switch( $this->ticking ) {
            case true: return "Still Running";
            case false: return $this->elapsed;
            case null: return "Not Started";
        }
    }
}

Difference between if () { } and if () : endif;

I used to use curly brackets for "if, else" conditions. However, I found "if(xxx): endif;" is more semantic if the code is heavily wrapped and easier to read in any editors.

Of course, lots editors are capable of recognise and highlight chunks of code when curly brackets are selected. Some also do well on "if(xxx): endif" pair (eg, NetBeans)

Personally, I would recommend "if(xxx): endif", but for small condition check (eg, only one line of code), there are not much differences.

OS X Terminal UTF-8 issues

In my case, simply using the uxterm command instead of xterm solved the problem. It's available in /opt/X11/bin/uxterm by installing the XQuartz package provided by Apple.

React.js, wait for setState to finish before triggering a function?

setState() has an optional callback parameter that you can use for this. You only need to change your code slightly, to this:

// Form Input
this.setState(
  {
    originId: input.originId,
    destinationId: input.destinationId,
    radius: input.radius,
    search: input.search
  },
  this.findRoutes         // here is where you put the callback
);

Notice the call to findRoutes is now inside the setState() call, as the second parameter.
Without () because you are passing the function.

Refreshing Web Page By WebDriver When Waiting For Specific Condition

In R you can use the refresh method, but to start with we navigate to a url using navigate method:

remDr$navigate("https://...")
remDr$refresh()

GroupBy pandas DataFrame and select most common value

Pandas >= 0.16

pd.Series.mode is available!

Use groupby, GroupBy.agg, and apply the pd.Series.mode function to each group:

source.groupby(['Country','City'])['Short name'].agg(pd.Series.mode)

Country  City            
Russia   Sankt-Petersburg    Spb
USA      New-York             NY
Name: Short name, dtype: object

If this is needed as a DataFrame, use

source.groupby(['Country','City'])['Short name'].agg(pd.Series.mode).to_frame()

                         Short name
Country City                       
Russia  Sankt-Petersburg        Spb
USA     New-York                 NY

The useful thing about Series.mode is that it always returns a Series, making it very compatible with agg and apply, especially when reconstructing the groupby output. It is also faster.

# Accepted answer.
%timeit source.groupby(['Country','City']).agg(lambda x:x.value_counts().index[0])
# Proposed in this post.
%timeit source.groupby(['Country','City'])['Short name'].agg(pd.Series.mode)

5.56 ms ± 343 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
2.76 ms ± 387 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

Dealing with Multiple Modes

Series.mode also does a good job when there are multiple modes:

source2 = source.append(
    pd.Series({'Country': 'USA', 'City': 'New-York', 'Short name': 'New'}),
    ignore_index=True)

# Now `source2` has two modes for the 
# ("USA", "New-York") group, they are "NY" and "New".
source2

  Country              City Short name
0     USA          New-York         NY
1     USA          New-York        New
2  Russia  Sankt-Petersburg        Spb
3     USA          New-York         NY
4     USA          New-York        New

source2.groupby(['Country','City'])['Short name'].agg(pd.Series.mode)

Country  City            
Russia   Sankt-Petersburg          Spb
USA      New-York            [NY, New]
Name: Short name, dtype: object

Or, if you want a separate row for each mode, you can use GroupBy.apply:

source2.groupby(['Country','City'])['Short name'].apply(pd.Series.mode)

Country  City               
Russia   Sankt-Petersburg  0    Spb
USA      New-York          0     NY
                           1    New
Name: Short name, dtype: object

If you don't care which mode is returned as long as it's either one of them, then you will need a lambda that calls mode and extracts the first result.

source2.groupby(['Country','City'])['Short name'].agg(
    lambda x: pd.Series.mode(x)[0])

Country  City            
Russia   Sankt-Petersburg    Spb
USA      New-York             NY
Name: Short name, dtype: object

Alternatives to (not) consider

You can also use statistics.mode from python, but...

source.groupby(['Country','City'])['Short name'].apply(statistics.mode)

Country  City            
Russia   Sankt-Petersburg    Spb
USA      New-York             NY
Name: Short name, dtype: object

...it does not work well when having to deal with multiple modes; a StatisticsError is raised. This is mentioned in the docs:

If data is empty, or if there is not exactly one most common value, StatisticsError is raised.

But you can see for yourself...

statistics.mode([1, 2])
# ---------------------------------------------------------------------------
# StatisticsError                           Traceback (most recent call last)
# ...
# StatisticsError: no unique mode; found 2 equally common values

Psql list all tables

To see the public tables you can do

list tables

\dt

list table, view, and access privileges

\dp or \z

or just the table names

select table_name from information_schema.tables where table_schema = 'public';

Remove Duplicate objects from JSON Array

The following works for me:

_.uniq(standardsList, JSON.stringify)

This would probably be slow for very long lists, however.

How to pass multiple parameters in thread in VB

Something like this (I'm not a VB programmer)

Public Class MyParameters
    public Name As String
    public Number As Integer
End Class



newThread as thread = new Thread( AddressOf DoWork)
Dim parameters As New MyParameters
parameters.Name = "Arne"
newThread.Start(parameters);

public shared sub DoWork(byval data as object)
{
    dim parameters = CType(data, Parameters)

}

Reliable method to get machine's MAC address in C#

IMHO returning first mac address isn't good idea, especially when virtual machines are hosted. Therefore i check send/received bytes sum and select most used connection, that is not perfect, but should be correct 9/10 times.

public string GetDefaultMacAddress()
{
    Dictionary<string, long> macAddresses = new Dictionary<string, long>();
    foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
    {
        if (nic.OperationalStatus == OperationalStatus.Up)
            macAddresses[nic.GetPhysicalAddress().ToString()] = nic.GetIPStatistics().BytesSent + nic.GetIPStatistics().BytesReceived;
    }
    long maxValue = 0;
    string mac = "";
    foreach(KeyValuePair<string, long> pair in macAddresses)
    {
        if (pair.Value > maxValue)
        {
            mac = pair.Key;
            maxValue = pair.Value;
        }
    }
    return mac;
}

What is the difference between ExecuteScalar, ExecuteReader and ExecuteNonQuery?

ExecuteNonQuery

This ExecuteNonQuery method will be used only for insert, update and delete, Create, and SET statements. ExecuteNonQuery method will return number of rows effected with INSERT, DELETE or UPDATE operations.

ExecuteScalar

It’s very fast to retrieve single values from database. Execute Scalar will return single row single column value i.e. single value, on execution of SQL Query or Stored procedure using command object. ExecuteReader

Execute Reader will be used to return the set of rows, on execution of SQL Query or Stored procedure using command object. This one is forward only retrieval of records and it is used to read the table values from first to last.

Entityframework Join using join method and lambdas

Generally i prefer the lambda syntax with LINQ, but Join is one example where i prefer the query syntax - purely for readability.

Nonetheless, here is the equivalent of your above query (i think, untested):

var query = db.Categories         // source
   .Join(db.CategoryMaps,         // target
      c => c.CategoryId,          // FK
      cm => cm.ChildCategoryId,   // PK
      (c, cm) => new { Category = c, CategoryMaps = cm }) // project result
   .Select(x => x.Category);  // select result

You might have to fiddle with the projection depending on what you want to return, but that's the jist of it.

Java random numbers using a seed

That's the principle of a Pseudo-RNG. The numbers are not really random. They are generated using a deterministic algorithm, but depending on the seed, the sequence of generated numbers vary. Since you always use the same seed, you always get the same sequence.

Pass Parameter to Gulp Task

Here is another way without extra modules:

I needed to guess the environment from the task name, I have a 'dev' task and a 'prod' task.

When I run gulp prod it should be set to prod environment. When I run gulp dev or anything else it should be set to dev environment.

For that I just check the running task name:

devEnv = process.argv[process.argv.length-1] !== 'prod';

One liner to check if element is in the list

I would use:

if (Stream.of("a","b","c").anyMatch("a"::equals)) {
    //Code to execute
};

or:

Stream.of("a","b","c")
    .filter("a"::equals)
    .findAny()
    .ifPresent(ignore -> /*Code to execute*/);

Sql Server trigger insert values from new row into another table

When you are in the context of a trigger you have access to the logical table INSERTED which contains all the rows that have just been inserted to the table. You can build your insert to the other table based on a select from Inserted.

How can I read inputs as numbers?

Convert to integers:

my_number = int(input("enter the number"))

Similarly for floating point numbers:

my_decimalnumber = float(input("enter the number"))

How to change the background color on a input checkbox with css?

I always use pseudo elements :before and :after for changing the appearance of checkboxes and radio buttons. it's works like a charm.

Refer this link for more info

CODEPEN

Steps

  1. Hide the default checkbox using css rules like visibility:hidden or opacity:0 or position:absolute;left:-9999px etc.
  2. Create a fake checkbox using :before element and pass either an empty or a non-breaking space '\00a0';
  3. When the checkbox is in :checked state, pass the unicode content: "\2713", which is a checkmark;
  4. Add :focus style to make the checkbox accessible.
  5. Done

Here is how I did it.

_x000D_
_x000D_
.box {_x000D_
  background: #666666;_x000D_
  color: #ffffff;_x000D_
  width: 250px;_x000D_
  padding: 10px;_x000D_
  margin: 1em auto;_x000D_
}_x000D_
p {_x000D_
  margin: 1.5em 0;_x000D_
  padding: 0;_x000D_
}_x000D_
input[type="checkbox"] {_x000D_
  visibility: hidden;_x000D_
}_x000D_
label {_x000D_
  cursor: pointer;_x000D_
}_x000D_
input[type="checkbox"] + label:before {_x000D_
  border: 1px solid #333;_x000D_
  content: "\00a0";_x000D_
  display: inline-block;_x000D_
  font: 16px/1em sans-serif;_x000D_
  height: 16px;_x000D_
  margin: 0 .25em 0 0;_x000D_
  padding: 0;_x000D_
  vertical-align: top;_x000D_
  width: 16px;_x000D_
}_x000D_
input[type="checkbox"]:checked + label:before {_x000D_
  background: #fff;_x000D_
  color: #333;_x000D_
  content: "\2713";_x000D_
  text-align: center;_x000D_
}_x000D_
input[type="checkbox"]:checked + label:after {_x000D_
  font-weight: bold;_x000D_
}_x000D_
_x000D_
input[type="checkbox"]:focus + label::before {_x000D_
    outline: rgb(59, 153, 252) auto 5px;_x000D_
}
_x000D_
<div class="content">_x000D_
  <div class="box">_x000D_
    <p>_x000D_
      <input type="checkbox" id="c1" name="cb">_x000D_
      <label for="c1">Option 01</label>_x000D_
    </p>_x000D_
    <p>_x000D_
      <input type="checkbox" id="c2" name="cb">_x000D_
      <label for="c2">Option 02</label>_x000D_
    </p>_x000D_
    <p>_x000D_
      <input type="checkbox" id="c3" name="cb">_x000D_
      <label for="c3">Option 03</label>_x000D_
    </p>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Much more stylish using :before and :after

_x000D_
_x000D_
body{_x000D_
  font-family: sans-serif;  _x000D_
}_x000D_
_x000D_
.container {_x000D_
    margin-top: 50px;_x000D_
    margin-left: 20px;_x000D_
    margin-right: 20px;_x000D_
}_x000D_
.checkbox {_x000D_
    width: 100%;_x000D_
    margin: 15px auto;_x000D_
    position: relative;_x000D_
    display: block;_x000D_
}_x000D_
_x000D_
.checkbox input[type="checkbox"] {_x000D_
    width: auto;_x000D_
    opacity: 0.00000001;_x000D_
    position: absolute;_x000D_
    left: 0;_x000D_
    margin-left: -20px;_x000D_
}_x000D_
.checkbox label {_x000D_
    position: relative;_x000D_
}_x000D_
.checkbox label:before {_x000D_
    content: '';_x000D_
    position: absolute;_x000D_
    left: 0;_x000D_
    top: 0;_x000D_
    margin: 4px;_x000D_
    width: 22px;_x000D_
    height: 22px;_x000D_
    transition: transform 0.28s ease;_x000D_
    border-radius: 3px;_x000D_
    border: 2px solid #7bbe72;_x000D_
}_x000D_
.checkbox label:after {_x000D_
  content: '';_x000D_
    display: block;_x000D_
    width: 10px;_x000D_
    height: 5px;_x000D_
    border-bottom: 2px solid #7bbe72;_x000D_
    border-left: 2px solid #7bbe72;_x000D_
    -webkit-transform: rotate(-45deg) scale(0);_x000D_
    transform: rotate(-45deg) scale(0);_x000D_
    transition: transform ease 0.25s;_x000D_
    will-change: transform;_x000D_
    position: absolute;_x000D_
    top: 12px;_x000D_
    left: 10px;_x000D_
}_x000D_
.checkbox input[type="checkbox"]:checked ~ label::before {_x000D_
    color: #7bbe72;_x000D_
}_x000D_
_x000D_
.checkbox input[type="checkbox"]:checked ~ label::after {_x000D_
    -webkit-transform: rotate(-45deg) scale(1);_x000D_
    transform: rotate(-45deg) scale(1);_x000D_
}_x000D_
_x000D_
.checkbox label {_x000D_
    min-height: 34px;_x000D_
    display: block;_x000D_
    padding-left: 40px;_x000D_
    margin-bottom: 0;_x000D_
    font-weight: normal;_x000D_
    cursor: pointer;_x000D_
    vertical-align: sub;_x000D_
}_x000D_
.checkbox label span {_x000D_
    position: absolute;_x000D_
    top: 50%;_x000D_
    -webkit-transform: translateY(-50%);_x000D_
    transform: translateY(-50%);_x000D_
}_x000D_
.checkbox input[type="checkbox"]:focus + label::before {_x000D_
    outline: 0;_x000D_
}
_x000D_
<div class="container"> _x000D_
  <div class="checkbox">_x000D_
     <input type="checkbox" id="checkbox" name="" value="">_x000D_
     <label for="checkbox"><span>Checkbox</span></label>_x000D_
  </div>_x000D_
_x000D_
  <div class="checkbox">_x000D_
     <input type="checkbox" id="checkbox2" name="" value="">_x000D_
     <label for="checkbox2"><span>Checkbox</span></label>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Importing project into Netbeans

You may try creating a new project in netbeans and then copy and and paste the files into it. I usually experience this problem when the project wasn't created in netbeans.

Base64 encoding and decoding in client-side Javascript

In Node.js we can do it in simple way

var base64 = 'SGVsbG8gV29ybGQ='
var base64_decode = new Buffer(base64, 'base64').toString('ascii');

console.log(base64_decode); // "Hello World"

How to parse XML using vba

You can use a XPath Query:

Dim objDom As Object        '// DOMDocument
Dim xmlStr As String, _
    xPath As String

xmlStr = _
    "<PointN xsi:type='typens:PointN' " & _
    "xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' " & _
    "xmlns:xs='http://www.w3.org/2001/XMLSchema'> " & _
    "    <X>24.365</X> " & _
    "    <Y>78.63</Y> " & _
    "</PointN>"

Set objDom = CreateObject("Msxml2.DOMDocument.3.0")     '// Using MSXML 3.0

'/* Load XML */
objDom.LoadXML xmlStr

'/*
' * XPath Query
' */        

'/* Get X */
xPath = "/PointN/X"
Debug.Print objDom.SelectSingleNode(xPath).text

'/* Get Y */
xPath = "/PointN/Y"
Debug.Print objDom.SelectSingleNode(xPath).text

Is there a way to create xxhdpi, xhdpi, hdpi, mdpi and ldpi drawables from a large scale image?

I wrote a Photoshop script to create ic_launcher png files from PSD file. Just check ic_launcher_exporter.

To use it, just download it and use the script from photoshop.

enter image description here

And configure where you want to generate output files.

enter image description here

Failed to load ApplicationContext (with annotation)

In my case, I had to do the following while running with Junit5

@SpringBootTest(classes = {abc.class}) @ExtendWith(SpringExtension.class

Here abc.class was the class that was being tested

How to find the index of an element in an array in Java?

I am providing the proper method to do this one

/**
     * Method to get the index of the given item from the list
     * @param stringArray
     * @param name
     * @return index of the item if item exists else return -1
     */
    public static int getIndexOfItemInArray(String[] stringArray, String name) {
        if (stringArray != null && stringArray.length > 0) {
            ArrayList<String> list = new ArrayList<String>(Arrays.asList(stringArray));
            int index = list.indexOf(name);
            list.clear();
            return index;
        }
        return -1;
    }

Comparing two .jar files

use java decompiler and decompile all the .class files and save all files as project structure .

then use meld diff viewer and compare as folders ..

How to hide Bootstrap previous modal when you opening new one?

Toggle both modals

$('#modalOne').modal('toggle');
$('#modalTwo').modal('toggle');

Making heatmap from pandas DataFrame

If you don't need a plot per say, and you're simply interested in adding color to represent the values in a table format, you can use the style.background_gradient() method of the pandas data frame. This method colorizes the HTML table that is displayed when viewing pandas data frames in e.g. the JupyterLab Notebook and the result is similar to using "conditional formatting" in spreadsheet software:

import numpy as np 
import pandas as pd


index= ['aaa', 'bbb', 'ccc', 'ddd', 'eee']
cols = ['A', 'B', 'C', 'D']
df = pd.DataFrame(abs(np.random.randn(5, 4)), index=index, columns=cols)
df.style.background_gradient(cmap='Blues')

enter image description here

For detailed usage, please see the more elaborate answer I provided on the same topic previously and the styling section of the pandas documentation.

Recommended SQL database design for tags or tagging

I've always kept the tags in a separate table and then had a mapping table. Of course I've never done anything on a really large scale either.

Having a "tags" table and a map table makes it pretty trivial to generate tag clouds & such since you can easily put together SQL to get a list of tags with counts of how often each tag is used.

How can I get the last 7 characters of a PHP string?

It would be better to have a check before getting the string.

$newstring = substr($dynamicstring, -7);

if characters are greater then 7 return last 7 characters else return the provided string.

or do this if you need to return message or error if length is less then 7

$newstring = (strlen($dynamicstring)>7)?substr($dynamicstring, -7):"message";

substr documentation

How to retrieve an Oracle directory path?

The ALL_DIRECTORIES data dictionary view will have information about all the directories that you have access to. That includes the operating system path

SELECT owner, directory_name, directory_path
  FROM all_directories

client denied by server configuration

For me the following worked which is copied from example in /etc/apache2/apache2.conf:

<Directory /srv/www/default>
    Options Indexes FollowSymLinks
    AllowOverride None
    Require all granted
</Directory>

Require all granted option is the solution for the first problem example in wiki.apache.org page dedicated for this issue for Apache version 2.4+.

More details about Require option can be found on official apache page for mod_authz module and on this page too. Namely:

Require all granted -> Access is allowed unconditionally.

What is the difference between a field and a property?

Basic and general difference is:

Fields

  • ALWAYS give both get and set access
  • CAN NOT cause side effects (throwing exceptions, calling methods, changing fields except the one being got/set, etc)

Properties

  • NOT ALWAYS give both get and set access
  • CAN cause side effects

window.location.reload with clear cache

In my case reload() doesn't work because the asp.net controls behavior. So, to solve this issue I've used this approach, despite seems a work around.

self.clear = function () {
    //location.reload(true); Doesn't work to IE neither Firefox;
    //also, hash tags must be removed or no postback will occur.
    window.location.href = window.location.href.replace(/#.*$/, '');
};

How do I select the "last child" with a specific class name in CSS?

You can use the adjacent sibling selector to achieve something similar, that might help.

.list-item.other-class + .list-item:not(.other-class)

Will effectively target the immediately following element after the last element with the class other-class.

Read more here: https://css-tricks.com/almanac/selectors/a/adjacent-sibling/

Rails: How to run `rails generate scaffold` when the model already exists?

You can make use of scaffold_controller and remember to pass the attributes of the model, or scaffold will be generated without the attributes.

rails g scaffold_controller User name email
# or
rails g scaffold_controller User name:string email:string

This command will generate following files:

create  app/controllers/users_controller.rb
invoke  haml
create    app/views/users
create    app/views/users/index.html.haml
create    app/views/users/edit.html.haml
create    app/views/users/show.html.haml
create    app/views/users/new.html.haml
create    app/views/users/_form.html.haml
invoke  test_unit
create    test/controllers/users_controller_test.rb
invoke  helper
create    app/helpers/users_helper.rb
invoke    test_unit
invoke  jbuilder
create    app/views/users/index.json.jbuilder
create    app/views/users/show.json.jbuilder

Construct pandas DataFrame from list of tuples of (row,col,values)

I submit that it is better to leave your data stacked as it is:

df = pandas.DataFrame(data, columns=['R_Number', 'C_Number', 'Avg', 'Std'])

# Possibly also this if these can always be the indexes:
# df = df.set_index(['R_Number', 'C_Number'])

Then it's a bit more intuitive to say

df.set_index(['R_Number', 'C_Number']).Avg.unstack(level=1)

This way it is implicit that you're seeking to reshape the averages, or the standard deviations. Whereas, just using pivot, it's purely based on column convention as to what semantic entity it is that you are reshaping.

Difference between the annotations @GetMapping and @RequestMapping(method = RequestMethod.GET)

@GetMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.GET).

@GetMapping is the newer annotaion. It supports consumes

Consume options are :

consumes = "text/plain"
consumes = {"text/plain", "application/*"}

For Further details see: GetMapping Annotation

or read: request mapping variants

RequestMapping supports consumes as well

GetMapping we can apply only on method level and RequestMapping annotation we can apply on class level and as well as on method level

Parse Json string in C#

I'm using Json.net in my project and it works great. In you case, you can do this to parse your json:

EDIT: I changed the code so it supports reading your json file (array)

Code to parse:

void Main()
{
    var json = System.IO.File.ReadAllText(@"d:\test.json");

    var objects = JArray.Parse(json); // parse as array  
    foreach(JObject root in objects)
    {
        foreach(KeyValuePair<String, JToken> app in root)
        {
            var appName = app.Key;
            var description = (String)app.Value["Description"];
            var value = (String)app.Value["Value"];

            Console.WriteLine(appName);
            Console.WriteLine(description);
            Console.WriteLine(value);
            Console.WriteLine("\n");
        }
    }
}

Output:

AppName
Lorem ipsum dolor sit amet
1


AnotherAppName
consectetur adipisicing elit
String


ThirdAppName
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua
Text


Application
Ut enim ad minim veniam
100


LastAppName
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat
ZZZ

BTW, you can use LinqPad to test your code, easier than creating a solution or project in Visual Studio I think.

'const string' vs. 'static readonly string' in C#

You can change the value of a static readonly string only in the static constructor of the class or a variable initializer, whereas you cannot change the value of a const string anywhere.

What’s the best way to get an HTTP response code from a URL?

Here's a solution that uses httplib instead.

import httplib

def get_status_code(host, path="/"):
    """ This function retreives the status code of a website by requesting
        HEAD data from the host. This means that it only requests the headers.
        If the host cannot be reached or something else goes wrong, it returns
        None instead.
    """
    try:
        conn = httplib.HTTPConnection(host)
        conn.request("HEAD", path)
        return conn.getresponse().status
    except StandardError:
        return None


print get_status_code("stackoverflow.com") # prints 200
print get_status_code("stackoverflow.com", "/nonexistant") # prints 404

How can I get the name of an object in Python?

Variable names can be found in the globals() and locals() dicts. But they won't give you what you're looking for above. "bla" will contain the value of each item of my_list, not the variable.

C# ASP.NET Send Email via TLS

I was almost using the same technology as you did, however I was using my app to connect an Exchange Server via Office 365 platform on WinForms. I too had the same issue as you did, but was able to accomplish by using code which has slight modification of what others have given above.

SmtpClient client = new SmtpClient(exchangeServer, 587);
client.Credentials = new System.Net.NetworkCredential(username, password);
client.EnableSsl = true;
client.Send(msg);

I had to use the Port 587, which is of course the default port over TSL and the did the authentication.

jquery draggable: how to limit the draggable area?

See excerpt from official documentation for containment option:

containment

Default: false

Constrains dragging to within the bounds of the specified element or region.
Multiple types supported:

  • Selector: The draggable element will be contained to the bounding box of the first element found by the selector. If no element is found, no containment will be set.
  • Element: The draggable element will be contained to the bounding box of this element.
  • String: Possible values: "parent", "document", "window".
  • Array: An array defining a bounding box in the form [ x1, y1, x2, y2 ].

Code examples:
Initialize the draggable with the containment option specified:

$( ".selector" ).draggable({
    containment: "parent" 
}); 

Get or set the containment option, after initialization:

// Getter
var containment = $( ".selector" ).draggable( "option", "containment" );
// Setter
$( ".selector" ).draggable( "option", "containment", "parent" );

JQuery: How to get selected radio button value?

This work for me hope this will help: to get radio selected value you have to use ratio name as selector like this

selectedVal = $('input[name="radio_name"]:checked').val();

selectedVal will have the required value, change the radio_name according to yours, in your case it would b "myradiobutton"

selectedVal = $('input[name="myradiobutton"]:checked').val();

HTML table headers always visible at top of window when viewing a large table

I've encountered this problem very recently. Unfortunately, I had to do 2 tables, one for the header and one for the body. It's probably not the best approach ever but here goes:

_x000D_
_x000D_
<html>_x000D_
<head>_x000D_
    <title>oh hai</title>_x000D_
</head>_x000D_
<body>_x000D_
    <table id="tableHeader">_x000D_
        <tr>_x000D_
            <th style="width:100px; background-color:#CCCCCC">col header</th>_x000D_
            <th style="width:100px; background-color:#CCCCCC">col header</th>_x000D_
        </tr>_x000D_
    </table>_x000D_
    <div style="height:50px; overflow:auto; width:250px">_x000D_
        <table>_x000D_
            <tr>_x000D_
                <td style="height:50px; width:100px; background-color:#DDDDDD">data1</td>_x000D_
                <td style="height:50px; width:100px; background-color:#DDDDDD">data1</td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td style="height:50px; width:100px; background-color:#DDDDDD">data2</td>_x000D_
                <td style="height:50px; width:100px; background-color:#DDDDDD">data2</td>_x000D_
            </tr>_x000D_
        </table>_x000D_
    </div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

This worked for me, it's probably not the elegant way but it does work. I'll investigate so see if I can do something better, but it allows for multiple tables.

Go read on the overflow propriety to see if it fits your need

ADB not responding. You can wait more,or kill "adb.exe" process manually and click 'Restart'

Go to

Tools > Android > (Uncheck) Enable ADB Integration (if studio hangs/gets stuck end adb process manually)

then,

Tools > Android > (Check) Enable ADB Integration

How to set seekbar min and max value

If you are using the AndroidX libraries (import androidx.preference.*), this functionality exists without any hacky workarounds!

    val seekbar = findPreference("your_seekbar") as SeekBarPreference
    seekbar.min = 1
    seekbar.max = 10
    seekbar.seekBarIncrement = 1

How can you speed up Eclipse?

One more trick is to disable automatic builds.

How to initailize byte array of 100 bytes in java with all 0's

Actually the default value of byte is 0.

Need a good hex editor for Linux

wxHexEditor is the only GUI disk editor for linux. to google "wxhexeditor site:archive.getdeb.net" and download the .deb file to install

Forward declaring an enum in C++

The reason the enum can't be forward declared is that without knowing the values, the compiler can't know the storage required for the enum variable. C++ Compiler's are allowed to specify the actual storage space based on the size necessary to contain all the values specified. If all that is visible is the forward declaration, the translation unit can't know what storage size will have been chosen - it could be a char or an int, or something else.


From Section 7.2.5 of the ISO C++ Standard:

The underlying type of an enumeration is an integral type that can represent all the enumerator values defined in the enumeration. It is implementation-defined which integral type is used as the underlying type for an enumeration except that the underlying type shall not be larger than int unless the value of an enumerator cannot fit in an int or unsigned int. If the enumerator-list is empty, the underlying type is as if the enumeration had a single enumerator with value 0. The value of sizeof() applied to an enumeration type, an object of enumeration type, or an enumerator, is the value of sizeof() applied to the underlying type.

Since the caller to the function must know the sizes of the parameters to correctly setup the call stack, the number of enumerations in an enumeration list must be known before the function prototype.

Update: In C++0X a syntax for foreward declaring enum types has been proposed and accepted. You can see the proposal at http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2764.pdf

Hide header in stack navigator React navigation

It's important to match which version of react-navigation library you're using to the solution as they're all different. For those still using react-navigation v1.0.0 for some reason like me, both these worked:

For disabling/hiding header on individual screens:

const AppScreens = StackNavigator(
  {
    Main: { screen: Main, navigationOptions: { header: null } },
    Login: { screen: Login },
    Profile: { screen: Profile, navigationOptions: { header: null } },
  });

For disabling/hiding all screens at once, use this:

const AppScreens = StackNavigator(
  {
    Main: { screen: Main},
    Login: { screen: Login },
    Profile: { screen: Profile },
  },
  {
    headerMode: 'none',
  }
);

How to revert multiple git commits?

Probably less elegant than other approaches here, but I've always used get reset --hard HEAD~N to undo multiple commits, where N is the number of commits you want to go back.

Or, if unsure of the exact number of commits, just running git reset --hard HEAD^ (which goes back one commit) multiple times until you reach the desired state.

Gerrit error when Change-Id in commit messages are missing

This can also happen if you have this restriction:

Please enter the commit message for your changes. Lines starting with '#' will be ignored, and an empty message aborts the commit.

and you do like me: write a commit message starting with "#" .....

I had the same error, but I already had the commit-msg and did the rebase and everything. Very silly mistake though :D

How to remove the focus from a TextBox in WinForms?

using System.Windows.Input

Keyboard.ClearFocus();

Get current AUTO_INCREMENT value for any table

I believe you're looking for MySQL's LAST_INSERT_ID() function. If in the command line, simply run the following:

LAST_INSERT_ID();

You could also obtain this value through a SELECT query:

SELECT LAST_INSERT_ID();

Convert a list to a string in C#

This method helped me when trying to retrieve data from Text File and store it in Array then Assign it to a string avariable.

string[] lines = File.ReadAllLines(Environment.CurrentDirectory + "\\Notes.txt");  
string marRes = string.Join(Environment.NewLine, lines.ToArray());

Hopefully may help Someone!!!!

How do I pass a variable to the layout using Laravel' Blade templating?

just try this simple method: in controller:-

 public function index()
   {
        $data = array(
            'title' => 'Home',
            'otherData' => 'Data Here'
        );
        return view('front.landing')->with($data);
   }

And in you layout (app.blade.php) :

<title>{{ $title }} - {{ config('app.name') }} </title>

Thats all.

Stuck while installing Visual Studio 2015 (Update for Microsoft Windows (KB2999226))

I managed to solve the problem by the following steps :
1. Disable windows updates(but check the option "let users install updates manually")
2. Reboot the PC
3. Manually install kb2999226 update from VS install folder (packages/Patch/x64/Windows6.1-KB299926-x64.msu)
4. Start the VS install
5. After install is finished turn back automatic updates

SQL server 2008 backup error - Operating system error 5(failed to retrieve text for this error. Reason: 15105)

It looks like the SQL Server doesn't have permission to access file C:\backup.bak. I would check the permissions of the account that is assigned to the SQL Server service account.

As part of the solution, you may want to save your backup files to somewhere other that the root of the C: drive. That might be one reason why you are having permission problems.

How to activate the Bootstrap modal-backdrop?

Just append a div with that class to body, then remove it when you're done:

// Show the backdrop
$('<div class="modal-backdrop"></div>').appendTo(document.body);

// Remove it (later)
$(".modal-backdrop").remove();

Live Example:

_x000D_
_x000D_
$("input").click(function() {_x000D_
  var bd = $('<div class="modal-backdrop"></div>');_x000D_
  bd.appendTo(document.body);_x000D_
  setTimeout(function() {_x000D_
    bd.remove();_x000D_
  }, 2000);_x000D_
});
_x000D_
<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet" type="text/css" />_x000D_
<script src="//code.jquery.com/jquery.min.js"></script>_x000D_
<script src="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script>_x000D_
<p>Click the button to get the backdrop for two seconds.</p>_x000D_
<input type="button" value="Click Me">
_x000D_
_x000D_
_x000D_

Create request with POST, which response codes 200 or 201 and content

In a few words:

  • 200 when an object is created and returned
  • 201 when an object is created but only its reference is returned (such as an ID or a link)

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

I think a lot of times when you see this code, it's from people who are in the habit of event handlers for forms, buttons, inputs, and things of that sort.

Basically, when you have something like:

<form onsubmit="return callSomeFunction();"></form>

or

<a href="#" onclick="return callSomeFunction();"></a>`

and callSomeFunction() returns true, then the form or a will submit, otherwise it won't.

Other more obvious general purposes for returning true or false as a result of a function are because they are expected to return a boolean.

Exact difference between CharSequence and String in java

From the Java API of CharSequence:

A CharSequence is a readable sequence of characters. This interface provides uniform, read-only access to many different kinds of character sequences.

This interface is then used by String, CharBuffer and StringBuffer to keep consistency for all method names.

When to use MongoDB or other document oriented database systems?

to store this unstructured data

As you said, MongoDB is best suitable to store unstructured data. And this can organize your data into document format. These RDBMS altenatives called NoSQL data stores (MongoDB, CouchDB, Voldemort) are very useful for applications that scales massively and require faster data access from these big data stores.

And the implementation of these databases are simpler than the regular RDBMS. Since these are simple key-valued or document style binary objects directly serialized into disk. These data stores don't enforce the ACID properties, and any schemas. This doesn't provide any transaction abilities. So this can scale big and we can achieve faster access (both read and write).

But in contrast, RDBM enforces ACID and schemas on datas. If you wanted to work with structured data you can go ahead with RDBM.

I would choose MySQL for creating forums for this kind of stuff. Because this is not going to scale big. And this is a very simple (common) application which has structured relations among the data.

What is the difference between Nexus and Maven?

Whatever I understood from my learning and what I think it is is here. I am Quoting some part from a book i learnt this things. Nexus Repository Manager and Nexus Repository Manager OSS started as a repository manager supporting the Maven repository format. While it supports many other repository formats now, the Maven repository format is still the most common and well supported format for build and provisioning tools running on the JVM and beyond. This chapter shows example configurations for using the repository manager with Apache Maven and a number of other tools. The setups take advantage of merging many repositories and exposing them via a repository group. Setting this up is documented in the chapter in addition to the configuration used by specific tools.

Details

Origin is not allowed by Access-Control-Allow-Origin

I've run into this a few times when working with various APIs. Often a quick fix is to add "&callback=?" to the end of a string. Sometimes the ampersand has to be a character code, and sometimes a "?": "?callback=?" (see Forecast.io API Usage with jQuery)

Get the last non-empty cell in a column in Google Sheets

Although the question is already answered, there is an eloquent way to do it.

Use just the column name to denote last non-empty row of that column.

For example:

If your data is in A1:A100 and you want to be able to add some more data to column A, say it can be A1:A105 or even A1:A1234 later, you can use this range:

A1:A

Sample

So to get last non-empty value in a range, we will use 2 functions:

  • COUNTA
  • INDEX

The answer is =INDEX(B3:B,COUNTA(B3:B)).

Here is the explanation:

COUNTA(range) returns number of values in a range, we can use this to get the count of rows.

INDEX(range, row, col) returns the value in a range at position row and col (col=1 if not specified)

Examples:

INDEX(A1:C5,1,1) = A1
INDEX(A1:C5,1) = A1 # implicitly states that col = 1
INDEX(A1:C5,1,2) = A2
INDEX(A1:C5,2,1) = B1
INDEX(A1:C5,2,2) = B2
INDEX(A1:C5,3,1) = C1
INDEX(A1:C5,3,2) = C2

For the picture above, our range will be B3:B. So we will count how many values are there in range B3:B by COUNTA(B3:B) first. In the left side, it will produce 8 since there are 8 values while it will produce 9 in the right side. We also know that the last value is in the 1st column of the range B3:B so the col parameter of INDEX must be 1 and the row parameter should be COUNTA(B3:B).

PS: please upvote @bloodymurderlive's answer since he wrote it first, I'm just explaining it here.

Jquery onclick on div

js

<script
  src="https://code.jquery.com/jquery-2.2.4.min.js"
  integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
  crossorigin="anonymous"></script>


<script type="text/javascript">

$(document).ready(function(){
    $("#div1").on('click', function(){
            console.log("click!!!");
        });
});

</script>

html

<div id="div1">div!</div>

Why does adb return offline after the device string?

  1. make sure the device is set for usb debugging
  2. Have the adb client running (e.g. via "adb usb" or adb start-server"
  3. LEAVE the device connected via usb!!!
  4. AND THEN reboot the device.

This always brings my Motorola MB525 "online" again, after adb complains it would be "offline". I'm using OSX btw.

Access to build environment variables from a groovy script in a Jenkins build step (Windows)

The Scriptler Groovy script doesn't seem to get all the environment variables of the build. But what you can do is force them in as parameters to the script:

  1. When you add the Scriptler build step into your job, select the option "Define script parameters"

  2. Add a parameter for each environment variable you want to pass in. For example "Name: JOB_NAME", "Value: $JOB_NAME". The value will get expanded from the Jenkins build environment using '$envName' type variables, most fields in the job configuration settings support this sort of expansion from my experience.

  3. In your script, you should have a variable with the same name as the parameter, so you can access the parameters with something like:

    println "JOB_NAME = $JOB_NAME"

I haven't used Sciptler myself apart from some experimentation, but your question posed an interesting problem. I hope this helps!

JPQL SELECT between date statement

Try this query (replace t.eventsDate with e.eventsDate):

SELECT e FROM Events e WHERE e.eventsDate BETWEEN :startDate AND :endDate

How to word wrap text in HTML?

Add this CSS to the paragraph.

width:420px; 
min-height:15px; 
height:auto!important; 
color:#666; 
padding: 1%; 
font-size: 14px; 
font-weight: normal;
word-wrap: break-word; 
text-align: left;

Binding value to input in Angular JS

Use ng-value for set value of input box after clicking on a button:

"input type="email"  class="form-control" id="email2" ng-value="myForm.email2" placeholder="Email"

and

Set Value as:

 $scope.myForm.email2 = $scope.names[0].success;

Xcode - Warning: Implicit declaration of function is invalid in C99

The function has to be declared before it's getting called. This could be done in various ways:

  • Write down the prototype in a header
    Use this if the function shall be callable from several source files. Just write your prototype
    int Fibonacci(int number);
    down in a .h file (e.g. myfunctions.h) and then #include "myfunctions.h" in the C code.

  • Move the function before it's getting called the first time
    This means, write down the function
    int Fibonacci(int number){..}
    before your main() function

  • Explicitly declare the function before it's getting called the first time
    This is the combination of the above flavors: type the prototype of the function in the C file before your main() function

As an additional note: if the function int Fibonacci(int number) shall only be used in the file where it's implemented, it shall be declared static, so that it's only visible in that translation unit.

How do I decode a base64 encoded string?

Simple:

byte[] data = Convert.FromBase64String(encodedString);
string decodedString = Encoding.UTF8.GetString(data);

how to remove the dotted line around the clicked a element in html

Removing outline will harm accessibility of a website.Therefore i just leave that there but make it invisible.

a {
   outline: transparent;
}

Can we execute a java program without a main() method?

Since you tagged Java-ee as well - then YES it is possible.

and in core java as well it is possible using static blocks

and check this How can you run a Java program without main method?

Edit:
as already pointed out in other answers - it does not support from Java 7

What's the correct way to communicate between controllers in AngularJS?

You can do it by using angular events that is $emit and $broadcast. As per our knowledge this is the best, efficient and effective way.

First we call a function from one controller.

var myApp = angular.module('sample', []);
myApp.controller('firstCtrl', function($scope) {
    $scope.sum = function() {
        $scope.$emit('sumTwoNumber', [1, 2]);
    };
});
myApp.controller('secondCtrl', function($scope) {
    $scope.$on('sumTwoNumber', function(e, data) {
        var sum = 0;
        for (var a = 0; a < data.length; a++) {
            sum = sum + data[a];
        }
        console.log('event working', sum);

    });
});

You can also use $rootScope in place of $scope. Use your controller accordingly.

Correct format specifier for double in printf

"%f" is the (or at least one) correct format for a double. There is no format for a float, because if you attempt to pass a float to printf, it'll be promoted to double before printf receives it1. "%lf" is also acceptable under the current standard -- the l is specified as having no effect if followed by the f conversion specifier (among others).

Note that this is one place that printf format strings differ substantially from scanf (and fscanf, etc.) format strings. For output, you're passing a value, which will be promoted from float to double when passed as a variadic parameter. For input you're passing a pointer, which is not promoted, so you have to tell scanf whether you want to read a float or a double, so for scanf, %f means you want to read a float and %lf means you want to read a double (and, for what it's worth, for a long double, you use %Lf for either printf or scanf).


1. C99, §6.5.2.2/6: "If the expression that denotes the called function has a type that does not include a prototype, the integer promotions are performed on each argument, and arguments that have type float are promoted to double. These are called the default argument promotions." In C++ the wording is somewhat different (e.g., it doesn't use the word "prototype") but the effect is the same: all the variadic parameters undergo default promotions before they're received by the function.

Can not deserialize instance of java.lang.String out of START_ARRAY token

The error is:

Can not deserialize instance of java.lang.String out of START_ARRAY token at [Source: line: 1, column: 1095] (through reference chain: JsonGen["platforms"])

In JSON, platforms look like this:

"platforms": [
    {
        "platform": "iphone"
    },
    {
        "platform": "ipad"
    },
    {
        "platform": "android_phone"
    },
    {
        "platform": "android_tablet"
    }
]

So try change your pojo to something like this:

private List platforms;

public List getPlatforms(){
    return this.platforms;
}

public void setPlatforms(List platforms){
    this.platforms = platforms;
}

EDIT: you will need change mobile_networks too. Will look like this:

private List mobile_networks;

public List getMobile_networks() {
    return mobile_networks;
}

public void setMobile_networks(List mobile_networks) {
    this.mobile_networks = mobile_networks;
}

change PATH permanently on Ubuntu

Assuming you want to add this path for all users on the system, add the following line to your /etc/profile.d/play.sh (and possibly play.csh, etc):

PATH=$PATH:/home/me/play
export PATH

PHP code to convert a MySQL query to CSV

// Export to CSV
if($_GET['action'] == 'export') {

  $rsSearchResults = mysql_query($sql, $db) or die(mysql_error());

  $out = '';
  $fields = mysql_list_fields('database','table',$db);
  $columns = mysql_num_fields($fields);

  // Put the name of all fields
  for ($i = 0; $i < $columns; $i++) {
    $l=mysql_field_name($fields, $i);
    $out .= '"'.$l.'",';
  }
  $out .="\n";

  // Add all values in the table
  while ($l = mysql_fetch_array($rsSearchResults)) {
    for ($i = 0; $i < $columns; $i++) {
      $out .='"'.$l["$i"].'",';
    }
    $out .="\n";
  }
  // Output to browser with appropriate mime type, you choose ;)
  header("Content-type: text/x-csv");
  //header("Content-type: text/csv");
  //header("Content-type: application/csv");
  header("Content-Disposition: attachment; filename=search_results.csv");
  echo $out;
  exit;
}

What is the use of static synchronized method in java?

Suppose there are multiple static synchronized methods (m1, m2, m3, m4) in a class, and suppose one thread is accessing m1, then no other thread at the same time can access any other static synchronized methods.

How to lookup JNDI resources on WebLogic?

I had a similar problem to this one. It got solved by deleting the java:comp/env/ prefix and using jdbc/myDataSource in the context lookup. Just as someone pointed out in the comments.

How to select first parent DIV using jQuery?

This gets parent if it is a div. Then it gets class.

var div = $(this).parent("div");
var _class = div.attr("class");

How do I resolve the "java.net.BindException: Address already in use: JVM_Bind" error?

(Windows Only)

To kill a process you first need to find the Process Id (pid)

By running the command :

netstat -ano | findstr :yourPortNumber

As shown in picture below

You will get your Process Id (PID), Now to kill the same process run this command:

taskkill /pid yourid /f

enter image description here

JRE installation directory in Windows

In the command line you can type java -version

How do I check which version of NumPy I'm using?

Simply

pip show numpy

and for pip3

pip3 show numpy

Works on both windows and linux. Should work on mac too if you are using pip.

SQL Query Multiple Columns Using Distinct on One Column Only

select * from tblFruit where
tblFruit_ID in (Select max(tblFruit_ID) FROM tblFruit group by tblFruit_FruitType)

How to cat <<EOF >> a file containing code?

I know this is a two year old question, but this is a quick answer for those searching for a 'how to'.

If you don't want to have to put quotes around anything you can simply write a block of text to a file, and escape variables you want to export as text (for instance for use in a script) and not escape one's you want to export as the value of the variable.

#!/bin/bash

FILE_NAME="test.txt"
VAR_EXAMPLE="\"string\""

cat > ${FILE_NAME} << EOF
\${VAR_EXAMPLE}=${VAR_EXAMPLE} in ${FILE_NAME}  
EOF

Will write "${VAR_EXAMPLE}="string" in test.txt" into test.txt

This can also be used to output blocks of text to the console with the same rules by omitting the file name

#!/bin/bash

VAR_EXAMPLE="\"string\""

cat << EOF
\${VAR_EXAMPLE}=${VAR_EXAMPLE} to console 
EOF

Will output "${VAR_EXAMPLE}="string" to console" to the console

In Windows cmd, how do I prompt for user input and use the result in another command?

I am not sure if this is the case for all versions of Windows, however on the XP machine I have, I need to use the following:

set /p Var1="Prompt String"

Without the prompt string in quotes, I get various results depending on the text.

Start new Activity and finish current one in Android?

You can use finish() method or you can use:

android:noHistory="true"

And then there is no need to call finish() anymore.

<activity android:name=".ClassName" android:noHistory="true" ... />

What is the difference between substr and substring?

substring (MDN) takes parameters as (from, to).
substr (MDN) takes parameters as (from, length).

Update: MDN considers substr legacy.

alert("abc".substr(1,2)); // returns "bc"
alert("abc".substring(1,2)); // returns "b"

You can remember substring (with an i) takes indices, as does yet another string extraction method, slice (with an i).

When starting from 0 you can use either method.

Auto Increment after delete in MySQL

here is a function that fix your problem

    public static void fixID(Connection conn, String table) {

    try {
        Statement myStmt = conn.createStatement();
        ResultSet myRs;
        int i = 1, id = 1, n = 0;
        boolean b;
        String sql;

        myRs = myStmt.executeQuery("select max(id) from " + table);
        if (myRs.next()) {
            n = myRs.getInt(1);
        }
        while (i <= n) {
            b = false;
            myRs = null;
            while (!b) {
                myRs = myStmt.executeQuery("select id from " + table + " where id=" + id);
                if (!myRs.next()) {
                    id++;
                } else {
                    b = true;
                }
            }

            sql = "UPDATE " + table + " set id =" + i + " WHERE id=" + id;
            myStmt.execute(sql);
            i++;
            id++;
        }

    } catch (SQLException e) {
        e.printStackTrace();
    }
}

In AngularJS, what's the difference between ng-pristine and ng-dirty?

ng-pristine ($pristine)

Boolean True if the form/input has not been used yet (not modified by the user)

ng-dirty ($dirty)

Boolean True if the form/input has been used (modified by the user)


$setDirty(); Sets the form to a dirty state. This method can be called to add the 'ng-dirty' class and set the form to a dirty state (ng-dirty class). This method will propagate current state to parent forms.

$setPristine(); Sets the form to its pristine state. This method sets the form's $pristine state to true, the $dirty state to false, removes the ng-dirty class and adds the ng-pristine class. Additionally, it sets the $submitted state to false. This method will also propagate to all the controls contained in this form.

Setting a form back to a pristine state is often useful when we want to 'reuse' a form after saving or resetting it.

Is there a method that calculates a factorial in Java?

You can use recursion version as well.

static int myFactorial(int i) {
    if(i == 1)
        return;
    else
        System.out.prinln(i * (myFactorial(--i)));
}

Recursion is usually less efficient because of having to push and pop recursions, so iteration is quicker. On the other hand, recursive versions use fewer or no local variables which is advantage.

How many threads is too many?

Some people would say that two threads is too many - I'm not quite in that camp :-)

Here's my advice: measure, don't guess. One suggestion is to make it configurable and initially set it to 100, then release your software to the wild and monitor what happens.

If your thread usage peaks at 3, then 100 is too much. If it remains at 100 for most of the day, bump it up to 200 and see what happens.

You could actually have your code itself monitor usage and adjust the configuration for the next time it starts but that's probably overkill.


For clarification and elaboration:

I'm not advocating rolling your own thread pooling subsystem, by all means use the one you have. But, since you were asking about a good cut-off point for threads, I assume your thread pool implementation has the ability to limit the maximum number of threads created (which is a good thing).

I've written thread and database connection pooling code and they have the following features (which I believe are essential for performance):

  • a minimum number of active threads.
  • a maximum number of threads.
  • shutting down threads that haven't been used for a while.

The first sets a baseline for minimum performance in terms of the thread pool client (this number of threads is always available for use). The second sets a restriction on resource usage by active threads. The third returns you to the baseline in quiet times so as to minimise resource use.

You need to balance the resource usage of having unused threads (A) against the resource usage of not having enough threads to do the work (B).

(A) is generally memory usage (stacks and so on) since a thread doing no work will not be using much of the CPU. (B) will generally be a delay in the processing of requests as they arrive as you need to wait for a thread to become available.

That's why you measure. As you state, the vast majority of your threads will be waiting for a response from the database so they won't be running. There are two factors that affect how many threads you should allow for.

The first is the number of DB connections available. This may be a hard limit unless you can increase it at the DBMS - I'm going to assume your DBMS can take an unlimited number of connections in this case (although you should ideally be measuring that as well).

Then, the number of threads you should have depend on your historical use. The minimum you should have running is the minimum number that you've ever had running + A%, with an absolute minimum of (for example, and make it configurable just like A) 5.

The maximum number of threads should be your historical maximum + B%.

You should also be monitoring for behaviour changes. If, for some reason, your usage goes to 100% of available for a significant time (so that it would affect the performance of clients), you should bump up the maximum allowed until it's once again B% higher.


In response to the "what exactly should I measure?" question:

What you should measure specifically is the maximum amount of threads in concurrent use (e.g., waiting on a return from the DB call) under load. Then add a safety factor of 10% for example (emphasised, since other posters seem to take my examples as fixed recommendations).

In addition, this should be done in the production environment for tuning. It's okay to get an estimate beforehand but you never know what production will throw your way (which is why all these things should be configurable at runtime). This is to catch a situation such as unexpected doubling of the client calls coming in.

Including JavaScript class definition from another file in Node.js

I just want to point out that most of the answers here don't work, I am new to NodeJS and IDK if throughout time the "module.exports.yourClass" method changed, or if people just entered the wrong answer.

// MyClass

module.exports.Ninja = class Ninja{
    test(){
        console.log('TESTING 1... 2... 3...');
    };
}
//Using MyClass in seprate File


const ninjaFw = require('./NinjaFw');

let ninja = new ninjaFw.Ninja();
ninja.test();

  • This is the method I am currently using. I like this syntax, becuase module.exports sits on the same line as the class declaration and that cleans the code up a little imo. The other way you can do it is like this:
//  Ninja Framework File


class Ninja{
    test(){
        console.log('TESTING 1... 2... 3...');
    };
}


module.exports.Ninja = Ninja;

  • Two different syntax but, in the end, the same result. Just a matter of syntax anesthetics.

How to calculate cumulative normal distribution?

Here's an example:

>>> from scipy.stats import norm
>>> norm.cdf(1.96)
0.9750021048517795
>>> norm.cdf(-1.96)
0.024997895148220435

In other words, approximately 95% of the standard normal interval lies within two standard deviations, centered on a standard mean of zero.

If you need the inverse CDF:

>>> norm.ppf(norm.cdf(1.96))
array(1.9599999999999991)

Convert a tensor to numpy array in Tensorflow?

I have faced and solved the tensor->ndarray conversion in the specific case of tensors representing (adversarial) images, obtained with cleverhans library/tutorials.

I think that my question/answer (here) may be an helpful example also for other cases.

I'm new with TensorFlow, mine is an empirical conclusion:

It seems that tensor.eval() method may need, in order to succeed, also the value for input placeholders. Tensor may work like a function that needs its input values (provided into feed_dict) in order to return an output value, e.g.

array_out = tensor.eval(session=sess, feed_dict={x: x_input})

Please note that the placeholder name is x in my case, but I suppose you should find out the right name for the input placeholder. x_input is a scalar value or array containing input data.

In my case also providing sess was mandatory.

My example also covers the matplotlib image visualization part, but this is OT.

Convert String to int array in java

In tight loops or on mobile devices it's not a good idea to generate lots of garbage through short-lived String objects, especially when parsing long arrays.

The method in my answer parses data without generating garbage, but it does not deal with invalid data gracefully and cannot parse negative numbers. If your data comes from untrusted source, you should be doing some additional validation or use one of the alternatives provided in other answers.

public static void readToArray(String line, int[] resultArray) {
    int index = 0;
    int number = 0;

    for (int i = 0, n = line.length(); i < n; i++) {
        char c = line.charAt(i);
        if (c == ',') {
            resultArray[index] = number;
            index++;
            number = 0;
        }
        else if (Character.isDigit(c)) {
            int digit = Character.getNumericValue(c);
            number = number * 10 + digit;
        }
    }

    if (index < resultArray.length) {
        resultArray[index] = number;
    }
}

public static int[] toArray(String line) {
    int[] result = new int[countOccurrences(line, ',') + 1];
    readToArray(line, result);
    return result;
}

public static int countOccurrences(String haystack, char needle) {
    int count = 0;
    for (int i=0; i < haystack.length(); i++) {
        if (haystack.charAt(i) == needle) {
            count++;
        }
    }
    return count;
}

countOccurrences implementation was shamelessly stolen from John Skeet

What is a web service endpoint?

A web service endpoint is the URL that another program would use to communicate with your program. To see the WSDL you add ?wsdl to the web service endpoint URL.

Web services are for program-to-program interaction, while web pages are for program-to-human interaction.

So: Endpoint is: http://www.blah.com/myproject/webservice/webmethod

Therefore, WSDL is: http://www.blah.com/myproject/webservice/webmethod?wsdl


To expand further on the elements of a WSDL, I always find it helpful to compare them to code:

A WSDL has 2 portions (physical & abstract).

Physical Portion:

Definitions - variables - ex: myVar, x, y, etc.

Types - data types - ex: int, double, String, myObjectType

Operations - methods/functions - ex: myMethod(), myFunction(), etc.

Messages - method/function input parameters & return types

  • ex: public myObjectType myMethod(String myVar)

Porttypes - classes (i.e. they are a container for operations) - ex: MyClass{}, etc.

Abstract Portion:

Binding - these connect to the porttypes and define the chosen protocol for communicating with this web service. - a protocol is a form of communication (so text/SMS, vs. phone vs. email, etc.).

Service - this lists the address where another program can find your web service (i.e. your endpoint).

PHP convert date format dd/mm/yyyy => yyyy-mm-dd

Here's another solution not using date(). not so smart:)

$var = '20/04/2012';
echo implode("-", array_reverse(explode("/", $var)));

Length of the String without using length() method

We can iterate through the string like a character array, and count that way (A much more down to earth way of doing it):

String s = "foo"
char arr[]=s.toCharArray();
int len = 0;
for(char single : arr){
  len++;
}

Using the "foreach" version of the for loop

Delete specified file from document directory

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

When to use %r instead of %s in Python?

%r shows with quotes:

It will be like:

I said: 'There are 10 types of people.'.

If you had used %s it would have been:

I said: There are 10 types of people..

What is a faster alternative to Python's http.server (or SimpleHTTPServer)?

Using Servez as a server

  1. Download Servez
  2. Install It, Run it
  3. Choose the folder to serve
  4. Pick "Start"
  5. Go to http://localhost:8080 or pick "Launch Browser"

servez

Note: I threw this together because Web Server for Chrome is going away since Chrome is removing support for apps and because I support art students who have zero experience with the command line

Is there a pure CSS way to make an input transparent?

The two methods previously described are not enough today. I personnally use :

input[type="text"]{
    background-color: transparent;
    border: 0px;
    outline: none;
    -webkit-box-shadow: none;
    -moz-box-shadow: none;
    box-shadow: none;
    width:5px;
    color:transparent;
    cursor:default;
}

It also removes the shadow set on some browsers, hide the text that could be input and make the cursor behave as if the input was not there.

You may want to set width to 0px also.

How to find out the username and password for mysql database

In your local system right,

   go to this url : http://localhost/phpmyadmin/

   In this click mysql default db, after that browser user table to get existing username and password.

The order of keys in dictionaries

From http://docs.python.org/tutorial/datastructures.html:

"The keys() method of a dictionary object returns a list of all the keys used in the dictionary, in arbitrary order (if you want it sorted, just apply the sorted() function to it)."

How can I open a .tex file?

A .tex file should be a LaTeX source file.

If this is the case, that file contains the source code for a LaTeX document. You can open it with any text editor (notepad, notepad++ should work) and you can view the source code. But if you want to view the final formatted document, you need to install a LaTeX distribution and compile the .tex file.

Of course, any program can write any file with any extension, so if this is not a LaTeX document, then we can't know what software you need to install to open it. Maybe if you upload the file somewhere and link it in your question we can see the file and provide more help to you.


Yes, this is the source code of a LaTeX document. If you were able to paste it here, then you are already viewing it. If you want to view the compiled document, you need to install a LaTeX distribution. You can try to install MiKTeX then you can use that to compile the document to a .pdf file.

You can also check out this question and answer for how to do it: How to compile a LaTeX document?

Also, there's an online LaTeX editor and you can paste your code in there to preview the document: https://www.overleaf.com/.

Why can't I define a default constructor for a struct in .NET?

Shorter explanation:

In C++, struct and class were just two sides of the same coin. The only real difference is that one was public by default and the other was private.

In .NET, there is a much greater difference between a struct and a class. The main thing is that struct provides value-type semantics, while class provides reference-type semantics. When you start thinking about the implications of this change, other changes start to make more sense as well, including the constructor behavior you describe.

Trigger change() event when setting <select>'s value with val() function

As jQuery won't trigger native change event but only triggers its own change event. If you bind event without jQuery and then use jQuery to trigger it the callbacks you bound won't run !

The solution is then like below (100% working) :

var sortBySelect = document.querySelector("select.your-class"); 
sortBySelect.value = "new value"; 
sortBySelect.dispatchEvent(new Event("change"));

Loading state button in Bootstrap 3

You need to detect the click from js side, your HTML remaining same. Note: this method is deprecated since v3.5.5 and removed in v4.

$("button").click(function() {
    var $btn = $(this);
    $btn.button('loading');
    // simulating a timeout
    setTimeout(function () {
        $btn.button('reset');
    }, 1000);
});

Also, don't forget to load jQuery and Bootstrap js (based on jQuery) file in your page.

JSFIDDLE

Official Documentation

Convert objective-c typedef to its string equivalent

Every answer here basically says the same thing, create a regular enum and then use a custom getter to switch between strings.

I employ a much simpler solution that is faster, shorter, and cleaner—using Macros!


#define kNames_allNames ((NSArray <NSString *> *)@[@"Alice", @"Bob", @"Eve"])
#define kNames_alice ((NSString *)kNames_allNames[0])
#define kNames_bob ((NSString *)kNames_allNames[1])
#define kNames_eve ((NSString *)kNames_allNames[2])

Then you can simply start to type kNam... and autocomplete will display the lists you desire!

Additionally, if you want to handle logic for all the names at once you can simply fast enumerate the literal array in order, as follows:

for (NSString *kName in kNames_allNames) {}

Lastly, the NSString casting in the macros ensures behavior similar to typedef!


Enjoy!

How to calculate number of days between two given dates?

There is also a datetime.toordinal() method that was not mentioned yet:

import datetime
print(datetime.date(2008,9,26).toordinal() - datetime.date(2008,8,18).toordinal())  # 39

https://docs.python.org/3/library/datetime.html#datetime.date.toordinal

date.toordinal()

Return the proleptic Gregorian ordinal of the date, where January 1 of year 1 has ordinal 1. For any date object d, date.fromordinal(d.toordinal()) == d.

Seems well suited for calculating days difference, though not as readable as timedelta.days.

How To Check If A Key in **kwargs Exists?

It is just this:

if 'errormessage' in kwargs:
    print("yeah it's here")

You need to check, if the key is in the dictionary. The syntax for that is some_key in some_dict (where some_key is something hashable, not necessarily a string).

The ideas you have linked (these ideas) contained examples for checking if specific key existed in dictionaries returned by locals() and globals(). Your example is similar, because you are checking existence of specific key in kwargs dictionary (the dictionary containing keyword arguments).

Should I learn C before learning C++?

My two cents:

I suggest to learn C first, because :

  • it is a fundamental language - a lot of languages descended from C
  • more platforms supports C compiler than C++,- be it embedded systems, GPU chips, etc.
  • according to TIOBE index C is still about 2 times more popular than C++.

jQuery/JavaScript to replace broken images

Handle the onError event for the image to reassign its source using JavaScript:

function imgError(image) {
    image.onerror = "";
    image.src = "/images/noimage.gif";
    return true;
}
<img src="image.png" onerror="imgError(this);"/>

Or without a JavaScript function:

<img src="image.png" onError="this.onerror=null;this.src='/images/noimage.gif';" />

The following compatibility table lists the browsers that support the error facility:

http://www.quirksmode.org/dom/events/error.html

Convert JSON to DataTable

I recommend you to use JSON.NET. it is an open source library to serialize and deserialize your c# objects into json and Json objects into .net objects ...

Serialization Example:

Product product = new Product();
product.Name = "Apple";
product.Expiry = new DateTime(2008, 12, 28);
product.Price = 3.99M;
product.Sizes = new string[] { "Small", "Medium", "Large" };

string json = JsonConvert.SerializeObject(product);
//{
//  "Name": "Apple",
//  "Expiry": new Date(1230422400000),
//  "Price": 3.99,
//  "Sizes": [
//    "Small",
//    "Medium",
//    "Large"
//  ]
//}

Product deserializedProduct = JsonConvert.DeserializeObject<Product>(json);

Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.2:java (default-cli)

Your problem is that you have declare twice the exec-maven-plugin :

<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>exec-maven-plugin</artifactId>
    <version>1.2.1</version>
    <executions>
        <execution>
            <goals>
                <goal>java</goal>
            </goals>
        </execution>
    </executions>
    <configuration>
        <mainClass>C:\apache-camel-2.11.0\examples\camel-example-smooks-  
      integration\src\main\java\example\Main< /mainClass>
    </configuration>
</plugin>

...

< plugin>
    < groupId>org.codehaus.mojo</groupId>
    < artifactId>exec-maven-plugin</artifactId>
    < version>1.2</version>
< /plugin>

Server configuration by allow_url_fopen=0 in

THIS IS A VERY SIMPLE PROBLEM

Here is the best method for solve this problem.

Step 1 : Login to your cPanel (http://website.com/cpanel OR http://cpanel.website.com).

Step 2 : SOFTWARE -> Select PHP Version

Step 3 : Change Your Current PHP version : 5.6

Step 3 : HIT 'Set as current' [ ENJOY ]

The type arguments cannot be inferred from the usage. Try specifying the type arguments explicitly

You are referring to the type rather than the instance. Make 'Model' lowercase in the example in your second and fourth code samples.

Model.GetHtmlAttributes

should be

model.GetHtmlAttributes

SQL Server 100% CPU Utilization - One database shows high CPU usage than others

According to this article on sqlserverstudymaterial;

Remember that "%Privileged time" is not based on 100%.It is based on number of processors.If you see 200 for sqlserver.exe and the system has 8 CPU then CPU consumed by sqlserver.exe is 200 out of 800 (only 25%).

If "% Privileged Time" value is more than 30% then it's generally caused by faulty drivers or anti-virus software. In such situations make sure the BIOS and filter drives are up to date and then try disabling the anti-virus software temporarily to see the change.

If "% User Time" is high then there is something consuming of SQL Server. There are several known patterns which can be caused high CPU for processes running in SQL Server including

Arduino Sketch upload issue - avrdude: stk500_recv(): programmer is not responding

In my case the problem was raised when I was trying to do some "weird" arithmetic expressions

eg (3.14/4)/5 or 3.15%2.55

So, I would suggest you to check all the arithmetic expressions in case some of them cannot be calculated by the Arduino.

Hope it helps.

Run a mySQL query as a cron job?

This was a very handy page as I have a requirement to DELETE records from a mySQL table where the expiry date is < Today.

I am on a shared host and CRON did not like the suggestion AndrewKDay. it also said (and I agree) that exposing the password in this way could be insecure.

I then tried turning Events ON in phpMyAdmin but again being on a shared host this was a no no. Sorry fancyPants.

So I turned to embedding the SQL script in a PHP file. I used the example [here][1]

[1]: https://www.w3schools.com/php/php_mysql_create_table.asp stored it in a sub folder somewhere safe and added an empty index.php for good measure. I was then able to test that this PHP file (and my SQL script) was working from the browser URL line.

All good so far. On to CRON. Following the above example almost worked. I ended up calling PHP before the path for my *.php file. Otherwise CRON didn't know what to do with the file.

my cron is set to run once per day and looks like this, modified for security.

00 * * * * php mywebsiteurl.com/wp-content/themes/ForteChildTheme/php/DeleteExpiredAssessment.php

For the final testing with CRON I initially set it to run each minute and had email alerts turned on. This quickly confirmed that it was running as planned and I changed it back to once per day.

Hope this helps.

How to use executables from a package installed locally in node_modules?

I've always used the same approach as @guneysus to solve this problem, which is creating a script in the package.json file and use it running npm run script-name.

However, in the recent months I've been using npx and I love it.

For example, I downloaded an Angular project and I didn't want to install the Angular CLI globally. So, with npx installed, instead of using the global angular cli command (if I had installed it) like this:

ng serve

I can do this from the console:

npx ng serve

Here's an article I wrote about NPX and that goes deeper into it.

Change the maximum upload file size

You can also use ini_set function (only for PHP version below 5.3):

ini_set('post_max_size', '64M');
ini_set('upload_max_filesize', '64M');

Like @acme said, in php 5.3 and above this settings are PHP_INI_PERDIR directives so they can't be set using ini_set. You can use user.ini instead.

How do I create/edit a Manifest file?

The simplest way to create a manifest is:

Project Properties -> Security -> Click "enable ClickOnce security settings" 
(it will generate default manifest in your project Properties) -> then Click 
it again in order to uncheck that Checkbox -> open your app.maifest and edit 
it as you wish.

Manifest location preview

error: src refspec master does not match any

Run the command git show-ref, the result refs/heads/YOURBRANCHNAME If your branch is not there, then you need to switch the branch by

git checkout -b "YOURBRANCHNAME"

git show-ref, will now show your branch reference.

Now you can do the operations on your branch.

Store JSON object in data attribute in HTML jQuery

Combine the use of window.btoa and window.atob together with JSON.stringify and JSON.parse.

- This works for strings containing single quotes

Encoding the data:

var encodedObject = window.btoa(JSON.stringify(dataObject));

Decoding the data:

var dataObject = JSON.parse(window.atob(encodedObject));

Here is an example of how the data is constructed and decoded later with the click event.

Construct the html and encode the data:

var encodedObject = window.btoa(JSON.stringify(dataObject));

"<td>" + "<a class='eventClass' href='#' data-topic='" + encodedObject + "'>" 
+ "Edit</a></td>"

Decode the data in the click event handler:

$("#someElementID").on('click', 'eventClass', function(e) {
            event.preventDefault();
            var encodedObject = e.target.attributes["data-topic"].value;
            var dataObject = JSON.parse(window.atob(encodedObject));

            // use the dataObject["keyName"] 
}

Checking Bash exit status of several commands efficiently

Sorry that I can not make a comment to the first answer But you should use new instance to execute the command: cmd_output=$($@)

#!/bin/bash

function check_exit {
    cmd_output=$($@)
    local status=$?
    echo $status
    if [ $status -ne 0 ]; then
        echo "error with $1" >&2
    fi
    return $status
}

function run_command() {
    exit 1
}

check_exit run_command

C++ alignment when printing cout <<

The setw manipulator function will be of help here.

Is there a way to crack the password on an Excel VBA Project?

In the event that your block of CMG="XXXX"\r\nDPB="XXXXX"\r\nGC="XXXXXX" in your 'known password' file is shorter than the existing block in the 'unknown password' file, pad your hex strings with trailing zeros to reach the correct length.

e.g.

CMG="xxxxxx"\r\nDPB="xxxxxxxx"\r\nGC="xxxxxxxxxx"

in the unknown password file, should be set to

CMG="XXXX00"\r\nDPB="XXXXX000"\r\nGC="XXXXXX0000" to preserve file length.

I have also had this working with .XLA (97/2003 format) files in office 2007.

Undefined behavior and sequence points

C++17 (N4659) includes a proposal Refining Expression Evaluation Order for Idiomatic C++ which defines a stricter order of expression evaluation.

In particular, the following sentence

8.18 Assignment and compound assignment operators:
....

In all cases, the assignment is sequenced after the value computation of the right and left operands, and before the value computation of the assignment expression. The right operand is sequenced before the left operand.

together with the following clarification

An expression X is said to be sequenced before an expression Y if every value computation and every side effect associated with the expression X is sequenced before every value computation and every side effect associated with the expression Y.

make several cases of previously undefined behavior valid, including the one in question:

a[++i] = i;

However several other similar cases still lead to undefined behavior.

In N4140:

i = i++ + 1; // the behavior is undefined

But in N4659

i = i++ + 1; // the value of i is incremented
i = i++ + i; // the behavior is undefined

Of course, using a C++17 compliant compiler does not necessarily mean that one should start writing such expressions.

Using '<%# Eval("item") %>'; Handling Null Value and showing 0 against

You can also create a public method on the page then call that from the code-in-front.

e.g. if using C#:

public string ProcessMyDataItem(object myValue)
{
  if (myValue == null)
  {
     return "0 value";
  }

  return myValue.ToString();
}

Then the label in the code-in-front will be something like:

<asp:Label ID="Label18" Text='<%# ProcessMyDataItem(Eval("item")) %>' runat="server"></asp:Label>

Sorry, haven't tested this code so can't guarantee I got the syntax of "<%# ProcessMyDataItem(Eval("item")) %>" entirely correct.

Breaking out of a for loop in Java

break; is what you need to break out of any looping statement like for, while or do-while.

In your case, its going to be like this:-

for(int x = 10; x < 20; x++) {
         // The below condition can be present before or after your sysouts, depending on your needs.
         if(x == 15){
             break; // A unlabeled break is enough. You don't need a labeled break here.
         }
         System.out.print("value of x : " + x );
         System.out.print("\n");
}

Is the size of C "int" 2 bytes or 4 bytes?

I know it's equal to sizeof(int). The size of an int is really compiler dependent. Back in the day, when processors were 16 bit, an int was 2 bytes. Nowadays, it's most often 4 bytes on a 32-bit as well as 64-bit systems.

Still, using sizeof(int) is the best way to get the size of an integer for the specific system the program is executed on.

EDIT: Fixed wrong statement that int is 8 bytes on most 64-bit systems. For example, it is 4 bytes on 64-bit GCC.

Append key/value pair to hash with << in Ruby

Similar as they are, merge! and store treat existing hashes differently depending on keynames, and will therefore affect your preference. Other than that from a syntax standpoint, merge!'s key: "value" syntax closely matches up against JavaScript and Python. I've always hated comma-separating key-value pairs, personally.

hash = {}
hash.merge!(key: "value")
hash.merge!(:key => "value")
puts hash

{:key=>"value"}

hash = {}
hash.store(:key, "value")
hash.store("key", "value")
puts hash

{:key=>"value", "key"=>"value"}

To get the shovel operator << working, I would advise using Mark Thomas's answer.

Closing Application with Exit button

try this for close app

Activity.finish();
System.exit(0);

How can I find whitespace in a String?

You can basically do this

if(s.charAt(i)==32){
   return true;
}

You must write boolean method.Whitespace char is 32.

Rename a dictionary key

In case someone wants to rename all the keys at once providing a list with the new names:

def rename_keys(dict_, new_keys):
    """
     new_keys: type List(), must match length of dict_
    """

    # dict_ = {oldK: value}
    # d1={oldK:newK,} maps old keys to the new ones:  
    d1 = dict( zip( list(dict_.keys()), new_keys) )

          # d1{oldK} == new_key 
    return {d1[oldK]: value for oldK, value in dict_.items()}

Hide keyboard in react-native

Updated usage of ScrollView for React Native 0.39

<ScrollView scrollEnabled={false} contentContainerStyle={{flex: 1}} />

Although, there is still a problem with two TextInput boxes. eg. A username and password form would now dismiss the keyboard when switching between inputs. Would love to get some suggestions to keep keyboard alive when switching between TextInputs while using a ScrollView.

How to make in CSS an overlay over an image?

You can achieve this with this simple CSS/HTML:

.image-container {
    position: relative;
    width: 200px;
    height: 300px;
}
.image-container .after {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    display: none;
    color: #FFF;
}
.image-container:hover .after {
    display: block;
    background: rgba(0, 0, 0, .6);
}

HTML

<div class="image-container">
    <img src="http://lorempixel.com/300/200" />
    <div class="after">This is some content</div>
</div>

Demo: http://jsfiddle.net/6Mt3Q/


UPD: Here is one nice final demo with some extra stylings.

_x000D_
_x000D_
.image-container {_x000D_
    position: relative;_x000D_
    display: inline-block;_x000D_
}_x000D_
.image-container img {display: block;}_x000D_
.image-container .after {_x000D_
    position: absolute;_x000D_
    top: 0;_x000D_
    left: 0;_x000D_
    width: 100%;_x000D_
    height: 100%;_x000D_
    display: none;_x000D_
    color: #FFF;_x000D_
}_x000D_
.image-container:hover .after {_x000D_
    display: block;_x000D_
    background: rgba(0, 0, 0, .6);_x000D_
}_x000D_
.image-container .after .content {_x000D_
    position: absolute;_x000D_
    bottom: 0;_x000D_
    font-family: Arial;_x000D_
    text-align: center;_x000D_
    width: 100%;_x000D_
    box-sizing: border-box;_x000D_
    padding: 5px;_x000D_
}_x000D_
.image-container .after .zoom {_x000D_
    color: #DDD;_x000D_
    font-size: 48px;_x000D_
    position: absolute;_x000D_
    top: 50%;_x000D_
    left: 50%;_x000D_
    margin: -30px 0 0 -19px;_x000D_
    height: 50px;_x000D_
    width: 45px;_x000D_
    cursor: pointer;_x000D_
}_x000D_
.image-container .after .zoom:hover {_x000D_
    color: #FFF;_x000D_
}
_x000D_
<link href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.min.css" rel="stylesheet"/>_x000D_
_x000D_
<div class="image-container">_x000D_
    <img src="http://lorempixel.com/300/180" />_x000D_
    <div class="after">_x000D_
        <span class="content">This is some content. It can be long and span several lines.</span>_x000D_
        <span class="zoom">_x000D_
            <i class="fa fa-search"></i>_x000D_
        </span>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to animate the change of image in an UIImageView?

I am not sure if you can animate UIViews with fade effect as it seems all supported view transitions are defined in UIViewAnimationTransition enumeration. Fading effect can be achieved using CoreAnimation. Sample example for this approach:

#import <QuartzCore/QuartzCore.h>
...
imageView.image = [UIImage imageNamed:(i % 2) ? @"3.jpg" : @"4.jpg"];

CATransition *transition = [CATransition animation];
transition.duration = 1.0f;
transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
transition.type = kCATransitionFade;

[imageView.layer addAnimation:transition forKey:nil];

How to make exe files from a node.js app?

By default, Windows associates .js files with the Windows Script Host, Microsoft's stand-alone JS runtime engine. If you type script.js at a command prompt (or double-click a .js file in Explorer), the script is executed by wscript.exe.

This may be solving a local problem with a global setting, but you could associate .js files with node.exe instead, so that typing script.js at a command prompt or double-clicking/dragging items onto scripts will launch them with Node.

Of course, if—like me—you've associated .js files with an editor so that double-clicking them opens up your favorite text editor, this suggestion won't do much good. You could also add a right-click menu entry of "Execute with Node" to .js files, although this alternative doesn't solve your command-line needs.


The simplest solution is probably to just use a batch file – you don't have to have a copy of Node in the folder your script resides in. Just reference the Node executable absolutely:

"C:\Program Files (x86)\nodejs\node.exe" app.js %*

Another alternative is this very simple C# app which will start Node using its own filename + .js as the script to run, and pass along any command line arguments.

class Program
{
    static void Main(string[] args)
    {
        var info = System.Diagnostics.Process.GetCurrentProcess();
        var proc = new System.Diagnostics.ProcessStartInfo(@"C:\Program Files (x86)\nodejs\node.exe", "\"" + info.ProcessName + ".js\" " + String.Join(" ", args));
        proc.UseShellExecute = false;
        System.Diagnostics.Process.Start(proc);
    }
}

So if you name the resulting EXE "app.exe", you can type app arg1 ... and Node will be started with the command line "app.js" arg1 .... Note the C# bootstrapper app will immediately exit, leaving Node in charge of the console window.

Since this is probably of relatively wide interest, I went ahead and made this available on GitHub, including the compiled exe if getting in to vans with strangers is your thing.

How do I get the n-th level parent of an element in jQuery?

If you plan on reusing this functionality, the optimal solution is to make a jQuery plugin:

(function($){
$.fn.nthParent = function(n){
  var $p = $(this);
  while ( n-- >= 0 )
  {
    $p = $p.parent();
  }
  return $p;
};
}(jQuery));

Of course, you may want to extend it to allow for an optional selector and other such things.

One note: this uses a 0 based index for parents, so nthParent(0) is the same as calling parent(). If you'd rather have 1 based indexing, use n-- > 0

jQuery: find element by text

Yes, use the jQuery contains selector.

How can I capitalize the first letter of each word in a string?

Why do you complicate your life with joins and for loops when the solution is simple and safe??

Just do this:

string = "the brown fox"
string[0].upper()+string[1:]

Please initialize the log4j system properly. While running web service

You can configure log4j.properties like above answers, or use org.apache.log4j.BasicConfigurator

public class FooImpl implements Foo {

    private static final Logger LOGGER = Logger.getLogger(FooBar.class);

    public Object createObject() {
        BasicConfigurator.configure();
        LOGGER.info("something");
        return new Object();
    }
}

So under the table, configure do:

  configure() {
    Logger root = Logger.getRootLogger();
    root.addAppender(new ConsoleAppender(
           new PatternLayout(PatternLayout.TTCC_CONVERSION_PATTERN)));
  }

How to have stored properties in Swift, the same way I had on Objective-C?

Associated objects API is a bit cumbersome to use. You can remove most of the boilerplate with a helper class.

public final class ObjectAssociation<T: AnyObject> {

    private let policy: objc_AssociationPolicy

    /// - Parameter policy: An association policy that will be used when linking objects.
    public init(policy: objc_AssociationPolicy = .OBJC_ASSOCIATION_RETAIN_NONATOMIC) {

        self.policy = policy
    }

    /// Accesses associated object.
    /// - Parameter index: An object whose associated object is to be accessed.
    public subscript(index: AnyObject) -> T? {

        get { return objc_getAssociatedObject(index, Unmanaged.passUnretained(self).toOpaque()) as! T? }
        set { objc_setAssociatedObject(index, Unmanaged.passUnretained(self).toOpaque(), newValue, policy) }
    }
}

Provided that you can "add" a property to objective-c class in a more readable manner:

extension SomeType {

    private static let association = ObjectAssociation<NSObject>()

    var simulatedProperty: NSObject? {

        get { return SomeType.association[self] }
        set { SomeType.association[self] = newValue }
    }
}

As for the solution:

extension CALayer {

    private static let initialPathAssociation = ObjectAssociation<CGPath>()
    private static let shapeLayerAssociation = ObjectAssociation<CAShapeLayer>()

    var initialPath: CGPath! {
        get { return CALayer.initialPathAssociation[self] }
        set { CALayer.initialPathAssociation[self] = newValue }
    }

    var shapeLayer: CAShapeLayer? {
        get { return CALayer.shapeLayerAssociation[self] }
        set { CALayer.shapeLayerAssociation[self] = newValue }
    }
}

TypeError: expected a character buffer object - while trying to save integer to textfile

Have you checked the docstring of write()? It says:

write(str) -> None. Write string str to file.

Note that due to buffering, flush() or close() may be needed before the file on disk reflects the data written.

So you need to convert y to str first.

Also note that the string will be written at the current position which will be at the end of the file, because you'll already have read the old value. Use f.seek(0) to get to the beginning of the file.`

Edit: As for the IOError, this issue seems related. A cite from there:

For the modes where both read and writing (or appending) are allowed (those which include a "+" sign), the stream should be flushed (fflush) or repositioned (fseek, fsetpos, rewind) between either a reading operation followed by a writing operation or a writing operation followed by a reading operation.

So, I suggest you try f.seek(0) and maybe the problem goes away.

Invert colors of an image in CSS or JavaScript

Can be done in major new broswers using the code below

.img {
    -webkit-filter:invert(100%);
     filter:progid:DXImageTransform.Microsoft.BasicImage(invert='1');
}

However, if you want it to work across all browsers you need to use Javascript. Something like this gist will do the job.

How do you get the currently selected <option> in a <select> via JavaScript?

This will do it for you:

var yourSelect = document.getElementById( "your-select-id" );
alert( yourSelect.options[ yourSelect.selectedIndex ].value )

How to run shell script file using nodejs?

You could use "child process" module of nodejs to execute any shell commands or scripts with in nodejs. Let me show you with an example, I am running a shell script(hi.sh) with in nodejs.

hi.sh

echo "Hi There!"

node_program.js

const { exec } = require('child_process');
var yourscript = exec('sh hi.sh',
        (error, stdout, stderr) => {
            console.log(stdout);
            console.log(stderr);
            if (error !== null) {
                console.log(`exec error: ${error}`);
            }
        });

Here, when I run the nodejs file, it will execute the shell file and the output would be:

Run

node node_program.js

output

Hi There!

You can execute any script just by mentioning the shell command or shell script in exec callback.

Hope this helps! Happy coding :)

How can I wait for a thread to finish with .NET?

The previous two answers are great and will work for simple scenarios. There are other ways to synchronize threads, however. The following will also work:

public void StartTheActions()
{
    ManualResetEvent syncEvent = new ManualResetEvent(false);

    Thread t1 = new Thread(
        () =>
        {
            // Do some work...
            syncEvent.Set();
        }
    );
    t1.Start();

    Thread t2 = new Thread(
        () =>
        {
            syncEvent.WaitOne();

            // Do some work...
        }
    );
    t2.Start();
}

ManualResetEvent is one of the various WaitHandle's that the .NET framework has to offer. They can provide much richer thread synchronization capabilities than the simple, but very common tools like lock()/Monitor, Thread.Join, etc.

They can also be used to synchronize more than two threads, allowing complex scenarios such as a 'master' thread that coordinates multiple 'child' threads, multiple concurrent processes that are dependent upon several stages of each other to be synchronized, etc.