Programs & Examples On #Radchart

RadChart is a feature-rich charting control for the .Net platform developed by Telerik.

Listing files in a specific "folder" of a AWS S3 bucket

While everybody say that there are no directories and files in s3, but only objects (and buckets), which is absolutely true, I would suggest to take advantage of CommonPrefixes, described in this answer. So, you can do following to get list of "folders" (commonPrefixes) and "files" (objectSummaries):

ListObjectsV2Request req = new ListObjectsV2Request().withBucketName(bucket.getName()).withPrefix(prefix).withDelimiter(DELIMITER);
ListObjectsV2Result listing = s3Client.listObjectsV2(req);
for (String commonPrefix : listing.getCommonPrefixes()) {
        System.out.println(commonPrefix);
}
for (S3ObjectSummary summary: listing.getObjectSummaries()) {
    System.out.println(summary.getKey());
}

In your case, for objectSummaries (files) it should return (in case of correct prefix):
users/user-id/contacts/contact-id/file1.txt
users/user-id/contacts/contact-id/file2.txt

for commonPrefixes:
users/user-id/contacts/contact-id/

Reference: https://docs.aws.amazon.com/AmazonS3/latest/API/API_ListObjectsV2.html

What is the difference between re.search and re.match?

re.search searches for the pattern throughout the string, whereas re.match does not search the pattern; if it does not, it has no other choice than to match it at start of the string.

ROW_NUMBER() in MySQL

This is not the most robust solution - but if you're just looking to create a partitioned rank on a field with only a few different values, it may not be unwieldily to use some case when logic with as many variables as you require.

Something like this has worked for me in the past:

SELECT t.*, 
   CASE WHEN <partition_field> = @rownum1 := @rownum1 + 1 
     WHEN <partition_field> = @rownum2 := @rownum2 + 1 
     ...
     END AS rank
FROM YOUR_TABLE t, 
   (SELECT @rownum1 := 0) r1, (SELECT @rownum2 := 0) r2
ORDER BY <rank_order_by_field>
;

Hope that makes sense / helps!

Combine two integer arrays

Here a simple function that use variable arguments:

final static
public int[] merge(final int[] ...arrays ) {
    int size = 0;
    for ( int[] a: arrays )
        size += a.length;

        int[] res = new int[size];

        int destPos = 0;
        for ( int i = 0; i < arrays.length; i++ ) {
            if ( i > 0 ) destPos += arrays[i-1].length;
            int length = arrays[i].length;
            System.arraycopy(arrays[i], 0, res, destPos, length);
        }

        return res;
}

To use:

int[] array1 = {1,2,3};
int[] array2 = {4,5,6};
int[] array3 = {7,8,9};
int[] array1and2and3 = merge(array1, array2, array3);
for ( int x: array1and2and3 ) 
    System.out.print( String.format("%3d", x) );

Find and replace string values in list

You can use, for example:

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

How to use moment.js library in angular 2 typescript app?

With systemjs what I did is, inside my systemjs.config I added map for moment

map: {
   .....,
   'moment': 'node_modules/moment/moment.js',
   .....
}

And then you can easily import moment just by doing

import * as moment from 'moment'

Local Storage vs Cookies

It is also worth mentioning that localStorage cannot be used when users browse in "private" mode in some versions of mobile Safari.

Quoted from MDN (https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage):

Note: Starting with iOS 5.1, Safari Mobile stores localStorage data in the cache folder, which is subject to occasional clean up, at the behest of the OS, typically if space is short. Safari Mobile's Private Browsing mode also prevents writing to localStorage entirely.

Get the first item from an iterable that matches a condition

The most efficient way in Python 3 are one of the following (using a similar example):

With "comprehension" style:

next(i for i in range(100000000) if i == 1000)

WARNING: The expression works also with Python 2, but in the example is used range that returns an iterable object in Python 3 instead of a list like Python 2 (if you want to construct an iterable in Python 2 use xrange instead).

Note that the expression avoid to construct a list in the comprehension expression next([i for ...]), that would cause to create a list with all the elements before filter the elements, and would cause to process the entire options, instead of stop the iteration once i == 1000.

With "functional" style:

next(filter(lambda i: i == 1000, range(100000000)))

WARNING: This doesn't work in Python 2, even replacing range with xrange due that filter create a list instead of a iterator (inefficient), and the next function only works with iterators.

Default value

As mentioned in other responses, you must add a extra-parameter to the function next if you want to avoid an exception raised when the condition is not fulfilled.

"functional" style:

next(filter(lambda i: i == 1000, range(100000000)), False)

"comprehension" style:

With this style you need to surround the comprehension expression with () to avoid a SyntaxError: Generator expression must be parenthesized if not sole argument:

next((i for i in range(100000000) if i == 1000), False)

django admin - add custom form fields that are not part of the model

It it possible to do in the admin, but there is not a very straightforward way to it. Also, I would like to advice to keep most business logic in your models, so you won't be dependent on the Django Admin.

Maybe it would be easier (and maybe even better) if you have the two seperate fields on your model. Then add a method on your model that combines them.

For example:

class MyModel(models.model):

    field1 = models.CharField(max_length=10)
    field2 = models.CharField(max_length=10)

    def combined_fields(self):
        return '{} {}'.format(self.field1, self.field2)

Then in the admin you can add the combined_fields() as a readonly field:

class MyModelAdmin(models.ModelAdmin):

    list_display = ('field1', 'field2', 'combined_fields')
    readonly_fields = ('combined_fields',)

    def combined_fields(self, obj):
        return obj.combined_fields()

If you want to store the combined_fields in the database you could also save it when you save the model:

def save(self, *args, **kwargs):
    self.field3 = self.combined_fields()
    super(MyModel, self).save(*args, **kwargs)

What does the C++ standard state the size of int, long type to be?

For floating point numbers there is a standard (IEEE754): floats are 32 bit and doubles are 64. This is a hardware standard, not a C++ standard, so compilers could theoretically define float and double to some other size, but in practice I've never seen an architecture that used anything different.

Running Groovy script from the command line

It will work on Linux kernel 2.6.28 (confirmed on 4.9.x). It won't work on FreeBSD and other Unix flavors.

Your /usr/local/bin/groovy is a shell script wrapping the Java runtime running Groovy.

See the Interpreter Scripts section of EXECVE(2) and EXECVE(2).

What is the difference between a token and a lexeme?

Token: The kind for (keywords,identifier,punctuation character, multi-character operators) is ,simply, a Token.

Pattern: A rule for formation of token from input characters.

Lexeme : Its a sequence of characters in SOURCE PROGRAM matched by a pattern for a token. Basically, its an element of Token.

Notepad++ change text color?

You can Change it from:

Menu Settings -> Style Configurator

See on screenshot:

enter image description here

A network-related or instance-specific error occurred while establishing a connection to SQL Server

Sql Server fire this error when your application don't have enough rights to access the database. there are several reason about this error . To fix this error you should follow the following instruction.

  1. Try to connect sql server from your server using management studio . if you use windows authentication to connect sql server then set your application pool identity to server administrator .

  2. if you use sql server authentication then check you connection string in web.config of your web application and set user id and password of sql server which allows you to log in .

  3. if your database in other server(access remote database) then first of enable remote access of sql server form sql server property from sql server management studio and enable TCP/IP form sql server configuration manager .

  4. after doing all these stuff and you still can't access the database then check firewall of server form where you are trying to access the database and add one rule in firewall to enable port of sql server(by default sql server use 1433 , to check port of sql server you need to check sql server configuration manager network protocol TCP/IP port).

  5. if your sql server is running on named instance then you need to write port number with sql serer name for example 117.312.21.21/nameofsqlserver,1433.

  6. If you are using cloud hosting like amazon aws or microsoft azure then server or instance will running behind cloud firewall so you need to enable 1433 port in cloud firewall if you have default instance or specific port for sql server for named instance.

  7. If you are using amazon RDS or SQL azure then you need to enable port from security group of that instance.

  8. If you are accessing sql server through sql server authentication mode them make sure you enabled "SQL Server and Windows Authentication Mode" sql server instance property. enter image description here

    1. Restart your sql server instance after making any changes in property as some changes will require restart.

if you further face any difficulty then you need to provide more information about your web site and sql server .

Validating URL in Java

The java.net.URL class is in fact not at all a good way of validating URLs. MalformedURLException is not thrown on all malformed URLs during construction. Catching IOException on java.net.URL#openConnection().connect() does not validate URL either, only tell wether or not the connection can be established.

Consider this piece of code:

    try {
        new URL("http://.com");
        new URL("http://com.");
        new URL("http:// ");
        new URL("ftp://::::@example.com");
    } catch (MalformedURLException malformedURLException) {
        malformedURLException.printStackTrace();
    }

..which does not throw any exceptions.

I recommend using some validation API implemented using a context free grammar, or in very simplified validation just use regular expressions. However I need someone to suggest a superior or standard API for this, I only recently started searching for it myself.

Note It has been suggested that URL#toURI() in combination with handling of the exception java.net. URISyntaxException can facilitate validation of URLs. However, this method only catches one of the very simple cases above.

The conclusion is that there is no standard java URL parser to validate URLs.

ASP.NET MVC Return Json Result?

It should be :

public async Task<ActionResult> GetSomeJsonData()
{
    var model = // ... get data or build model etc.

    return Json(new { Data = model }, JsonRequestBehavior.AllowGet); 
}

or more simply:

return Json(model, JsonRequestBehavior.AllowGet); 

I did notice that you are calling GetResources() from another ActionResult which wont work. If you are looking to get JSON back, you should be calling GetResources() from ajax directly...

How to create a file name with the current date & time in Python?

While not using datetime, this solves your problem (answers your question) of getting a string with the current time and date format you specify:

import time
timestr = time.strftime("%Y%m%d-%H%M%S")
print timestr

yields:

20120515-155045

so your filename could append or use this string.

How to restart a rails server on Heroku?

heroku ps:restart [web|worker] --app app_name

works for all processes declared in your Procfile. So if you have multiple web processes or worker processes, each labeled with a number, you can selectively restart one of them:

heroku ps:restart web.2 --app app_name
heroku ps:restart worker.3 --app app_name

php: check if an array has duplicates

As you specifically said you didn't want to use array_unique I'm going to ignore the other answers despite the fact they're probably better.

Why don't you use array_count_values() and then check if the resulting array has any value greater than 1?

Working around MySQL error "Deadlock found when trying to get lock; try restarting transaction"

The answer is correct, however the perl documentation on how to handle deadlocks is a bit sparse and perhaps confusing with PrintError, RaiseError and HandleError options. It seems that rather than going with HandleError, use on Print and Raise and then use something like Try:Tiny to wrap your code and check for errors. The below code gives an example where the db code is inside a while loop that will re-execute an errored sql statement every 3 seconds. The catch block gets $_ which is the specific err message. I pass this to a handler function "dbi_err_handler" which checks $_ against a host of errors and returns 1 if the code should continue (thereby breaking the loop) or 0 if its a deadlock and should be retried...

$sth = $dbh->prepare($strsql);
my $db_res=0;
while($db_res==0)
{
   $db_res=1;
   try{$sth->execute($param1,$param2);}
   catch
   {
       print "caught $_ in insertion to hd_item_upc for upc $upc\n";
       $db_res=dbi_err_handler($_); 
       if($db_res==0){sleep 3;}
   }
}

dbi_err_handler should have at least the following:

sub dbi_err_handler
{
    my($message) = @_;
    if($message=~ m/DBD::mysql::st execute failed: Deadlock found when trying to get lock; try restarting transaction/)
    {
       $caught=1;
       $retval=0; # we'll check this value and sleep/re-execute if necessary
    }
    return $retval;
}

You should include other errors you wish to handle and set $retval depending on whether you'd like to re-execute or continue..

Hope this helps someone -

why windows 7 task scheduler task fails with error 2147942667

For a more generic answer, convert the error value to hex, then lookup the hex value at Windows Task Scheduler Error and Success Constants

Lambda function in list comprehensions

This question touches a very stinking part of the "famous" and "obvious" Python syntax - what takes precedence, the lambda, or the for of list comprehension.

I don't think the purpose of the OP was to generate a list of squares from 0 to 9. If that was the case, we could give even more solutions:

squares = []
for x in range(10): squares.append(x*x)
  • this is the good ol' way of imperative syntax.

But it's not the point. The point is W(hy)TF is this ambiguous expression so counter-intuitive? And I have an idiotic case for you at the end, so don't dismiss my answer too early (I had it on a job interview).

So, the OP's comprehension returned a list of lambdas:

[(lambda x: x*x) for x in range(10)]

This is of course just 10 different copies of the squaring function, see:

>>> [lambda x: x*x for _ in range(3)]
[<function <lambda> at 0x00000000023AD438>, <function <lambda> at 0x00000000023AD4A8>, <function <lambda> at 0x00000000023AD3C8>]

Note the memory addresses of the lambdas - they are all different!

You could of course have a more "optimal" (haha) version of this expression:

>>> [lambda x: x*x] * 3
[<function <lambda> at 0x00000000023AD2E8>, <function <lambda> at 0x00000000023AD2E8>, <function <lambda> at 0x00000000023AD2E8>]

See? 3 time the same lambda.

Please note, that I used _ as the for variable. It has nothing to do with the x in the lambda (it is overshadowed lexically!). Get it?

I'm leaving out the discussion, why the syntax precedence is not so, that it all meant:

[lambda x: (x*x for x in range(10))]

which could be: [[0, 1, 4, ..., 81]], or [(0, 1, 4, ..., 81)], or which I find most logical, this would be a list of 1 element - a generator returning the values. It is just not the case, the language doesn't work this way.

BUT What, If...

What if you DON'T overshadow the for variable, AND use it in your lambdas???

Well, then crap happens. Look at this:

[lambda x: x * i for i in range(4)]

this means of course:

[(lambda x: x * i) for i in range(4)]

BUT it DOESN'T mean:

[(lambda x: x * 0), (lambda x: x * 1), ... (lambda x: x * 3)]

This is just crazy!

The lambdas in the list comprehension are a closure over the scope of this comprehension. A lexical closure, so they refer to the i via reference, and not its value when they were evaluated!

So, this expression:

[(lambda x: x * i) for i in range(4)]

IS roughly EQUIVALENT to:

[(lambda x: x * 3), (lambda x: x * 3), ... (lambda x: x * 3)]

I'm sure we could see more here using a python decompiler (by which I mean e.g. the dis module), but for Python-VM-agnostic discussion this is enough. So much for the job interview question.

Now, how to make a list of multiplier lambdas, which really multiply by consecutive integers? Well, similarly to the accepted answer, we need to break the direct tie to i by wrapping it in another lambda, which is getting called inside the list comprehension expression:

Before:

>>> a = [(lambda x: x * i) for i in (1, 2)]
>>> a[1](1)
2
>>> a[0](1)
2

After:

>>> a = [(lambda y: (lambda x: y * x))(i) for i in (1, 2)]
>>> a[1](1)
2
>>> a[0](1)
1

(I had the outer lambda variable also = i, but I decided this is the clearer solution - I introduced y so that we can all see which witch is which).

Edit 2019-08-30:

Following a suggestion by @josoler, which is also present in an answer by @sheridp - the value of the list comprehension "loop variable" can be "embedded" inside an object - the key is for it to be accessed at the right time. The section "After" above does it by wrapping it in another lambda and calling it immediately with the current value of i. Another way (a little bit easier to read - it produces no 'WAT' effect) is to store the value of i inside a partial object, and have the "inner" (original) lambda take it as an argument (passed supplied by the partial object at the time of the call), i.e.:

After 2:

>>> from functools import partial
>>> a = [partial(lambda y, x: y * x, i) for i in (1, 2)]
>>> a[0](2), a[1](2)
(2, 4)

Great, but there is still a little twist for you! Let's say we wan't to make it easier on the code reader, and pass the factor by name (as a keyword argument to partial). Let's do some renaming:

After 2.5:

>>> a = [partial(lambda coef, x: coef * x, coef=i) for i in (1, 2)]
>>> a[0](1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: <lambda>() got multiple values for argument 'coef'

WAT?

>>> a[0]()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: <lambda>() missing 1 required positional argument: 'x'

Wait... We're changing the number of arguments by 1, and going from "too many" to "too few"?

Well, it's not a real WAT, when we pass coef to partial in this way, it becomes a keyword argument, so it must come after the positional x argument, like so:

After 3:

>>> a = [partial(lambda x, coef: coef * x, coef=i) for i in (1, 2)]
>>> a[0](2), a[1](2)
(2, 4)

I would prefer the last version over the nested lambda, but to each their own...

Edit 2020-08-18:

Thanks to commenter dasWesen, I found out that this stuff is covered in the Python documentation: https://docs.python.org/3.4/faq/programming.html#why-do-lambdas-defined-in-a-loop-with-different-values-all-return-the-same-result - it deals with loops instead of list comprehensions, but the idea is the same - global or nonlocal variable access in the lambda function. There's even a solution - using default argument values (like for any function):

>>> a = [lambda x, coef=i: coef * x for i in (1, 2)]
>>> a[0](2), a[1](2)
(2, 4)

This way the coef value is bound to the value of i at the time of function definition (see James Powell's talk "Top To Down, Left To Right", which also explains why mutable default values are shunned).

Image overlay on responsive sized images bootstrap

When you specify position:absolute it positions itself to the next-highest element with position:relative. In this case, that's the .project div.

If you give the image's immediate parent div a style of position:relative, the overlay will key to that instead of the div which includes the text. For example: http://jsfiddle.net/7gYUU/1/

 <div class="parent">
    <img src="http://placehold.it/500x500" class="img-responsive"/>
    <div class="fa fa-plus project-overlay"></div>
 </div>

.parent {
   position: relative;
}

Jenkins / Hudson environment variables

1- add to your profil file".bash_profile" file

it is in "/home/your_user/" folder

vi .bash_profile

add:

export JENKINS_HOME=/apps/data/jenkins  
export PATH=$PATH:$JENKINS_HOME

==> it's the e jenkins workspace

2- If you use jetty : go to jenkins.xml file

and add :

<Arg>/apps/data/jenkins</Arg>

Check if object value exists within a Javascript array of objects and if not add a new object to array

xorWith in Lodash can be used to achieve this

let objects = [ { id: 1, username: 'fred' }, { id: 2, username: 'bill' }, { id: 2, username: 'ted' } ]
let existingObject = { id: 1, username: 'fred' };
let newObject = { id: 1729, username: 'Ramanujan' }

_.xorWith(objects, [existingObject], _.isEqual)
// returns [ { id: 2, username: 'bill' }, { id: 2, username: 'ted' } ]

_.xorWith(objects, [newObject], _.isEqual)
// returns [ { id: 1, username: 'fred' }, { id: 2, username: 'bill' }, { id: 2, username: 'ted' } ,{ id: 1729, username: 'Ramanujan' } ]

ERROR 1396 (HY000): Operation CREATE USER failed for 'jack'@'localhost'

two method 
one :
setp 1: drop user 'jack'@'localhost';
setp 2: create user 'jack'@localhost identified by 'ddd';

two:
setp 1: delete from user where user='jack'and host='localhost';
setp 2: flush privileges;
setp 3: create user 'jack'@'localhost' identified by 'ddd';

Why are Python's 'private' methods not actually private?

From http://www.faqs.org/docs/diveintopython/fileinfo_private.html

Strictly speaking, private methods are accessible outside their class, just not easily accessible. Nothing in Python is truly private; internally, the names of private methods and attributes are mangled and unmangled on the fly to make them seem inaccessible by their given names. You can access the __parse method of the MP3FileInfo class by the name _MP3FileInfo__parse. Acknowledge that this is interesting, then promise to never, ever do it in real code. Private methods are private for a reason, but like many other things in Python, their privateness is ultimately a matter of convention, not force.

Windows Scheduled task succeeds but returns result 0x1

I was running a PowerShell script into the task scheduller but i forgot to enable the execution-policy to unrestricted, in an elevated PowerShell console:

Set-ExecutionPolicy Unrestricted

After that, the error disappeared (0x1).

Status bar and navigation bar appear over my view's bounds in iOS 7

If you want the view to have the translucent nav bar (which is kind of nice) you have to setup a contentInset or similar.

Here is how I do it:

// Check if we are running on ios7
if([[[[UIDevice currentDevice] systemVersion] componentsSeparatedByString:@"."][0] intValue] >= 7) {
      CGRect statusBarViewRect = [[UIApplication sharedApplication] statusBarFrame];
      float heightPadding = statusBarViewRect.size.height+self.navigationController.navigationBar.frame.size.height;

      myContentView.contentInset = UIEdgeInsetsMake(heightPadding, 0.0, 0.0, 0.0);
}

How do I concatenate strings with variables in PowerShell?

Try this

Get-ChildItem  | % { Write-Host "$($_.FullName)\$buildConfig\$($_.Name).dll" }

In your code,

  1. $build-Config is not a valid variable name.
  2. $.FullName should be $_.FullName
  3. $ should be $_.Name

How can I backup a Docker-container with its data-volumes?

If your project uses docker-compose, here is an approach for backing up and restoring your volumes.

docker-compose.yml

Basically you add db-backup and db-restore services to your docker-compose.yml file, and adapt it for the name of your volume. My volume is named dbdata in this example.

version: "3"

services:
  db:
    image: percona:5.7
    volumes:
      - dbdata:/var/lib/mysql

  db-backup:
    image: alpine    
    tty: false
    environment:
      - TARGET=dbdata
    volumes:
      - ./backup:/backup
      - dbdata:/volume
    command: sh -c "tar -cjf /backup/$${TARGET}.tar.bz2 -C /volume ./"

  db-restore:
    image: alpine    
    environment:
      - SOURCE=dbdata
    volumes:
      - ./backup:/backup
      - dbdata:/volume
    command: sh -c "rm -rf /volume/* /volume/..?* /volume/.[!.]* ; tar -C /volume/ -xjf /backup/$${SOURCE}.tar.bz2"

Avoid corruption

For data consistency, stop your db container before backing up or restoring

docker-compose stop db

Backing up

To back up to the default destination (backup/dbdata.tar.bz2):

docker-compose run --rm db-backup

Or, if you want to specify an alternate target name, do:

docker-compose run --rm -e TARGET=mybackup db-backup

Restoring

To restore from backup/dbdata.tar.bz2, do:

docker-compose run --rm db-restore

Or restore from a specific file using:

docker-compose run --rm -e SOURCE=mybackup db-restore

I adapted commands from https://loomchild.net/2017/03/26/backup-restore-docker-named-volumes/ to create this approach.

Get index of current item in a PowerShell loop

.NET has some handy utility methods for this sort of thing in System.Array:

PS> $a = 'a','b','c'
PS> [array]::IndexOf($a, 'b')
1
PS> [array]::IndexOf($a, 'c')
2

Good points on the above approach in the comments. Besides "just" finding an index of an item in an array, given the context of the problem, this is probably more suitable:

$letters = { 'A', 'B', 'C' }
$letters | % {$i=0} {"Value:$_ Index:$i"; $i++}

Foreach (%) can have a Begin sciptblock that executes once. We set an index variable there and then we can reference it in the process scripblock where it gets incremented before exiting the scriptblock.

Getting current date and time in JavaScript

Just use:

var d = new Date();
document.write(d.toLocaleString());
document.write("<br>");

ffprobe or avprobe not found. Please install one

This is an old question. But if you're using a virtualenv with python, place the contents of the downloaded libav bin folder in the Scriptsfolder of your virtualenv.

How can I check if char* variable points to empty string?

Give it a chance:

Try getting string via function gets(string) then check condition as if(string[0] == '\0')

Get device token for push notification

To get Token Device you can do by some steps:

1) Enable APNS (Apple Push Notification Service) for both Developer Certification and Distribute Certification, then redownload those two file.

2) Redownload both Developer Provisioning and Distribute Provisioning file.

3) In Xcode interface: setting provisioning for PROJECT and TARGETS with two file provisioning have download.

4) Finally, you need to add the code below in AppDelegate file to get Token Device (note: run app in real device).

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {    
     [self.window addSubview:viewController.view];
     [self.window makeKeyAndVisible];

     NSLog(@"Registering for push notifications...");    
     [[UIApplication sharedApplication] registerForRemoteNotificationTypes:
 (UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)];
     return YES;
}

- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken { 
     NSString *str = [NSString stringWithFormat:@"Device Token=%@",deviceToken];
     NSLog(@"%@", str);
}

- (void)application:(UIApplication *)app didFailToRegisterForRemoteNotificationsWithError:(NSError *)err { 
     NSString *str = [NSString stringWithFormat: @"Error: %@", err];
     NSLog(@"%@",str);
}

Rails Object to hash

not sure if that's what you need but try this in ruby console:

h = Hash.new
h["name"] = "test"
h["post_number"] = 20
h["active"] = true
h

obviously it will return you a hash in console. if you want to return a hash from within a method - instead of just "h" try using "return h.inspect", something similar to:

def wordcount(str)
  h = Hash.new()
  str.split.each do |key|
    if h[key] == nil
      h[key] = 1
    else
      h[key] = h[key] + 1
    end
  end
  return h.inspect
end

Compute a confidence interval from sample data

Start with looking up the z-value for your desired confidence interval from a look-up table. The confidence interval is then mean +/- z*sigma, where sigma is the estimated standard deviation of your sample mean, given by sigma = s / sqrt(n), where s is the standard deviation computed from your sample data and n is your sample size.

Specifying width and height as percentages without skewing photo proportions in HTML

Given the lack of information regarding the original image size, specifying percentages for the width and height would result in highly erratic results. If you are trying to ensure that an image will fit within a specific location on your page then you'll need to use some server side code to manage that rescaling.

How to change credentials for SVN repository in Eclipse?

On Mac OS X, go to folder /$HOME (/Users/{user home}/). You will see file '.eclipse_keyring'. Remove it. All saved credentials will be lost.

Cross-reference (named anchor) in markdown

Markdown Anchor supports the hashmark, so a link to an anchor in the page would simply be [Pookie](#pookie)

Generating the anchor is not actually supported in Gruber Markdown, but is in other implementations, such as Markdown Extra.

In Markdown Extra, the anchor ID is appended to a header or subhead with {#pookie}.

Github Flavored Markdown in Git repository pages (but not in Gists) automatically generates anchors with several markup tags on all headers (h1, h2, h3, etc.), including:

  • id="user-content-HEADERTEXT"
  • class="anchor"
  • href="#HEADERTEXT"
  • aria-hidden="true" (this is for an svg link icon that displays on mouseover)

Excluding the aria/svg icon, when one writes:

  • # Header Title

Github generates:

  • <h1><a id="user-content-header-title" class="anchor" href="#header-title">Header Title</a></h1>

Therefore, one need do nothing to create the header links, and can always link to them with:

  • Link to the [Header Title](#header-title)

How to link home brew python version and set it as default

The problem with me is that I have so many different versions of python, so it opens up a different python3.7 even after I did brew link. I did the following additional steps to make it default after linking

First, open up the document setting up the path of python

 nano ~/.bash_profile

Then something like this shows up:

# Setting PATH for Python 3.7
# The original version is saved in .bash_profile.pysave
PATH="/Library/Frameworks/Python.framework/Versions/3.7/bin:${PATH}"
export PATH

# Setting PATH for Python 3.6
# The original version is saved in .bash_profile.pysave
PATH="/Library/Frameworks/Python.framework/Versions/3.6/bin:${PATH}"
export PATH

The thing here is that my Python for brew framework is not in the Library Folder!! So I changed the framework for python 3.7, which looks like follows in my system

# Setting PATH for Python 3.7
# The original version is saved in .bash_profile.pysave
PATH="/usr/local/Frameworks/Python.framework/Versions/3.7/bin:${PATH}"
export PATH

Change and save the file. Restart the computer, and typing in python3.7, I get the python I installed for brew.

Not sure if my case is applicable to everyone, but worth a try. Not sure if the framework path is the same for everyone, please made sure before trying out.

How to run shell script file using nodejs?

you can go:

var cp = require('child_process');

and then:

cp.exec('./myScript.sh', function(err, stdout, stderr) {
  // handle err, stdout, stderr
});

to run a command in your $SHELL.
Or go

cp.spawn('./myScript.sh', [args], function(err, stdout, stderr) {
  // handle err, stdout, stderr
});

to run a file WITHOUT a shell.
Or go

cp.execFile();

which is the same as cp.exec() but doesn't look in the $PATH.

You can also go

cp.fork('myJS.js', function(err, stdout, stderr) {
  // handle err, stdout, stderr
});

to run a javascript file with node.js, but in a child process (for big programs).

EDIT

You might also have to access stdin and stdout with event listeners. e.g.:

var child = cp.spawn('./myScript.sh', [args]);
child.stdout.on('data', function(data) {
  // handle stdout as `data`
});

How to handle an IF STATEMENT in a Mustache template?

I have a simple and generic hack to perform key/value if statement instead of boolean-only in mustache (and in an extremely readable fashion!) :

function buildOptions (object) {
    var validTypes = ['string', 'number', 'boolean'];
    var value;
    var key;
    for (key in object) {
        value = object[key];
        if (object.hasOwnProperty(key) && validTypes.indexOf(typeof value) !== -1) {
            object[key + '=' + value] = true;
        }
    }
    return object;
}

With this hack, an object like this:

var contact = {
  "id": 1364,
  "author_name": "Mr Nobody",
  "notified_type": "friendship",
  "action": "create"
};

Will look like this before transformation:

var contact = {
  "id": 1364,
  "id=1364": true,
  "author_name": "Mr Nobody",
  "author_name=Mr Nobody": true,
  "notified_type": "friendship",
  "notified_type=friendship": true,
  "action": "create",
  "action=create": true
};

And your mustache template will look like this:

{{#notified_type=friendship}}
    friendship…
{{/notified_type=friendship}}

{{#notified_type=invite}}
    invite…
{{/notified_type=invite}}

Adding simple legend to plot in R

Take a look at ?legend and try this:

legend('topright', names(a)[-1] , 
   lty=1, col=c('red', 'blue', 'green',' brown'), bty='n', cex=.75)

enter image description here

Updating .class file in jar

Do you want to do it automatically or manually? If manually, a JAR file is really just a ZIP file, so you should be able to open it with any ZIP reader. (You may need to change the extension first.) If you want to update the JAR file automatically via Eclipse, you may want to look into Ant support in Eclipse and look at the zip task.

Anaconda export Environment file

The easiest way to save the packages from an environment to be installed in another computer is:

$ conda list -e > req.txt

then you can install the environment using

$ conda create -n <environment-name> --file req.txt

if you use pip, please use the following commands: reference https://pip.pypa.io/en/stable/reference/pip_freeze/

$ env1/bin/pip freeze > requirements.txt
$ env2/bin/pip install -r requirements.txt

Android Spinner : Avoid onItemSelected calls during initialization

My solution:

protected boolean inhibit_spinner = true;


@Override
        public void onItemSelected(AdapterView<?> arg0, View arg1,
                int pos, long arg3) {

            if (inhibit_spinner) {
                inhibit_spinner = false;
            }else {

            if (getDataTask != null) getDataTask.cancel(true);
            updateData();
            }

        }

Fatal error: Call to undefined function base_url() in C:\wamp\www\Test-CI\application\views\layout.php on line 5

Just create a variable as $base_url

$base_url = load_class('Config')->config['base_url'];

<?php echo $base_url ?>

and call it in your code..

How to print to console when using Qt

#include <QTextStream>
...
qDebug()<<"Bla bla bla";

What is PHPSESSID?

Check php.ini for auto session id.

If you enable it, you will have PHPSESSID in your cookies.

Remove an array element and shift the remaining ones

You can't achieve what you want with arrays. Use vectors instead, and read about the std::remove algorithm. Something like:

std::remove(array, array+5, 3)

will work on your array, but it will not shorten it (why -- because it's impossible). With vectors, it'd be something like

v.erase(std::remove(v.begin(), v.end(), 3), v.end())

How to change the spinner background in Android?

You can change background color and drop down icon like doing this way

Step1: In drawable folder make background.xml for border of spinner.

<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="@android:color/transparent" />
<corners android:radius="5dp" />
<stroke
    android:width="1dp"
    android:color="@color/darkGray" />
</shape>  //edited

Step2: for layout design of spinner use this drop down icon or any image drop.pnjuse this image like as

  <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginRight="3dp"
                    android:layout_weight=".28"
                    android:background="@drawable/spinner_border"
                    android:orientation="horizontal">

                    <Spinner
                        android:id="@+id/spinner2"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_centerVertical="true"
                        android:layout_gravity="center"
                        android:background="@android:color/transparent"
                        android:gravity="center"
                        android:layout_marginLeft="5dp"
                        android:spinnerMode="dropdown" />

                    <ImageView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_alignParentRight="true"
                        android:layout_centerVertical="true"
                        android:layout_gravity="center"
                        android:src="@mipmap/drop" />

                </RelativeLayout>

Finally looks like below image and it is every where clickable in round area and no need of to write click Lister for imageView.

For more details , you can see Here

enter image description here

Remove category & tag base from WordPress url - without a plugin

  1. Set Custom Structure: /%postname%/
  2. Set Category base: . (dot not /)

  3. Save. 100% work correctly.

Maximum size for a SQL Server Query? IN clause? Is there a Better Approach

Per batch, 65536 * Network Packet Size which is 4k so 256 MB

However, IN will stop way before that but it's not precise.

You end up with memory errors but I can't recall the exact error. A huge IN will be inefficient anyway.

Edit: Remus reminded me: the error is about "stack size"

Detecting which UIButton was pressed in a UITableView

create an nsmutable array and put all button in that array usint[array addObject:yourButton];

in the button press method

-

 (void)buttonPressedAction:(id)sender
{
    UIButton *button = (UIButton *)sender;

for(int i=0;i<[yourArray count];i++){

if([buton isEqual:[yourArray objectAtIndex:i]]){

//here write wat u need to do

}
}

Unable to start debugging on the web server. Could not start ASP.NET debugging VS 2010, II7, Win 7 x64

Be sure your site's Application Pool uses the correct framework version. I got the "Unable to start debugging" error on an ASP.Net 2005 site. It was incorrectly using the DefaultAppPool on Windows 7 (which I believe was using .Net Framework 4). I created a new a App Pool based on .Net Framework 2 and assigned it to the problem web site. After that debugging worked fine.

How to view the dependency tree of a given npm module?

You can use the npm-remote-ls module. You can install it globally:

npm install -g npm-remote-ls

And then call:

npm-remote-ls bower

Alternatively, [email protected] installed then you can use npx and avoid globally installing the command - just call:

npx npm-remote-ls bower

How to delete images from a private docker registry?

Simple ruby script based on this answer: registry_cleaner.

You can run it on local machine:

./registry_cleaner.rb --host=https://registry.exmpl.com --repository=name --tags_count=4

And then on the registry machine remove blobs with /bin/registry garbage-collect /etc/docker/registry/config.yml.

How to send FormData objects with Ajax-requests in jQuery?

I do it like this and it's work for me, I hope this will help :)

   <div id="data">
        <form>
            <input type="file" name="userfile" id="userfile" size="20" />
            <br /><br />
            <input type="button" id="upload" value="upload" />
        </form>
    </div>
  <script>
        $(document).ready(function(){
                $('#upload').click(function(){

                    console.log('upload button clicked!')
                    var fd = new FormData();    
                    fd.append( 'userfile', $('#userfile')[0].files[0]);

                    $.ajax({
                      url: 'upload/do_upload',
                      data: fd,
                      processData: false,
                      contentType: false,
                      type: 'POST',
                      success: function(data){
                        console.log('upload success!')
                        $('#data').empty();
                        $('#data').append(data);

                      }
                    });
                });
        });
    </script>   

forward declaration of a struct in C?

Try this

#include <stdio.h>

struct context;

struct funcptrs{
  void (*func0)(struct context *ctx);
  void (*func1)(void);
};

struct context{
    struct funcptrs fps;
}; 

void func1 (void) { printf( "1\n" ); }
void func0 (struct context *ctx) { printf( "0\n" ); }

void getContext(struct context *con){
    con->fps.func0 = func0;  
    con->fps.func1 = func1;  
}

int main(int argc, char *argv[]){
 struct context c;
   c.fps.func0 = func0;
   c.fps.func1 = func1;
   getContext(&c);
   c.fps.func0(&c);
   getchar();
   return 0;
}

How can I manually generate a .pyc file from a .py file

You can use compileall in the terminal. The following command will go recursively into sub directories and make pyc files for all the python files it finds. The compileall module is part of the python standard library, so you don't need to install anything extra to use it. This works exactly the same way for python2 and python3.

python -m compileall .

How to resolve ORA-011033: ORACLE initialization or shutdown in progress

After some googling, I found the advice to do the following, and it worked:

SQL> startup mount

ORACLE Instance started

SQL> recover database 

Media recovery complete

SQL> alter database open;

Database altered

How to hide only the Close (x) button?

Well you can hide the close button by changing the FormBorderStyle from the properties section or programmatically in the constructor using:

public Form1()
{
InitializeComponent();
this.FormBorderStyle = FormBorderStyle.None;
}

then you create a menu strip item to exit the application.

cheers

Modal width (increase)

This was the solution that worked for me:

_x000D_
_x000D_
.modal{_x000D_
 padding: 0 !important;_x000D_
}_x000D_
.modal-dialog {_x000D_
  max-width: 80% !important;_x000D_
  height: 100%;_x000D_
  padding: 0;_x000D_
  margin: 0;_x000D_
}_x000D_
_x000D_
.modal-content {_x000D_
  border-radius: 0 !important;_x000D_
  height: 100%;_x000D_
}
_x000D_
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" />_x000D_
<a href="#" class="menu-toggler" data-toggle="modal" data-target=".bd-example-modal-lg">Menu</a>_x000D_
_x000D_
<div class="modal mobile-nav-modal fade bd-example-modal-lg" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true">_x000D_
  <div class="modal-dialog modal-lg">_x000D_
    <div class="modal-content">_x000D_
      <a href="#" class="" data-dismiss="modal">Close Menu</a>_x000D_
_x000D_
      <nav class="modal-nav">_x000D_
        <ul>_x000D_
          <li><a data-toggle="collapse" href="#collapseExample" role="button">Shop</a>_x000D_
            <div class="collapse" id="collapseExample">_x000D_
              <ul>_x000D_
                <li><a href="#">List 1</a></li>_x000D_
                <li><a href="#">List 2</a></li>_x000D_
                <li><a href="#">List 3</a></li>_x000D_
              </ul>_x000D_
              <ul>_x000D_
                <li><a href="#">List 1</a></li>_x000D_
                <li><a href="#">List 2</a></li>_x000D_
                <li><a href="#">List 3</a></li>_x000D_
              </ul>_x000D_
            </div>_x000D_
          </li>_x000D_
          <li><a href="#">Made To Order</a></li>_x000D_
          <li><a href="#">Heritage</a></li>_x000D_
          <li><a href="#">Style & Fit</a></li>_x000D_
          <li><a href="#">Sign In</a></li>_x000D_
        </ul>_x000D_
      </nav>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Replacing H1 text with a logo image: best method for SEO and accessibility?

One point no one has touched on is the fact that the h1 attribute should be specific to every page and using the site logo will effectively replicate the H1 on every page of the site.

I like to use a z index hidden h1 for each page as the best SEO h1 is often not the best for sales or aesthetic value.

cleanest way to skip a foreach if array is empty

There are a million ways to do this.

The first one would be to go ahead and run the array through foreach anyway, assuming you do have an array.

In other cases this is what you might need:

foreach ((array) $items as $item) {
    print $item;
}

Note: to all the people complaining about typecast, please note that the OP asked cleanest way to skip a foreach if array is empty (emphasis is mine). A value of true, false, numbers or strings is not considered empty. In addition, this would work with objects implementing \Traversable, whereas is_array wouldn't work.

How can I make a countdown with NSTimer?

Make Countdown app Xcode 8.1, Swift 3

import UIKit
import Foundation

class ViewController: UIViewController, UITextFieldDelegate {

    var timerCount = 0
    var timerRunning = false

    @IBOutlet weak var timerLabel: UILabel! //ADD Label
    @IBOutlet weak var textField: UITextField! //Add TextField /Enter any number to Countdown

    override func viewDidLoad() {
        super.viewDidLoad()

        //Reset
        timerLabel.text = ""
        if timerCount == 0 {
            timerRunning = false
        }
}

       //Figure out Count method
    func Counting() {
        if timerCount > 0 {
        timerLabel.text = "\(timerCount)"
            timerCount -= 1
        } else {
            timerLabel.text = "GO!"

        }

    }

    //ADD Action Button
    @IBAction func startButton(sender: UIButton) {

        //Figure out timer
        if timerRunning == false {
         _ = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(ViewController.Counting), userInfo: nil, repeats: true)
            timerRunning = true
        }

        //unwrap textField and Display result
        if let countebleNumber = Int(textField.text!) {
            timerCount = countebleNumber
            textField.text = "" //Clean Up TextField
        } else {
            timerCount = 3 //Defoult Number to Countdown if TextField is nil
            textField.text = "" //Clean Up TextField
        }

    }

    //Dismiss keyboard
    func keyboardDismiss() {
        textField.resignFirstResponder()
    }

    //ADD Gesture Recignizer to Dismiss keyboard then view tapped
    @IBAction func viewTapped(_ sender: AnyObject) {
        keyboardDismiss()
    }

    //Dismiss keyboard using Return Key (Done) Button
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        keyboardDismiss()

        return true
    }

}

https://github.com/nikae/CountDown-

Python Pandas - Find difference between two data frames

By using drop_duplicates

pd.concat([df1,df2]).drop_duplicates(keep=False)

Update :

Above method only working for those dataframes they do not have duplicate itself, For example

df1=pd.DataFrame({'A':[1,2,3,3],'B':[2,3,4,4]})
df2=pd.DataFrame({'A':[1],'B':[2]})

It will output like below , which is wrong

Wrong Output :

pd.concat([df1, df2]).drop_duplicates(keep=False)
Out[655]: 
   A  B
1  2  3

Correct Output

Out[656]: 
   A  B
1  2  3
2  3  4
3  3  4

How to achieve that?

Method 1: Using isin with tuple

df1[~df1.apply(tuple,1).isin(df2.apply(tuple,1))]
Out[657]: 
   A  B
1  2  3
2  3  4
3  3  4

Method 2: merge with indicator

df1.merge(df2,indicator = True, how='left').loc[lambda x : x['_merge']!='both']
Out[421]: 
   A  B     _merge
1  2  3  left_only
2  3  4  left_only
3  3  4  left_only

jQuery UI Dialog - missing close icon

I had the same exact issue, Maybe you already chececked this but got it solved just by placing the "images" folder in the same location as the jquery-ui.css

How to pass table value parameters to stored procedure from .net code

DataTable, DbDataReader, or IEnumerable<SqlDataRecord> objects can be used to populate a table-valued parameter per the MSDN article Table-Valued Parameters in SQL Server 2008 (ADO.NET).

The following example illustrates using either a DataTable or an IEnumerable<SqlDataRecord>:

SQL Code:

CREATE TABLE dbo.PageView
(
    PageViewID BIGINT NOT NULL CONSTRAINT pkPageView PRIMARY KEY CLUSTERED,
    PageViewCount BIGINT NOT NULL
);
CREATE TYPE dbo.PageViewTableType AS TABLE
(
    PageViewID BIGINT NOT NULL
);
CREATE PROCEDURE dbo.procMergePageView
    @Display dbo.PageViewTableType READONLY
AS
BEGIN
    MERGE INTO dbo.PageView AS T
    USING @Display AS S
    ON T.PageViewID = S.PageViewID
    WHEN MATCHED THEN UPDATE SET T.PageViewCount = T.PageViewCount + 1
    WHEN NOT MATCHED THEN INSERT VALUES(S.PageViewID, 1);
END

C# Code:

private static void ExecuteProcedure(bool useDataTable, 
                                     string connectionString, 
                                     IEnumerable<long> ids) 
{
    using (SqlConnection connection = new SqlConnection(connectionString)) 
    {
        connection.Open();
        using (SqlCommand command = connection.CreateCommand()) 
        {
            command.CommandText = "dbo.procMergePageView";
            command.CommandType = CommandType.StoredProcedure;

            SqlParameter parameter;
            if (useDataTable) {
                parameter = command.Parameters
                              .AddWithValue("@Display", CreateDataTable(ids));
            }
            else 
            {
                parameter = command.Parameters
                              .AddWithValue("@Display", CreateSqlDataRecords(ids));
            }
            parameter.SqlDbType = SqlDbType.Structured;
            parameter.TypeName = "dbo.PageViewTableType";

            command.ExecuteNonQuery();
        }
    }
}

private static DataTable CreateDataTable(IEnumerable<long> ids) 
{
    DataTable table = new DataTable();
    table.Columns.Add("ID", typeof(long));
    foreach (long id in ids) 
    {
        table.Rows.Add(id);
    }
    return table;
}

private static IEnumerable<SqlDataRecord> CreateSqlDataRecords(IEnumerable<long> ids) 
{
    SqlMetaData[] metaData = new SqlMetaData[1];
    metaData[0] = new SqlMetaData("ID", SqlDbType.BigInt);
    SqlDataRecord record = new SqlDataRecord(metaData);
    foreach (long id in ids) 
    {
        record.SetInt64(0, id);
        yield return record;
    }
}

Copying the cell value preserving the formatting from one cell to another in excel using VBA

Using Excel 2010 ? Try

Selection.PasteSpecial Paste:=xlPasteAllUsingSourceTheme, Operation:=xlNone, SkipBlanks:=False, Transpose:=False

Remove all special characters except space from a string using JavaScript

_x000D_
_x000D_
const input = `#if_1 $(PR_CONTRACT_END_DATE) == '23-09-2019' # _x000D_
Test27919<[email protected]> #elseif_1 $(PR_CONTRACT_START_DATE) ==  '20-09-2019' #_x000D_
Sender539<[email protected]> #elseif_1 $(PR_ACCOUNT_ID) == '1234' #_x000D_
AdestraSID<[email protected]> #else_1#Test27919<[email protected]>#endif_1#`;_x000D_
const replaceString = input.split('$(').join('->').split(')').join('<-');_x000D_
_x000D_
_x000D_
console.log(replaceString.match(/(?<=->).*?(?=<-)/g));
_x000D_
_x000D_
_x000D_

How to get streaming url from online streaming radio station

The provided answers didn't work for me. I'm adding another answer because this is where I ended up when searching for radio stream urls.

Radio Browser is a searchable site with streaming urls for radio stations around the world:

http://www.radio-browser.info/

Search for a station like FIP, Pinguin Radio or Radio Paradise, then click the save button, which downloads a PLS file that you can open in your radioplayer (Rhythmbox), or you open the file in a text editor and copy the URL to add in Goodvibes.

Convert String to Integer in XSLT 1.0

Adding to jelovirt's answer, you can use number() to convert the value to a number, then round(), floor(), or ceiling() to get a whole integer.

Example

<xsl:variable name="MyValAsText" select="'5.14'"/>
<xsl:value-of select="number($MyValAsText) * 2"/> <!-- This outputs 10.28 -->
<xsl:value-of select="floor($MyValAsText)"/> <!-- outputs 5 -->
<xsl:value-of select="ceiling($MyValAsText)"/> <!-- outputs 6 -->
<xsl:value-of select="round($MyValAsText)"/> <!-- outputs 5 -->

How do we use runOnUiThread in Android?

If using in fragment then simply write

getActivity().runOnUiThread(new Runnable() {
    @Override
    public void run() {
        // Do something on UiThread
    }
});

Add Auto-Increment ID to existing table?

Proceed like that :

Make a dump of your database first

Remove the primary key like that

ALTER TABLE yourtable DROP PRIMARY KEY

Add the new column like that

ALTER TABLE yourtable add column Id INT NOT NULL AUTO_INCREMENT FIRST, ADD primary KEY Id(Id)

The table will be looked and the AutoInc updated.

Making text background transparent but not text itself

For a fully transparent background use:

background: transparent;

Otherwise for a semi-transparent color fill use:

background: rgba(255,255,255,0.5); // or hsla(0, 0%, 100%, 0.5)

where the values are:

background: rgba(red,green,blue,opacity); // or hsla(hue, saturation, lightness, opacity)

You can also use rgba values for gradient backgrounds.

To get transparency on an image background simply reduce the opacity of the image in an image editor of you choice beforehand.

Remove a specific character using awk or sed

Using just awk you could do (I also shortened some of your piping):

strings -a libAddressDoctor5.so | awk '/EngineVersion/ { if(NR==2) { gsub("\"",""); print $2 } }'

I can't verify it for you because I don't know your exact input, but the following works:

echo "Blah EngineVersion=\"123\"" | awk '/EngineVersion/ { gsub("\"",""); print $2 }'

See also this question on removing single quotes.

Class constructor type in typescript?

Solution from typescript interfaces reference:

interface ClockConstructor {
    new (hour: number, minute: number): ClockInterface;
}
interface ClockInterface {
    tick();
}

function createClock(ctor: ClockConstructor, hour: number, minute: number): ClockInterface {
    return new ctor(hour, minute);
}

class DigitalClock implements ClockInterface {
    constructor(h: number, m: number) { }
    tick() {
        console.log("beep beep");
    }
}
class AnalogClock implements ClockInterface {
    constructor(h: number, m: number) { }
    tick() {
        console.log("tick tock");
    }
}

let digital = createClock(DigitalClock, 12, 17);
let analog = createClock(AnalogClock, 7, 32);

So the previous example becomes:

interface AnimalConstructor {
    new (): Animal;
}

class Animal {
    constructor() {
        console.log("Animal");
    }
}

class Penguin extends Animal {
    constructor() {
        super();
        console.log("Penguin");
    }
}

class Lion extends Animal {
    constructor() {
        super();
        console.log("Lion");
    }
}

class Zoo {
    AnimalClass: AnimalConstructor // AnimalClass can be 'Lion' or 'Penguin'

    constructor(AnimalClass: AnimalConstructor) {
        this.AnimalClass = AnimalClass
        let Hector = new AnimalClass();
    }
}

Convert string to ASCII value python

def stringToNumbers(ord(message)):
    return stringToNumbers
    stringToNumbers.append = (ord[0])
    stringToNumbers = ("morocco")

Should I use pt or px?

Have a look at this excellent article at CSS-Tricks:

Taken from the article:


pt

The final unit of measurement that it is possible to declare font sizes in is point values (pt). Point values are only for print CSS! A point is a unit of measurement used for real-life ink-on-paper typography. 72pts = one inch. One inch = one real-life inch like-on-a-ruler. Not an inch on a screen, which is totally arbitrary based on resolution.

Just like how pixels are dead-accurate on monitors for font-sizing, point sizes are dead-accurate on paper. For the best cross-browser and cross-platform results while printing pages, set up a print stylesheet and size all fonts with point sizes.

For good measure, the reason we don't use point sizes for screen display (other than it being absurd), is that the cross-browser results are drastically different:

px

If you need fine-grained control, sizing fonts in pixel values (px) is an excellent choice (it's my favorite). On a computer screen, it doesn't get any more accurate than a single pixel. With sizing fonts in pixels, you are literally telling browsers to render the letters exactly that number of pixels in height:

Windows, Mac, aliased, anti-aliased, cross-browsers, doesn't matter, a font set at 14px will be 14px tall. But that isn't to say there won't still be some variation. In a quick test below, the results were slightly more consistent than with keywords but not identical:

Due to the nature of pixel values, they do not cascade. If a parent element has an 18px pixel size and the child is 16px, the child will be 16px. However, font-sizing settings can be using in combination. For example, if the parent was set to 16px and the child was set to larger, the child would indeed come out larger than the parent. A quick test showed me this:

"Larger" bumped the 16px of the parent into 20px, a 25% increase.

Pixels have gotten a bad wrap in the past for accessibility and usability concerns. In IE 6 and below, font-sizes set in pixels cannot be resized by the user. That means that us hip young healthy designers can set type in 12px and read it on the screen just fine, but when folks a little longer in the tooth go to bump up the size so they can read it, they are unable to. This is really IE 6's fault, not ours, but we gots what we gots and we have to deal with it.

Setting font-size in pixels is the most accurate (and I find the most satisfying) method, but do take into consideration the number of visitors still using IE 6 on your site and their accessibility needs. We are right on the bleeding edge of not needing to care about this anymore.


Change the location of an object programmatically

You need to pass the whole point to location

var point = new Point(50, 100);
this.balancePanel.Location = point;

In PHP, what is a closure and why does it use the "use" identifier?

The function () use () {} is like closure for PHP.

Without use, function cannot access parent scope variable

$s = "hello";
$f = function () {
    echo $s;
};

$f(); // Notice: Undefined variable: s
$s = "hello";
$f = function () use ($s) {
    echo $s;
};

$f(); // hello

The use variable's value is from when the function is defined, not when called

$s = "hello";
$f = function () use ($s) {
    echo $s;
};

$s = "how are you?";
$f(); // hello

use variable by-reference with &

$s = "hello";
$f = function () use (&$s) {
    echo $s;
};

$s = "how are you?";
$f(); // how are you?

git status (nothing to commit, working directory clean), however with changes commited

I had the same issue because I had 2 .git folders in the working directory.

Your problem may be caused by the same thing, so I recommend checking to see if you have multiple .git folders, and, if so, deleting one of them.

That allowed me to upload the project successfully.

Keeping session alive with Curl and PHP

This is how you do CURL with sessions

//initial request with login data

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://www.example.com/login.php');
curl_setopt($ch, CURLOPT_USERAGENT,'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/32.0.1700.107 Chrome/32.0.1700.107 Safari/537.36');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, "username=XXXXX&password=XXXXX");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_COOKIESESSION, true);
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie-name');  //could be empty, but cause problems on some hosts
curl_setopt($ch, CURLOPT_COOKIEFILE, '/var/www/ip4.x/file/tmp');  //could be empty, but cause problems on some hosts
$answer = curl_exec($ch);
if (curl_error($ch)) {
    echo curl_error($ch);
}

//another request preserving the session

curl_setopt($ch, CURLOPT_URL, 'http://www.example.com/profile');
curl_setopt($ch, CURLOPT_POST, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, "");
$answer = curl_exec($ch);
if (curl_error($ch)) {
    echo curl_error($ch);
}

I've seen this on ImpressPages

How to pass in parameters when use resource service?

I suggest you to use provider. Provide is good when you want to configure it first before to use (against Service/Factory)

Something like:

.provider('Magazines', function() {

    this.url = '/';
    this.urlArray = '/';
    this.organId = 'Default';

    this.$get = function() {
        var url = this.url;
        var urlArray = this.urlArray;
        var organId = this.organId;

        return {
            invoke: function() {
                return ......
            }
        }
    };

    this.setUrl  = function(url) {
        this.url = url;
    };

   this.setUrlArray  = function(urlArray) {
        this.urlArray = urlArray;
    };

    this.setOrganId  = function(organId) {
        this.organId = organId;
    };
});

.config(function(MagazinesProvider){
    MagazinesProvider.setUrl('...');
    MagazinesProvider.setUrlArray('...');
    MagazinesProvider.setOrganId('...');
});

And now controller:

function MyCtrl($scope, Magazines) {        

        Magazines.invoke();

       ....

}

Types in Objective-C on iOS

Update for the new 64bit arch

Ranges:
CHAR_MIN:   -128
CHAR_MAX:   127
SHRT_MIN:   -32768
SHRT_MAX:   32767
INT_MIN:    -2147483648
INT_MAX:    2147483647
LONG_MIN:   -9223372036854775808
LONG_MAX:   9223372036854775807
ULONG_MAX:  18446744073709551615
LLONG_MIN:  -9223372036854775808
LLONG_MAX:  9223372036854775807
ULLONG_MAX: 18446744073709551615

How do I put variables inside javascript strings?

I wrote a function which solves the problem precisely.

First argument is the string that wanted to be parameterized. You should put your variables in this string like this format "%s1, %s2, ... %s12".

Other arguments are the parameters respectively for that string.

/***
 * @example parameterizedString("my name is %s1 and surname is %s2", "John", "Doe");
 * @return "my name is John and surname is Doe"
 *
 * @firstArgument {String} like "my name is %s1 and surname is %s2"
 * @otherArguments {String | Number}
 * @returns {String}
 */
const parameterizedString = (...args) => {
  const str = args[0];
  const params = args.filter((arg, index) => index !== 0);
  if (!str) return "";
  return str.replace(/%s[0-9]+/g, matchedStr => {
    const variableIndex = matchedStr.replace("%s", "") - 1;
    return params[variableIndex];
  });
}

Examples

parameterizedString("my name is %s1 and surname is %s2", "John", "Doe");
// returns "my name is John and surname is Doe"

parameterizedString("this%s1 %s2 %s3", " method", "sooo", "goood");
// returns "this method sooo goood"

If variable position changes in that string, this function supports it too without changing the function parameters.

parameterizedString("i have %s2 %s1 and %s4 %s3.", "books", 5, "pencils", "6");
// returns "i have 5 books and 6 pencils."

Open a local HTML file using window.open in Chrome

First, make sure that the source page and the target page are both served through the file URI scheme. You can't force an http page to open a file page (but it works the other way around).

Next, your script that calls window.open() should be invoked by a user-initiated event, such as clicks, keypresses and the like. Simply calling window.open() won't work.

You can test this right here in this question page. Run these in Chrome's JavaScript console:

// Does nothing
window.open('http://google.com');

// Click anywhere within this page and the new window opens
$(document.body).unbind('click').click(function() { window.open('http://google.com'); });

// This will open a new window, but it would be blank
$(document.body).unbind('click').click(function() { window.open('file:///path/to/a/local/html/file.html'); });

You can also test if this works with a local file. Here's a sample HTML file that simply loads jQuery:

<html>
    <head>
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"></script>
    </head>
    <body>
        <h5>Feel the presha</h5>
        <h3>Come play my game, I'll test ya</h3>
        <h1>Psycho- somatic- addict- insane!</h1>
    </body>
</html>

Then open Chrome's JavaScript console and run the statements above. The 3rd one will now work.

Running SSH Agent when starting Git Bash on Windows

In a git bash session, you can add a script to ~/.profile or ~/.bashrc (with ~ being usually set to %USERPROFILE%), in order for said session to launch automatically the ssh-agent. If the file doesn't exist, just create it.

This is what GitHub describes in "Working with SSH key passphrases".

The "Auto-launching ssh-agent on Git for Windows" section of that article has a robust script that checks if the agent is running or not. Below is just a snippet, see the GitHub article for the full solution.

# This is just a snippet. See the article above.
if ! agent_is_running; then
    agent_start
    ssh-add
elif ! agent_has_keys; then
    ssh-add
fi

Other Resources:

"Getting ssh-agent to work with git run from windows command shell" has a similar script, but I'd refer to the GitHub article above primarily, which is more robust and up to date.

how to hide a vertical scroll bar when not needed

overflow: auto (or overflow-y: auto) is the correct way to go.

The problem is that your text area is taller than your div. The div ends up cutting off the textbox, so even though it looks like it should start scrolling when the text is taller than 159px it won't start scrolling until the text is taller than 400px which is the height of the textbox.

Try this: http://jsfiddle.net/G9rfq/1/

I set overflow:auto on the text box, and made the textbox the same size as the div.

Also I don't believe it's valid to have a div inside a label, the browser will render it, but it might cause some funky stuff to happen. Also your div isn't closed.

How to add CORS request in header in Angular 5

If you are like me and you are using a local SMS Gateway server and you make a GET request to an IP like 192.168.0.xx you will get for sure CORS error.

Unfortunately I could not find an Angular solution, but with the help of a previous replay I got my solution and I am posting an updated version for Angular 7 8 9

import {from} from 'rxjs';

getData(): Observable<any> {
    return from(
      fetch(
        'http://xxxxx', // the url you are trying to access
        {
          headers: {
            'Content-Type': 'application/json',
          },
          method: 'GET', // GET, POST, PUT, DELETE
          mode: 'no-cors' // the most important option
        }
      ));
  }

Just .subscribe like the usual.

Can I automatically increment the file build version when using Visual Studio?

As of right now, for my application,

string ver = Application.ProductVersion;

returns ver = 1.0.3251.27860

The value 3251 is the number of days since 1/1/2000. I use it to put a version creation date on the splash screen of my application. When dealing with a user, I can ask the creation date which is easier to communicate than some long number.

(I'm a one-man dept supporting a small company. This approach may not work for you.)

Is there a simple way to convert C++ enum to string?

Adding even more simplicity of use to Jasper Bekkers' fantastic answer:

Set up once:

#define MAKE_ENUM(VAR) VAR,
#define MAKE_STRINGS(VAR) #VAR,
#define MAKE_ENUM_AND_STRINGS(source, enumName, enumStringName) \
    enum enumName { \
    source(MAKE_ENUM) \
    };\
const char* const enumStringName[] = { \
    source(MAKE_STRINGS) \
    };

Then, for usage:

#define SOME_ENUM(DO) \
    DO(Foo) \
    DO(Bar) \
    DO(Baz)
...
MAKE_ENUM_AND_STRINGS(SOME_ENUM, someEnum, someEnumNames)

How to make a PHP SOAP call using the SoapClient class

There is an option to generate php5 objects with WsdlInterpreter class. See more here: https://github.com/gkwelding/WSDLInterpreter

for example:

require_once 'WSDLInterpreter-v1.0.0/WSDLInterpreter.php';
$wsdlLocation = '<your wsdl url>?wsdl';
$wsdlInterpreter = new WSDLInterpreter($wsdlLocation);
$wsdlInterpreter->savePHP('.');

Removing an element from an Array (Java)

I hope you use the java collection / java commons collections!

With an java.util.ArrayList you can do things like the following:

yourArrayList.remove(someObject);

yourArrayList.add(someObject);

Two's Complement in Python

This will give you the two's complement efficiently using bitwise logic:

def twos_complement(value, bitWidth):
    if value >= 2**bitWidth:
        # This catches when someone tries to give a value that is out of range
        raise ValueError("Value: {} out of range of {}-bit value.".format(value, bitWidth))
    else:
        return value - int((value << 1) & 2**bitWidth)

How it works:

First, we make sure that the user has passed us a value that is within the range of the supplied bit range (e.g. someone gives us 0xFFFF and specifies 8 bits) Another solution to that problem would be to bitwise AND (&) the value with (2**bitWidth)-1

To get the result, the value is shifted by 1 bit to the left. This moves the MSB of the value (the sign bit) into position to be anded with 2**bitWidth. When the sign bit is '0' the subtrahend becomes 0 and the result is value - 0. When the sign bit is '1' the subtrahend becomes 2**bitWidth and the result is value - 2**bitWidth

Example 1: If the parameters are value=0xFF (255d, b11111111) and bitWidth=8

  1. 0xFF - int((0xFF << 1) & 2**8)
  2. 0xFF - int((0x1FE) & 0x100)
  3. 0xFF - int(0x100)
  4. 255 - 256
  5. -1

Example 2: If the parameters are value=0x1F (31d, b11111) and bitWidth=6

  1. 0x1F - int((0x1F << 1) & 2**6)
  2. 0x1F - int((0x3E) & 0x40)
  3. 0x1F - int(0x00)
  4. 31 - 0
  5. 31

Example 3: value = 0x80, bitWidth = 7

ValueError: Value: 128 out of range of 7-bit value.

Example 4: value = 0x80, bitWitdh = 8

  1. 0x80 - int((0x80 << 1) & 2**8)
  2. 0x80 - int((0x100) & 0x100)
  3. 0x80 - int(0x100)
  4. 128 - 256
  5. -128

Now, using what others have already posted, pass your bitstring into int(bitstring,2) and pass to the twos_complement method's value parameter.

Chrome net::ERR_INCOMPLETE_CHUNKED_ENCODING error

I solved this by changing datatype from '.js' to '.json'.

Change Git repository directory location.

A more Git based approach would be to make the changes to your local copy using cd or copy and pasting and then pushing these changes from local to remote repository.

If you try checking status of your local repo, it may show "untracked changes" which are actually the relocated files. To push these changes forcefully, you need to stage these files/directories by using

$ git add -A
#And commiting them
$ git commit -m "Relocating image demo files"
#And finally, push
$ git push -u local_repo -f HEAD:master

Hope it helps.

Using HTML5/JavaScript to generate and save a file

Simple solution for HTML5 ready browsers...

function download(filename, text) {
    var pom = document.createElement('a');
    pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
    pom.setAttribute('download', filename);

    if (document.createEvent) {
        var event = document.createEvent('MouseEvents');
        event.initEvent('click', true, true);
        pom.dispatchEvent(event);
    }
    else {
        pom.click();
    }
}

Usage

download('test.txt', 'Hello world!');

How to do a deep comparison between 2 objects with lodash?

Here's a concise solution:

_.differenceWith(a, b, _.isEqual);

How to reference static assets within vue javascript

Right after oppening script tag just add import someImage from '../assets/someImage.png' and use it for an icon url iconUrl: someImage

Java Could not reserve enough space for object heap error

I had this problem. I solved it with downloading 64x of the Java. Here is the link: http://javadl.sun.com/webapps/download/AutoDL?BundleId=87443

How to get value by key from JObject?

You can also get the value of an item in the jObject like this:

JToken value;
if (json.TryGetValue(key, out value))
{
   DoSomething(value);
}

Excel Macro : How can I get the timestamp in "yyyy-MM-dd hh:mm:ss" format?

Timestamp in saving workbook path, the ":" needs to be changed. I used ":" -> "." which implies that I need to add the extension back "xlsx".

wb(x).SaveAs ThisWorkbook.Path & "\" & unique(x) & " - " & Format(Now(), "mm-dd-yy, hh.mm.ss") & ".xlsx"

When should null values of Boolean be used?

There are three quick reasons:

  • to represent Database boolean values, which may be true, false or null
  • to represent XML Schema's xsd:boolean values declared with xsd:nillable="true"
  • to be able to use generic types: List<Boolean> - you can't use List<boolean>

Angular HTML binding

If you have templates in your angular (or whatever framework) application, and you return HTML templates from your backend through a HTTP request/response, you are mixing up templates between the frontend and the backend.

Why not just leave the templating stuff either in the frontend (i would suggest that), or in the backend (pretty intransparent imo)?

And if you keep templates in the frontend, why not just respond with JSON for requests to the backend. You do not even have to implement a RESTful structure, but keeping templates on one side makes your code more transparent.

This will pay back when someone else has to cope with your code (or even you yourself are re-entering your own code after a while)!

If you do it right, you will have small components with small templates, and best of all, if your code is imba, someone who doesn't know coding languages will be able to understand your templates and your logic! So additionally, keep your functions/methods as small you can. You will eventually find out that maintaining, refactoring, reviewing, and adding features will be much easier compared to large functions/methods/classes and mixing up templating and logic between the frontend and the backend - and keep as much of the logic in the backend if your frontend needs to be more flexible (e.g. writing an android frontend or switching to a different frontend framework).

Philosophy, man :)

p.s.: you do not have to implement 100% clean code, because it is very expensive - especially if you have to motivate team members ;) but: you should find a good balance between an approach to cleaner code and what you have (maybe it is already pretty clean)

check the book if you can and let it enter your soul: https://de.wikipedia.org/wiki/Clean_Code

Check if a variable exists in a list in Bash

Matvey is right, but you should quote $x and consider any kind of "spaces" (e.g. new line) with

[[ $list =~ (^|[[:space:]])"$x"($|[[:space:]]) ]] && echo 'yes' || echo 'no' 

so, i.e.

# list_include_item "10 11 12" "2"
function list_include_item {
  local list="$1"
  local item="$2"
  if [[ $list =~ (^|[[:space:]])"$item"($|[[:space:]]) ]] ; then
    # yes, list include item
    result=0
  else
    result=1
  fi
  return $result
}

end then

`list_include_item "10 11 12" "12"`  && echo "yes" || echo "no"

or

if `list_include_item "10 11 12" "1"` ; then
  echo "yes"
else 
  echo "no"
fi

Note that you must use "" in case of variables:

`list_include_item "$my_list" "$my_item"`  && echo "yes" || echo "no"

How can I pass an argument to a PowerShell script?

You can also define a variable directly in the PowerShell command line and then execute the script. The variable will be defined there, too. This helped me in a case where I couldn't modify a signed script.

Example:

 PS C:\temp> $stepsize = 30
 PS C:\temp> .\itunesForward.ps1

with iTunesForward.ps1 being

$iTunes = New-Object -ComObject iTunes.Application

if ($iTunes.playerstate -eq 1)
{
  $iTunes.PlayerPosition = $iTunes.PlayerPosition + $stepsize
}

Python-Requests close http connection

please use response.close() to close to avoid "too many open files" error

for example:

r = requests.post("https://stream.twitter.com/1/statuses/filter.json", data={'track':toTrack}, auth=('username', 'passwd'))
....
r.close()

How to use FormData in react-native?

Providing some other solution; we're also using react-native-image-picker; and the server side is using koa-multer; this set-up is working good:

ui

ImagePicker.showImagePicker(options, (response) => {
      if (response.didCancel) {}
      else if (response.error) {}
      else if (response.customButton) {}
      else {
        this.props.addPhoto({ // leads to handleAddPhoto()
          fileName: response.fileName,
          path: response.path,
          type: response.type,
          uri: response.uri,
          width: response.width,
          height: response.height,
        });
      }
    });

handleAddPhoto = (photo) => { // photo is the above object
    uploadImage({ // these 3 properties are required
      uri: photo.uri,
      type: photo.type,
      name: photo.fileName,
    }).then((data) => {
      // ...
    });
  }

client

export function uploadImage(file) { // so uri, type, name are required properties
  const formData = new FormData();
  formData.append('image', file);

  return fetch(`${imagePathPrefix}/upload`, { // give something like https://xx.yy.zz/upload/whatever
    method: 'POST',
    body: formData,
  }
  ).then(
    response => response.json()
  ).then(data => ({
    uri: data.uri,
    filename: data.filename,
  })
  ).catch(
    error => console.log('uploadImage error:', error)
  );
}

server

import multer from 'koa-multer';
import RouterBase from '../core/router-base';

const upload = multer({ dest: 'runtime/upload/' });

export default class FileUploadRouter extends RouterBase {
  setupRoutes({ router }) {
    router.post('/upload', upload.single('image'), async (ctx, next) => {
      const file = ctx.req.file;
      if (file != null) {
        ctx.body = {
          uri: file.filename,
          filename: file.originalname,
        };
      } else {
        ctx.body = {
          uri: '',
          filename: '',
        };
      }
    });
  }
}

How to loop over a Class attributes in Java?

While I agree with Jörn's answer if your class conforms to the JavaBeabs spec, here is a good alternative if it doesn't and you use Spring.

Spring has a class named ReflectionUtils that offers some very powerful functionality, including doWithFields(class, callback), a visitor-style method that lets you iterate over a classes fields using a callback object like this:

public void analyze(Object obj){
    ReflectionUtils.doWithFields(obj.getClass(), field -> {

        System.out.println("Field name: " + field.getName());
        field.setAccessible(true);
        System.out.println("Field value: "+ field.get(obj));

    });
}

But here's a warning: the class is labeled as "for internal use only", which is a pity if you ask me

How to fix git error: RPC failed; curl 56 GnuTLS

After reading your posts, I solved it simply by

apt install gnutls-bin

What does "implements" do on a class?

Implements means that it takes on the designated behavior that the interface specifies. Consider the following interface:

public interface ISpeak
{
   public String talk();
}

public class Dog implements ISpeak
{
   public String talk()
   {
        return "bark!";
   }
}

public class Cat implements ISpeak
{
    public String talk()
    {
        return "meow!";
    }
}

Both the Cat and Dog class implement the ISpeak interface.

What's great about interfaces is that we can now refer to instances of this class through the ISpeak interface. Consider the following example:

  Dog dog = new Dog();
  Cat cat = new Cat();

  List<ISpeak> animalsThatTalk = new ArrayList<ISpeak>();

  animalsThatTalk.add(dog);
  animalsThatTalk.add(cat);

  for (ISpeak ispeak : animalsThatTalk)
  {
      System.out.println(ispeak.talk());
  }

The output for this loop would be:

bark!
meow!

Interface provide a means to interact with classes in a generic way based upon the things they do without exposing what the implementing classes are.

One of the most common interfaces used in Java, for example, is Comparable. If your object implements this interface, you can write an implementation that consumers can use to sort your objects.

For example:

public class Person implements Comparable<Person>
{
  private String firstName;
  private String lastName;

  // Getters/Setters

  public int compareTo(Person p)
  {
    return this.lastName.compareTo(p.getLastName());  
  }
}

Now consider this code:

//  Some code in other class

List<Person> people = getPeopleList();

Collections.sort(people);

What this code did was provide a natural ordering to the Person class. Because we implemented the Comparable interface, we were able to leverage the Collections.sort() method to sort our List of Person objects by its natural ordering, in this case, by last name.

How to calculate the bounding box for a given lat/lng location?

I wrote an article about finding the bounding coordinates:

http://JanMatuschek.de/LatitudeLongitudeBoundingCoordinates

The article explains the formulae and also provides a Java implementation. (It also shows why Federico's formula for the min/max longitude is inaccurate.)

How to save python screen output to a text file

A quick and dirty hack to do this within the script is to direct the screen output to a file:

import sys 

stdoutOrigin=sys.stdout 
sys.stdout = open("log.txt", "w")

and then reverting back to outputting to screen at the end of your code:

sys.stdout.close()
sys.stdout=stdoutOrigin

This should work for a simple code, but for a complex code there are other more formal ways of doing it such as using Python logging.

Replace new line/return with space using regex

\s is a shortcut for whitespace characters in regex. It has no meaning in a string. ==> You can't use it in your replacement string. There you need to put exactly the character(s) that you want to insert. If this is a space just use " " as replacement.

The other thing is: Why do you use 3 backslashes as escape sequence? Two are enough in Java. And you don't need a | (alternation operator) in a character class.

L.replaceAll("[\\t\\n\\r]+"," ");

Remark

L is not changed. If you want to have a result you need to do

String result =     L.replaceAll("[\\t\\n\\r]+"," ");

Test code:

String in = "This is my text.\n\nAnd here is a new line";
System.out.println(in);

String out = in.replaceAll("[\\t\\n\\r]+"," ");
System.out.println(out);

git stash apply version

git Stash list 

List will show all stashed items eg:stash@{0}:,stash@{1}:,..,stash@{n}:

Then select the number n which denotes stash@{n}:

git stash apply n 

for example:

git stash apply 1 

will apply that particular stashed changes to the current branch

Properties file in python (similar to Java Properties)

This is a one-to-one replacement of java.util.Propeties

From the doc:

  def __parse(self, lines):
        """ Parse a list of lines and create
        an internal property dictionary """

        # Every line in the file must consist of either a comment
        # or a key-value pair. A key-value pair is a line consisting
        # of a key which is a combination of non-white space characters
        # The separator character between key-value pairs is a '=',
        # ':' or a whitespace character not including the newline.
        # If the '=' or ':' characters are found, in the line, even
        # keys containing whitespace chars are allowed.

        # A line with only a key according to the rules above is also
        # fine. In such case, the value is considered as the empty string.
        # In order to include characters '=' or ':' in a key or value,
        # they have to be properly escaped using the backslash character.

        # Some examples of valid key-value pairs:
        #
        # key     value
        # key=value
        # key:value
        # key     value1,value2,value3
        # key     value1,value2,value3 \
        #         value4, value5
        # key
        # This key= this value
        # key = value1 value2 value3

        # Any line that starts with a '#' is considerered a comment
        # and skipped. Also any trailing or preceding whitespaces
        # are removed from the key/value.

        # This is a line parser. It parses the
        # contents like by line.

Django: Redirect to previous page after login

I linked to the login form by passing the current page as a GET parameter and then used 'next' to redirect to that page. Thanks!

Convert byte slice to io.Reader

r := strings(byteData)

This also works to turn []byte into io.Reader

Printing all variables value from a class

If the output from ReflectionToStringBuilder.toString() is not enough readable for you, here is code that:
1) sorts field names alphabetically
2) flags non-null fields with asterisks in the beginning of the line

public static Collection<Field> getAllFields(Class<?> type) {
    TreeSet<Field> fields = new TreeSet<Field>(
            new Comparator<Field>() {
        @Override
        public int compare(Field o1, Field o2) {
            int res = o1.getName().compareTo(o2.getName());
            if (0 != res) {
                return res;
            }
            res = o1.getDeclaringClass().getSimpleName().compareTo(o2.getDeclaringClass().getSimpleName());
            if (0 != res) {
                return res;
            }
            res = o1.getDeclaringClass().getName().compareTo(o2.getDeclaringClass().getName());
            return res;
        }
    });
    for (Class<?> c = type; c != null; c = c.getSuperclass()) {
        fields.addAll(Arrays.asList(c.getDeclaredFields()));
    }
    return fields;
}
public static void printAllFields(Object obj) {
    for (Field field : getAllFields(obj.getClass())) {
        field.setAccessible(true);
        String name = field.getName();
        Object value = null;
        try {
            value = field.get(obj);
        } catch (IllegalArgumentException | IllegalAccessException e) {
            e.printStackTrace();
        }
        System.out.printf("%s %s.%s = %s;\n", value==null?" ":"*", field.getDeclaringClass().getSimpleName(), name, value);
    }
}

test harness:

public static void main(String[] args) {
    A a = new A();
    a.x = 1;
    B b = new B();
    b.x=10;
    b.y=20;
    System.out.println("=======");
    printAllFields(a);
    System.out.println("=======");
    printAllFields(b);
    System.out.println("=======");
}

class A {
    int x;
    String z = "z";
    Integer b; 
}
class B extends A {
    int y;
    private double z = 12345.6;
    public int a = 55;
}

How can I adjust DIV width to contents

You could try using float:left; or display:inline-block;.

Both of these will change the element's behaviour from defaulting to 100% width to defaulting to the natural width of its contents.

However, note that they'll also both have an impact on the layout of the surrounding elements as well. I would suggest that inline-block will have less of an impact though, so probably best to try that first.

Jackson with JSON: Unrecognized field, not marked as ignorable

Annotate the field students as below since there is mismatch in names of json property and java property

public Class Wrapper {
    @JsonProperty("wrapper")
    private List<Student> students;
    //getters & setters here
}

Python and SQLite: insert into table

#The Best way is to use `fStrings` (very easy and powerful in python3)   
#Format: f'your-string'   
#For Example:

mylist=['laks',444,'M']

cursor.execute(f'INSERT INTO mytable VALUES ("{mylist[0]}","{mylist[1]}","{mylist[2]}")')

#THATS ALL!! EASY!!
#You can use it with for loop!

How do I position a div relative to the mouse pointer using jQuery?

<script type="text/javascript" language="JavaScript">

  var cX = 0;
  var cY = 0;
  var rX = 0;
  var rY = 0;

  function UpdateCursorPosition(e) {
    cX = e.pageX;
    cY = e.pageY;
  }

  function UpdateCursorPositionDocAll(e) {
    cX = event.clientX;
    cY = event.clientY;
  }
  if (document.all) {
    document.onmousemove = UpdateCursorPositionDocAll;
  } else {
    document.onmousemove = UpdateCursorPosition;
  }

  function AssignPosition(d) {
    if (self.pageYOffset) {
      rX = self.pageXOffset;
      rY = self.pageYOffset;
    } else if (document.documentElement && document.documentElement.scrollTop) {
      rX = document.documentElement.scrollLeft;
      rY = document.documentElement.scrollTop;
    } else if (document.body) {
      rX = document.body.scrollLeft;
      rY = document.body.scrollTop;
    }
    if (document.all) {
      cX += rX;
      cY += rY;
    }
    d.style.left = (cX + 10) + "px";
    d.style.top = (cY + 10) + "px";
  }

  function HideContent(d) {
    if (d.length < 1) {
      return;
    }
    document.getElementById(d).style.display = "none";
  }

  function ShowContent(d) {
    if (d.length < 1) {
      return;
    }
    var dd = document.getElementById(d);
    AssignPosition(dd);
    dd.style.display = "block";
  }

  function ReverseContentDisplay(d) {
    if (d.length < 1) {
      return;
    }
    var dd = document.getElementById(d);
    AssignPosition(dd);
    if (dd.style.display == "none") {
      dd.style.display = "block";
    } else {
      dd.style.display = "none";
    }
  }
  //-->
</script>


<a onmouseover="ShowContent('uniquename3'); return true;" onmouseout="HideContent('uniquename3'); return true;" href="javascript:ShowContent('uniquename3')">
[show on mouseover, hide on mouseout]
</a>
<div id="uniquename3" style="display:none;
position:absolute;
border-style: solid;
background-color: white;
padding: 5px;">
  Content goes here.
</div>

How can I find non-ASCII characters in MySQL?

for this question we can also use this method :

Question from sql zoo:
Find all details of the prize won by PETER GRÜNBERG

Non-ASCII characters

ans: select*from nobel where winner like'P% GR%_%berg';

Chosen Jquery Plugin - getting selected values

Like from any regular input/select/etc...:

$("form.my-form .chosen-select").val()

Plotting 4 curves in a single plot, with 3 y-axes

I know of plotyy that allows you to have two y-axes, but no "plotyyy"!

Perhaps you can normalize the y values to have the same scale (min/max normalization, zscore standardization, etc..), then you can just easily plot them using normal plot, hold sequence.

Here's an example:

%# random data
x=1:20;
y = [randn(20,1)*1 + 0 , randn(20,1)*5 + 10 , randn(20,1)*0.3 + 50];

%# plotyy
plotyy(x,y(:,1), x,y(:,3))

%# orginial
figure
subplot(221), plot(x,y(:,1), x,y(:,2), x,y(:,3))
title('original'), legend({'y1' 'y2' 'y3'})

%# normalize: (y-min)/(max-min) ==> [0,1]
yy = bsxfun(@times, bsxfun(@minus,y,min(y)), 1./range(y));
subplot(222), plot(x,yy(:,1), x,yy(:,2), x,yy(:,3))
title('minmax')

%# standarize: (y - mean) / std ==> N(0,1)
yy = zscore(y);
subplot(223), plot(x,yy(:,1), x,yy(:,2), x,yy(:,3))
title('zscore')

%# softmax normalization with logistic sigmoid ==> [0,1]
yy = 1 ./ ( 1 + exp( -zscore(y) ) );
subplot(224), plot(x,yy(:,1), x,yy(:,2), x,yy(:,3))
title('softmax')

plotyy normalization

When to use 'raise NotImplementedError'?

One could also do a raise NotImplementedError() inside the child method of an @abstractmethod-decorated base class method.


Imagine writing a control script for a family of measurement modules (physical devices). The functionality of each module is narrowly-defined, implementing just one dedicated function: one could be an array of relays, another a multi-channel DAC or ADC, another an ammeter etc.

Much of the low-level commands in use would be shared between the modules for example to read their ID numbers or to send a command to them. Let's see what we have at this point:

Base Class

from abc import ABC, abstractmethod  #< we'll make use of these later

class Generic(ABC):
    ''' Base class for all measurement modules. '''

    # Shared functions
    def __init__(self):
        # do what you must...

    def _read_ID(self):
        # same for all the modules

    def _send_command(self, value):
        # same for all the modules

Shared Verbs

We then realise that much of the module-specific command verbs and, therefore, the logic of their interfaces is also shared. Here are 3 different verbs whose meaning would be self-explanatory considering a number of target modules.

  • get(channel)

  • relay: get the on/off status of the relay on channel

  • DAC: get the output voltage on channel

  • ADC: get the input voltage on channel

  • enable(channel)

  • relay: enable the use of the relay on channel

  • DAC: enable the use of the output channel on channel

  • ADC: enable the use of the input channel on channel

  • set(channel)

  • relay: set the relay on channel on/off

  • DAC: set the output voltage on channel

  • ADC: hmm... nothing logical comes to mind.


Shared Verbs Become Enforced Verbs

I'd argue that there is a strong case for the above verbs to be shared across the modules as we saw that their meaning is evident for each one of them. I'd continue writing my base class Generic like so:

class Generic(ABC):  # ...continued
    
    @abstractmethod
    def get(self, channel):
        pass

    @abstractmethod
    def enable(self, channel):
        pass

    @abstractmethod
    def set(self, channel):
        pass

Subclasses

We now know that our subclasses will all have to define these methods. Let's see what it could look like for the ADC module:

class ADC(Generic):

    def __init__(self):
        super().__init__()  #< applies to all modules
        # more init code specific to the ADC module
    
    def get(self, channel):
        # returns the input voltage measured on the given 'channel'

    def enable(self, channel):
        # enables accessing the given 'channel'

You may now be wondering:

But this won't work for the ADC module as set makes no sense there as we've just seen this above!

You're right: not implementing set is not an option as Python would then fire the error below when you tried to instantiate your ADC object.

TypeError: Can't instantiate abstract class 'ADC' with abstract methods 'set'

So you must implement something, because we made set an enforced verb (aka '@abstractmethod'), which is shared by two other modules but, at the same time, you must also not implement anything as set does not make sense for this particular module.

NotImplementedError to the Rescue

By completing the ADC class like this:

class ADC(Generic): # ...continued

    def set(self, channel):
        raise NotImplementedError("Can't use 'set' on an ADC!")

You are doing three very good things at once:

  1. You are protecting a user from erroneously issuing a command ('set') that is not (and shouldn't!) be implemented for this module.
  2. You are telling them explicitly what the problem is (see TemporalWolf's link about 'Bare exceptions' for why this is important)
  3. You are protecting the implementation of all the other modules for which the enforced verbs do make sense. I.e. you ensure that those modules for which these verbs do make sense will implement these methods and that they will do so using exactly these verbs and not some other ad-hoc names.

How do I use System.getProperty("line.separator").toString()?

The other responders are correct that split() takes a regex as the argument, so you'll have to fix that first. The other problem is that you're assuming that the line break characters are the same as the system default. Depending on where the data is coming from, and where the program is running, this assumption may not be correct.

Declare a const array

This is a way to do what you want:

using System;
using System.Collections.ObjectModel;
using System.Collections.Generic;

public ReadOnlyCollection<string> Titles { get { return new List<string> { "German", "Spanish", "Corrects", "Wrongs" }.AsReadOnly();}}

It is very similar to doing a readonly array.

How do I detect IE 8 with jQuery?

You should also look at jQuery.support. Feature detection is a lot more reliable than browser detection for coding your functionality (unless you are just trying to log browser versions).

Typescript: Type 'string | undefined' is not assignable to type 'string'

You trying to set variable name1, witch type set as strict string (it MUST be string) with value from object field name, witch value type set as optional string (it can be string or undefined, because of question sign). If you really need this behavior, you have to change type of name1 like this:

let name1: string | undefined = person.name;

And it'll be ok;

Check if an image is loaded (no errors) with jQuery

var isImgLoaded = function(imgSelector){
  return $(imgSelector).prop("complete") && $(imgSelector).prop("naturalWidth") !== 0;
}

// Or As a Plugin

    $.fn.extend({
      isLoaded: function(){
        return this.prop("complete") && this.prop("naturalWidth") !== 0;
      }
    })

// $(".myImage").isLoaded() 

How to run Java program in command prompt

You can use javac *.java command to compile all you java sources. Also you should learn a little about classpath because it seems that you should set appropriate classpath for succesful compilation (because your IDE use some libraries for building WebService clients). Also I can recommend you to check wich command your IDE use to build your project.

How to read and write xml files?

Writing XML using JAXB (Java Architecture for XML Binding):

http://www.mkyong.com/java/jaxb-hello-world-example/

package com.mkyong.core;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Customer {

    String name;
    int age;
    int id;

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

    @XmlElement
    public void setAge(int age) {
        this.age = age;
    }

    public int getId() {
        return id;
    }

    @XmlAttribute
    public void setId(int id) {
        this.id = id;
    }

} 

package com.mkyong.core;

import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

public class JAXBExample {
    public static void main(String[] args) {

      Customer customer = new Customer();
      customer.setId(100);
      customer.setName("mkyong");
      customer.setAge(29);

      try {

        File file = new File("C:\\file.xml");
        JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

        // output pretty printed
        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        jaxbMarshaller.marshal(customer, file);
        jaxbMarshaller.marshal(customer, System.out);

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

    }
}

How can I scroll a div to be visible in ReactJS?

For React 16, the correct answer is different from earlier answers:

class Something extends Component {
  constructor(props) {
    super(props);
    this.boxRef = React.createRef();
  }

  render() {
    return (
      <div ref={this.boxRef} />
    );
  }
}

Then to scroll, just add (after constructor):

componentDidMount() {
  if (this.props.active) { // whatever your test might be
    this.boxRef.current.scrollIntoView();
  }
}

Note: You must use '.current,' and you can send options to scrollIntoView:

scrollIntoView({
  behavior: 'smooth',
  block: 'center',
  inline: 'center',
});

(Found at http://www.albertgao.xyz/2018/06/07/scroll-a-not-in-view-component-into-the-view-using-react/)

Reading the spec, it was a little hard to suss out the meaning of block and inline, but after playing with it, I found that for a vertical scrolling list, block: 'end' made sure the element was visible without artificially scrolling the top of my content off the viewport. With 'center', an element near the bottom would be slid up too far and empty space appeared below it. But my container is a flex parent with justify: 'stretch' so that may affect the behavior. I didn't dig too much further. Elements with overflow hidden will impact how the scrollIntoView acts, so you'll probably have to experiment on your own.

My application has a parent that must be in view and if a child is selected, it then also scrolls into view. This worked well since parent DidMount happens before child's DidMount, so it scrolls to the parent, then when the active child is rendered, scrolls further to bring that one in view.

How to delete from multiple tables in MySQL?

The syntax looks right to me ... try to change it to use INNER JOIN ...

Have a look at this.

How to update npm

You can use npm package manager:

npm install npm@latest

This installs npm using itself @ latest version.

Build fails with "Command failed with a nonzero exit code"

I had the same error Restarting Xcode and Recompiling Fixed the issue for me.

Android SDK folder taking a lot of disk space. Do we need to keep all of the System Images?

You do not need to keep the system images unless you want to use the emulator on your desktop. Along with it you can remove other unwanted stuff to clear disk space.

Adding as an answer to my own question as I've had to narrate this to people in my team more than a few times. Hence this answer as a reference to share with other curious ones.

In the last few weeks there were several colleagues who asked me how to safely get rid of the unwanted stuff to release disk space (most of them were beginners). I redirected them to this question but they came back to me for steps. So for android beginners here is a step by step guide to safely remove unwanted stuff.

Note

  • Do not blindly delete everything directly from disk that you "think" is not required occupying. I did that once and had to re-download.
  • Make sure you have a list of all active projects with the kind of emulators (if any) and API Levels and Build tools required for those to continue working/compiling properly.

First, be sure you are not going to use emulators and will always do you development on a physical device. In case you are going to need emulators, note down the API Levels and type of emulators you'll need. Do not remove those. For the rest follow the below steps:

Steps to safely clear up unwanted stuff from Android SDK folder on the disk

  1. Open the Stand Alone Android SDK Manager. To open do one of the following:
  • Click the SDK Manager button on toolbar in android studio or eclipse
  • In Android Studio, go to settings and search "Android SDK". Click Android SDK -> "Open Standalone SDK Manager"
  • In Eclipse, open the "Window" menu and select "Android SDK Manager"
  • Navigate to the location of the android-sdk directory on your computer and run "SDK Manager.exe"

.

  1. Uncheck all items ending with "System Image". Each API Level will have more than a few. In case you need some and have figured the list already leave them checked to avoid losing them and having to re-download.

.

  1. Optional (may help save a marginally more amount of disk space): To free up some more space, you can also entirely uncheck unrequired API levels. Be careful again to avoid re-downloading something you are actually using in other projects.

.

  1. In the end make sure you have at least the following (check image below) for the remaining API levels to be able to seamlessly work with your physical device.

In the end the clean android sdk installed components should look something like this in the SDK manager.

enter image description here

Chart.js v2 - hiding grid lines

OK, nevermind.. I found the trick:

    scales: {
      yAxes: [
        {
          gridLines: {
                lineWidth: 0
            }
        }
      ]
    }

How to round an image with Glide library?

You can simply call the RoundedCornersTransformation constructor, which has cornerType enum input. Like this:

Glide.with(context)
            .load(bizList.get(position).getCover())
            .bitmapTransform(new RoundedCornersTransformation(context,20,0, RoundedCornersTransformation.CornerType.TOP))
            .into(holder.bizCellCoverImg);

but first you have to add Glide Transformations to your project.

Hide html horizontal but not vertical scrollbar

For me:

.ui-jqgrid .ui-jqgrid-bdiv {
   position: relative;
   margin: 0;
   padding: 0;
   overflow-y: auto;  <------
   overflow-x: hidden; <-----
   text-align: left;
}

Of course remove the arrows

How to prevent browser to invoke basic auth popup and handle 401 error using Jquery?

If WWW-Authenticate header is removed, then you wont get the caching of credentials and wont get back the Authorization header in request. That means now you will have to enter the credentials for every new request you generate.

Docker compose, running containers in net:host

Just print

network_mode: "host"

Multiple aggregate functions in HAVING clause

select CUSTOMER_CODE,nvl(sum(decode(TRANSACTION_TYPE,'D',AMOUNT)),0)) DEBIT,nvl(sum(DECODE(TRANSACTION_TYPE,'C',AMOUNT)),0)) CREDIT,
nvl(sum(decode(TRANSACTION_TYPE,'D',AMOUNT)),0)) - nvl(sum(DECODE(TRANSACTION_TYPE,'C',AMOUNT)),0)) BALANCE from TRANSACTION   
GROUP BY CUSTOMER_CODE
having nvl(sum(decode(TRANSACTION_TYPE,'D',AMOUNT)),0)) > 0
AND (nvl(sum(decode(TRANSACTION_TYPE,'D',AMOUNT)),0)) - nvl(sum(DECODE(TRANSACTION_TYPE,'C',AMOUNT)),0))) > 0

Node.js: what is ENOSPC error and how to solve?

On Linux, this is likely to be a limit on the number of file watches.

The development server uses inotify to implement hot-reloading. The inotify API allows the development server to watch files and be notified when they change.

The default inotify file watch limit varies from distribution to distribution (8192 on Fedora). The needs of the development server often exceeds this limit.

The best approach is to try increasing the file watch limit temporarily, then making that a permanent configuration change if you're happy with it. Note, though, that this changes your entire system's configuration, not just node.

To view your current limit:

sysctl fs.inotify.max_user_watches

To temporarily set a new limit:

# this limit will revert after reset
sudo sysctl fs.inotify.max_user_watches=524288
sudo sysctl -p
# now restart the server and see if it works

To set a permanent limit:

echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf
sudo sysctl -p

SQL How to remove duplicates within select query?

There are multiple rows with the same date, but the time is different. Therefore, DISTINCT start_date will not work. What you need is: cast the start_date to a DATE (so the TIME part is gone), and then do a DISTINCT:

SELECT DISTINCT CAST(start_date AS DATE) FROM table;

Depending on what database you use, the type name for DATE is different.

random.seed(): What does it do?

In this case, random is actually pseudo-random. Given a seed, it will generate numbers with an equal distribution. But with the same seed, it will generate the same number sequence every time. If you want it to change, you'll have to change your seed. A lot of people like to generate a seed based on the current time or something.

React JS Error: is not defined react/jsx-no-undef

Here you have not specified class name to be imported from Map.js file. If Map is class exportable class name exist in the Map.js file, your code should be as follow.

import React, { Component } from 'react';
import Map from  './Map';
class App extends Component {
   render() {
     return (
         <div className="App">
            <Map/>
         </div>
     );
   }
}
export default App;

How to programmatically click a button in WPF?

When using the MVVM Command pattern for Button function (recommended practice), a simple way to trigger the effect of the Button is as follows:

someButton.Command.Execute(someButton.CommandParameter);

This will use the Command object which the button triggers and pass the CommandParameter defined by the XAML.

HTML-Tooltip position relative to mouse pointer

This CAN be done with pure html and css. It may not be the best way but we all have different limitations. There are 3 ways that could be useful depending on what your specific circumstances are.

  1. The first involves overlaying an invisible table over top of your link with a hover action on each cell that displays an image.

_x000D_
_x000D_
#imagehover td:hover::after{_x000D_
  content: "             ";_x000D_
  white-space: pre;_x000D_
  background-image: url("http://www.google.com/images/srpr/logo4w.png");_x000D_
  position: relative;_x000D_
  left: 5px;_x000D_
  top: 5px;_x000D_
  font-size: 20px;_x000D_
  background-color: transparent;_x000D_
  background-position: 0px 0px;_x000D_
  background-size: 60px 20px;_x000D_
  background-repeat: no-repeat;_x000D_
  _x000D_
}_x000D_
_x000D_
_x000D_
#imagehover table, #imagehover th, #imagehover td {_x000D_
  border: 0px;_x000D_
  border-spacing: 0px;_x000D_
}
_x000D_
<a href="https://www.google.com">_x000D_
<table id="imagehover" style="width:50px;height:10px;z-index:9999;position:absolute" cellspacing="0">_x000D_
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>_x000D_
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>_x000D_
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>_x000D_
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>_x000D_
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>_x000D_
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>_x000D_
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>_x000D_
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>_x000D_
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>_x000D_
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>_x000D_
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>_x000D_
_x000D_
</table>_x000D_
Google</a>
_x000D_
_x000D_
_x000D_

  1. The second relies on being able to create your own cursor image

_x000D_
_x000D_
#googleLink{_x000D_
_x000D_
cursor: url(https://winter-bush-d06c.sto.workers.dev/cursor-extern.php?id=98272),url(https://9dc1a5c00e8109665645209c2d036b1c.cloudflareworkers.com/cursor-extern.php?id=98272),auto;_x000D_
_x000D_
}
_x000D_
<a href="https://www.google.com" id="googleLink">Google</a>
_x000D_
_x000D_
_x000D_

  1. While the normal title tooltip doesn't technically allow images it does allow any unicode characters including block letters and emojis which may suite your needs.

_x000D_
_x000D_
<a href="https://www.google.com" title="??" alt="??">Google</a>
_x000D_
_x000D_
_x000D_

How to deploy a war file in JBoss AS 7?

Actually, for the latest JBOSS 7 AS, we need a .dodeploy marker even for archives. So add a marker to trigger the deployment.

In my case, I added a Hello.war.deployed file in the same directory and then everything worked fine.

Hope this helps someone!

Test credit card numbers for use with PayPal sandbox

A bit late in the game but just in case it helps anyone.

If you are testing using the Sandbox and on the payment page you want to test payments NOT using a PayPal account but using the "Pay with Debit or Credit Card option" (i.e. when a regular Joe/Jane, NOT PayPal users, want to buy your stuff) and want to save yourself some time: just go to a site like http://www.getcreditcardnumbers.com/ and get numbers from there. You can use any Expiry date (in the future) and any numeric CCV (123 works).

The "test credit card numbers" in the PayPal documentation are just another brick in their infuriating wall of convoluted stuff.

I got the url above from PayPal's tech support.

Tested using a simple Hosted button and IPN. Good luck.

How to properly exit a C# application?

In this case, the most proper way to exit the application in to override onExit() method in App.xaml.cs:

protected override void OnExit(ExitEventArgs e) {
    base.OnExit(e); 
}

VMWare Player vs VMWare Workstation

Workstation has some features that Player lacks, such as teams (groups of VMs connected by private LAN segments) and multi-level snapshot trees. It's aimed at power users and developers; they even have some hooks for using a debugger on the host to debug code in the VM (including kernel-level stuff). The core technology is the same, though.

Webdriver Screenshot

You can use below function for relative path as absolute path is not a good idea to add in script

Import

import sys, os

Use code as below :

ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
screenshotpath = os.path.join(os.path.sep, ROOT_DIR,'Screenshots'+ os.sep)
driver.get_screenshot_as_file(screenshotpath+"testPngFunction.png")

make sure you create the folder where the .py file is present.

os.path.join also prevent you to run your script in cross-platform like: UNIX and windows. It will generate path separator as per OS at runtime. os.sep is similar like File.separtor in java

.gitignore all the .DS_Store files in every folder and subfolder

You can also add the --cached flag to auco's answer to maintain local .DS_store files, as Edward Newell mentioned in his original answer. The modified command looks like this: find . -name .DS_Store -print0 | xargs -0 git rm --cached --ignore-unmatch ..cheers and thanks!

Angular 6: saving data to local storage

First you should understand how localStorage works. you are doing wrong way to set/get values in local storage. Please read this for more information : How to Use Local Storage with JavaScript

In PANDAS, how to get the index of a known value?

Using the .loc[] accessor:

In [25]: a.loc[a['c1'] == 8].index[0]
Out[25]: 4

Can also use the get_loc() by setting 'c1' as the index. This will not change the original dataframe.

In [17]: a.set_index('c1').index.get_loc(8)
Out[17]: 4

Why does .json() return a promise?

Why does response.json return a promise?

Because you receive the response as soon as all headers have arrived. Calling .json() gets you another promise for the body of the http response that is yet to be loaded. See also Why is the response object from JavaScript fetch API a promise?.

Why do I get the value if I return the promise from the then handler?

Because that's how promises work. The ability to return promises from the callback and get them adopted is their most relevant feature, it makes them chainable without nesting.

You can use

fetch(url).then(response => 
    response.json().then(data => ({
        data: data,
        status: response.status
    })
).then(res => {
    console.log(res.status, res.data.title)
}));

or any other of the approaches to access previous promise results in a .then() chain to get the response status after having awaited the json body.

Get restaurants near my location

Is this what you are looking for?

https://maps.googleapis.com/maps/api/place/search/xml?location=49.260691,-123.137784&radius=500&sensor=false&key=*PlacesAPIKey*&types=restaurant

types is optional

Convert a row of a data frame to vector

Here is a dplyr based option:

newV = df %>% slice(1) %>% unlist(use.names = FALSE)

# or slightly different:
newV = df %>% slice(1) %>% unlist() %>% unname()

Command not found when using sudo

Ok this is my solution: in ~/.bash_aliases just add the following:

# ADDS MY PATH WHEN SET AS ROOT
if [ $(id -u) = "0" ]; then
   export PATH=$PATH:/home/your_user/bin 
fi

Voila! Now you can execute your own scripts with sudo or set as ROOT without having to do an export PATH=$PATH:/home/your_user/bin everytime.

Notice that I need to be explicit when adding my PATH since HOME for superuser is /root

SQL statement to get column type

In TSQL/MSSQL it looks like:

SELECT t.name, c.name 
FROM sys.tables t 
JOIN sys.columns c ON t.object_id = c.object_id
JOIN sys.types y ON y.user_type_id = c.user_type_id
WHERE t.name = ''

How do I debug error ECONNRESET in Node.js?

A simple tcp server I had for serving the flash policy file was causing this. I can now catch the error using a handler:

# serving the flash policy file
net = require("net")

net.createServer((socket) =>
  //just added
  socket.on("error", (err) =>
    console.log("Caught flash policy server socket error: ")
    console.log(err.stack)
  )

  socket.write("<?xml version=\"1.0\"?>\n")
  socket.write("<!DOCTYPE cross-domain-policy SYSTEM \"http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd\">\n")
  socket.write("<cross-domain-policy>\n")
  socket.write("<allow-access-from domain=\"*\" to-ports=\"*\"/>\n")
  socket.write("</cross-domain-policy>\n")
  socket.end()
).listen(843)

What possibilities can cause "Service Unavailable 503" error?

Primarily what that means is that there are too many concurrent requests and further that they exceed the default 1000 queued requests. That is there are 1000 or more queued requests to your website.

This could happen (assuming there are no faults in your app) if there are long running tasks and as a result the Request queue is backed up.

Depending on how the application pool has been set up you may see this kind of thing. Typically, the app pool's Process Model has an item called Maximum Worker Processes. By default this is 1. If you set it to more than 1 (typically up to a max of the number of cores on the hardware) you may not see this happen.

Just to note that unless the site is extremely busy you should not see this. If you do, it's really pointing to long running tasks

Disable all table constraints in Oracle

It doesn't look like you can do this with a single command, but here's the closest thing to it that I could find.

How to change the default GCC compiler in Ubuntu?

Here's a complete example of jHackTheRipper's answer for the TL;DR crowd. :-) In this case, I wanted to run g++-4.5 on an Ubuntu system that defaults to 4.6. As root:

apt-get install g++-4.5
update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-4.6 100
update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-4.5 50
update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-4.6 100
update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-4.5 50
update-alternatives --install /usr/bin/cpp cpp-bin /usr/bin/cpp-4.6 100
update-alternatives --install /usr/bin/cpp cpp-bin /usr/bin/cpp-4.5 50
update-alternatives --set g++ /usr/bin/g++-4.5
update-alternatives --set gcc /usr/bin/gcc-4.5
update-alternatives --set cpp-bin /usr/bin/cpp-4.5

Here, 4.6 is still the default (aka "auto mode"), but I explicitly switch to 4.5 temporarily (manual mode). To go back to 4.6:

update-alternatives --auto g++
update-alternatives --auto gcc
update-alternatives --auto cpp-bin

(Note the use of cpp-bin instead of just cpp. Ubuntu already has a cpp alternative with a master link of /lib/cpp. Renaming that link would remove the /lib/cpp link, which could break scripts.)

Mixed mode assembly is built against version ‘v2.0.50727' of the runtime

Try to use another config file (not the one from your project) and RESTART Visual Studio:

C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\CommonExtensions\Microsoft\TestWindow\vstest.executionengine.x86.exe.config
(32-bit)

or

C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\CommonExtensions\Microsoft\TestWindow\vstest.executionengine.exe.config
(64-bit)

SVN - Checksum mismatch while updating

I had a similar error and fixed as follows:

(My 'fix' is based on an assumption which may or may not be correct as I don't know that much about how subversion works internally, but it definitely worked for me)

I am assuming that .svn\text-base\import.php.svn-base is expected to match the latest commit.

When I checked the file I was having the error on , the base file did NOT match the latest commit in the repository.

I copied the text from the latest commit and saved that in the .svn folder, replacing the incorrect file (made a backup copy in case my assumptions were wrong). (file was marked read only, I cleared that flag, overwrote and set it back to read only)

I was then able to commit successfully.

AngularJS does not send hidden field value

Directly assign the value to model in data-ng-value attribute. Since Angular interpreter doesn't recognize hidden fields as part of ngModel.

<input type="hidden" name="pfuserid" data-ng-value="newPortfolio.UserId = data.Id"/>

Radio Buttons ng-checked with ng-model

I think you should only use ng-model and should work well for you, here is the link to the official documentation of angular https://docs.angularjs.org/api/ng/input/input%5Bradio%5D

The code from the example should not be difficult to adapt to your specific situation:

<script>
   function Ctrl($scope) {
      $scope.color = 'blue';
      $scope.specialValue = {
         "id": "12345",
         "value": "green"
      };
   }
</script>
<form name="myForm" ng-controller="Ctrl">
   <input type="radio" ng-model="color" value="red">  Red <br/>
   <input type="radio" ng-model="color" ng-value="specialValue"> Green <br/>
   <input type="radio" ng-model="color" value="blue"> Blue <br/>
   <tt>color = {{color | json}}</tt><br/>
</form>

jQuery remove all list items from an unordered list

As noted by others, $('ul').empty() works fine, as does:

$('ul li').remove();

JS Fiddle demo.

How to redirect all HTTP requests to HTTPS

This redirects all the URLs to https and www

RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTPS_HOST} !^www.example.com$ [NC,OR]
RewriteCond %{HTTP_HOST} !^www.example.com$ [NC]
RewriteRule ^(.*)$ https://www.example.com/$1 [L,R=301]

How can I disable all views inside the layout?

this one is recursive for ViewGroups

private void disableEnableControls(boolean enable, ViewGroup vg){
    for (int i = 0; i < vg.getChildCount(); i++){
       View child = vg.getChildAt(i);
       child.setEnabled(enable);
       if (child instanceof ViewGroup){ 
          disableEnableControls(enable, (ViewGroup)child);
       }
    }
}

Go to "next" iteration in JavaScript forEach loop

You can simply return if you want to skip the current iteration.

Since you're in a function, if you return before doing anything else, then you have effectively skipped execution of the code below the return statement.

Converting JSON to XLS/CSV in Java

you can use commons csv to convert into CSV format. or use POI to convert into xls. if you need helper to convert into xls, you can use jxls, it can convert java bean (or list) into excel with expression language.

Basically, the json doc maybe is a json array, right? so it will be same. the result will be list, and you just write the property that you want to display in excel format that will be read by jxls. See http://jxls.sourceforge.net/reference/collections.html

If the problem is the json can't be read in the jxls excel property, just serialize it into collection of java bean first.

error: member access into incomplete type : forward declaration of

You must have the definition of class B before you use the class. How else would the compiler otherwise know that there exists such a function as B::add?

Either define class B before class A, or move the body of A::doSomething to after class B have been defined, like

class B;

class A
{
    B* b;

    void doSomething();
};

class B
{
    A* a;

    void add() {}
};

void A::doSomething()
{
    b->add();
}

Maven: add a dependency to a jar by relative path

This is working for me: Let's say I have this dependency

<dependency>
    <groupId>com.company.app</groupId>
    <artifactId>my-library</artifactId>
    <version>1.0</version>
    <scope>system</scope>
    <systemPath>${project.basedir}/lib/my-library.jar</systemPath>
</dependency>

Then, add the class-path for your system dependency manually like this

<Class-Path>libs/my-library-1.0.jar</Class-Path>

Full config:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-jar-plugin</artifactId>
    <version>2.4</version>
    <configuration>
        <archive>
            <manifestEntries>
                <Build-Jdk>${jdk.version}</Build-Jdk>
                <Implementation-Title>${project.name}</Implementation-Title>
                <Implementation-Version>${project.version}</Implementation-Version>
                <Specification-Title>${project.name} Library</Specification-Title>
                <Specification-Version>${project.version}</Specification-Version>
                <Class-Path>libs/my-library-1.0.jar</Class-Path>
            </manifestEntries>
            <manifest>
                <addClasspath>true</addClasspath>
                <mainClass>com.company.app.MainClass</mainClass>
                <classpathPrefix>libs/</classpathPrefix>
            </manifest>
        </archive>
    </configuration>
</plugin>
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-dependency-plugin</artifactId>
    <version>2.5.1</version>
    <executions>
        <execution>
            <id>copy-dependencies</id>
            <phase>package</phase>
            <goals>
                <goal>copy-dependencies</goal>
            </goals>
            <configuration>
                <outputDirectory>${project.build.directory}/libs/</outputDirectory>
            </configuration>
        </execution>
    </executions>
</plugin>

Check if a specific tab page is selected (active)

For whatever reason the above would not work for me. This is what did:

if (tabControl.SelectedTab.Name == "tabName" )
{
     .. do stuff
}

where tabControl.SelectedTab.Name is the name attribute assigned to the page in the tabcontrol itself.

htaccess redirect to https://www

There are a lot of solutions out there. Here is a link to the apache wiki which deals with this issue directly.

http://wiki.apache.org/httpd/RewriteHTTPToHTTPS

RewriteEngine On
# This will enable the Rewrite capabilities

RewriteCond %{HTTPS} !=on
# This checks to make sure the connection is not already HTTPS

RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L]
# This rule will redirect users from their original location, to the same location but using HTTPS.
# i.e.  http://www.example.com/foo/ to https://www.example.com/foo/
# The leading slash is made optional so that this will work either in httpd.conf
# or .htaccess context

How to send value attribute from radio button in PHP

The radio buttons are sent on form submit when they are checked only...

use isset() if true then its checked otherwise its not

creating array without declaring the size - java

As others have said, use ArrayList. Here's how:

public class t
{
 private List<Integer> x = new ArrayList<Integer>();

 public void add(int num)
 {
   this.x.add(num);
 }
}

As you can see, your add method just calls the ArrayList's add method. This is only useful if your variable is private (which it is).

Update elements in a JSONObject

Use the put method: https://developer.android.com/reference/org/json/JSONObject.html

JSONObject person =  jsonArray.getJSONObject(0).getJSONObject("person");
person.put("name", "Sammie");

Check for column name in a SqlDataReader object

In your particular situation (all procedures has the same columns except 1 which has additional 1 column), it will be better and faster to check reader. FieldCount property to distinguish between them.

const int NormalColCount=.....
if(reader.FieldCount > NormalColCount)
{
// Do something special
}

I know it is an old post but I decided to answer to help other in the same situation. you can also (for performance reason) mix this solution with the solution iterating solution.

Generate JSON string from NSDictionary in iOS

In Swift (version 2.0):

class func jsonStringWithJSONObject(jsonObject: AnyObject) throws -> String? {
    let data: NSData? = try? NSJSONSerialization.dataWithJSONObject(jsonObject, options: NSJSONWritingOptions.PrettyPrinted)

    var jsonStr: String?
    if data != nil {
        jsonStr = String(data: data!, encoding: NSUTF8StringEncoding)
    }

    return jsonStr
}

List all employee's names and their managers by manager name using an inner join

You have an incorrect ON clause at the join, this works:

inner join Employees m on e.mgr = m.EmpId;

The mgr column references the EmpId column.

DEMO

Jquery checking success of ajax post

using jQuery 1.8 and above, should use the following:

var request = $.ajax({
    type: 'POST',
    url: 'mmm.php',
    data: { abc: "abcdefghijklmnopqrstuvwxyz" } })
    .done(function(data) { alert("success"+data.slice(0, 100)); })
    .fail(function() { alert("error"); })
    .always(function() { alert("complete"); });

check out the docs as @hitautodestruct stated.

Working with SQL views in Entity Framework Core

Here is a new way to work with SQL views in EF Core: Query Types.

Convert python long/int to fixed size byte array

long/int to the byte array looks like exact purpose of struct.pack. For long integers that exceed 4(8) bytes, you can come up with something like the next:

>>> limit = 256*256*256*256 - 1
>>> i = 1234567890987654321
>>> parts = []
>>> while i:
        parts.append(i & limit)
        i >>= 32

>>> struct.pack('>' + 'L'*len(parts), *parts )
'\xb1l\x1c\xb1\x11"\x10\xf4'

>>> struct.unpack('>LL', '\xb1l\x1c\xb1\x11"\x10\xf4')
(2976652465L, 287445236)
>>> (287445236L << 32) + 2976652465L
1234567890987654321L

Python pandas Filtering out nan from a data selection of a column of strings

df = pd.DataFrame({'movie': ['thg', 'thg', 'mol', 'mol', 'lob', 'lob'],'rating': [3., 4., 5., np.nan, np.nan, np.nan],'name': ['John','James', np.nan, np.nan, np.nan,np.nan]})

for col in df.columns:
    df = df[~pd.isnull(df[col])]

How to convert a string of numbers to an array of numbers?

Array.from() for details go to MDN

var a = "1,2,3,4";
var b = Array.from(a.split(','),Number);

b is an array of numbers

Where is the <conio.h> header file on Linux? Why can't I find <conio.h>?

The original conio.h was implemented by Borland, so its not a part of the C Standard Library nor is defined by POSIX.

But here is an implementation for Linux that uses ncurses to do the job.

How do I make a div full screen?

.widget-HomePageSlider .slider-loader-hide {
    position: fixed;
    top: 0px;
    left: 0px;
    width: 100%;
    height: 100%;
    z-index: 10000;
    background: white;
}

How do I append text to a file?

Other possible way is:

echo "text" | tee -a filename >/dev/null

The -a will append at the end of the file.

If needing sudo, use:

echo "text" | sudo tee -a filename >/dev/null