Programs & Examples On #Nsdate

NSDate objects represent a single point in time. NSDate is a class cluster; its single public superclass, NSDate, declares the programmatic interface for specific and relative time values. The objects you create using NSDate are referred to as date objects. They are immutable objects. Because of the nature of class clusters, objects returned by the NSDate class are instances not of that abstract class but of one of its private subclasses.

iOS: Convert UTC NSDate to local Timezone

Please use this code.

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss"]; 
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
NSDate *date = [dateFormatter dateFromString:@"2015-04-01T11:42:00"]; // create date from string

[dateFormatter setDateFormat:@"EEE, MMM d, yyyy - h:mm a"];
[dateFormatter setTimeZone:[NSTimeZone localTimeZone]];
NSString *timestamp = [dateFormatter stringFromDate:date];

How to convert NSDate into unix timestamp iphone sdk?

As per @kexik's suggestion using the UNIX time function as below :

  time_t result = time(NULL);
  NSLog([NSString stringWithFormat:@"The current Unix epoch time is %d",(int)result]);

.As per my experience - don't use timeIntervalSince1970 , it gives epoch timestamp - number of seconds you are behind GMT.

There used to be a bug with [[NSDate date]timeIntervalSince1970] , it used to add/subtract time based on the timezone of the phone but it seems to be resolved now.

Convert NSDate to NSString

In Swift:

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

Convert string to date in Swift

Swift 3.0 - 4.2

import Foundation

extension String {

    func toDate(withFormat format: String = "yyyy-MM-dd HH:mm:ss")-> Date?{

        let dateFormatter = DateFormatter()
        dateFormatter.timeZone = TimeZone(identifier: "Asia/Tehran")
        dateFormatter.locale = Locale(identifier: "fa-IR")
        dateFormatter.calendar = Calendar(identifier: .gregorian)
        dateFormatter.dateFormat = format
        let date = dateFormatter.date(from: self)

        return date

    }
}

extension Date {

    func toString(withFormat format: String = "EEEE ? d MMMM yyyy") -> String {

        let dateFormatter = DateFormatter()
        dateFormatter.locale = Locale(identifier: "fa-IR")
        dateFormatter.timeZone = TimeZone(identifier: "Asia/Tehran")
        dateFormatter.calendar = Calendar(identifier: .persian)
        dateFormatter.dateFormat = format
        let str = dateFormatter.string(from: self)

        return str
    }
}

Converting NSString to NSDate (and back again)

If anyone is interested in doing something like this in Swift these days, I have a start on something, although it's not perfect.

func detectDate(dateString: NSString) -> NSDate {

    var error: NSError?
    let detector: NSDataDetector = NSDataDetector.dataDetectorWithTypes(NSTextCheckingType.Date.toRaw(), error: &error)!

    if error == nil {
        var matches = detector.matchesInString(dateString, options: nil, range: NSMakeRange(0, dateString.length))

        let currentLocale = NSLocale.currentLocale()
        for match in matches {
            match.resultType == NSTextCheckingType.Date
            NSLog("Date: \(match.date.description)")
            return match.date
        }
    }
    return NSDate()
}

How to compare two NSDates: Which is more recent?

Use this simple function for date comparison

-(BOOL)dateComparision:(NSDate*)date1 andDate2:(NSDate*)date2{

BOOL isTokonValid;

if ([date1 compare:date2] == NSOrderedDescending) {
    NSLog(@"date1 is later than date2");
    isTokonValid = YES;
} else if ([date1 compare:date2] == NSOrderedAscending) {
    NSLog(@"date1 is earlier than date2");
    isTokonValid = NO;
} else {
    isTokonValid = NO;
    NSLog(@"dates are the same");
}

return isTokonValid;}

Get UTC time and local time from NSDate object

let date = Date() 
print(date) // printed date is UTC 

If you are using playground, use a print statement to check the time. Playground shows local time until you print it. Do not depend on the right side panel of playground. enter image description here

This code gives date in UTC. If you need the local time, you should call the following extension with timezone as Timezone.current

 extension Date {

   var currentUTCTimeZoneDate: String {
        let formatter = DateFormatter()
        formatter.timeZone = TimeZone(identifier: "UTC")
        formatter.amSymbol = "AM"
        formatter.pmSymbol = "PM"
        formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"

        return formatter.string(from: self)
    }
}

For UTC time, use it like: Date().currentUTCTimeZoneDate

NSDate get year/month/day

If you wish to get the individual NSDateComponents from NSDate, you would definitely need the solution suggested by Itai Ferber. But if you want to go from NSDate directly to an NSString, you can use NSDateFormatter.

How do you create a Swift Date object?

Swift doesn't have its own Date type, but you to use the existing Cocoa NSDate type, e.g:

class Date {

    class func from(year: Int, month: Int, day: Int) -> Date {
        let gregorianCalendar = NSCalendar(calendarIdentifier: .gregorian)!

        var dateComponents = DateComponents()
        dateComponents.year = year
        dateComponents.month = month
        dateComponents.day = day

        let date = gregorianCalendar.date(from: dateComponents)!
        return date
    }

    class func parse(_ string: String, format: String = "yyyy-MM-dd") -> Date {
        let dateFormatter = DateFormatter()
        dateFormatter.timeZone = NSTimeZone.default
        dateFormatter.dateFormat = format

        let date = dateFormatter.date(from: string)!
        return date
    }
}

Which you can use like:

var date = Date.parse("2014-05-20")
var date = Date.from(year: 2014, month: 05, day: 20)

How do I get hour and minutes from NSDate?

If you were to use the C library then this could be done:

time_t t;
struct tm * timeinfo;

time (&t);
timeinfo = localtime (&t);

NSLog(@"Hour: %d Minutes: %d", timeinfo->tm_hour, timeinfo->tm_min);

And using Swift:

var t = time_t()
time(&t)
let x = localtime(&t)

println("Hour: \(x.memory.tm_hour) Minutes: \(x.memory.tm_min)")

For further guidance see: http://www.cplusplus.com/reference/ctime/localtime/

Get Current date & time with [NSDate date]

NSLocale* currentLocale = [NSLocale currentLocale];
[[NSDate date] descriptionWithLocale:currentLocale];  

or use

NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init]; 
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
// or @"yyyy-MM-dd hh:mm:ss a" if you prefer the time with AM/PM 
NSLog(@"%@",[dateFormatter stringFromDate:[NSDate date]]);

Get current NSDate in timestamp format

To get timestamp from NSDate Swift 3

func getCurrentTimeStampWOMiliseconds(dateToConvert: NSDate) -> String {
    let objDateformat: DateFormatter = DateFormatter()
    objDateformat.dateFormat = "yyyy-MM-dd HH:mm:ss"
    let strTime: String = objDateformat.string(from: dateToConvert as Date)
    let objUTCDate: NSDate = objDateformat.date(from: strTime)! as NSDate
    let milliseconds: Int64 = Int64(objUTCDate.timeIntervalSince1970)
    let strTimeStamp: String = "\(milliseconds)"
    return strTimeStamp
}

To use

let now = NSDate()
let nowTimeStamp = self.getCurrentTimeStampWOMiliseconds(dateToConvert: now)

Getting the difference between two Dates (months/days/hours/minutes/seconds) in Swift

Slightly modified code for Swift 3.0

let calendar = NSCalendar.current as NSCalendar

// Replace the hour (time) of both dates with 00:00
let date1 = calendar.startOfDay(for: startDateTime)
let date2 = calendar.startOfDay(for: endDateTime)

let flags = NSCalendar.Unit.day
let components = calendar.components(flags, from: date1, to: date2, options: [])

return components.day!

Date Format in Swift

swift 3

let date : Date = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMM dd, yyyy"
let todaysDate = dateFormatter.string(from: date)

Formatting NSDate into particular styles for both year, month, day, and hour, minute, seconds

    NSDateFormatter *dateformat = [[NSDateFormatter alloc] init];
    [dateformat setDateFormat:@"Your Date Format"];

set the format to return is....

yyyy-MM-dd return 2015-12-17 date

yyyy-MMM-dd return 2015-Dec-17 date

yy-MM-dd return 15-12-17 date

dd-MM-yy return 17-12-15 date

dd-MM-yyyy return 17-12-2015 date

yyyy-MMM-dd HH:mm:ss return 2015-Dec-17 08:07:13 date and time

yyyy-MMM-dd HH:mm return 2015-Dec-17 08:07 date and time

For more Details Data and Time Format for Click Now.

Thank you.....

How do I add 1 day to an NSDate?

Use the below function and use days paramater to get the date daysAhead/daysBehind just pass parameter as positive for future date or negative for previous dates:

+ (NSDate *) getDate:(NSDate *)fromDate daysAhead:(NSUInteger)days
{
    NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
    dateComponents.day = days;
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDate *previousDate = [calendar dateByAddingComponents:dateComponents
                                                     toDate:fromDate
                                                    options:0];
    [dateComponents release];
    return previousDate;
}

How to convert string to date to string in Swift iOS?

First, you need to convert your string to NSDate with its format. Then, you change the dateFormatter to your simple format and convert it back to a String.

Swift 3

let dateString = "Thu, 22 Oct 2015 07:45:17 +0000"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EEE, dd MMM yyyy hh:mm:ss +zzzz"
dateFormatter.locale = Locale.init(identifier: "en_GB")

let dateObj = dateFormatter.date(from: dateString)

dateFormatter.dateFormat = "MM-dd-yyyy"
print("Dateobj: \(dateFormatter.string(from: dateObj!))")

The printed result is: Dateobj: 10-22-2015

How to get time (hour, minute, second) in Swift 3 using NSDate?

Swift 5+

extension Date {
    
    func get(_ type: Calendar.Component)-> String {
        let calendar = Calendar.current
        let t = calendar.component(type, from: self)
        return (t < 10 ? "0\(t)" : t.description)
    }
}

Usage:

print(Date().get(.year)) // => 2020
print(Date().get(.month)) // => 08
print(Date().get(.day)) // => 18 

iOS: Compare two dates

I take it you are asking what the return value is in the comparison function.

If the dates are equal then returning NSOrderedSame

If ascending ( 2nd arg > 1st arg ) return NSOrderedAscending

If descending ( 2nd arg < 1st arg ) return NSOrderedDescending

How do I get the current date in Cocoa

You have problems with iOS 4.2? Use this Code:

NSDate *currDate = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"dd.MM.YY HH:mm:ss"];
NSString *dateString = [dateFormatter stringFromDate:currDate];
NSLog(@"%@",dateString);

-->20.01.2011 10:36:02

Get day of week using NSDate

Swift 3 Date extension

extension Date {
    var weekdayOrdinal: Int {
        return Calendar.current.component(.weekday, from: self)
    }
}

Get current date in Swift 3?

You can do it in this way with Swift 3.0:

let date = Date()
let calendar = Calendar.current
let components = calendar.dateComponents([.year, .month, .day], from: date)

let year =  components.year
let month = components.month
let day = components.day

print(year)
print(month)
print(day)

How can I convert string date to NSDate?

Swift 4

import Foundation

let dateString = "2014-07-15" // change to your date format

var dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"

let date = dateFormatter.date(from: dateString)
println(date)

Swift 3

import Foundation

var dateString = "2014-07-15" // change to your date format

var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"

var date = dateFormatter.dateFromString(dateString)
println(date)

I can do it with this code.

How can I calculate the difference between two dates?

NSDate *date1 = [NSDate dateWithString:@"2010-01-01 00:00:00 +0000"];
NSDate *date2 = [NSDate dateWithString:@"2010-02-03 00:00:00 +0000"];

NSTimeInterval secondsBetween = [date2 timeIntervalSinceDate:date1];

int numberOfDays = secondsBetween / 86400;

NSLog(@"There are %d days in between the two dates.", numberOfDays);

EDIT:

Remember, NSDate objects represent exact moments of time, they do not have any associated time-zone information. When you convert a string to a date using e.g. an NSDateFormatter, the NSDateFormatter converts the time from the configured timezone. Therefore, the number of seconds between two NSDate objects will always be time-zone-agnostic.

Furthermore, this documentation specifies that Cocoa's implementation of time does not account for leap seconds, so if you require such accuracy, you will need to roll your own implementation.

get current date from [NSDate date] but set the time to 10:00 am

You can use this method for any minute / hour / period (aka am/pm) combination:

- (NSDate *)todayModifiedWithHours:(NSString *)hours
                           minutes:(NSString *)minutes
                         andPeriod:(NSString *)period
{
    NSDate *todayModified = NSDate.date;

    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

    NSDateComponents *components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit|NSMinuteCalendarUnit fromDate:todayModified];

    [components setMinute:minutes.intValue];

    int hour = 0;

    if ([period.uppercaseString isEqualToString:@"AM"]) {

        if (hours.intValue == 12) {
            hour = 0;
        }
        else {
            hour = hours.intValue;
        }
    }
    else if ([period.uppercaseString isEqualToString:@"PM"]) {

        if (hours.intValue != 12) {
            hour = hours.intValue + 12;
        }
        else {
            hour = 12;
        }
    }
    [components setHour:hour];

    todayModified = [calendar dateFromComponents:components];

    return todayModified;
}

Requested Example:

NSDate *todayAt10AM = [self todayModifiedWithHours:@"10"
                                           minutes:@"00"
                                         andPeriod:@"am"];

Is there an easy way to return a string repeated X number of times?

Another approach is to consider string as IEnumerable<char> and have a generic extension method which will multiply the items in a collection by the specified factor.

public static IEnumerable<T> Repeat<T>(this IEnumerable<T> source, int times)
{
    source = source.ToArray();
    return Enumerable.Range(0, times).SelectMany(_ => source);
}

So in your case:

string indent = "---";
var f = string.Concat(indent.Repeat(0)); //.NET 4 required
//or
var g = new string(indent.Repeat(5).ToArray());

Hibernate Auto Increment ID

In case anyone "bumps" in this SO question in search for strategies for Informix table when PK is type Serial.

I have found that this works...as an example.

@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name = "special_serial_pk")
private Integer special_serial_pk;

For this to work make sure when you do session.SaveOrUpdate you pass the value for the column special_serial_pk NULL .

In my case i do an HTML POST with JSON like so...

{
"special_serial_pk": null, //<-- Field to be incremented
"specialcolumn1": 1,
"specialcolumn2": "I love to code",
"specialcolumn3": true
}

update to python 3.7 using anaconda

This can be installed via conda with the command conda install -c anaconda python=3.7 as per https://anaconda.org/anaconda/python.

Though not all packages support 3.7 yet, running conda update --all may resolve some dependency failures.

PostgreSQL naming conventions

Regarding tables names, case, etc, the prevalent convention is:

  • SQL keywords: UPPER CASE
  • names (identifiers): lower_case_with_underscores

For example:

UPDATE my_table SET name = 5;

This is not written in stone, but the bit about identifiers in lower case is highly recommended, IMO. Postgresql treats identifiers case insensitively when not quoted (it actually folds them to lowercase internally), and case sensitively when quoted; many people are not aware of this idiosyncrasy. Using always lowercase you are safe. Anyway, it's acceptable to use camelCase or PascalCase (or UPPER_CASE), as long as you are consistent: either quote identifiers always or never (and this includes the schema creation!).

I am not aware of many more conventions or style guides. Surrogate keys are normally made from a sequence (usually with the serial macro), it would be convenient to stick to that naming for those sequences if you create them by hand (tablename_colname_seq).

See also some discussion here, here and (for general SQL) here, all with several related links.

Note: Postgresql 10 introduced identity columns as an SQL-compliant replacement for serial.

Meaning of 'const' last in a function declaration of a class?

I would like to add the following point.

You can also make it a const & and const &&

So,

struct s{
    void val1() const {
     // *this is const here. Hence this function cannot modify any member of *this
    }
    void val2() const & {
    // *this is const& here
    }
    void val3() const && {
    // The object calling this function should be const rvalue only.
    }
    void val4() && {
    // The object calling this function should be rvalue reference only.
    }

};

int main(){
  s a;
  a.val1(); //okay
  a.val2(); //okay
  // a.val3() not okay, a is not rvalue will be okay if called like
  std::move(a).val3(); // okay, move makes it a rvalue
}

Feel free to improve the answer. I am no expert

Is there a command line utility for rendering GitHub flavored Markdown?

I use Pandoc with the option --from=gfm for GitHub Flavored Markdown like this:

$ pandoc my_file.md   --from=gfm -t html -o my_file.html

How to avoid reverse engineering of an APK file?

Here are few methods you can try:

  1. Use obfuscation and tools like ProGuard.
  2. Encrypt some part of source and data.
  3. Use a proprietary inbuilt checksum in the app to detect tampering.
  4. Introduce code to avoid loading in a debugger, that is, let the app have the ability to detect the debugger and exit / kill the debugger.
  5. Separate the authentication as an online service.
  6. Use application diversity
  7. Use the finger printing technique for e.g., hardware signatures of the devices from different subsystem before authenticating the device.

java.util.Date format SSSSSS: if not microseconds what are the last 3 digits?

SSSSSS is microseconds. Let us say the time is 10:30:22 (Seconds 22) and 10:30:22.1 would be 22 seconds and 1/10 of a second . Extending the same logic , 10:32.22.000132 would be 22 seconds and 132/1,000,000 of a second, which is nothing but microseconds.

How to check that an element is in a std::set?

I was able to write a general contains function for std::list and std::vector,

template<typename T>
bool contains( const list<T>& container, const T& elt )
{
  return find( container.begin(), container.end(), elt ) != container.end() ;
}

template<typename T>
bool contains( const vector<T>& container, const T& elt )
{
  return find( container.begin(), container.end(), elt ) != container.end() ;
}

// use:
if( contains( yourList, itemInList ) ) // then do something

This cleans up the syntax a bit.

But I could not use template template parameter magic to make this work arbitrary stl containers.

// NOT WORKING:
template<template<class> class STLContainer, class T>
bool contains( STLContainer<T> container, T elt )
{
  return find( container.begin(), container.end(), elt ) != container.end() ;
}

Any comments about improving the last answer would be nice.

Sum all values in every column of a data.frame in R

You can use function colSums() to calculate sum of all values. [,-1] ensures that first column with names of people is excluded.

 colSums(people[,-1])
Height Weight 
   199    425

Assuming there could be multiple columns that are not numeric, or that your column order is not fixed, a more general approach would be:

colSums(Filter(is.numeric, people))

Getting the text from a drop-down box

Here is an easy and short method

document.getElementById('elementID').selectedOptions[0].innerHTML

'Must Override a Superclass Method' Errors after importing a project into Eclipse

This is my second time encounter this problem. first time according the alphazero's recommendation it worked. but in the second time I set to 1.6 it don't work it just like 'CACHE' this error after clean and rebuild.

Try to switch off 'Build Automatically' as Rollin_s said -> error still here!

So I removed the problem project (already set to 1.6) from Package Explorer and import it again -> it start a rebuild and no error this time

Hope this help someone

Getting rid of \n when using .readlines()

I had the same problem and i found the following solution to be very efficient. I hope that it will help you or everyone else who wants to do the same thing.

First of all, i would start with a "with" statement as it ensures the proper open/close of the file.

It should look something like this:

with open("filename.txt", "r+") as f:
    contents = [x.strip() for x in f.readlines()]

If you want to convert those strings (every item in the contents list is a string) in integer or float you can do the following:

contents = [float(contents[i]) for i in range(len(contents))]

Use int instead of float if you want to convert to integer.

It's my first answer in SO, so sorry if it's not in the proper formatting.

python 3.x ImportError: No module named 'cStringIO'

From Python 3.0 changelog;

The StringIO and cStringIO modules are gone. Instead, import the io module and use io.StringIO or io.BytesIO for text and data respectively.

From the Python 3 email documentation it can be seen that io.StringIO should be used instead:

from io import StringIO
from email.generator import Generator
fp = StringIO()
g = Generator(fp, mangle_from_=True, maxheaderlen=60)
g.flatten(msg)
text = fp.getvalue()

Reference: https://docs.python.org/3/library/io.html

How to add label in chart.js for pie chart

EDIT: http://jsfiddle.net/nCFGL/223/ My Example.

You should be able to like follows:

var pieData = [{
    value: 30,
    color: "#F38630",
    label: 'Sleep',
    labelColor: 'white',
    labelFontSize: '16'
  },
  ...
];

Include the Chart.js located at:

https://github.com/nnnick/Chart.js/pull/35

Flatten List in LINQ

Try SelectMany()

var result = iList.SelectMany( i => i );

PyCharm error: 'No Module' when trying to import own module (python script)

Content roots are folders holding your project code while source roots are defined as same too. The only difference i came to understand was that the code in source roots is built before the code in the content root.

Unchecking them wouldn't affect the runtime till the point you're not making separate modules in your package which are manually connected to Django. That means if any of your files do not hold the 'from django import...' or any of the function isn't called via django, unchecking these 2 options will result in a malfunction.

Update - the problem only arises when using Virtual Environmanet, and only when controlling the project via the provided terminal. Cause the terminal still works via the default system pyhtonpath and not the virtual env. while the python django control panel works fine.

Creating a List of Lists in C#

A quick example:

List<List<string>> myList = new List<List<string>>();
myList.Add(new List<string> { "a", "b" });
myList.Add(new List<string> { "c", "d", "e" });
myList.Add(new List<string> { "qwerty", "asdf", "zxcv" });
myList.Add(new List<string> { "a", "b" });

// To iterate over it.
foreach (List<string> subList in myList)
{
    foreach (string item in subList)
    {
        Console.WriteLine(item);
    }
}

Is that what you were looking for? Or are you trying to create a new class that extends List<T> that has a member that is a `List'?

add an onclick event to a div

Everythings works well. You can't use divtag.onclick, becease "onclick" attribute doesn't exist. You need first create this attribute by using .setAttribute(). Look on this http://reference.sitepoint.com/javascript/Element/setAttribute . You should read documentations first before you start giving "-".

Search of table names

Adding on to @[RichardTheKiwi]'s answer.

Whenever I search for a list of tables, in general I want to select from all of them or delete them. Below is a script that generates those scripts for you.

The generated select script also adds a tableName column so you know what table you're looking at:

select 'select ''' + name + ''' as TableName, * from ' + name as SelectTable,
'delete from ' + name as DeleteTable
from sys.tables
where name like '%xxxx%'
and is_ms_shipped = 0; 

How to order by with union in SQL?

Add a column to the query which can sub identify the data to sort on that.

In the below example I use a Common Table Expression with the selects you showed which places them in specific groups in the CTE, and then do a union off of both of those groups into AllStudents.

The final select will then sort AllStudents by the SortIndex column first and then by the name such as:

WITH Juveniles as
(
      Select 1 as [SortIndex], id,name,age From Student
      Where age < 15
),

AStudents as
(
      Select 2 as [SortIndex], id,name,age From Student
      Where Name like "%a%" 
),

AllStudents as
(
      select * from Juveniles
      union 
      select * from AStudents
)

select * from AllStudents
sort by [SortIndex], name;

To summarize, it will get all the students which will be sorted by group first, and subsorted by the name within the group after that.

Capture keyboardinterrupt in Python without try-except

You can prevent printing a stack trace for KeyboardInterrupt, without try: ... except KeyboardInterrupt: pass (the most obvious and propably "best" solution, but you already know it and asked for something else) by replacing sys.excepthook. Something like

def custom_excepthook(type, value, traceback):
    if type is KeyboardInterrupt:
        return # do nothing
    else:
        sys.__excepthook__(type, value, traceback)

How do you change the character encoding of a postgres database?

# dump into file
pg_dump myDB > /tmp/myDB.sql

# create an empty db with the right encoding (on older versions the escaped single quotes are needed!)
psql -c 'CREATE DATABASE "tempDB" WITH OWNER = "myself" LC_COLLATE = '\''de_DE.utf8'\'' TEMPLATE template0;'

# import in the new DB
psql -d tempDB -1 -f /tmp/myDB.sql

# rename databases
psql -c 'ALTER DATABASE "myDB" RENAME TO "myDB_wrong_encoding";' 
psql -c 'ALTER DATABASE "tempDB" RENAME TO "myDB";'

# see the result
psql myDB -c "SHOW LC_COLLATE"   

Python error message io.UnsupportedOperation: not readable

This will let you read, write and create the file if it don't exist:

f = open('filename.txt','a+')
f = open('filename.txt','r+')

Often used commands:

f.readline() #Read next line
f.seek(0) #Jump to beginning
f.read(0) #Read all file
f.write('test text') #Write 'test text' to file
f.close() #Close file

How to run a .jar in mac?

You don't need JDK to run Java based programs. JDK is for development which stands for Java Development Kit.

You need JRE which should be there in Mac.

Try: java -jar Myjar_file.jar

EDIT: According to this article, for Mac OS 10

The Java runtime is no longer installed automatically as part of the OS installation.

Then, you need to install JRE to your machine.

How do I add 1 day to an NSDate?

Swift 4, if all you really need is a 24 hour shift (60*60*24 seconds) and not "1 calendar day"

Future: let dayAhead = Date(timeIntervalSinceNow: TimeInterval(86400.0))

Past: let dayAgo = Date(timeIntervalSinceNow: TimeInterval(-86400.0))

How do you debug PHP scripts?

I use Netbeans with XDebug and the Easy XDebug FireFox Add-on

The add-on is essential when you debug MVC projects, because the normal way XDebug runs in Netbeans is to register the dbug session via the url. With the add-on installed in FireFox, you would set your Netbeans project properties -> Run Configuratuion -> Advanced and select "Do Not Open Web Browser" You can now set your break points and start the debugging session with Ctrl-F5 as usual. Open FireFox and right-click the Add-on icon in the right bottom corner to start monitoring for breakpoints. When the code reaches the breakpoint it will stop and you can inspect your variable states and call-stack.

mssql convert varchar to float

You can convert varchars to floats, and you can do it in the manner you have expressed. Your varchar must not be a numeric value. There must be something else in it. You can use IsNumeric to test it. See this:

declare @thing varchar(100)

select @thing = '122.332'

--This returns 1 since it is numeric.
select isnumeric(@thing)

--This converts just fine.
select convert(float,@thing)

select @thing = '122.332.'

--This returns 0 since it is not numeric.
select isnumeric(@thing)

--This convert throws.
select convert(float,@thing)

ElasticSearch, Sphinx, Lucene, Solr, Xapian. Which fits for which usage?

The only elasticsearch vs solr performance comparison I've been able to find so far is here:

Solr vs elasticsearch Deathmatch!

How to select all checkboxes with jQuery?

Top answer will not work in Jquery 1.9+ because of attr() method. Use prop() instead:

$(function() {
    $('#select_all').change(function(){
        var checkboxes = $(this).closest('form').find(':checkbox');
        if($(this).prop('checked')) {
          checkboxes.prop('checked', true);
        } else {
          checkboxes.prop('checked', false);
        }
    });
});

How to retrieve data from a SQL Server database in C#?

 public Person SomeMethod(string fName)
        {
            var con = ConfigurationManager.ConnectionStrings["Yourconnection"].ToString();

            Person matchingPerson = new Person();
            using (SqlConnection myConnection = new SqlConnection(con))
            {
                string oString = "Select * from Employees where FirstName=@fName";
                SqlCommand oCmd = new SqlCommand(oString, myConnection);
                oCmd.Parameters.AddWithValue("@Fname", fName);           
                myConnection.Open();
                using (SqlDataReader oReader = oCmd.ExecuteReader())
                {
                    while (oReader.Read())
                    {    
                        matchingPerson.firstName = oReader["FirstName"].ToString();
                        matchingPerson.lastName = oReader["LastName"].ToString();                       
                    }

                    myConnection.Close();
                }               
            }
            return matchingPerson;
        }

Few things to note here: I used a parametrized query, which makes your code safer. The way you are making the select statement with the "where x = "+ Textbox.Text +"" part opens you up to SQL injection.

I've changed this to:

  "Select * from Employees where FirstName=@fName"
  oCmd.Parameters.AddWithValue("@fname", fName);  

So what this block of code is going to do is:

Execute an SQL statement against your database, to see if any there are any firstnames matching the one you provided. If that is the case, that person will be stored in a Person object (see below in my answer for the class). If there is no match, the properties of the Person object will be null.

Obviously I don't exactly know what you are trying to do, so there's a few things to pay attention to: When there are more then 1 persons with a matching name, only the last one will be saved and returned to you. If you want to be able to store this data, you can add them to a List<Person> .

Person class to make it cleaner:

 public class Person
    {
            public string firstName { get; set; }
            public string lastName { get; set; }
    }

Now to call the method:

Person x = SomeMethod("John");

You can then fill your textboxes with values coming from the Person object like so:

txtLastName.Text = x.LastName;

What is the best way to dump entire objects to a log in C#?

You could use Visual Studio Immediate Window

Just paste this (change actual to your object name obviously):

Newtonsoft.Json.JsonConvert.SerializeObject(actual);

It should print object in JSON enter image description here

You should be able to copy it over textmechanic text tool or notepad++ and replace escaped quotes (\") with " and newlines (\r\n) with empty space, then remove double quotes (") from beginning and end and paste it to jsbeautifier to make it more readable.

UPDATE to OP's comment

public static class Dumper
{
    public static void Dump(this object obj)
    {
        Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(obj)); // your logger
    }
}

this should allow you to dump any object.

Hope this saves you some time.

Jquery get form field value

var textValue = $("input[type=text]").val()

this will get all values of all text boxes. You can use methods like children, firstchild, etc to hone in. Like by form $('form[name=form1] input[type=text]') Easier to use IDs for targeting elements but if it's purely dynamic you can get all input values then loop through then with JS.

How do I convert csv file to rdd

I think you can try to load that csv into a RDD and then create a dataframe from that RDD, here is the document of creating dataframe from rdd:http://spark.apache.org/docs/latest/sql-programming-guide.html#interoperating-with-rdds

How to change color of the back arrow in the new material theme?

I found a solution that works pre Lollipop. Set the "colorControlNormal" within the "actionBarWidgetTheme" to change the homeAsUpIndicator color. Modifying rockgecko's answer from above to look like this:

<style name="MyTheme" parent="Theme.AppCompat.Light">        
    <item name="actionBarTheme">@style/MyApp.ActionBarTheme</item>
    <item name="actionBarStyle">@style/MyApp.ActionBar</item>
    <!-- color for widget theming, eg EditText. Doesn't effect ActionBar. -->
    <item name="colorControlNormal">@color/my_awesome_color</item>
    <!-- The animated arrow style -->
    <item name="drawerArrowStyle">@style/DrawerArrowStyle</item>
    <!-- The style for the widgets on the ActionBar. -->
    <item name="actionBarWidgetTheme">@style/WidgetStyle</item>
</style>

<style name="WidgetStyle" parent="style/ThemeOverlay.AppCompat.Light">
    <item name="colorControlNormal">@color/my_awesome_color</item>
</style>

How to customize the background/border colors of a grouped table view cell?

UPDATE: In iPhone OS 3.0 and later UITableViewCell now has a backgroundColor property that makes this really easy (especially in combination with the [UIColor colorWithPatternImage:] initializer). But I'll leave the 2.0 version of the answer here for anyone that needs it…


It's harder than it really should be. Here's how I did this when I had to do it:

You need to set the UITableViewCell's backgroundView property to a custom UIView that draws the border and background itself in the appropriate colors. This view needs to be able to draw the borders in 4 different modes, rounded on the top for the first cell in a section, rounded on the bottom for the last cell in a section, no rounded corners for cells in the middle of a section, and rounded on all 4 corners for sections that contain one cell.

Unfortunately I couldn't figure out how to have this mode set automatically, so I had to set it in the UITableViewDataSource's -cellForRowAtIndexPath method.

It's a real PITA but I've confirmed with Apple engineers that this is currently the only way.

Update Here's the code for that custom bg view. There's a drawing bug that makes the rounded corners look a little funny, but we moved to a different design and scrapped the custom backgrounds before I had a chance to fix it. Still this will probably be very helpful for you:

//
//  CustomCellBackgroundView.h
//
//  Created by Mike Akers on 11/21/08.
//  Copyright 2008 __MyCompanyName__. All rights reserved.
//

#import <UIKit/UIKit.h>

typedef enum  {
    CustomCellBackgroundViewPositionTop, 
    CustomCellBackgroundViewPositionMiddle, 
    CustomCellBackgroundViewPositionBottom,
    CustomCellBackgroundViewPositionSingle
} CustomCellBackgroundViewPosition;

@interface CustomCellBackgroundView : UIView {
    UIColor *borderColor;
    UIColor *fillColor;
    CustomCellBackgroundViewPosition position;
}

    @property(nonatomic, retain) UIColor *borderColor, *fillColor;
    @property(nonatomic) CustomCellBackgroundViewPosition position;
@end

//
//  CustomCellBackgroundView.m
//
//  Created by Mike Akers on 11/21/08.
//  Copyright 2008 __MyCompanyName__. All rights reserved.
//

#import "CustomCellBackgroundView.h"

static void addRoundedRectToPath(CGContextRef context, CGRect rect,
                                 float ovalWidth,float ovalHeight);

@implementation CustomCellBackgroundView
@synthesize borderColor, fillColor, position;

- (BOOL) isOpaque {
    return NO;
}

- (id)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        // Initialization code
    }
    return self;
}

- (void)drawRect:(CGRect)rect {
    // Drawing code
    CGContextRef c = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(c, [fillColor CGColor]);
    CGContextSetStrokeColorWithColor(c, [borderColor CGColor]);

    if (position == CustomCellBackgroundViewPositionTop) {
        CGContextFillRect(c, CGRectMake(0.0f, rect.size.height - 10.0f, rect.size.width, 10.0f));
        CGContextBeginPath(c);
        CGContextMoveToPoint(c, 0.0f, rect.size.height - 10.0f);
        CGContextAddLineToPoint(c, 0.0f, rect.size.height);
        CGContextAddLineToPoint(c, rect.size.width, rect.size.height);
        CGContextAddLineToPoint(c, rect.size.width, rect.size.height - 10.0f);
        CGContextStrokePath(c);
        CGContextClipToRect(c, CGRectMake(0.0f, 0.0f, rect.size.width, rect.size.height - 10.0f));
    } else if (position == CustomCellBackgroundViewPositionBottom) {
        CGContextFillRect(c, CGRectMake(0.0f, 0.0f, rect.size.width, 10.0f));
        CGContextBeginPath(c);
        CGContextMoveToPoint(c, 0.0f, 10.0f);
        CGContextAddLineToPoint(c, 0.0f, 0.0f);
        CGContextStrokePath(c);
        CGContextBeginPath(c);
        CGContextMoveToPoint(c, rect.size.width, 0.0f);
        CGContextAddLineToPoint(c, rect.size.width, 10.0f);
        CGContextStrokePath(c);
        CGContextClipToRect(c, CGRectMake(0.0f, 10.0f, rect.size.width, rect.size.height));
    } else if (position == CustomCellBackgroundViewPositionMiddle) {
        CGContextFillRect(c, rect);
        CGContextBeginPath(c);
        CGContextMoveToPoint(c, 0.0f, 0.0f);
        CGContextAddLineToPoint(c, 0.0f, rect.size.height);
        CGContextAddLineToPoint(c, rect.size.width, rect.size.height);
        CGContextAddLineToPoint(c, rect.size.width, 0.0f);
        CGContextStrokePath(c);
        return; // no need to bother drawing rounded corners, so we return
    }

    // At this point the clip rect is set to only draw the appropriate
    // corners, so we fill and stroke a rounded rect taking the entire rect

    CGContextBeginPath(c);
    addRoundedRectToPath(c, rect, 10.0f, 10.0f);
    CGContextFillPath(c);  

    CGContextSetLineWidth(c, 1);  
    CGContextBeginPath(c);
    addRoundedRectToPath(c, rect, 10.0f, 10.0f);  
    CGContextStrokePath(c); 
}


- (void)dealloc {
    [borderColor release];
    [fillColor release];
    [super dealloc];
}


@end

static void addRoundedRectToPath(CGContextRef context, CGRect rect,
                                float ovalWidth,float ovalHeight)

{
    float fw, fh;

    if (ovalWidth == 0 || ovalHeight == 0) {// 1
        CGContextAddRect(context, rect);
        return;
    }

    CGContextSaveGState(context);// 2

    CGContextTranslateCTM (context, CGRectGetMinX(rect),// 3
                           CGRectGetMinY(rect));
    CGContextScaleCTM (context, ovalWidth, ovalHeight);// 4
    fw = CGRectGetWidth (rect) / ovalWidth;// 5
    fh = CGRectGetHeight (rect) / ovalHeight;// 6

    CGContextMoveToPoint(context, fw, fh/2); // 7
    CGContextAddArcToPoint(context, fw, fh, fw/2, fh, 1);// 8
    CGContextAddArcToPoint(context, 0, fh, 0, fh/2, 1);// 9
    CGContextAddArcToPoint(context, 0, 0, fw/2, 0, 1);// 10
    CGContextAddArcToPoint(context, fw, 0, fw, fh/2, 1); // 11
    CGContextClosePath(context);// 12

    CGContextRestoreGState(context);// 13
}

Get drop down value

Like this:

$dd = document.getElementById("yourselectelementid");
$so = $dd.options[$dd.selectedIndex];

How to pass command line arguments to a rake task

If you can't be bothered to remember what argument position is for what and you want do something like a ruby argument hash. You can use one argument to pass in a string and then regex that string into an options hash.

namespace :dummy_data do
  desc "Tests options hash like arguments"
  task :test, [:options] => :environment do |t, args|
    arg_options = args[:options] || '' # nil catch incase no options are provided
    two_d_array = arg_options.scan(/\W*(\w*): (\w*)\W*/)
    puts two_d_array.to_s + ' # options are regexed into a 2d array'
    string_key_hash = two_d_array.to_h
    puts string_key_hash.to_s + ' # options are in a hash with keys as strings'
    options = two_d_array.map {|p| [p[0].to_sym, p[1]]}.to_h
    puts options.to_s + ' # options are in a hash with symbols'
    default_options = {users: '50', friends: '25', colour: 'red', name: 'tom'}
    options = default_options.merge(options)
    puts options.to_s + ' # default option values are merged into options'
  end
end

And on the command line you get.

$ rake dummy_data:test["users: 100 friends: 50 colour: red"]
[["users", "100"], ["friends", "50"], ["colour", "red"]] # options are regexed into a 2d array
{"users"=>"100", "friends"=>"50", "colour"=>"red"} # options are in a hash with keys as strings
{:users=>"100", :friends=>"50", :colour=>"red"} # options are in a hash with symbols
{:users=>"100", :friends=>"50", :colour=>"red", :name=>"tom"} # default option values are merged into options

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

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

Response.Redirect
Cookies
Application Variables
HttpContext

Response.Redirect

SET :

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

GET :

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

Cookies

SET :

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

GET :

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

Application Variables

SET :

Application["Name"] = "pandian";

GET :

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

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

getting a checkbox array value from POST

// if you do the input like this
<input id="'.$userid.'" value="'.$userid.'"  name="invite['.$userid.']" type="checkbox">

// you can access the value directly like this:
$invite = $_POST['invite'][$userid];

how to list all sub directories in a directory

FolderBrowserDialog fbd = new FolderBrowserDialog();

        DialogResult result = fbd.ShowDialog();

        string[] files = Directory.GetFiles(fbd.SelectedPath);
        string[] dirs = Directory.GetDirectories(fbd.SelectedPath);

        foreach (string item2 in dirs)
        {
            FileInfo f = new FileInfo(item2);

            listBox1.Items.Add(f.Name);

        }

        foreach (string item in files)
        {
            FileInfo f = new FileInfo(item);

            listBox1.Items.Add(f.Name);

        }

Try-catch speeding up my code?

9 years later and the bug is still there! You can see it easily with:

   static void Main( string[] args )
    {
      int hundredMillion = 1000000;
      DateTime start = DateTime.Now;
      double sqrt;
      for (int i=0; i < hundredMillion; i++)
      {
        sqrt = Math.Sqrt( DateTime.Now.ToOADate() );
      }
      DateTime end = DateTime.Now;

      double sqrtMs = (end - start).TotalMilliseconds;

      Console.WriteLine( "Elapsed milliseconds: " + sqrtMs );

      DateTime start2 = DateTime.Now;

      double sqrt2;
      for (int i = 0; i < hundredMillion; i++)
      {
        try
        {
          sqrt2 = Math.Sqrt( DateTime.Now.ToOADate() );
        }
        catch (Exception e)
        {
          int br = 0;
        }
      }
      DateTime end2 = DateTime.Now;

      double sqrtMsTryCatch = (end2 - start2).TotalMilliseconds;

      Console.WriteLine( "Elapsed milliseconds: " + sqrtMsTryCatch );

      Console.WriteLine( "ratio is " + sqrtMsTryCatch / sqrtMs );

      Console.ReadLine();
    }

The ratio is less than one on my machine, running the latest version of MSVS 2019, .NET 4.6.1

WARNING: Can't verify CSRF token authenticity rails

I struggled with this issue for days. Any GET call was working correctly, but all PUTs would generate a "Can't verify CSRF token authenticity" error. My website was working fine until I had added a SSL cert to nginx.

I finally stumbled on this missing line in my nginx settings:

location @puma { 
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 
    proxy_set_header Host $http_host; 
    proxy_redirect off;
    proxy_set_header X-Forwarded-Proto https;   # Needed to avoid 'WARNING: Can't verify CSRF token authenticity'
    proxy_pass http://puma; 
}

After adding the missing line "proxy_set_header X-Forwarded-Proto https;", all my CSRF token errors quit.

Hopefully this helps someone else who also is beating their head against a wall. haha

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

Whenever I've had this particular error come up, it's turned out that the folder that Visual Studio is loading assemblies from is different from the folder the web-application is running from.

That is, the application server is running the application from

C:\dev\MyApplication\bin 

but Visual studio is debugging from

C:\dev\MyOtherApplication\bin (or something along those lines, anyway).

Note - for various reasons, I do my debugging with IIS as the application host instead of the dinky standalone gizmo that most people use. This could influence the usefulness of my answer!

Update:

For IIS the application server directory (i.e. C:\dev\MyApplication above) is the physical directory configured for the web application - this can be controlled by changing basic settings for the app.

For Visual studio the debugging directory (i.e. C:\dev\MyOtherApplication above) is the directory in which your svc files are found, usually the same directory as your csproj project file.

Preloading images with jQuery

Use JavaScript Image object.

This function allows you to trigger a callback upon loading all pictures. However, note that it will never trigger a callback if at least one resource is not loaded. This can be easily fixed by implementing onerror callback and incrementing loaded value or handling the error.

var preloadPictures = function(pictureUrls, callback) {
    var i,
        j,
        loaded = 0;

    for (i = 0, j = pictureUrls.length; i < j; i++) {
        (function (img, src) {
            img.onload = function () {                               
                if (++loaded == pictureUrls.length && callback) {
                    callback();
                }
            };

            // Use the following callback methods to debug
            // in case of an unexpected behavior.
            img.onerror = function () {};
            img.onabort = function () {};

            img.src = src;
        } (new Image(), pictureUrls[i]));
    }
};

preloadPictures(['http://foo/picture.bar', 'http://foo/picture.bar', 'http://foo/picture.bar', 'http://foo/picture.bar'], function(){
    console.log('a');
});

preloadPictures(['http://foo/picture.bar', 'http://foo/picture.bar', 'http://foo/picture.bar', 'http://foo/picture.bar'], function(){
    console.log('b');
});

How to change the button text for 'Yes' and 'No' buttons in the MessageBox.Show dialog?

I didn't think it would be that simple! go to this link: https://www.codeproject.com/Articles/18399/Localizing-System-MessageBox

Download the source. Take the MessageBoxManager.cs file, add it to your project. Now just register it once in your code (for example in the Main() method inside your Program.cs file) and it will work every time you call MessageBox.Show():

    MessageBoxManager.OK = "Alright";
    MessageBoxManager.Yes = "Yep!";
    MessageBoxManager.No = "Nope";
    MessageBoxManager.Register();

See this answer for the source code here for MessageBoxManager.cs.

How to make layout with View fill the remaining space?

When using a relative layout, you can make a view stretch by anchoring it to both of the views it's supposed to stretch toward. Although the specified height will be disregarded, Android still requires a height attribute, which is why I wrote "0dp". Example:

<View
    android:id="@+id/topView"
    android:layout_width="match_parent"
    android:layout_height="40dp"
    android:layout_alignParentTop="true"
    android:layout_marginTop="8dp"/>

<View
    android:id="@+id/stretchableView"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_below="@id/topView"
    android:layout_above="@+id/bottomView"
    android:layout_marginTop="8dp"
    android:layout_marginBottom="8dp"
    android:adjustViewBounds="true"/>

<View
    android:id="@id/bottomView"
    android:layout_width="wrap_content"
    android:layout_height="40dp"
    android:layout_alignParentBottom="true"
    android:layout_marginBottom="16dp"/>

JOptionPane YES/No Options Confirm Dialog Box Issue

int opcion = JOptionPane.showConfirmDialog(null, "Realmente deseas salir?", "Aviso", JOptionPane.YES_NO_OPTION);

if (opcion == 0) { //The ISSUE is here
   System.out.print("si");
} else {
   System.out.print("no");
}

How to find longest string in the table column data

You can get it like this:

SELECT TOP 1 CR
FROM tbl
ORDER BY len(CR) DESC

but i'm sure, there is a more elegant way to do it

SQLite error 'attempt to write a readonly database' during insert?

I used:

echo exec('whoami');

to find out who is running the script (say username), and then gave the user permissions to the entire application directory, like:

sudo chown -R :username /var/www/html/myapp

Hope this helps someone out there.

change type of input field with jQuery

Here is a little snippet that allows you to change the type of elements in documents.

jquery.type.js (GitHub Gist):

var rtype = /^(?:button|input)$/i;

jQuery.attrHooks.type.set = function(elem, value) {
    // We can't allow the type property to be changed (since it causes problems in IE)
    if (rtype.test(elem.nodeName) && elem.parentNode) {
        // jQuery.error( "type property can't be changed" );

        // JB: Or ... can it!?
        var $el = $(elem);
        var insertionFn = 'after';
        var $insertionPoint = $el.prev();
        if (!$insertionPoint.length) {
            insertionFn = 'prepend';
            $insertionPoint = $el.parent();
        }

        $el.detach().attr('type', value);
        $insertionPoint[insertionFn]($el);
        return value;

    } else if (!jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input")) {
        // Setting the type on a radio button after the value resets the value in IE6-9
        // Reset value to it's default in case type is set after value
        // This is for element creation
        var val = elem.value;
        elem.setAttribute("type", value);
        if (val) {
            elem.value = val;
        }
        return value;
    }
}

It gets around the issue by removing the input from the document, changing the type and then putting it back where it was originally.

Note that this snippet was only tested for WebKit browsers – no guarantees on anything else!

Visual Studio keyboard shortcut to automatically add the needed 'using' statement

It's ctrl + . when, for example, you try to type List you need to type < at the end and press ctrl + . for it to work.

Where can I find php.ini?

Run this in the command line:

php -r "echo php_ini_loaded_file().PHP_EOL;"

Change image in HTML page every few seconds

below will change link and banner every 10 seconds

   <script>
        var links = ["http://www.abc.com","http://www.def.com","http://www.ghi.com"];
        var images = ["http://www.abc.com/1.gif","http://www.def.com/2.gif","http://www.ghi.com/3gif"];
        var i = 0;
        var renew = setInterval(function(){
            if(links.length == i){
                i = 0;
            }
            else {
            document.getElementById("bannerImage").src = images[i]; 
            document.getElementById("bannerLink").href = links[i]; 
            i++;

        }
        },10000);
        </script>



<a id="bannerLink" href="http://www.abc.com" onclick="void window.open(this.href); return false;">
<img id="bannerImage" src="http://www.abc.com/1.gif" width="694" height="83" alt="some text">
</a>

Change line width of lines in matplotlib pyplot legend

@ImportanceOfBeingErnest 's answer is good if you only want to change the linewidth inside the legend box. But I think it is a bit more complex since you have to copy the handles before changing legend linewidth. Besides, it can not change the legend label fontsize. The following two methods can not only change the linewidth but also the legend label text font size in a more concise way.

Method 1

import numpy as np
import matplotlib.pyplot as plt

# make some data
x = np.linspace(0, 2*np.pi)

y1 = np.sin(x)
y2 = np.cos(x)

# plot sin(x) and cos(x)
fig = plt.figure()
ax  = fig.add_subplot(111)
ax.plot(x, y1, c='b', label='y1')
ax.plot(x, y2, c='r', label='y2')

leg = plt.legend()
# get the individual lines inside legend and set line width
for line in leg.get_lines():
    line.set_linewidth(4)
# get label texts inside legend and set font size
for text in leg.get_texts():
    text.set_fontsize('x-large')

plt.savefig('leg_example')
plt.show()

Method 2

import numpy as np
import matplotlib.pyplot as plt

# make some data
x = np.linspace(0, 2*np.pi)

y1 = np.sin(x)
y2 = np.cos(x)

# plot sin(x) and cos(x)
fig = plt.figure()
ax  = fig.add_subplot(111)
ax.plot(x, y1, c='b', label='y1')
ax.plot(x, y2, c='r', label='y2')

leg = plt.legend()
# get the lines and texts inside legend box
leg_lines = leg.get_lines()
leg_texts = leg.get_texts()
# bulk-set the properties of all lines and texts
plt.setp(leg_lines, linewidth=4)
plt.setp(leg_texts, fontsize='x-large')
plt.savefig('leg_example')
plt.show()

The above two methods produce the same output image:

output image

Using Exit button to close a winform program

this.Close();

Closes the form programmatically.

How to convert color code into media.brush?

For simplicity you could create an extension:-

    public static SolidColorBrush ToSolidColorBrush(this string hex_code)
    {
        return (SolidColorBrush)new BrushConverter().ConvertFromString(hex_code);
    }

And then to use:-

 SolidColorBrush accentBlue = "#3CACDC".ToSolidColorBrush();

Mysql password expired. Can't connect

The password expiration is a new feature in MySQL 5.6 or 5.7.

The answer is clear: Use a client which is capable of expired password changing (I think Sequel Pro can do it).

MySQLi library obviously isnt able to change the expired password.

If you have limited access to localhost and you only have a console client, the standard mysql client can do it.

How to execute only one test spec with angular-cli

If you want to be able to control which files are selected from the command line, I managed to do this for Angular 7.

In summary, you need to install @angular-devkit/build-angular:browser and then create a custom webpack plugin to pass the test file regex through. For example:

angular.json - change the test builder from @angular-devkit/build-angular:browser and set a custom config file:

...

        "test": {
          "builder": "@angular-builders/custom-webpack:browser",
          "options": {
            "customWebpackConfig": {
              "path": "./extra-webpack.config.js"
            },
...

extra-webpack.config.js - create a webpack configuration that reads the regex from the command line:

const webpack = require('webpack');
const FILTER = process.env.KARMA_FILTER;
let KARMA_SPEC_FILTER = '/.spec.ts$/';
if (FILTER) {
  KARMA_SPEC_FILTER = `/${FILTER}.spec.ts$/`;
}
module.exports = {
  plugins: [new webpack.DefinePlugin({KARMA_SPEC_FILTER})]
}

test.ts - edit the spec

...
// Then we find all the tests.
declare const KARMA_CONTEXT_SPEC: any;
const context = require.context('./', true, KARMA_CONTEXT_SPEC);

Then use as follows to override the default:

KARMA_FILTER='somefile-.*\.spec\.ts$' npm run test

I documented the backstory here, apologies in advance for types and mis-links. Credit to the answer above by @Aish-Anu for pointing me in the right direction.

jQuery.getJSON - Access-Control-Allow-Origin Issue

It's simple, use $.getJSON() function and in your URL just include

callback=?

as a parameter. That will convert the call to JSONP which is necessary to make cross-domain calls. More info: http://api.jquery.com/jQuery.getJSON/

MySQL delete multiple rows in one query conditions unique to each row

Took a lot of googling but here is what I do in Python for MySql when I want to delete multiple items from a single table using a list of values.

#create some empty list
values = []
#continue to append the values you want to delete to it
#BUT you must ensure instead of a string it's a single value tuple
values.append(([Your Variable],))
#Then once your array is loaded perform an execute many
cursor.executemany("DELETE FROM YourTable WHERE ID = %s", values)

how to get javaScript event source element?

I believe the solution by @slipset was correct, but wasn't cross-browser ready.

According to Javascript.info, events (when referenced outside markup events) are cross-browser ready once you assure it's defined with this simple line: event = event || window.event.

So the complete cross-browser ready function would look like this:

function doSomething(param){
  event = event || window.event;
  var source = event.target || event.srcElement;
  console.log(source);
}

How to exclude subdirectories in the destination while using /mir /xd switch in robocopy

Try my way :

robocopy.exe "Desktop\Test folder 1" "Desktop\Test folder 2" /XD "C:\Users\Steve\Desktop\Test folder 2\XXX dont touch" /MIR

Had to put /XD before /MIR while including the full Destination Source directly after /XD.

How to get the cell value by column name not by index in GridView in asp.net

protected void CheckedRecords(object sender, EventArgs e)

    {
       string email = string.Empty;
        foreach (GridViewRow gridrows in GridView1.Rows)

        {

            CheckBox chkbox = (CheckBox)gridrows.FindControl("ChkRecords");
    if (chkbox != null & chkbox.Checked)

            {

    int columnIndex = 0;
                foreach (DataControlFieldCell cell in gridrows.Cells)
                {
                    if (cell.ContainingField is BoundField)
                        if (((BoundField)cell.ContainingField).DataField.Equals("UserEmail"))
                            break;
                    columnIndex++; 
                }


                email += gridrows.Cells[columnIndex].Text + ',';
                  }

        }

        Label1.Text = "email:" + email;

    }                           

Representing EOF in C code?

EOF is not a character (in most modern operating systems). It is simply a condition that applies to a file stream when the end of the stream is reached. The confusion arises because a user may signal EOF for console input by typing a special character (e.g Control-D in Unix, Linux, et al), but this character is not seen by the running program, it is caught by the operating system which in turn signals EOF to the process.

Note: in some very old operating systems EOF was a character, e.g. Control-Z in CP/M, but this was a crude hack to avoid the overhead of maintaining actual file lengths in file system directories.

What is compiler, linker, loader?

A compiler is a special program that processes statements written in a particular programming language and turns them into machine language or "code" that a computer's processor uses

How to prevent Right Click option using jquery

The following code will disable mouse right click from full page.

$(document).ready(function () {
   $("body").on("contextmenu",function(e){
     return false;
   });
});

The full tutorial and working demo can be found from here - Disable mouse right click using jQuery

npm WARN enoent ENOENT: no such file or directory, open 'C:\Users\Nuwanst\package.json'

NOTE: if you are experiencing this issue in your CI pipeline, it is usually because npm runs npm ci instead of npm install. npm ci requires an accurate package-lock.json.

To fix this, whenever you are modifying packages in package.json (e.g. moving packages from devDependencies to Dependencies like I was doing) you should regenerate package-lock.json in your repository by running these commands locally, and then push the changes upstream:

rm -rf node_modules
npm install
git commit package-lock.json
git push

Doctrine 2 ArrayCollection filter method

The Collection#filter method really does eager load all members. Filtering at the SQL level will be added in doctrine 2.3.

Convert float to double without losing precision

I find converting to the binary representation easier to grasp this problem.

float f = 0.27f;
double d2 = (double) f;
double d3 = 0.27d;

System.out.println(Integer.toBinaryString(Float.floatToRawIntBits(f)));
System.out.println(Long.toBinaryString(Double.doubleToRawLongBits(d2)));
System.out.println(Long.toBinaryString(Double.doubleToRawLongBits(d3)));

You can see the float is expanded to the double by adding 0s to the end, but that the double representation of 0.27 is 'more accurate', hence the problem.

   111110100010100011110101110001
11111111010001010001111010111000100000000000000000000000000000
11111111010001010001111010111000010100011110101110000101001000

How to sort the letters in a string alphabetically in Python

Sorted() solution can give you some unexpected results with other strings.

List of other solutions:

Sort letters and make them distinct:

>>> s = "Bubble Bobble"
>>> ''.join(sorted(set(s.lower())))
' belou'

Sort letters and make them distinct while keeping caps:

>>> s = "Bubble Bobble"
>>> ''.join(sorted(set(s)))
' Bbelou'

Sort letters and keep duplicates:

>>> s = "Bubble Bobble"
>>> ''.join(sorted(s))
' BBbbbbeellou'

If you want to get rid of the space in the result, add strip() function in any of those mentioned cases:

>>> s = "Bubble Bobble"
>>> ''.join(sorted(set(s.lower()))).strip()
'belou'

Using member variable in lambda capture list inside a member function

Summary of the alternatives:

capture this:

auto lambda = [this](){};

use a local reference to the member:

auto& tmp = grid;
auto lambda = [ tmp](){}; // capture grid by (a single) copy
auto lambda = [&tmp](){}; // capture grid by ref

C++14:

auto lambda = [ grid = grid](){}; // capture grid by copy
auto lambda = [&grid = grid](){}; // capture grid by ref

example: https://godbolt.org/g/dEKVGD

Android: Internet connectivity change listener

Here's the Java code using registerDefaultNetworkCallback (and registerNetworkCallback for API < 24):

ConnectivityManager.NetworkCallback networkCallback = new ConnectivityManager.NetworkCallback() {
    @Override
    public void onAvailable(Network network) {
        // network available
    }

    @Override
    public void onLost(Network network) {
        // network unavailable
    }
};

ConnectivityManager connectivityManager =
        (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
    connectivityManager.registerDefaultNetworkCallback(networkCallback);
} else {
    NetworkRequest request = new NetworkRequest.Builder()
            .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET).build();
    connectivityManager.registerNetworkCallback(request, networkCallback);
}

How to send JSON instead of a query string with $.ajax?

No, the dataType option is for parsing the received data.

To post JSON, you will need to stringify it yourself via JSON.stringify and set the processData option to false.

$.ajax({
    url: url,
    type: "POST",
    data: JSON.stringify(data),
    processData: false,
    contentType: "application/json; charset=UTF-8",
    complete: callback
});

Note that not all browsers support the JSON object, and although jQuery has .parseJSON, it has no stringifier included; you'll need another polyfill library.

How do I specify new lines on Python, when writing on files?

\n - simple newline character insertion works:

# Here's the test example - string with newline char:
In [36]: test_line = "Hi!!!\n testing first line.. \n testing second line.. \n and third line....."

# Output:
In [37]: print(test_line)

Hi!!!
 testing first line..
 testing second line..
 and third line.....

Pull request vs Merge request

As mentioned in previous answers, both serve almost same purpose. Personally I like git rebase and merge request (as in gitlab). It takes burden off of the reviewer/maintainer, making sure that while adding merge request, the feature branch includes all of the latest commits done on main branch after feature branch is created. Here is a very useful article explaining rebase in detail: https://git-scm.com/book/en/v2/Git-Branching-Rebasing

merge one local branch into another local branch

Just in case you arrived here because you copied a branch name from Github, note that a remote branch is not automatically also a local branch, so a merge will not work and give the "not something we can merge" error.

In that case, you have two options:

git checkout [branchYouWantToMergeInto]
git merge origin/[branchYouWantToMerge]

or

# this creates a local branch
git checkout [branchYouWantToMerge]

git checkout [branchYouWantToMergeInto]
git merge [branchYouWantToMerge]

FutureWarning: elementwise comparison failed; returning scalar, but in the future will perform elementwise comparison

I've compared a few of the methods possible for doing this, including pandas, several numpy methods, and a list comprehension method.

First, let's start with a baseline:

>>> import numpy as np
>>> import operator
>>> import pandas as pd

>>> x = [1, 2, 1, 2]
>>> %time count = np.sum(np.equal(1, x))
>>> print("Count {} using numpy equal with ints".format(count))
CPU times: user 52 µs, sys: 0 ns, total: 52 µs
Wall time: 56 µs
Count 2 using numpy equal with ints

So, our baseline is that the count should be correct 2, and we should take about 50 us.

Now, we try the naive method:

>>> x = ['s', 'b', 's', 'b']
>>> %time count = np.sum(np.equal('s', x))
>>> print("Count {} using numpy equal".format(count))
CPU times: user 145 µs, sys: 24 µs, total: 169 µs
Wall time: 158 µs
Count NotImplemented using numpy equal
/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/ipykernel_launcher.py:1: FutureWarning: elementwise comparison failed; returning scalar instead, but in the future will perform elementwise comparison
  """Entry point for launching an IPython kernel.

And here, we get the wrong answer (NotImplemented != 2), it takes us a long time, and it throws the warning.

So we'll try another naive method:

>>> %time count = np.sum(x == 's')
>>> print("Count {} using ==".format(count))
CPU times: user 46 µs, sys: 1 µs, total: 47 µs
Wall time: 50.1 µs
Count 0 using ==

Again, the wrong answer (0 != 2). This is even more insidious because there's no subsequent warnings (0 can be passed around just like 2).

Now, let's try a list comprehension:

>>> %time count = np.sum([operator.eq(_x, 's') for _x in x])
>>> print("Count {} using list comprehension".format(count))
CPU times: user 55 µs, sys: 1 µs, total: 56 µs
Wall time: 60.3 µs
Count 2 using list comprehension

We get the right answer here, and it's pretty fast!

Another possibility, pandas:

>>> y = pd.Series(x)
>>> %time count = np.sum(y == 's')
>>> print("Count {} using pandas ==".format(count))
CPU times: user 453 µs, sys: 31 µs, total: 484 µs
Wall time: 463 µs
Count 2 using pandas ==

Slow, but correct!

And finally, the option I'm going to use: casting the numpy array to the object type:

>>> x = np.array(['s', 'b', 's', 'b']).astype(object)
>>> %time count = np.sum(np.equal('s', x))
>>> print("Count {} using numpy equal".format(count))
CPU times: user 50 µs, sys: 1 µs, total: 51 µs
Wall time: 55.1 µs
Count 2 using numpy equal

Fast and correct!

Failed to Connect to MySQL at localhost:3306 with user root

  1. set root user to mysql_native_password

$ sudo mysql -u root -p # I had to use "sudo" since is new installation

mysql:~ USE mysql;
mysql:~ SELECT User, Host, plugin FROM mysql.user;
mysql:~ UPDATE user SET plugin='mysql_native_password' WHERE User='root';
mysql:~ FLUSH PRIVILEGES;
mysql:~ exit;

$ service mysql restart

Wordpress plugin install: Could not create directory

wordpressProject is the project name.

/var/www/html/wordpressProject sudo chmod -R 777 wp-content

Thanks. It will work.

how to open a url in python

You could also try:

import os
os.system("start \"\" http://example.com")

This, other than @aaronasterling ´s answer has the advantage that it opens the default web browser. Be sure not to forget the "http://".

How do I prevent the padding property from changing width or height in CSS?

If you would like to indent text within a div without changing the size of the div use the CSS text-indent instead of padding-left.

_x000D_
_x000D_
.indent {_x000D_
  text-indent: 1em;_x000D_
}_x000D_
.border {_x000D_
  border-style: solid;_x000D_
}
_x000D_
<div class="border">_x000D_
  Non indented_x000D_
</div>_x000D_
_x000D_
<br>_x000D_
_x000D_
<div class="border indent">_x000D_
  Indented_x000D_
</div>
_x000D_
_x000D_
_x000D_

Setting top and left CSS attributes

You can also use the setProperty method like below

document.getElementById('divName').style.setProperty("top", "100px");

cURL not working (Error #77) for SSL connections on CentOS for non-root users

Check that you have the correct rights set on CA certificates bundle. Usually, that means read access for everyone to CA files in the /etc/ssl/certs directory, for instance /etc/ssl/certs/ca-certificates.crt.

You can see what files have been configured for you curl version with the

curl-config --configure
command :

$ curl-config --configure
 '--prefix=/usr' 
 '--mandir=/usr/share/man' 
 '--disable-dependency-tracking' 
 '--disable-ldap' 
 '--disable-ldaps' 
 '--enable-ipv6' 
 '--enable-manual' 
 '--enable-versioned-symbols' 
 '--enable-threaded-resolver' 
 '--without-libidn' 
 '--with-random=/dev/urandom' 
 '--with-ca-bundle=/etc/ssl/certs/ca-certificates.crt' 
 'CFLAGS=-march=x86-64 -mtune=generic -O2 -pipe -fstack-protector --param=ssp-buffer-size=4' 'LDFLAGS=-Wl,-O1,--sort-common,--as-needed,-z,relro' 
 'CPPFLAGS=-D_FORTIFY_SOURCE=2'

Here you need read access to /etc/ssl/certs/ca-certificates.crt

$ curl-config --configure
 '--build' 'i486-linux-gnu' 
 '--prefix=/usr' 
 '--mandir=/usr/share/man' 
 '--disable-dependency-tracking' 
 '--enable-ipv6' 
 '--with-lber-lib=lber' 
 '--enable-manual' 
 '--enable-versioned-symbols' 
 '--with-gssapi=/usr' 
 '--with-ca-path=/etc/ssl/certs' 
 'build_alias=i486-linux-gnu' 
 'CFLAGS=-g -O2' 
 'LDFLAGS=' 
 'CPPFLAGS='

And the same here.

sqlite copy data from one table to another

INSERT INTO Destination SELECT * FROM Source;

See SQL As Understood By SQLite: INSERT for a formal definition.

Pandas: ValueError: cannot convert float NaN to integer

I know this has been answered but wanted to provide alternate solution for anyone in the future:

You can use .loc to subset the dataframe by only values that are notnull(), and then subset out the 'x' column only. Take that same vector, and apply(int) to it.

If column x is float:

df.loc[df['x'].notnull(), 'x'] = df.loc[df['x'].notnull(), 'x'].apply(int)

Copy row but with new id

SET @table = 'the_table';
SELECT GROUP_CONCAT(IF(COLUMN_NAME IN ('id'), 0, CONCAT("\`", COLUMN_NAME, "\`"))) FROM INFORMATION_SCHEMA.COLUMNS
                  WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = @table INTO @columns;
SET @s = CONCAT('INSERT INTO ', @table, ' SELECT ', @columns,' FROM ', @table, ' WHERE id=1');
PREPARE stmt FROM @s;
EXECUTE stmt;

jQuery "on create" event for dynamically-created elements

As mentioned in several other answers, mutation events have been deprecated, so you should use MutationObserver instead. Since nobody has given any details on that yet, here it goes...

Basic JavaScript API

The API for MutationObserver is fairly simple. It's not quite as simple as the mutation events, but it's still okay.

_x000D_
_x000D_
function callback(records) {_x000D_
  records.forEach(function (record) {_x000D_
    var list = record.addedNodes;_x000D_
    var i = list.length - 1;_x000D_
    _x000D_
 for ( ; i > -1; i-- ) {_x000D_
   if (list[i].nodeName === 'SELECT') {_x000D_
     // Insert code here..._x000D_
     console.log(list[i]);_x000D_
   }_x000D_
 }_x000D_
  });_x000D_
}_x000D_
_x000D_
var observer = new MutationObserver(callback);_x000D_
_x000D_
var targetNode = document.body;_x000D_
_x000D_
observer.observe(targetNode, { childList: true, subtree: true });
_x000D_
<script>_x000D_
  // For testing_x000D_
  setTimeout(function() {_x000D_
    var $el = document.createElement('select');_x000D_
    document.body.appendChild($el);_x000D_
  }, 500);_x000D_
</script>
_x000D_
_x000D_
_x000D_

Let's break that down.

var observer = new MutationObserver(callback);

This creates the observer. The observer isn't watching anything yet; this is just where the event listener gets attached.

observer.observe(targetNode, { childList: true, subtree: true });

This makes the observer start up. The first argument is the node that the observer will watch for changes on. The second argument is the options for what to watch for.

  • childList means I want to watch for child elements being added or removed.
  • subtree is a modifier that extends childList to watch for changes anywhere in this element's subtree (otherwise, it would just look at changes directly within targetNode).

The other two main options besides childList are attributes and characterData, which mean about what they sound like. You must use one of those three.

function callback(records) {
  records.forEach(function (record) {

Things get a little tricky inside the callback. The callback receives an array of MutationRecords. Each MutationRecord can describe several changes of one type (childList, attributes, or characterData). Since I only told the observer to watch for childList, I won't bother checking the type.

var list = record.addedNodes;

Right here I grab a NodeList of all the child nodes that were added. This will be empty for all the records where nodes aren't added (and there may be many such records).

From there on, I loop through the added nodes and find any that are <select> elements.

Nothing really complex here.

jQuery

...but you asked for jQuery. Fine.

(function($) {

  var observers = [];

  $.event.special.domNodeInserted = {

    setup: function setup(data, namespaces) {
      var observer = new MutationObserver(checkObservers);

      observers.push([this, observer, []]);
    },

    teardown: function teardown(namespaces) {
      var obs = getObserverData(this);

      obs[1].disconnect();

      observers = $.grep(observers, function(item) {
        return item !== obs;
      });
    },

    remove: function remove(handleObj) {
      var obs = getObserverData(this);

      obs[2] = obs[2].filter(function(event) {
        return event[0] !== handleObj.selector && event[1] !== handleObj.handler;
      });
    },

    add: function add(handleObj) {
      var obs = getObserverData(this);

      var opts = $.extend({}, {
        childList: true,
        subtree: true
      }, handleObj.data);

      obs[1].observe(this, opts);

      obs[2].push([handleObj.selector, handleObj.handler]);
    }
  };

  function getObserverData(element) {
    var $el = $(element);

    return $.grep(observers, function(item) {
      return $el.is(item[0]);
    })[0];
  }

  function checkObservers(records, observer) {
    var obs = $.grep(observers, function(item) {
      return item[1] === observer;
    })[0];

    var triggers = obs[2];

    var changes = [];

    records.forEach(function(record) {
      if (record.type === 'attributes') {
        if (changes.indexOf(record.target) === -1) {
          changes.push(record.target);
        }

        return;
      }

      $(record.addedNodes).toArray().forEach(function(el) {
        if (changes.indexOf(el) === -1) {
          changes.push(el);
        }
      })
    });

    triggers.forEach(function checkTrigger(item) {
      changes.forEach(function(el) {
        var $el = $(el);

        if ($el.is(item[0])) {
          $el.trigger('domNodeInserted');
        }
      });
    });
  }

})(jQuery);

This creates a new event called domNodeInserted, using the jQuery special events API. You can use it like so:

$(document).on("domNodeInserted", "select", function () {
  $(this).combobox();
});

I would personally suggest looking for a class because some libraries will create select elements for testing purposes.

Naturally, you can also use .off("domNodeInserted", ...) or fine-tune the watching by passing in data like this:

$(document.body).on("domNodeInserted", "select.test", {
  attributes: true,
  subtree: false
}, function () {
  $(this).combobox();
});

This would trigger checking for the appearance of a select.test element whenever attributes changed for elements directly inside the body.

You can see it live below or on jsFiddle.

_x000D_
_x000D_
(function($) {_x000D_
  $(document).on("domNodeInserted", "select", function() {_x000D_
    console.log(this);_x000D_
    //$(this).combobox();_x000D_
  });_x000D_
})(jQuery);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<script>_x000D_
  // For testing_x000D_
  setTimeout(function() {_x000D_
    var $el = document.createElement('select');_x000D_
    document.body.appendChild($el);_x000D_
  }, 500);_x000D_
</script>_x000D_
_x000D_
<script>_x000D_
  (function($) {_x000D_
_x000D_
    var observers = [];_x000D_
_x000D_
    $.event.special.domNodeInserted = {_x000D_
_x000D_
      setup: function setup(data, namespaces) {_x000D_
        var observer = new MutationObserver(checkObservers);_x000D_
_x000D_
        observers.push([this, observer, []]);_x000D_
      },_x000D_
_x000D_
      teardown: function teardown(namespaces) {_x000D_
        var obs = getObserverData(this);_x000D_
_x000D_
        obs[1].disconnect();_x000D_
_x000D_
        observers = $.grep(observers, function(item) {_x000D_
          return item !== obs;_x000D_
        });_x000D_
      },_x000D_
_x000D_
      remove: function remove(handleObj) {_x000D_
        var obs = getObserverData(this);_x000D_
_x000D_
        obs[2] = obs[2].filter(function(event) {_x000D_
          return event[0] !== handleObj.selector && event[1] !== handleObj.handler;_x000D_
        });_x000D_
      },_x000D_
_x000D_
      add: function add(handleObj) {_x000D_
        var obs = getObserverData(this);_x000D_
_x000D_
        var opts = $.extend({}, {_x000D_
          childList: true,_x000D_
          subtree: true_x000D_
        }, handleObj.data);_x000D_
_x000D_
        obs[1].observe(this, opts);_x000D_
_x000D_
        obs[2].push([handleObj.selector, handleObj.handler]);_x000D_
      }_x000D_
    };_x000D_
_x000D_
    function getObserverData(element) {_x000D_
      var $el = $(element);_x000D_
_x000D_
      return $.grep(observers, function(item) {_x000D_
        return $el.is(item[0]);_x000D_
      })[0];_x000D_
    }_x000D_
_x000D_
    function checkObservers(records, observer) {_x000D_
      var obs = $.grep(observers, function(item) {_x000D_
        return item[1] === observer;_x000D_
      })[0];_x000D_
_x000D_
      var triggers = obs[2];_x000D_
_x000D_
      var changes = [];_x000D_
_x000D_
      records.forEach(function(record) {_x000D_
        if (record.type === 'attributes') {_x000D_
          if (changes.indexOf(record.target) === -1) {_x000D_
            changes.push(record.target);_x000D_
          }_x000D_
_x000D_
          return;_x000D_
        }_x000D_
_x000D_
        $(record.addedNodes).toArray().forEach(function(el) {_x000D_
          if (changes.indexOf(el) === -1) {_x000D_
            changes.push(el);_x000D_
          }_x000D_
        })_x000D_
      });_x000D_
_x000D_
      triggers.forEach(function checkTrigger(item) {_x000D_
        changes.forEach(function(el) {_x000D_
          var $el = $(el);_x000D_
_x000D_
          if ($el.is(item[0])) {_x000D_
            $el.trigger('domNodeInserted');_x000D_
          }_x000D_
        });_x000D_
      });_x000D_
    }_x000D_
_x000D_
  })(jQuery);_x000D_
</script>
_x000D_
_x000D_
_x000D_


Note

This jQuery code is a fairly basic implementation. It does not trigger in cases where modifications elsewhere make your selector valid.

For example, suppose your selector is .test select and the document already has a <select>. Adding the class test to <body> will make the selector valid, but because I only check record.target and record.addedNodes, the event would not fire. The change has to happen to the element you wish to select itself.

This could be avoided by querying for the selector whenever mutations happen. I chose not to do that to avoid causing duplicate events for elements that had already been handled. Properly dealing with adjacent or general sibling combinators would make things even trickier.

For a more comprehensive solution, see https://github.com/pie6k/jquery.initialize, as mentioned in Damien Ó Ceallaigh's answer. However, the author of that library has announced that the library is old and suggests that you shouldn't use jQuery for this.

405 method not allowed Web API

Make sure your controller inherits from Controller class.

It might even be crazier that stuff would work locally even without that.

How to remove multiple deleted files in Git repository

git status | sed 's/^#\s*deleted:\s*//' | sed 's/^#.*//' | xargs git rm -rf

What is the Python equivalent of Matlab's tic and toc functions?

Building on Stefan and antonimmo's answers, I ended up putting

def Tictoc():
    start_stack = []
    start_named = {}

    def tic(name=None):
        if name is None:
            start_stack.append(time())
        else:
            start_named[name] = time()

    def toc(name=None):
        if name is None:
            start = start_stack.pop()
        else:
            start = start_named.pop(name)
        elapsed = time() - start
        return elapsed
    return tic, toc

in a utils.py module, and I use it with a

from utils import Tictoc
tic, toc = Tictoc()

This way

  • you can simply use tic(), toc() and nest them like in Matlab
  • alternatively, you can name them: tic(1), toc(1) or tic('very-important-block'), toc('very-important-block') and timers with different names won't interfere
  • importing them this way prevents interference between modules using it.

(here toc does not print the elapsed time, but returns it.)

How do I increase the RAM and set up host-only networking in Vagrant?

I could not get any of these answers to work. Here's what I ended up putting at the very top of my Vagrantfile, before the Vagrant::Config.run do block:

Vagrant.configure("2") do |config|
  config.vm.provider "virtualbox" do |vb|
    vb.customize ["modifyvm", :id, "--memory", "1024"]
  end
end

I noticed that the shortcut accessor style, "vb.memory = 1024", didn't seem to work.

How to prevent Browser cache on Angular 2 site?

Found a way to do this, simply add a querystring to load your components, like so:

@Component({
  selector: 'some-component',
  templateUrl: `./app/component/stuff/component.html?v=${new Date().getTime()}`,
  styleUrls: [`./app/component/stuff/component.css?v=${new Date().getTime()}`]
})

This should force the client to load the server's copy of the template instead of the browser's. If you would like it to refresh only after a certain period of time you could use this ISOString instead:

new Date().toISOString() //2016-09-24T00:43:21.584Z

And substring some characters so that it will only change after an hour for example:

new Date().toISOString().substr(0,13) //2016-09-24T00

Hope this helps

How to perform runtime type checking in Dart?

Dart Object type has a runtimeType instance member (source is from dart-sdk v1.14, don't know if it was available earlier)

class Object {
  //...
  external Type get runtimeType;
}

Usage:

Object o = 'foo';
assert(o.runtimeType == String);

How do you round a number to two decimal places in C#?

Try this:

twoDec = Math.Round(val, 2)

CSS customized scroll bar in div

For people still looking for a good solution just I find out this plugin simplebar

Custom scrollbars vanilla javascript library with native scroll, done simple, lightweight, easy to use and cross-browser.

In my case, I was looking for reactJS solutions, the author also provides wrappers for react, angular, vue and next examples

What is the best way to test for an empty string in Go?

As per official guidelines and from performance point of view they appear equivalent (ANisus answer), the s != "" would be better due to a syntactical advantage. s != "" will fail at compile time if the variable is not a string, while len(s) == 0 will pass for several other data types.

AFNetworking Post Request

NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
                       height, @"user[height]",
                       weight, @"user[weight]",
                       nil];

AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:
                                             [NSURL URLWithString:@"http://localhost:8080/"]];

[client postPath:@"/mypage.php" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
     NSString *text = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
     NSLog(@"Response: %@", text);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
     NSLog(@"%@", [error localizedDescription]);
}];

DSO missing from command line

DSO here means Dynamic Shared Object; since the error message says it's missing from the command line, I guess you have to add it to the command line.

That is, try adding -lpthread to your command line.

Android - Get value from HashMap

HashMap<String, String> meMap = new HashMap<String, String>();
meMap.put("Color1", "Red");
meMap.put("Color2", "Blue");
meMap.put("Color3", "Green");
meMap.put("Color4", "White");

Iterator myVeryOwnIterator = meMap.values().iterator();
while(myVeryOwnIterator.hasNext()) {
    Toast.makeText(getBaseContext(), myVeryOwnIterator.next(), Toast.LENGTH_SHORT).show();
}

Checking if a list is empty with LINQ

I would make one small addition to the code you seem to have settled on: check also for ICollection, as this is implemented even by some non-obsolete generic classes as well (i.e., Queue<T> and Stack<T>). I would also use as instead of is as it's more idiomatic and has been shown to be faster.

public static bool IsEmpty<T>(this IEnumerable<T> list)
{
    if (list == null)
    {
        throw new ArgumentNullException("list");
    }

    var genericCollection = list as ICollection<T>;
    if (genericCollection != null)
    {
        return genericCollection.Count == 0;
    }

    var nonGenericCollection = list as ICollection;
    if (nonGenericCollection != null)
    {
        return nonGenericCollection.Count == 0;
    }

    return !list.Any();
}

Cycles in family tree software

I hate commenting on such a screwed up situation, but the easiest way to not rejigger all of your invariants is to create a phantom vertex in your graph that acts as a proxy back to the incestuous dad.

Sorting using Comparator- Descending order (User defined classes)

For whats its worth here is my standard answer. The only thing new here is that is uses the Collections.reverseOrder(). Plus it puts all suggestions into one example:

/*
**  Use the Collections API to sort a List for you.
**
**  When your class has a "natural" sort order you can implement
**  the Comparable interface.
**
**  You can use an alternate sort order when you implement
**  a Comparator for your class.
*/
import java.util.*;

public class Person implements Comparable<Person>
{
    String name;
    int age;

    public Person(String name, int age)
    {
        this.name = name;
        this.age = age;
    }

    public String getName()
    {
        return name;
    }

    public int getAge()
    {
        return age;
    }

    public String toString()
    {
        return name + " : " + age;
    }

    /*
    **  Implement the natural order for this class
    */
    public int compareTo(Person p)
    {
        return getName().compareTo(p.getName());
    }

    static class AgeComparator implements Comparator<Person>
    {
        public int compare(Person p1, Person p2)
        {
            int age1 = p1.getAge();
            int age2 = p2.getAge();

            if (age1 == age2)
                return 0;
            else if (age1 > age2)
                return 1;
            else
                return -1;
        }
    }

    public static void main(String[] args)
    {
        List<Person> people = new ArrayList<Person>();
        people.add( new Person("Homer", 38) );
        people.add( new Person("Marge", 35) );
        people.add( new Person("Bart", 15) );
        people.add( new Person("Lisa", 13) );

        // Sort by natural order

        Collections.sort(people);
        System.out.println("Sort by Natural order");
        System.out.println("\t" + people);

        // Sort by reverse natural order

        Collections.sort(people, Collections.reverseOrder());
        System.out.println("Sort by reverse natural order");
        System.out.println("\t" + people);

        //  Use a Comparator to sort by age

        Collections.sort(people, new Person.AgeComparator());
        System.out.println("Sort using Age Comparator");
        System.out.println("\t" + people);

        //  Use a Comparator to sort by descending age

        Collections.sort(people,
            Collections.reverseOrder(new Person.AgeComparator()));
        System.out.println("Sort using Reverse Age Comparator");
        System.out.println("\t" + people);
    }
}

How to right-align and justify-align in Markdown?

If you want to use justify align in Jupyter Notebook use the following syntax:

<p style='text-align: justify;'> Your Text </p>

For right alignment:

<p style='text-align: right;'> Your Text </p>

Pinging an IP address using PHP and echoing the result

i just wrote a very fast solution by combining all knowledge gain above

    function pinger($address){
        if(strtolower(PHP_OS)=='winnt'){
            $command = "ping -n 1 $address";
            exec($command, $output, $status);
        }else{
            $command = "ping -c 1 $address";
            exec($command, $output, $status);
        }
        if($status === 0){
            return true;
        }else{
            return false;
        }
    }

How to comment a block in Eclipse?

For single line comment you can use Ctrl+/ and for multiple line comment you can use Ctrl + Shift + / after selecting the lines you want to comment in java editor.

On Mac/OS X you can use ? + / to comment out single lines or selected blocks.

How to get current user, and how to use User class in MVC5?

In .Net MVC5 core 2.2, I use HttpContext.User.Identity.Name . It worked for me.

What is the 'open' keyword in Swift?

open is a new access level in Swift 3, introduced with the implementation of

It is available with the Swift 3 snapshot from August 7, 2016, and with Xcode 8 beta 6.

In short:

  • An open class is accessible and subclassable outside of the defining module. An open class member is accessible and overridable outside of the defining module.
  • A public class is accessible but not subclassable outside of the defining module. A public class member is accessible but not overridable outside of the defining module.

So open is what public used to be in previous Swift releases and the access of public has been restricted. Or, as Chris Lattner puts it in SE-0177: Allow distinguishing between public access and public overridability:

“open” is now simply “more public than public”, providing a very simple and clean model.

In your example, open var hashValue is a property which is accessible and can be overridden in NSObject subclasses.

For more examples and details, have a look at SE-0117.

Read a Csv file with powershell and capture corresponding data

What you should be looking at is Import-Csv

Once you import the CSV you can use the column header as the variable.

Example CSV:

Name  | Phone Number | Email
Elvis | 867.5309     | [email protected]
Sammy | 555.1234     | [email protected]

Now we will import the CSV, and loop through the list to add to an array. We can then compare the value input to the array:

$Name = @()
$Phone = @()

Import-Csv H:\Programs\scripts\SomeText.csv |`
    ForEach-Object {
        $Name += $_.Name
        $Phone += $_."Phone Number"
    }

$inputNumber = Read-Host -Prompt "Phone Number"

if ($Phone -contains $inputNumber)
    {
    Write-Host "Customer Exists!"
    $Where = [array]::IndexOf($Phone, $inputNumber)
    Write-Host "Customer Name: " $Name[$Where]
    }

And here is the output:

I Found Sammy

Good ways to sort a queryset? - Django

Here's a way that allows for ties for the cut-off score.

author_count = Author.objects.count()
cut_off_score = Author.objects.order_by('-score').values_list('score')[min(30, author_count)]
top_authors = Author.objects.filter(score__gte=cut_off_score).order_by('last_name')

You may get more than 30 authors in top_authors this way and the min(30,author_count) is there incase you have fewer than 30 authors.

How to include CSS file in Symfony 2 and Twig?

The other answers are valid, but the Official Symfony Best Practices guide suggests using the web/ folder to store all assets, instead of different bundles.

Scattering your web assets across tens of different bundles makes it more difficult to manage them. Your designers' lives will be much easier if all the application assets are in one location.

Templates also benefit from centralizing your assets, because the links are much more concise[...]

I'd add to this by suggesting that you only put micro-assets within micro-bundles, such as a few lines of styles only required for a button in a button bundle, for example.

Add a space (" ") after an element using :after

Turns out it needs to be specified via escaped unicode. This question is related and contains the answer.

The solution:

h2:after {
    content: "\00a0";
}

How to set the locale inside a Debian/Ubuntu Docker container?

You guys don't need those complex things to set locales on Ubuntu/Debian. You don't even need /etc/local.gen file.

Simply locale-gen will do everything and the author only missed locales package.

RUN apt-get update && apt-get install -y locales && rm -rf /var/lib/apt/lists/* \
 && locale-gen "en_US.UTF-8"
ENV LANG=en_US.UTF-8 \
    LANGUAGE=en_US:en \
    LC_ALL=en_US.UTF-8

I found this the simplest and the most effective. I confirm it works on Ubuntu 16.04.

Firestore Getting documents id from collection

To obtain the id of the documents in a collection, you must use snapshotChanges()

    this.shirtCollection = afs.collection<Shirt>('shirts');
    // .snapshotChanges() returns a DocumentChangeAction[], which contains
    // a lot of information about "what happened" with each change. If you want to
    // get the data and the id use the map operator.
    this.shirts = this.shirtCollection.snapshotChanges().map(actions => {
      return actions.map(a => {
        const data = a.payload.doc.data() as Shirt;
        const id = a.payload.doc.id;
        return { id, ...data };
      });
    });

Documentation https://github.com/angular/angularfire2/blob/7eb3e51022c7381dfc94ffb9e12555065f060639/docs/firestore/collections.md#example

How to enable loglevel debug on Apache2 server

Do note that on newer Apache versions the RewriteLog and RewriteLogLevel have been removed, and in fact will now trigger an error when trying to start Apache (at least on my XAMPP installation with Apache 2.4.2):

AH00526: Syntax error on line xx of path/to/config/file.conf: Invalid command 'RewriteLog', perhaps misspelled or defined by a module not included in the server configuration`

Instead, you're now supposed to use the general LogLevel directive, with a level of trace1 up to trace8. 'debug' didn't display any rewrite messages in the log for me.

Example: LogLevel warn rewrite:trace3

For the official documentation, see here.

Of course this also means that now your rewrite logs will be written in the general error log file and you'll have to sort them out yourself.

The storage engine for the table doesn't support repair. InnoDB or MyISAM?

First is you have to understand the difference between MyISAM and InnoDB Engines. And this is clearly stated on this link. You can use this sql statement if you want to convert InnoDB to MyISAM:

 ALTER TABLE t1 ENGINE=MyISAM;

How to print from Flask @app.route to python console

We can also use logging to print data on the console.

Example:

import logging
from flask import Flask

app = Flask(__name__)

@app.route('/print')
def printMsg():
    app.logger.warning('testing warning log')
    app.logger.error('testing error log')
    app.logger.info('testing info log')
    return "Check your console"

if __name__ == '__main__':
    app.run(debug=True)

Unmarshaling nested JSON objects

I was working on something like this. But is working only with structures generated from proto. https://github.com/flowup-labs/grpc-utils

in your proto

message Msg {
  Firstname string = 1 [(gogoproto.jsontag) = "name.firstname"];
  PseudoFirstname string = 2 [(gogoproto.jsontag) = "lastname"];
  EmbedMsg = 3  [(gogoproto.nullable) = false, (gogoproto.embed) = true];
  Lastname string = 4 [(gogoproto.jsontag) = "name.lastname"];
  Inside string  = 5 [(gogoproto.jsontag) = "name.inside.a.b.c"];
}

message EmbedMsg{
   Opt1 string = 1 [(gogoproto.jsontag) = "opt1"];
}

Then your output will be

{
"lastname": "Three",
"name": {
    "firstname": "One",
    "inside": {
        "a": {
            "b": {
                "c": "goo"
            }
        }
    },
    "lastname": "Two"
},
"opt1": "var"
}

SQL Server® 2016, 2017 and 2019 Express full download

Download the developer edition. There you can choose Express as license when installing.

enter image description here

Is it possible to import a whole directory in sass using @import?

You can generate SASS file which imports everything automatically, I use this Gulp task:

concatFilenames = require('gulp-concat-filenames')

let concatFilenamesOptions = {
    root: './',
    prepend: "@import '",
    append: "'"
}
gulp.task('sass-import', () => {
    gulp.src(path_src_sass)
        .pipe(concatFilenames('app.sass', concatFilenamesOptions))
        .pipe(gulp.dest('./build'))
})

You can also control importing order by ordering the folders like this:

path_src_sass = [
    './style/**/*.sass', // mixins, variables - import first
    './components/**/*.sass', // singule components
    './pages/**/*.sass' // higher-level templates that could override components settings if necessary
]

Android: How to create a Dialog without a title?

Think you can just use this now:

AlertDialog dialog = new AlertDialog.Builder(this)
  .setView(view)
  .setTitle("")
  .create()

How do I programmatically "restart" an Android app?

Try using FLAG_ACTIVITY_CLEAR_TASK

Why does find -exec mv {} ./target/ + not work?

find . -name "*.mp3" -exec mv --target-directory=/home/d0k/??????/ {} \+

How can I enable the MySQLi extension in PHP 7?

For all docker users, just run docker-php-ext-install mysqli from inside your php container.

Update: More information on https://hub.docker.com/_/php in the section "How to install more PHP extensions".

How can I include css files using node, express, and ejs?

I have used the following steps to resolve this problem

  1. create new folder (static) and move all js and css file into this folder.
  2. then add app.use('/static', express.static('static'))
  3. add css like < link rel="stylesheet" type="text/css" href="/static/style.css"/>
  4. restart server to view impact after changes.

Node JS Error: ENOENT

You can include a different jade file into your template, that to from a different directory

views/
     layout.jade
static/
     page.jade

To include the layout file from views dir to static/page.jade

page.jade

extends ../views/layout

git stash changes apply to new branch?

Is the standard procedure not working?

  • make changes
  • git stash save
  • git branch xxx HEAD
  • git checkout xxx
  • git stash pop

Shorter:

  • make changes
  • git stash
  • git checkout -b xxx
  • git stash pop

How can I find the number of years between two dates?

This will work and if you want the number of years replace 12 to 1

    String date1 = "07-01-2015";
    String date2 = "07-11-2015";
    int i = Integer.parseInt(date1.substring(6));
    int j = Integer.parseInt(date2.substring(6));
    int p = Integer.parseInt(date1.substring(3,5));
    int q = Integer.parseInt(date2.substring(3,5));


    int z;
    if(q>=p){
        z=q-p + (j-i)*12;
    }else{
        z=p-q + (j-i)*12;
    }
    System.out.println("The Total Months difference between two dates is --> "+z+" Months");

Spring Boot - Loading Initial Data

As suggestion try this:

@Bean
public CommandLineRunner loadData(CustomerRepository repository) {
    return (args) -> {
        // save a couple of customers
        repository.save(new Customer("Jack", "Bauer"));
        repository.save(new Customer("Chloe", "O'Brian"));
        repository.save(new Customer("Kim", "Bauer"));
        repository.save(new Customer("David", "Palmer"));
        repository.save(new Customer("Michelle", "Dessler"));

        // fetch all customers
        log.info("Customers found with findAll():");
        log.info("-------------------------------");
        for (Customer customer : repository.findAll()) {
            log.info(customer.toString());
        }
        log.info("");

        // fetch an individual customer by ID
        Customer customer = repository.findOne(1L);
        log.info("Customer found with findOne(1L):");
        log.info("--------------------------------");
        log.info(customer.toString());
        log.info("");

        // fetch customers by last name
        log.info("Customer found with findByLastNameStartsWithIgnoreCase('Bauer'):");
        log.info("--------------------------------------------");
        for (Customer bauer : repository
                .findByLastNameStartsWithIgnoreCase("Bauer")) {
            log.info(bauer.toString());
        }
        log.info("");
    }
}

Option 2: Initialize with schema and data scripts

Prerequisites: in application.properties you have to mention this:

spring.jpa.hibernate.ddl-auto=none (otherwise scripts will be ignored by hibernate, and it will scan project for @Entity and/or @Table annotated classes)

Then, in your MyApplication class paste this:

@Bean(name = "dataSource")
public DriverManagerDataSource dataSource() {
    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setDriverClassName("org.h2.Driver");
    dataSource.setUrl("jdbc:h2:~/myDB;MV_STORE=false");
    dataSource.setUsername("sa");
    dataSource.setPassword("");

    // schema init
    Resource initSchema = new ClassPathResource("scripts/schema-h2.sql");
    Resource initData = new ClassPathResource("scripts/data-h2.sql");
    DatabasePopulator databasePopulator = new ResourceDatabasePopulator(initSchema, initData);
    DatabasePopulatorUtils.execute(databasePopulator, dataSource);

    return dataSource;
}

Where scripts folder is located under resources folder (IntelliJ Idea)

Hope it helps someone

ReDim Preserve to a Multi-Dimensional Array in Visual Basic 6

You can use a user defined type containing an array of strings which will be the inner array. Then you can use an array of this user defined type as your outer array.

Have a look at the following test project:

'1 form with:
'  command button: name=Command1
'  command button: name=Command2
Option Explicit

Private Type MyArray
  strInner() As String
End Type

Private mudtOuter() As MyArray

Private Sub Command1_Click()
  'change the dimensens of the outer array, and fill the extra elements with "1"
  Dim intOuter As Integer
  Dim intInner As Integer
  Dim intOldOuter As Integer
  intOldOuter = UBound(mudtOuter)
  ReDim Preserve mudtOuter(intOldOuter + 2) As MyArray
  For intOuter = intOldOuter + 1 To UBound(mudtOuter)
    ReDim mudtOuter(intOuter).strInner(intOuter) As String
    For intInner = 0 To UBound(mudtOuter(intOuter).strInner)
      mudtOuter(intOuter).strInner(intInner) = "1"
    Next intInner
  Next intOuter
End Sub

Private Sub Command2_Click()
  'change the dimensions of the middle inner array, and fill the extra elements with "2"
  Dim intOuter As Integer
  Dim intInner As Integer
  Dim intOldInner As Integer
  intOuter = UBound(mudtOuter) / 2
  intOldInner = UBound(mudtOuter(intOuter).strInner)
  ReDim Preserve mudtOuter(intOuter).strInner(intOldInner + 5) As String
  For intInner = intOldInner + 1 To UBound(mudtOuter(intOuter).strInner)
    mudtOuter(intOuter).strInner(intInner) = "2"
  Next intInner
End Sub

Private Sub Form_Click()
  'clear the form and print the outer,inner arrays
  Dim intOuter As Integer
  Dim intInner As Integer
  Cls
  For intOuter = 0 To UBound(mudtOuter)
    For intInner = 0 To UBound(mudtOuter(intOuter).strInner)
      Print CStr(intOuter) & "," & CStr(intInner) & " = " & mudtOuter(intOuter).strInner(intInner)
    Next intInner
    Print "" 'add an empty line between the outer array elements
  Next intOuter
End Sub

Private Sub Form_Load()
  'init the arrays
  Dim intOuter As Integer
  Dim intInner As Integer
  ReDim mudtOuter(5) As MyArray
  For intOuter = 0 To UBound(mudtOuter)
    ReDim mudtOuter(intOuter).strInner(intOuter) As String
    For intInner = 0 To UBound(mudtOuter(intOuter).strInner)
      mudtOuter(intOuter).strInner(intInner) = CStr((intOuter + 1) * (intInner + 1))
    Next intInner
  Next intOuter
  WindowState = vbMaximized
End Sub

Run the project, and click on the form to display the contents of the arrays.

Click on Command1 to enlarge the outer array, and click on the form again to show the results.

Click on Command2 to enlarge an inner array, and click on the form again to show the results.

Be careful though: when you redim the outer array, you also have to redim the inner arrays for all the new elements of the outer array

How to convert java.sql.timestamp to LocalDate (java8) java.time?

I'll slightly expand @assylias answer to take time zone into account. There are at least two ways to get LocalDateTime for specific time zone.

You can use setDefault time zone for whole application. It should be called before any timestamp -> java.time conversion:

public static void main(String... args) {
    TimeZone utcTimeZone = TimeZone.getTimeZone("UTC");
    TimeZone.setDefault(utcTimeZone);
    ...
    timestamp.toLocalDateTime().toLocalDate();
}

Or you can use toInstant.atZone chain:

timestamp.toInstant()
        .atZone(ZoneId.of("UTC"))
        .toLocalDate();

Why do I need 'b' to encode a string with Base64?

base64 encoding takes 8-bit binary byte data and encodes it uses only the characters A-Z, a-z, 0-9, +, /* so it can be transmitted over channels that do not preserve all 8-bits of data, such as email.

Hence, it wants a string of 8-bit bytes. You create those in Python 3 with the b'' syntax.

If you remove the b, it becomes a string. A string is a sequence of Unicode characters. base64 has no idea what to do with Unicode data, it's not 8-bit. It's not really any bits, in fact. :-)

In your second example:

>>> encoded = base64.b64encode('data to be encoded')

All the characters fit neatly into the ASCII character set, and base64 encoding is therefore actually a bit pointless. You can convert it to ascii instead, with

>>> encoded = 'data to be encoded'.encode('ascii')

Or simpler:

>>> encoded = b'data to be encoded'

Which would be the same thing in this case.


* Most base64 flavours may also include a = at the end as padding. In addition, some base64 variants may use characters other than + and /. See the Variants summary table at Wikipedia for an overview.

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

I separate it, and then use an identity comparison to dictate what is does next.

$("#selectField").change(function(){
  if(this.value === 'textValue1'){ $(".contentClass1").fadeIn(); }
  if(this.value === 'textValue2'){ $(".contentclass2").fadeIn(); }
});

Convert Python program to C/C++ code?

I know this is an older thread but I wanted to give what I think to be helpful information.

I personally use PyPy which is really easy to install using pip. I interchangeably use Python/PyPy interpreter, you don't need to change your code at all and I've found it to be roughly 40x faster than the standard python interpreter (Either Python 2x or 3x). I use pyCharm Community Edition to manage my code and I love it.

I like writing code in python as I think it lets you focus more on the task than the language, which is a huge plus for me. And if you need it to be even faster, you can always compile to a binary for Windows, Linux, or Mac (not straight forward but possible with other tools). From my experience, I get about 3.5x speedup over PyPy when compiling, meaning 140x faster than python. PyPy is available for Python 3x and 2x code and again if you use an IDE like PyCharm you can interchange between say PyPy, Cython, and Python very easily (takes a little of initial learning and setup though).

Some people may argue with me on this one, but I find PyPy to be faster than Cython. But they're both great choices though.

Edit: I'd like to make another quick note about compiling: when you compile, the resulting binary is much bigger than your python script as it builds all dependencies into it, etc. But then you get a few distinct benefits: speed!, now the app will work on any machine (depending on which OS you compiled for, if not all. lol) without Python or libraries, it also obfuscates your code and is technically 'production' ready (to a degree). Some compilers also generate C code, which I haven't really looked at or seen if it's useful or just gibberish. Good luck.

Hope that helps.

How to connect to a docker container from outside the host (same network) [Windows]

After trying several things, this worked for me:

  • use the --publish=0.0.0.0:8080:8080 docker flag
  • set the virtualbox network mode to NAT, and don't use any port forwarding

With addresses other than 0.0.0.0 I had no success.

Resource interpreted as Document but transferred with MIME type application/zip

I had a similar issue when performing a file download through Javascript. Adding the download attribute made no difference but adding target='_blank' did - I no longer get the 'Resource interpreted as Document...' console message.

Here's my nicely simple code:

var link = document.createElement('a');
link.target = '_blank';
link.href = url;
document.body.appendChild(link); // Required for Firefox
link.click();
link.remove(); 

I haven't tried it with direct HTML but would expect it to work.

Note I discovered that Firefox requires the link to be appended to the document whereas Chrome will work without it.

typeof !== "undefined" vs. != null

_x000D_
_x000D_
(function(){_x000D_
_x000D_
  var a= b = 3;_x000D_
  var ed = 103;_x000D_
  _x000D_
})();_x000D_
_x000D_
_x000D_
_x000D_
//console.log(ed); //ed is not defined_x000D_
_x000D_
console.log("a defined? " + (typeof a !== 'undefined')); //no define_x000D_
console.log("b defined? " + (typeof b !== 'undefined')); //yes define_x000D_
console.log(typeof(b)); //number_x000D_
console.log(typeof(4+7));   //number_x000D_
console.log(b); //3_x000D_
console.log(typeof("4"+"7")); //string_x000D_
var e= "ggg";_x000D_
console.log(typeof(e)); //string_x000D_
 var ty=typeof(b);_x000D_
console.log(ty); //number_x000D_
console.log(typeof false); //boolean_x000D_
console.log(typeof 1); //number_x000D_
console.log(typeof 0); //number_x000D_
console.log(typeof true); //boolean_x000D_
_x000D_
_x000D_
console.log(typeof Math.tan);  //function_x000D_
console.log(typeof function(){}); //function _x000D_
_x000D_
if(typeof neverDeclared == "undefined") //no errors_x000D_
if(typeof neverDeclared === "undefined") //no errors_x000D_
_x000D_
//if(neverDeclared == null) //showing error _x000D_
_x000D_
_x000D_
console.log(typeof {a:1}); //object_x000D_
console.log(typeof null); //object_x000D_
console.log(typeof JSON); //object_x000D_
console.log(typeof Math); //object_x000D_
console.log(typeof /a-z/); //object_x000D_
console.log(typeof new Date()); //object_x000D_
_x000D_
console.log(typeof afbc); //undefined_x000D_
//console.log(typeof new);//error_x000D_
_x000D_
document.write("<br> * oprator as math ");_x000D_
var r=14*"4";_x000D_
document.write(r);_x000D_
_x000D_
document.write("<br> + oprator as string ");_x000D_
var r=14+"44";_x000D_
document.write(r);_x000D_
_x000D_
document.write("<br> Minus Operator work as mathematic ");_x000D_
var r=64-"44";_x000D_
document.write(r);_x000D_
_x000D_
_x000D_
document.write("<br>");_x000D_
console.log(typeof(4*"7")); //returns number_x000D_
console.log(typeof(4+"7")); //returns string_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
 
_x000D_
Interview Question in JavaScript
_x000D_
_x000D_
_x000D_

ping: google.com: Temporary failure in name resolution

I've faced the exactly same problem but I've fixed it with another approache.

Using Ubuntu 18.04, first disable systemd-resolved service.

sudo systemctl disable systemd-resolved.service

Stop the service

sudo systemctl stop systemd-resolved.service

Then, remove the link to /run/systemd/resolve/stub-resolv.conf in /etc/resolv.conf

sudo rm /etc/resolv.conf

Add a manually created resolv.conf in /etc/

sudo vim /etc/resolv.conf

Add your prefered DNS server there

nameserver 208.67.222.222

I've tested this with success.

jQuery checkbox check/uncheck

Use .prop() instead and if we go with your code then compare like this:

Look at the example jsbin:

  $("#news_list tr").click(function () {
    var ele = $(this).find(':checkbox');
    if ($(':checked').length) {
      ele.prop('checked', false);
      $(this).removeClass('admin_checked');
    } else {
      ele.prop('checked', true);
      $(this).addClass('admin_checked');
    }
 });

Changes:

  1. Changed input to :checkbox.
  2. Comparing the length of the checked checkboxes.

Is it possible to have a custom facebook like button?

It's possible with a lot of work.

Basically, you have to post likes action via the Open Graph API. Then, you can add a custom design to your like button.

But then, you''ll need to keep track yourself of the likes so a returning user will be able to unlike content he liked previously.

Plus, you'll need to ask user to log into your app and ask them the publish_action permission.

All in all, if you're doing this for an application, it may worth it. For a website where you basically want user to like articles, then this is really to much.

Also, consider that you increase your drop-off rate each time you ask user a permission via a Facebook login.

If you want to see an example, I've recently made an app using the open graph like button, just hover on some photos in the mosaique to see it

Count number of 1's in binary representation

The below method can count the number of 1s in negative numbers as well.

private static int countBits(int number)    {
    int result = 0;
    while(number != 0)  {
        result += number & 1;
        number = number >>> 1;
    }
    return result;
}

However, a number like -1 is represented in binary as 11111111111111111111111111111111 and so will require a lot of shifting. If you don't want to do so many shifts for small negative numbers, another way could be as follows:

private static int countBits(int number)    {
    boolean negFlag = false;
    if(number < 0)  { 
        negFlag = true;
        number = ~number;
    }

    int result = 0;
    while(number != 0)  {
        result += number & 1;
        number = number >> 1;
    }
    return negFlag? (32-result): result;
}

What does "Object reference not set to an instance of an object" mean?

Most of the time, when you try to assing value into object, and if the value is null, then this kind of exception occur. Please check this link.

for the sake of self learning, you can put some check condition. like

if (myObj== null)
Console.Write("myObj is NULL");

How to insert multiple rows from array using CodeIgniter framework?

You could prepare the query for inserting one row using the mysqli_stmt class, and then iterate over the array of data. Something like:

$stmt =  $db->stmt_init();
$stmt->prepare("INSERT INTO mytbl (fld1, fld2, fld3, fld4) VALUES(?, ?, ?, ?)");
foreach($myarray as $row)
{
    $stmt->bind_param('idsb', $row['fld1'], $row['fld2'], $row['fld3'], $row['fld4']);
    $stmt->execute();
}
$stmt->close();

Where 'idsb' are the types of the data you're binding (int, double, string, blob).

Docker: adding a file from a parent directory

If you are using skaffold, use 'context:' to specify context location for each image dockerfile - context: ../../../

            apiVersion: skaffold/v2beta4
            kind: Config
            metadata:
                name: frontend
            build:
                artifacts:
                    - image: nginx-angular-ui
                      context: ../../../
                      sync:
                          # A local build will update dist and sync it to the container
                          manual:
                              - src: './dist/apps'
                                dest: '/usr/share/nginx/html'
                      docker:
                          dockerfile: ./tools/pipelines/dockerfile/nginx.dev.dockerfile
                    - image: webapi/image
                      context: ../../../../api/
                      docker:
                          dockerfile: ./dockerfile
            deploy:
                kubectl:
                    manifests:
                        - ./.k8s/*.yml

skaffold run -f ./skaffold.yaml

How to get the MD5 hash of a file in C++?

For anyone redirected from "https://stackoverflow.com/questions/4393017/md5-implementation-in-c" because it's been incorrectly labelled a duplicate.

The example located here works:

http://www.zedwood.com/article/cpp-md5-function

If you are compiling in VC++2010 then you will need to change his main.cpp to this:

#include <iostream> //for std::cout
#include <string.h> //for std::string
#include "MD5.h"

using std::cout; using std::endl;

int main(int argc, char *argv[])
{
    std::string Temp =  md5("The quick brown fox jumps over the lazy dog");
    cout << Temp.c_str() << endl;

    return 0;
}

You will have to change the MD5 class slightly if you are to read in a char * array instead of a string to answer the question on this page here.

EDIT:

Apparently modifying the MD5 library isn't clear, well a Full VC++2010 solution is here for your convenience to include char *'s:

https://github.com/alm4096/MD5-Hash-Example-VS

A bit of an explanation is here:

#include <iostream> //for std::cout
#include <string.h> //for std::string
#include <fstream>
#include "MD5.h"

using std::cout; using std::endl;

int main(int argc, char *argv[])
{
    //Start opening your file
    ifstream inBigArrayfile;
    inBigArrayfile.open ("Data.dat", std::ios::binary | std::ios::in);

    //Find length of file
    inBigArrayfile.seekg (0, std::ios::end);
    long Length = inBigArrayfile.tellg();
    inBigArrayfile.seekg (0, std::ios::beg);    

    //read in the data from your file
    char * InFileData = new char[Length];
    inBigArrayfile.read(InFileData,Length);

    //Calculate MD5 hash
    std::string Temp =  md5(InFileData,Length);
    cout << Temp.c_str() << endl;

    //Clean up
    delete [] InFileData;

    return 0;
}

I have simply added the following into the MD5 library:

MD5.cpp:

MD5::MD5(char * Input, long length)
{
  init();
  update(Input, length);
  finalize();
}

MD5.h:

std::string md5(char * Input, long length);

How to specify the current directory as path in VBA?

I thought I had misunderstood but I was right. In this scenario, it will be ActiveWorkbook.Path

But the main issue was not here. The problem was with these 2 lines of code

strFile = Dir(strPath & "*.csv")

Which should have written as

strFile = Dir(strPath & "\*.csv")

and

With .QueryTables.Add(Connection:="TEXT;" & strPath & strFile, _

Which should have written as

With .QueryTables.Add(Connection:="TEXT;" & strPath & "\" & strFile, _

How to get table list in database, using MS SQL 2008?

This query will get you all the tables in the database

USE [DatabaseName];

SELECT * FROM information_schema.tables;

WHERE statement after a UNION in SQL?

If you want to apply the WHERE clause to the result of the UNION, then you have to embed the UNION in the FROM clause:

SELECT *
  FROM (SELECT * FROM TableA
        UNION
        SELECT * FROM TableB
       ) AS U
 WHERE U.Col1 = ...

I'm assuming TableA and TableB are union-compatible. You could also apply a WHERE clause to each of the individual SELECT statements in the UNION, of course.

Loading custom functions in PowerShell

You have to dot source them:

. .\build_funtions.ps1
. .\build_builddefs.ps1

Note the extra .

This heyscriptingguy article should be of help - How to Reuse Windows PowerShell Functions in Scripts

delete a column with awk or sed

This might work for you (GNU sed):

sed -i -r 's/\S+//3' file

If you want to delete the white space before the 3rd field:

sed -i -r 's/(\s+)?\S+//3' file

Vue JS mounted()

You can also move mounted out of the Vue instance and make it a function in the top-level scope. This is also a useful trick for server side rendering in Vue.

function init() {
  // Use `this` normally
}

new Vue({
  methods:{
    init
  },
  mounted(){
    init.call(this)
  }
})

Set UITableView content inset permanently

In Swift:

override func viewDidLayoutSubviews() {
      super.viewDidLayoutSubviews()
      self.tableView.contentInset = UIEdgeInsets(top: 108, left: 0, bottom: 0, right: 0)
}

Proper way to initialize a C# dictionary with values?

You can initialize a Dictionary (and other collections) inline. Each member is contained with braces:

Dictionary<int, StudentName> students = new Dictionary<int, StudentName>
{
    { 111, new StudentName { FirstName = "Sachin", LastName = "Karnik", ID = 211 } },
    { 112, new StudentName { FirstName = "Dina", LastName = "Salimzianova", ID = 317 } },
    { 113, new StudentName { FirstName = "Andy", LastName = "Ruth", ID = 198 } }
};

See Microsoft Docs for details.

Convert char* to string C++

There seems to be a few details left out of your explanation, but I will do my best...

If these are NUL-terminated strings or the memory is pre-zeroed, you can just iterate down the length of the memory segment until you hit a NUL (0) character or the maximum length (whichever comes first). Use the string constructor, passing the buffer and the size determined in the previous step.

string retrieveString( char* buf, int max ) {

    size_t len = 0;
    while( (len < max) && (buf[ len ] != '\0') ) {
        len++;
    }

    return string( buf, len );

}

If the above is not the case, I'm not sure how you determine where a string ends.

Docker: Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock

2019-02-16

Most of the steps were the same for me as the others has written. However, I was not able to add jenkins to the group docker using usermod with the mentioned solutions.

I tried the following command from the docker host, and from the running docker container:

sudo usermod -a -G docker jenkins

(I entered to the running docker container with the following command from the docker host:

docker exec -t -i my_container_id_or_name /bin/bash

)

Received from docker host:

usermod: user 'jenkins' does not exist

Received from docker container:

We trust you have received the usual lecture from the local System Administrator. It usually boils down to these three things:

#1) Respect the privacy of others.
#2) Think before you type.
#3) With great power comes great responsibility.

[sudo] password for jenkins:

I didnt know the password.

Without the sudo part of the command, in the docker container I received:

usermod: Permission denied. usermod: cannot lock /etc/passwd; try again later.

Solution: I entered to the running docker container from the docker host with the following command:

docker exec -t -i -u root my_container_id_or_name /bin/bash

Now, I entered as root, and issued the following command:

usermod -a -G docker jenkins

Then, from the docker host, I restarted my running docker container with the following command:

docker restart my_container_id_or_name

After that, I started the jenkins job and it finished with success.

I only used the root user to issue the usermod command for the user jenkins.

A generic list of anonymous class

I checked the IL on several answers. This code efficiently provides an empty List:

    using System.Linq;
    …
    var list = new[]{new{Id = default(int), Name = default(string)}}.Skip(1).ToList();

Annotations from javax.validation.constraints not working

You need to add @Valid to each member variable, which was also an object that contained validation constraints.

how to set start page in webconfig file in asp.net c#

You can achieve it by code also, In you Global.asax file in Session_Start event write response.redirect to your start page like following.

void Session_Start(object sender, EventArgs e)
        {
            // Code that runs when a new session is started

            Response.Redirect("~/Index.aspx");

        }

You can get redirect page name from database or any other storage to change the application start page while application is running no need to edit web.config or change any IIS settings

difference between width auto and width 100 percent

It's about margins and border. If you use width: auto, then add border, your div won't become bigger than its container. On the other hand, if you use width: 100% and some border, the element's width will be 100% + border or margin. For more info see this.

When is the finalize() method called in Java?

finalize method is not guaranteed.This method is called when the object becomes eligible for GC. There are many situations where the objects may not be garbage collected.

Split text file into smaller multiple text file using command line

I know the question has been asked a long time ago, but I am surprised that nobody has given the most straightforward unix answer:

split -l 5000 -d --additional-suffix=.txt $FileName file
  • -l 5000: split file into files of 5,000 lines each.
  • -d: numerical suffix. This will make the suffix go from 00 to 99 by default instead of aa to zz.
  • --additional-suffix: lets you specify the suffix, here the extension
  • $FileName: name of the file to be split.
  • file: prefix to add to the resulting files.

As always, check out man split for more details.

For Mac, the default version of split is apparently dumbed down. You can install the GNU version using the following command. (see this question for more GNU utils)

brew install coreutils

and then you can run the above command by replacing split with gsplit. Check out man gsplit for details.

When use ResponseEntity<T> and @RestController for Spring RESTful applications

According to official documentation: Creating REST Controllers with the @RestController annotation

@RestController is a stereotype annotation that combines @ResponseBody and @Controller. More than that, it gives more meaning to your Controller and also may carry additional semantics in future releases of the framework.

It seems that it's best to use @RestController for clarity, but you can also combine it with ResponseEntity for flexibility when needed (According to official tutorial and the code here and my question to confirm that).

For example:

@RestController
public class MyController {

    @GetMapping(path = "/test")
    @ResponseStatus(HttpStatus.OK)
    public User test() {
        User user = new User();
        user.setName("Name 1");

        return user;
    }

}

is the same as:

@RestController
public class MyController {

    @GetMapping(path = "/test")
    public ResponseEntity<User> test() {
        User user = new User();
        user.setName("Name 1");

        HttpHeaders responseHeaders = new HttpHeaders();
        // ...
        return new ResponseEntity<>(user, responseHeaders, HttpStatus.OK);
    }

}

This way, you can define ResponseEntity only when needed.

Update

You can use this:

    return ResponseEntity.ok().headers(responseHeaders).body(user);

How can I force clients to refresh JavaScript files?

Appending the current time to the URL is indeed a common solution. However, you can also manage this at the web server level, if you want to. The server can be configured to send different HTTP headers for javascript files.

For example, to force the file to be cached for no longer than 1 day, you would send:

Cache-Control: max-age=86400, must-revalidate

For beta, if you want to force the user to always get the latest, you would use:

Cache-Control: no-cache, must-revalidate

Is it possible to decrypt SHA1

SHA1 is a one way hash. So you can not really revert it.

That's why applications use it to store the hash of the password and not the password itself.

Like every hash function SHA-1 maps a large input set (the keys) to a smaller target set (the hash values). Thus collisions can occur. This means that two values of the input set map to the same hash value.

Obviously the collision probability increases when the target set is getting smaller. But vice versa this also means that the collision probability decreases when the target set is getting larger and SHA-1's target set is 160 bit.

Jeff Preshing, wrote a very good blog about Hash Collision Probabilities that can help you to decide which hash algorithm to use. Thanks Jeff.

In his blog he shows a table that tells us the probability of collisions for a given input set.

Hash Collision Probabilities Table

As you can see the probability of a 32-bit hash is 1 in 2 if you have 77163 input values.

A simple java program will show us what his table shows:

public class Main {

    public static void main(String[] args) {
        char[] inputValue = new char[10];

        Map<Integer, String> hashValues = new HashMap<Integer, String>();

        int collisionCount = 0;

        for (int i = 0; i < 77163; i++) {
            String asString = nextValue(inputValue);
            int hashCode = asString.hashCode();
            String collisionString = hashValues.put(hashCode, asString);
            if (collisionString != null) {
                collisionCount++;
                System.out.println("Collision: " + asString + " <-> " + collisionString);
            }
        }

        System.out.println("Collision count: " + collisionCount);
    }

    private static String nextValue(char[] inputValue) {
        nextValue(inputValue, 0);

        int endIndex = 0;
        for (int i = 0; i < inputValue.length; i++) {
            if (inputValue[i] == 0) {
                endIndex = i;
                break;
            }
        }

        return new String(inputValue, 0, endIndex);
    }

    private static void nextValue(char[] inputValue, int index) {
        boolean increaseNextIndex = inputValue[index] == 'z';

        if (inputValue[index] == 0 || increaseNextIndex) {
            inputValue[index] = 'A';
        } else {
            inputValue[index] += 1;
        }

        if (increaseNextIndex) {
            nextValue(inputValue, index + 1);
        }

    }

}

My output end with:

Collision: RvV <-> SWV
Collision: SvV <-> TWV
Collision: TvV <-> UWV
Collision: UvV <-> VWV
Collision: VvV <-> WWV
Collision: WvV <-> XWV
Collision count: 35135

It produced 35135 collsions and that's the nearly the half of 77163. And if I ran the program with 30084 input values the collision count is 13606. This is not exactly 1 in 10, but it is only a probability and the example program is not perfect, because it only uses the ascii chars between A and z.

Let's take the last reported collision and check

System.out.println("VvV".hashCode());
System.out.println("WWV".hashCode());

My output is

86390
86390

Conclusion:

If you have a SHA-1 value and you want to get the input value back you can try a brute force attack. This means that you have to generate all possible input values, hash them and compare them with the SHA-1 you have. But that will consume a lot of time and computing power. Some people created so called rainbow tables for some input sets. But these do only exist for some small input sets.

And remember that many input values map to a single target hash value. So even if you would know all mappings (which is impossible, because the input set is unbounded) you still can't say which input value it was.

How to compare only date components from DateTime in EF?

Just always compare the Date property of DateTime, instead of the full date time.

When you make your LINQ query, use date.Date in the query, ie:

var results = from c in collection
              where c.Date == myDateTime.Date
              select c;

PHP page redirect

if you want to include the redirect in your php file without necessarily having it at the top, you can activate output buffering at the top, then call redirect from anywhere within the page. Example;

 <?php
 ob_start(); //first line
 ... do some work here
 ... do some more
 header("Location: http://www.yourwebsite.com/user.php"); 
 exit();
 ... do some work here
 ... do some more

How can I set the background color of <option> in a <select> element?

Just like normal background-color: #f0f

You just need a way to target it, eg: <option id="myPinkOption">blah</option>

Displaying Image in Java

import java.awt.FlowLayout;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

public class DisplayImage {

    public static void main(String avg[]) throws IOException
    {
        DisplayImage abc=new DisplayImage();
    }

    public DisplayImage() throws IOException
    {
        BufferedImage img=ImageIO.read(new File("f://images.jpg"));
        ImageIcon icon=new ImageIcon(img);
        JFrame frame=new JFrame();
        frame.setLayout(new FlowLayout());
        frame.setSize(200,300);
        JLabel lbl=new JLabel();
        lbl.setIcon(icon);
        frame.add(lbl);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

Static nested class in Java, why?

Well, for one thing, non-static inner classes have an extra, hidden field that points to the instance of the outer class. So if the Entry class weren't static, then besides having access that it doesn't need, it would carry around four pointers instead of three.

As a rule, I would say, if you define a class that's basically there to act as a collection of data members, like a "struct" in C, consider making it static.

Package doesn't exist error in intelliJ

What happens here is the particular package is not available in the cache. Resetting will help solve the problem.

  1. File -> Invalidate Caches /Restart
  2. Goto terminal and build the project again

    ./gradlew build
    

This should download all the missing packages again

Implementing Singleton with an Enum (in Java)

As has, to some extent, been mentioned before, an enum is a java class with the special condition that its definition must start with at least one "enum constant".

Apart from that, and that enums cant can't be extended or used to extend other classes, an enum is a class like any class and you use it by adding methods below the constant definitions:

public enum MySingleton {
    INSTANCE;

    public void doSomething() { ... }

    public synchronized String getSomething() { return something; }

    private String something;
}

You access the singleton's methods along these lines:

MySingleton.INSTANCE.doSomething();
String something = MySingleton.INSTANCE.getSomething();

The use of an enum, instead of a class, is, as has been mentioned in other answers, mostly about a thread-safe instantiation of the singleton and a guarantee that it will always only be one copy.

And, perhaps, most importantly, that this behavior is guaranteed by the JVM itself and the Java specification.

Here's a section from the Java specification on how multiple instances of an enum instance is prevented:

An enum type has no instances other than those defined by its enum constants. It is a compile-time error to attempt to explicitly instantiate an enum type. The final clone method in Enum ensures that enum constants can never be cloned, and the special treatment by the serialization mechanism ensures that duplicate instances are never created as a result of deserialization. Reflective instantiation of enum types is prohibited. Together, these four things ensure that no instances of an enum type exist beyond those defined by the enum constants.

Worth noting is that after the instantiation any thread-safety concerns must be handled like in any other class with the synchronized keyword etc.

Calculate the display width of a string in Java

I personally was searching for something to let me compute the multiline string area, so I could determine if given area is big enough to print the string - with preserving specific font.

private static Hashtable hash = new Hashtable();
private Font font;
private LineBreakMeasurer lineBreakMeasurer;
private int start, end;

public PixelLengthCheck(Font font) {
    this.font = font;
}

public boolean tryIfStringFits(String textToMeasure, Dimension areaToFit) {
    AttributedString attributedString = new AttributedString(textToMeasure, hash);
    attributedString.addAttribute(TextAttribute.FONT, font);
    AttributedCharacterIterator attributedCharacterIterator =
            attributedString.getIterator();
    start = attributedCharacterIterator.getBeginIndex();
    end = attributedCharacterIterator.getEndIndex();

    lineBreakMeasurer = new LineBreakMeasurer(attributedCharacterIterator,
            new FontRenderContext(null, false, false));

    float width = (float) areaToFit.width;
    float height = 0;
    lineBreakMeasurer.setPosition(start);

    while (lineBreakMeasurer.getPosition() < end) {
        TextLayout textLayout = lineBreakMeasurer.nextLayout(width);
        height += textLayout.getAscent();
        height += textLayout.getDescent() + textLayout.getLeading();
    }

    boolean res = height <= areaToFit.getHeight();

    return res;
}

Detect all changes to a <input type="text"> (immediately) using JQuery

Add this code somewhere, this will do the trick.

var originalVal = $.fn.val;
$.fn.val = function(){
    var result =originalVal.apply(this,arguments);
    if(arguments.length>0)
        $(this).change(); // OR with custom event $(this).trigger('value-changed');
    return result;
};

Found this solution at val() doesn't trigger change() in jQuery

show and hide divs based on radio button click

The hide selector was incorrect. I hid the blocks at page load and showed the selected value. I also changed the car div id's to make it easier to append the radio button value and create the proper id selector.

<div id="myRadioGroup">
  2 Cars<input type="radio" name="cars" checked="checked" value="2"  />
  3 Cars<input type="radio" name="cars" value="3" />
  <div id="car-2">
  2 Cars
  </div>
  <div id="car-3">
  3 Cars
  </div>
</div>

<script type="text/javascript">
$(document).ready(function(){ 
  $("div div").hide();
  $("#car-2").show();
  $("input[name$='cars']").click(function() {
      var test = $(this).val();
      $("div div").hide();
      $("#car-"+test).show();
  }); 
});
</script>

Excel VBA Automation Error: The object invoked has disconnected from its clients

Couple of things to try...

  1. Comment out the second "Set NewBook" line of code...

  2. You already have an object reference to the workbook.

  3. Do your SaveAs after copying the sheets.

NodeJs : TypeError: require(...) is not a function

I think this means that module.exports in your ./app/routes module is not assigned to be a function so therefore require('./app/routes') does not resolve to a function so therefore, you cannot call it as a function like this require('./app/routes')(app, passport).

Show us ./app/routes if you want us to comment further on that.

It should look something like this;

module.exports = function(app, passport) {
    // code here
}

You are exporting a function that can then be called like require('./app/routes')(app, passport).


One other reason a similar error could occur is if you have a circular module dependency where module A is trying to require(B) and module B is trying to require(A). When this happens, it will be detected by the require() sub-system and one of them will come back as null and thus trying to call that as a function will not work. The fix in that case is to remove the circular dependency, usually by breaking common code into a third module that both can separately load though the specifics of fixing a circular dependency are unique for each situation.

How do you set a JavaScript onclick event to a class with css

Asking about "a class" in the question title, the answer is getElementsByClassName:

  var hrefs = document.getElementsByClassName("YOUR-CLASS-NAME-HERE");
  for (var i = 0; i < hrefs.length; i++) {
   hrefs.item(i).addEventListener('click', function(e){
    e.preventDefault(); /*use if you want to prevent the original link following action*/
    alert('hohoho');
   });
  }

ORA-12154 could not resolve the connect identifier specified

I am going to assume you are using the tnsnames.ora file to specify your available database services. If so connection errors usually come down to two things.

  1. The application cannot find the TNS entry you specified in the connection string.

  2. The TNS entry was found, but the IP or host is not correct in the tnsnames.ora file.

To expand on number 1 (which I think is your problem). When you tell Oracle to connect using something like:

sqlplus user/pass@service

The service is defined in the tnsnames.ora file. If I attempt to connect with a service that is not defined in my tnsnames.ora, I get the error you get:

[sodonnel@home ~]$ sqlplus sodonnel/sodonnel@nowhere

SQL*Plus: Release 11.2.0.1.0 Production on Mon Oct 31 21:42:15 2011

Copyright (c) 1982, 2009, Oracle.  All rights reserved.

ERROR:
ORA-12154: TNS:could not resolve the connect identifier specified

So you need to check a few things:

  1. Is there a tnsnames.ora file - I think yes because your console can connect
  2. Is there an entry in the file for the service - I think also yes as the console connects
  3. Can the application find the tnsnames.ora?

Your problem may well be number 3 - does the application run as a different user than when you run the console?

Oracle looks for the tnsnames.ora file in the directory defined in the TNS_ADMIN environment variable - If you are running as different users, then maybe the TNS_ADMIN environment variable is not set, and therefore it cannot find the file?

Are PostgreSQL column names case-sensitive?

The column names which are mixed case or uppercase have to be double quoted in PostgresQL. So best convention will be to follow all small case with underscore.

android ellipsize multiline textview

The top answer here from Micah Hainline works great, but even better is the library that was built from it by user aleb as he posted in the comments under Micahs answer:

I created an Android library with this component and changed it to be able to show as many lines of text as possible and ellipsize the last one; see github.com/triposo/barone

There are some more features to it, if you only need the TextView, it is here.

Maybe this will help others find it faster than I did :-)

Get Row Index on Asp.net Rowcommand event

I was able to use @rahularyansharma's answer above in my own project, with one minor modification. I needed to get the value of particular cells on the row on which the user clicks a LinkButton. The second line can be modified to get the value of as many cells as you wish.

Here is my solution:

GridViewRow gvr = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);
string typecore = gvr.Cells[3].Text.ToString().Trim();

How to run a program automatically as admin on Windows 7 at startup?

You need to plug it into the task scheduler, such that it is launched after login of a user, using a user account that has administrative access on the system, with the highest privileges that are afforded to processes launched by that account.

This is the implementation that is used to autostart processes with administrative privileges when logging in as an ordinary user.

I've used it to launch the 'OpenVPN GUI' helper process which needs elevated privileges to work correctly, and thus would not launch properly from the registry key.

From the command line, you can create the task from an XML description of what you want to accomplish; so for example we have this, exported from my system, which would start notepad with the highest privileges when i log in:

<?xml version="1.0" encoding="UTF-16"?>
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
  <RegistrationInfo>
    <Date>2015-01-27T18:30:34</Date>
    <Author>Pete</Author>
  </RegistrationInfo>
  <Triggers>
    <LogonTrigger>
      <StartBoundary>2015-01-27T18:30:00</StartBoundary>
      <Enabled>true</Enabled>
    </LogonTrigger>
  </Triggers>
  <Principals>
    <Principal id="Author">
      <UserId>CHUMBAWUMBA\Pete</UserId>
      <LogonType>InteractiveToken</LogonType>
      <RunLevel>HighestAvailable</RunLevel>
    </Principal>
  </Principals>
  <Settings>
    <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
    <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
    <StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>
    <AllowHardTerminate>true</AllowHardTerminate>
    <StartWhenAvailable>false</StartWhenAvailable>
    <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
    <IdleSettings>
      <StopOnIdleEnd>true</StopOnIdleEnd>
      <RestartOnIdle>false</RestartOnIdle>
    </IdleSettings>
    <AllowStartOnDemand>true</AllowStartOnDemand>
    <Enabled>true</Enabled>
    <Hidden>false</Hidden>
    <RunOnlyIfIdle>false</RunOnlyIfIdle>
    <WakeToRun>false</WakeToRun>
    <ExecutionTimeLimit>PT0S</ExecutionTimeLimit>
    <Priority>7</Priority>
  </Settings>
  <Actions Context="Author">
    <Exec>
      <Command>"c:\windows\system32\notepad.exe"</Command>
    </Exec>
  </Actions>
</Task>

and it's registered by an administrator command prompt using:

schtasks /create /tn "start notepad on login" /xml startnotepad.xml

this answer should really be moved over to one of the other stackexchange sites, as it's not actually a programming question per se.

How to change value of object which is inside an array using JavaScript or jQuery?

This is my response to the problem. My underscore version was 1.7 hence I could not use .findIndex.

So I manually got the index of item and replaced it. Here is the code for the same.

 var students = [ 
{id:1,fName:"Ajay", lName:"Singh", age:20, sex:"M" },
{id:2,fName:"Raj", lName:"Sharma", age:21, sex:"M" },
{id:3,fName:"Amar", lName:"Verma", age:22, sex:"M" },
{id:4,fName:"Shiv", lName:"Singh", age:22, sex:"M" }
               ]

Below method will replace the student with id:4 with more attributes in the object

function updateStudent(id) {
 var indexOfRequiredStudent = -1;
    _.each(students,function(student,index) {                    
      if(student.id === id) {                        
           indexOfRequiredStudent = index; return;      
      }});
 students[indexOfRequiredStudent] = _.extend(students[indexOfRequiredStudent],{class:"First Year",branch:"CSE"});           

}

With underscore 1.8 it will be simplified as we have methods _.findIndexOf.

Chrome ignores autocomplete="off"

After lot of digging I found that autocomplete dropdown on Chrome(Version 83.0.4103.116) doesn't shows up when we remove name and id attribute on input tag eg. code as below

_x000D_
_x000D_
<div>
<span>
  Auto complete off works if name and id attribute is not set on input tag 
  <input type="text"/>
</span>
<span>
  Auto complete will work here since id attribute is set
  <input id="name" type="text"/>
</span>
</div>
_x000D_
_x000D_
_x000D_

Best Way to Refresh Adapter/ListView on Android

adapter.notifyDataSetChanged();

how to achieve transfer file between client and server using java socket

Reading quickly through the source it seems that you're not far off. The following link should help (I did something similar but for FTP). For a file send from server to client, you start off with a file instance and an array of bytes. You then read the File into the byte array and write the byte array to the OutputStream which corresponds with the InputStream on the client's side.

http://www.rgagnon.com/javadetails/java-0542.html

Edit: Here's a working ultra-minimalistic file sender and receiver. Make sure you understand what the code is doing on both sides.

package filesendtest;

import java.io.*;
import java.net.*;

class TCPServer {

    private final static String fileToSend = "C:\\test1.pdf";

    public static void main(String args[]) {

        while (true) {
            ServerSocket welcomeSocket = null;
            Socket connectionSocket = null;
            BufferedOutputStream outToClient = null;

            try {
                welcomeSocket = new ServerSocket(3248);
                connectionSocket = welcomeSocket.accept();
                outToClient = new BufferedOutputStream(connectionSocket.getOutputStream());
            } catch (IOException ex) {
                // Do exception handling
            }

            if (outToClient != null) {
                File myFile = new File( fileToSend );
                byte[] mybytearray = new byte[(int) myFile.length()];

                FileInputStream fis = null;

                try {
                    fis = new FileInputStream(myFile);
                } catch (FileNotFoundException ex) {
                    // Do exception handling
                }
                BufferedInputStream bis = new BufferedInputStream(fis);

                try {
                    bis.read(mybytearray, 0, mybytearray.length);
                    outToClient.write(mybytearray, 0, mybytearray.length);
                    outToClient.flush();
                    outToClient.close();
                    connectionSocket.close();

                    // File sent, exit the main method
                    return;
                } catch (IOException ex) {
                    // Do exception handling
                }
            }
        }
    }
}

package filesendtest;

import java.io.*;
import java.io.ByteArrayOutputStream;
import java.net.*;

class TCPClient {

    private final static String serverIP = "127.0.0.1";
    private final static int serverPort = 3248;
    private final static String fileOutput = "C:\\testout.pdf";

    public static void main(String args[]) {
        byte[] aByte = new byte[1];
        int bytesRead;

        Socket clientSocket = null;
        InputStream is = null;

        try {
            clientSocket = new Socket( serverIP , serverPort );
            is = clientSocket.getInputStream();
        } catch (IOException ex) {
            // Do exception handling
        }

        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        if (is != null) {

            FileOutputStream fos = null;
            BufferedOutputStream bos = null;
            try {
                fos = new FileOutputStream( fileOutput );
                bos = new BufferedOutputStream(fos);
                bytesRead = is.read(aByte, 0, aByte.length);

                do {
                        baos.write(aByte);
                        bytesRead = is.read(aByte);
                } while (bytesRead != -1);

                bos.write(baos.toByteArray());
                bos.flush();
                bos.close();
                clientSocket.close();
            } catch (IOException ex) {
                // Do exception handling
            }
        }
    }
}

Related

Byte array of unknown length in java

Edit: The following could be used to fingerprint small files before and after transfer (use SHA if you feel it's necessary):

public static String md5String(File file) {
    try {
        InputStream fin = new FileInputStream(file);
        java.security.MessageDigest md5er = MessageDigest.getInstance("MD5");
        byte[] buffer = new byte[1024];
        int read;
        do {
            read = fin.read(buffer);
            if (read > 0) {
                md5er.update(buffer, 0, read);
            }
        } while (read != -1);
        fin.close();
        byte[] digest = md5er.digest();
        if (digest == null) {
            return null;
        }
        String strDigest = "0x";
        for (int i = 0; i < digest.length; i++) {
            strDigest += Integer.toString((digest[i] & 0xff)
                    + 0x100, 16).substring(1).toUpperCase();
        }
        return strDigest;
    } catch (Exception e) {
        return null;
    }
}

Equivalent of "continue" in Ruby

Use next, it will bypass that condition and rest of the code will work. Below i have provided the Full script and out put

class TestBreak
  puts " Enter the nmber"
  no= gets.to_i
  for i in 1..no
    if(i==5)
      next
    else 
      puts i
    end
  end
end

obj=TestBreak.new()

Output: Enter the nmber 10

1 2 3 4 6 7 8 9 10

What are the advantages of NumPy over regular Python lists?

All have highlighted almost all major differences between numpy array and python list, I will just brief them out here:

  1. Numpy arrays have a fixed size at creation, unlike python lists (which can grow dynamically). Changing the size of ndarray will create a new array and delete the original.

  2. The elements in a Numpy array are all required to be of the same data type (we can have the heterogeneous type as well but that will not gonna permit you mathematical operations) and thus will be the same size in memory

  3. Numpy arrays are facilitated advances mathematical and other types of operations on large numbers of data. Typically such operations are executed more efficiently and with less code than is possible using pythons build in sequences

Right way to convert data.frame to a numeric matrix, when df also contains strings?

Edit 2: See @flodel's answer. Much better.

Try:

# assuming SFI is your data.frame
as.matrix(sapply(SFI, as.numeric))  

Edit: or as @ CarlWitthoft suggested in the comments:

matrix(as.numeric(unlist(SFI)),nrow=nrow(SFI))

Checking if sys.argv[x] is defined

Another way I haven't seen listed yet is to set your sentinel value ahead of time. This method takes advantage of Python's lazy evaluation, in which you don't always have to provide an else statement. Example:

startingpoint = 'blah'
if len(sys.argv) >= 2:
  startingpoint = sys.argv[1]

Or if you're going syntax CRAZY you could use Python's ternary operator:

startingpoint = sys.argv[1] if len(sys.argv) >= 2 else 'blah'

Why does Date.parse give incorrect results?

This light weight date parsing library should solve all similar problems. I like the library because it is quite easy to extend. It's also possible to i18n it (not very straight forward, but not that hard).

Parsing example:

var caseOne = Date.parseDate("Jul 8, 2005", "M d, Y");
var caseTwo = Date.parseDate("2005-07-08", "Y-m-d");

And formatting back to string (you will notice both cases give exactly the same result):

console.log( caseOne.dateFormat("M d, Y") );
console.log( caseTwo.dateFormat("M d, Y") );
console.log( caseOne.dateFormat("Y-m-d") );
console.log( caseTwo.dateFormat("Y-m-d") );

How to generate a random number between a and b in Ruby?

Just note the difference between the range operators:

3..10  # includes 10
3...10 # doesn't include 10

AngularJS error: 'argument 'FirstCtrl' is not a function, got undefined'

sometimes something wrong in the syntax of the code inside the function throws this error. Check your function correctly. In my case it happened when I was trying to assign Json fields with values and was using colon : to make the assignment instead of equal sign = ...

json: cannot unmarshal object into Go value of type

Here's a fixed version of it: http://play.golang.org/p/w2ZcOzGHKR

The biggest fix that was needed is when Unmarshalling an array, that property needs to be an array/slice in the struct as well.

For example:

{ "things": ["a", "b", "c"] }

Would Unmarshal into a:

type Item struct {
    Things []string
}

And not into:

type Item struct {
    Things string
}

The other thing to watch out for when Unmarshaling is that the types line up exactly. It will fail when Unmarshalling a JSON string representation of a number into an int or float field -- "1" needs to Unmarshal into a string, not into an int like we saw with ShippingAdditionalCost int

How to get the selected radio button value using js

you can use this

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

or, for older version of jquery

$('input[@name="field_value"]:checked').val();

Using Get-childitem to get a list of files modified in the last 3 days

I wanted to just add this as a comment to the previous answer, but I can't. I tried Dave Sexton's answer but had problems if the count was 1. This forces an array even if one object is returned.

([System.Object[]](gci c:\pstback\ -Filter *.pst | 
    ? { $_.LastWriteTime -gt (Get-Date).AddDays(-3)})).Count

It still doesn't return zero if empty, but testing '-lt 1' works.