Programs & Examples On #Dyld

dyld, the Dynamic Link Editor, is the binary loader for Darwin (Mac OS X). Questions about dyld typically involve shared libraries being unavailable at link-time, or unavailable at runtime.

registerForRemoteNotificationTypes: is not supported in iOS 8.0 and later

I couldn't figure out what the "categories" NSSet variable should be set to, so if someone could fill me in I will gladly edit this post. The following does, however, bring up the push notification dialog.

[[UIApplication sharedApplication] registerForRemoteNotifications];
UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert) categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];

Edit: I got a push notification to send to my phone with this code, so I'm not sure the categories parameter is necessary.

iOS app with framework crashed on device, dyld: Library not loaded, Xcode 6 Beta

If have development pod Delete your app from simulator install from pod -> clean - > run again...

dyld: Library not loaded: @rpath/libswiftCore.dylib

In my case,

I have set @executable_path/Frameworks

But I have to also set "Framework search paths"

$(PROJECT_DIR)/Frameworks

change as recursive

Which works for me.

Broken references in Virtualenvs

This occurred when I updated to Mac OS X Mavericks from Snow Leopard. I had to re-install brew beforehand too. Hopefully you ran the freeze command for your project with pip.

To resolve, you have to update the paths that the virtual environment points to.

  • Install a version of python with brew:

brew install python

  • Re-install virtualenvwrapper.

pip install --upgrade virtualenvwrapper

  • Removed the old virtual environment:

rmvirtualenv old_project

  • Create a new virtual environment:

mkvirtualenv new_project

  • Work on new virtual environment

workon new_project

  • Use pip to install the requirements for the new project.

pip install -r requirements.txt

This should leave the project as it was before.

dyld: Library not loaded: /usr/local/lib/libpng16.16.dylib with anything php related

I had this error that wasn't solved by brew update && brew upgrade. For some reason I needed to install it from scratch:

$ brew install libpng

Reason: no suitable image found

I solve the problem by check my local keychains.Keep login.keychain has the right certificate

OS X Framework Library not loaded: 'Image not found'

open xcode -> general -> Embedded Binaries -> add QBImagepicker.framework and RSKImageCropper -> clean project

just add QBImagePicker.framework and RSKImageCropper.framework at embedded binaries worked for me

dyld: Library not loaded ... Reason: Image not found

If you're using Xcode 11 onwards:

Go to General tab and add the framework in Frameworks, Libraries, and Embedded Content section.

Important: By default it might be marked as Do Not Embed, change it to Embed Without Signing like shown in the image and you are good to go.

enter image description here

For Xcode versions below 11:

Just add the framework in Embedded Binaries section and you are done.

Cheers!

Swift: print() vs println() vs NSLog()

There's another method called dump() which can also be used for logging:

func dump<T>(T, name: String?, indent: Int, maxDepth: Int, maxItems: Int)

Dumps an object’s contents using its mirror to standard output.

From Swift Standard Library Functions

Why use Gradle instead of Ant or Maven?

It's also much easier to manage native builds. Ant and Maven are effectively Java-only. Some plugins exist for Maven that try to handle some native projects, but they don't do an effective job. Ant tasks can be written that compile native projects, but they are too complex and awkward.

We do Java with JNI and lots of other native bits. Gradle simplified our Ant mess considerably. When we started to introduce dependency management to the native projects it was messy. We got Maven to do it, but the equivalent Gradle code was a tiny fraction of what was needed in Maven, and people could read it and understand it without becoming Maven gurus.

Where can I view Tomcat log files in Eclipse?

Go to the "Server" view, then double-click the Tomcat server you're running. The access log files are stored relative to the path in the "Server path" field, which itself is relative to the workspace path.

javascript push multidimensional array

Use []:

cookie_value_add.push([productID,itemColorTitle, itemColorPath]);

or

arrayToPush.push([value1, value2, ..., valueN]);

How do I get the entity that represents the current user in Symfony2?

The thread is a bit old but i think this could probably save someone's time ...

I ran into the same problem as the original question, that the type is showed as Symfony\Component\Security\Core\User\User

It eventually turned out that i was logged in using an in memory user

my security.yml looks something like this

security:
    providers:
        chain_provider:
            chain:
                providers: [in_memory, fos_userbundle]
        fos_userbundle:
            id: fos_user.user_manager
        in_memory:
            memory:
                users:
                    user:  { password: userpass, roles: [ 'ROLE_USER' ] }
                    admin: { password: adminpass, roles: [ 'ROLE_ADMIN', 'ROLE_SONATA_ADMIN' ] }

the in_memory user type is always Symfony\Component\Security\Core\User\User if you want to use your own entity, log in using that provider's user.

Thanks, hj

How do you round a float to 2 decimal places in JRuby?

to truncate a decimal I've used the follow code:

<th><%#= sprintf("%0.01f",prom/total) %><!--1dec,aprox-->
    <% if prom == 0 or total == 0 %>
        N.E.
    <% else %>
        <%= Integer((prom/total).to_d*10)*0.1 %><!--1decimal,truncado-->
    <% end %>
        <%#= prom/total %>
</th>

If you want to truncate to 2 decimals, you should use Integr(a*100)*0.01

What is the opposite of :hover (on mouse leave)?

The opposite is using :not

e.g.

selection:not(:hover) { rules }

MySQL Query - Records between Today and Last 30 Days

Here's a solution without using curdate() function, this is a solution for those who use TSQL I guess

SELECT myDate
FROM myTable
WHERE myDate BETWEEN DATEADD(DAY, -30, GETDATE()) AND GETDATE()

When is assembly faster than C?

Matrix operations using SIMD instructions is probably faster than compiler generated code.

Get list of databases from SQL Server

To exclude system databases :

SELECT name FROM master.dbo.sysdatabases where sid <>0x01

Specify path to node_modules in package.json

I'm not sure if this is what you had in mind, but I ended up on this question because I was unable to install node_modules inside my project dir as it was mounted on a filesystem that did not support symlinks (a VM "shared" folder).

I found the following workaround:

  1. Copy the package.json file to a temp folder on a different filesystem
  2. Run npm install there
  3. Copy the resulting node_modules directory back into the project dir, using cp -r --dereference to expand symlinks into copies.

I hope this helps someone else who ends up on this question when looking for a way to move node_modules to a different filesystem.

Other options

There is another workaround, which I found on the github issue that @Charminbear linked to, but this doesn't work with grunt because it does not support NODE_PATH as per https://github.com/browserify/resolve/issues/136:

lets say you have /media/sf_shared and you can't install symlinks in there, which means you can't actually npm install from /media/sf_shared/myproject because some modules use symlinks.

  • $ mkdir /home/dan/myproject && cd /home/dan/myproject
  • $ ln -s /media/sf_shared/myproject/package.json (you can symlink in this direction, just can't create one inside of /media/sf_shared)
  • $ npm install
  • $ cd /media/sf_shared/myproject
  • $ NODE_PATH=/home/dan/myproject/node_modules node index.js

Setting multiple attributes for an element at once with JavaScript

You can create a function that takes a variable number of arguments:

function setAttributes(elem /* attribute, value pairs go here */) {
    for (var i = 1; i < arguments.length; i+=2) {
        elem.setAttribute(arguments[i], arguments[i+1]);
    }
}

setAttributes(elem, 
    "src", "http://example.com/something.jpeg",
    "height", "100%",
    "width", "100%");

Or, you pass the attribute/value pairs in on an object:

 function setAttributes(elem, obj) {
     for (var prop in obj) {
         if (obj.hasOwnProperty(prop)) {
             elem[prop] = obj[prop];
         }
     }
 }

setAttributes(elem, {
    src: "http://example.com/something.jpeg",
    height: "100%",
    width: "100%"
});

You could also make your own chainable object wrapper/method:

function $$(elem) {
    return(new $$.init(elem));
}

$$.init = function(elem) {
    if (typeof elem === "string") {
        elem = document.getElementById(elem);
    }
    this.elem = elem;
}

$$.init.prototype = {
    set: function(prop, value) {
        this.elem[prop] = value;
        return(this);
    }
};

$$(elem).set("src", "http://example.com/something.jpeg").set("height", "100%").set("width", "100%");

Working example: http://jsfiddle.net/jfriend00/qncEz/

Using String Format to show decimal up to 2 places or simple integer

An inelegant way would be:

var my = DoFormat(123.0);

With DoFormat being something like:

public static string DoFormat( double myNumber )
{
    var s = string.Format("{0:0.00}", myNumber);

    if ( s.EndsWith("00") )
    {
        return ((int)myNumber).ToString();
    }
    else
    {
        return s;
    }
}

Not elegant but working for me in similar situations in some projects.

How to assign colors to categorical variables in ggplot2 that have stable mapping?

For simple situations like the exact example in the OP, I agree that Thierry's answer is the best. However, I think it's useful to point out another approach that becomes easier when you're trying to maintain consistent color schemes across multiple data frames that are not all obtained by subsetting a single large data frame. Managing the factors levels in multiple data frames can become tedious if they are being pulled from separate files and not all factor levels appear in each file.

One way to address this is to create a custom manual colour scale as follows:

#Some test data
dat <- data.frame(x=runif(10),y=runif(10),
        grp = rep(LETTERS[1:5],each = 2),stringsAsFactors = TRUE)

#Create a custom color scale
library(RColorBrewer)
myColors <- brewer.pal(5,"Set1")
names(myColors) <- levels(dat$grp)
colScale <- scale_colour_manual(name = "grp",values = myColors)

and then add the color scale onto the plot as needed:

#One plot with all the data
p <- ggplot(dat,aes(x,y,colour = grp)) + geom_point()
p1 <- p + colScale

#A second plot with only four of the levels
p2 <- p %+% droplevels(subset(dat[4:10,])) + colScale

The first plot looks like this:

enter image description here

and the second plot looks like this:

enter image description here

This way you don't need to remember or check each data frame to see that they have the appropriate levels.

How can I find the current OS in Python?

https://docs.python.org/library/os.html

To complement Greg's post, if you're on a posix system, which includes MacOS, Linux, Unix, etc. you can use os.uname() to get a better feel for what kind of system it is.

CREATE FILE encountered operating system error 5(failed to retrieve text for this error. Reason: 15105)

Start->Run->services.msc->scroll through the list of services until you find SQL Server->right-click->properties->Log On tab:

Then choose Local System Account and check the Allow service to interact with desktop checkbox.

Restart the service.

Services

Groovy / grails how to determine a data type?

To determine the class of an object simply call:

someObject.getClass()

You can abbreviate this to someObject.class in most cases. However, if you use this on a Map it will try to retrieve the value with key 'class'. Because of this, I always use getClass() even though it's a little longer.

If you want to check if an object implements a particular interface or extends a particular class (e.g. Date) use:

(somObject instanceof Date)

or to check if the class of an object is exactly a particular class (not a subclass of it), use:

(somObject.getClass() == Date)

Can you detect "dragging" in jQuery?

Try this: it shows when is 'dragged' state. ;) fiddle link

$(function() {
    var isDragging = false;
    $("#status").html("status:");
    $("a")
    .mousedown(function() {
        $("#status").html("status: DRAGGED");        
    })
    .mouseup(function() {
        $("#status").html("status: dropped");   
    });

    $("ul").sortable();
});

How to handle errors with boto3?

  • Only one import needed.
  • No if statement needed.
  • Use the client built-in exception as intended.

Ex:

from boto3 import client

cli = client('iam')
try:
    cli.create_user(
        UserName = 'Brian'
    )
except cli.exceptions.EntityAlreadyExistsException:
    pass

a CloudWatch example:

cli = client('logs')
try:
    cli.create_log_group(
        logGroupName = 'MyLogGroup'
    )
except cli.exceptions.ResourceAlreadyExistsException:
    pass

Calling a php function by onclick event

onclick event to call a function

  <strike> <input type="button" value="NEXT"  onclick="document.write('<?php //call a function here ex- 'fun();' ?>');" />    </strike>

it will surely help you

it take a little more time than normal but wait it will work

How can I use an array of function pointers?

Can use it in the way like this:

//! Define:
#define F_NUM 3
int (*pFunctions[F_NUM])(void * arg);

//! Initialise:
int someFunction(void * arg) {
    int a= *((int*)arg);
    return a*a;
}

pFunctions[0]= someFunction;

//! Use:
int someMethod(int idx, void * arg, int * result) {
    int done= 0;
    if (idx < F_NUM && pFunctions[idx] != NULL) {
        *result= pFunctions[idx](arg);
        done= 1;
    }
    return done;
}

int x= 2;
int z= 0;
someMethod(0, (void*)&x, &z);
assert(z == 4);

What is a CSRF token? What is its importance and how does it work?

The Cloud Under blog has a good explanation of CSRF tokens. (archived)

Imagine you had a website like a simplified Twitter, hosted on a.com. Signed in users can enter some text (a tweet) into a form that’s being sent to the server as a POST request and published when they hit the submit button. On the server the user is identified by a cookie containing their unique session ID, so your server knows who posted the Tweet.

The form could be as simple as that:

 <form action="http://a.com/tweet" method="POST">
   <input type="text" name="tweet">
   <input type="submit">
 </form> 

Now imagine, a bad guy copies and pastes this form to his malicious website, let’s say b.com. The form would still work. As long

as a user is signed in to your Twitter (i.e. they’ve got a valid session cookie for a.com), the POST request would be sent to http://a.com/tweet and processed as usual when the user clicks the submit button.

So far this is not a big issue as long as the user is made aware about what the form exactly does, but what if our bad guy tweaks the form like this:

 <form action="https://example.com/tweet" method="POST">
   <input type="hidden" name="tweet" value="Buy great products at http://b.com/#iambad">
   <input type="submit" value="Click to win!">
 </form> 

Now, if one of your users ends up on the bad guy’s website and hits the “Click to win!” button, the form is submitted to

your website, the user is correctly identified by the session ID in the cookie and the hidden Tweet gets published.

If our bad guy was even worse, he would make the innocent user submit this form as soon they open his web page using JavaScript, maybe even completely hidden away in an invisible iframe. This basically is cross-site request forgery.

A form can easily be submitted from everywhere to everywhere. Generally that’s a common feature, but there are many more cases where it’s important to only allow a form being submitted from the domain where it belongs to.

Things are even worse if your web application doesn’t distinguish between POST and GET requests (e.g. in PHP by using $_REQUEST instead of $_POST). Don’t do that! Data altering requests could be submitted as easy as <img src="http://a.com/tweet?tweet=This+is+really+bad">, embedded in a malicious website or even an email.

How do I make sure a form can only be submitted from my own website? This is where the CSRF token comes in. A CSRF token is a random, hard-to-guess string. On a page with a form you want to protect, the server would generate a random string, the CSRF token, add it to the form as a hidden field and also remember it somehow, either by storing it in the session or by setting a cookie containing the value. Now the form would look like this:

    <form action="https://example.com/tweet" method="POST">
      <input type="hidden" name="csrf-token" value="nc98P987bcpncYhoadjoiydc9ajDlcn">
      <input type="text" name="tweet">
      <input type="submit">
    </form> 

When the user submits the form, the server simply has to compare the value of the posted field csrf-token (the name doesn’t

matter) with the CSRF token remembered by the server. If both strings are equal, the server may continue to process the form. Otherwise the server should immediately stop processing the form and respond with an error.

Why does this work? There are several reasons why the bad guy from our example above is unable to obtain the CSRF token:

Copying the static source code from our page to a different website would be useless, because the value of the hidden field changes with each user. Without the bad guy’s website knowing the current user’s CSRF token your server would always reject the POST request.

Because the bad guy’s malicious page is loaded by your user’s browser from a different domain (b.com instead of a.com), the bad guy has no chance to code a JavaScript, that loads the content and therefore our user’s current CSRF token from your website. That is because web browsers don’t allow cross-domain AJAX requests by default.

The bad guy is also unable to access the cookie set by your server, because the domains wouldn’t match.

When should I protect against cross-site request forgery? If you can ensure that you don’t mix up GET, POST and other request methods as described above, a good start would be to protect all POST requests by default.

You don’t have to protect PUT and DELETE requests, because as explained above, a standard HTML form cannot be submitted by a browser using those methods.

JavaScript on the other hand can indeed make other types of requests, e.g. using jQuery’s $.ajax() function, but remember, for AJAX requests to work the domains must match (as long as you don’t explicitly configure your web server otherwise).

This means, often you do not even have to add a CSRF token to AJAX requests, even if they are POST requests, but you will have to make sure that you only bypass the CSRF check in your web application if the POST request is actually an AJAX request. You can do that by looking for the presence of a header like X-Requested-With, which AJAX requests usually include. You could also set another custom header and check for its presence on the server side. That’s safe, because a browser would not add custom headers to a regular HTML form submission (see above), so no chance for Mr Bad Guy to simulate this behaviour with a form.

If you’re in doubt about AJAX requests, because for some reason you cannot check for a header like X-Requested-With, simply pass the generated CSRF token to your JavaScript and add the token to the AJAX request. There are several ways of doing this; either add it to the payload just like a regular HTML form would, or add a custom header to the AJAX request. As long as your server knows where to look for it in an incoming request and is able to compare it to the original value it remembers from the session or cookie, you’re sorted.

UnsatisfiedDependencyException: Error creating bean with name

If you describe a field as criteria in method definition ("findBy"), You must pass that parameter to the method, otherwise you will get "Unsatisfied dependency expressed through method parameter" exception.

public interface ClientRepository extends JpaRepository<Client, Integer> {
       Client findByClientId();                ////WRONG !!!!
       Client findByClientId(int clientId);    /// CORRECT 
}

*I assume that your Client entity has clientId attribute.

Cannot find "Package Explorer" view in Eclipse

Try Window > Open Perspective > Java Browsing or some other Java perspectives

Iterate over each line in a string in PHP

preg_split the variable containing the text, and iterate over the returned array:

foreach(preg_split("/((\r?\n)|(\r\n?))/", $subject) as $line){
    // do stuff with $line
} 

Why does pycharm propose to change method to static

PyCharm "thinks" that you might have wanted to have a static method, but you forgot to declare it to be static (using the @staticmethod decorator).

PyCharm proposes this because the method does not use self in its body and hence does not actually change the class instance. Hence the method could be static, i.e. callable without passing a class instance or without even having created a class instance.

Formatting floats without trailing zeros

OP would like to remove superflouous zeros and make the resulting string as short as possible.

I find the %g exponential formatting shortens the resulting string for very large and very small values. The problem comes for values that don't need exponential notation, like 128.0, which is neither very large or very small.

Here is one way to format numbers as short strings that uses %g exponential notation only when Decimal.normalize creates strings that are too long. This might not be the fastest solution (since it does use Decimal.normalize)

def floatToString (inputValue, precision = 3):
    rc = str(Decimal(inputValue).normalize())
    if 'E' in rc or len(rc) > 5:
        rc = '{0:.{1}g}'.format(inputValue, precision)        
    return rc

inputs = [128.0, 32768.0, 65536, 65536 * 2, 31.5, 1.000, 10.0]

outputs = [floatToString(i) for i in inputs]

print(outputs)

# ['128', '32768', '65536', '1.31e+05', '31.5', '1', '10']

Target class controller does not exist - Laravel 8

Happened to me when I passing null to the middleware function

Route::middleware(null)->group(function () {
    Route::get('/some-path', [SomeController::class, 'search']);
});

Passing [] for no middleware works or probably just remove the middleware call if not using middleware :D

Carriage Return\Line feed in Java

bw.newLine(); cannot ensure compatibility with all systems.

If you are sure it is going to be opened in windows, you can format it to windows newline.

If you are already using native unix commands, try unix2dos and convert teh already generated file to windows format and then send the mail.

If you are not using unix commands and prefer to do it in java, use ``bw.write("\r\n")` and if it does not complicate your program, have a method that finds out the operating system and writes the appropriate newline.

Explicit Return Type of Lambda

The return type of a lambda (in C++11) can be deduced, but only when there is exactly one statement, and that statement is a return statement that returns an expression (an initializer list is not an expression, for example). If you have a multi-statement lambda, then the return type is assumed to be void.

Therefore, you should do this:

  remove_if(rawLines.begin(), rawLines.end(), [&expression, &start, &end, &what, &flags](const string& line) -> bool
  {
    start = line.begin();
    end = line.end();
    bool temp = boost::regex_search(start, end, what, expression, flags);
    return temp;
  })

But really, your second expression is a lot more readable.

iOS: Compare two dates

I don't know exactly if you have asked this but if you only want to compare the date component of a NSDate you have to use NSCalendar and NSDateComponents to remove the time component.

Something like this should work as a category for NSDate:

- (NSComparisonResult)compareDateOnly:(NSDate *)otherDate {
    NSUInteger dateFlags = NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit;
    NSCalendar *gregorianCalendar = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
    NSDateComponents *selfComponents = [gregorianCalendar components:dateFlags fromDate:self];
    NSDate *selfDateOnly = [gregorianCalendar dateFromComponents:selfComponents];

    NSDateComponents *otherCompents = [gregorianCalendar components:dateFlags fromDate:otherDate];
    NSDate *otherDateOnly = [gregorianCalendar dateFromComponents:otherCompents];
    return [selfDateOnly compare:otherDateOnly];
}

How do I create a file and write to it?

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class FileWriterExample {
    public static void main(String [] args) {
        FileWriter fw= null;
        File file =null;
        try {
            file=new File("WriteFile.txt");
            if(!file.exists()) {
                file.createNewFile();
            }
            fw = new FileWriter(file);
            fw.write("This is an string written to a file");
            fw.flush();
            fw.close();
            System.out.println("File written Succesfully");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Tracing XML request/responses with JAX-WS

Inject SOAPHandler to endpoint interface. we can trace the SOAP request and response

Implementing SOAPHandler with Programmatic

ServerImplService service = new ServerImplService();
Server port = imgService.getServerImplPort();
/**********for tracing xml inbound and outbound******************************/
Binding binding = ((BindingProvider)port).getBinding();
List<Handler> handlerChain = binding.getHandlerChain();
handlerChain.add(new SOAPLoggingHandler());
binding.setHandlerChain(handlerChain);

Declarative by adding @HandlerChain(file = "handlers.xml") annotation to your endpoint interface.

handlers.xml

<?xml version="1.0" encoding="UTF-8"?>
<handler-chains xmlns="http://java.sun.com/xml/ns/javaee">
    <handler-chain>
        <handler>
            <handler-class>SOAPLoggingHandler</handler-class>
        </handler>
    </handler-chain>
</handler-chains>

SOAPLoggingHandler.java

/*
 * This simple SOAPHandler will output the contents of incoming
 * and outgoing messages.
 */


public class SOAPLoggingHandler implements SOAPHandler<SOAPMessageContext> {
    public Set<QName> getHeaders() {
        return null;
    }

    public boolean handleMessage(SOAPMessageContext context) {
        Boolean isRequest = (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
        if (isRequest) {
            System.out.println("is Request");
        } else {
            System.out.println("is Response");
        }
        SOAPMessage message = context.getMessage();
        try {
            SOAPEnvelope envelope = message.getSOAPPart().getEnvelope();
            SOAPHeader header = envelope.getHeader();
            message.writeTo(System.out);
        } catch (SOAPException | IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return true;
    }

    public boolean handleFault(SOAPMessageContext smc) {
        return true;
    }

    // nothing to clean up
    public void close(MessageContext messageContext) {
    }

}

How to save a Python interactive session?

IPython is extremely useful if you like using interactive sessions. For example for your use-case there is the %save magic command, you just input %save my_useful_session 10-20 23 to save input lines 10 to 20 and 23 to my_useful_session.py (to help with this, every line is prefixed by its number).

Furthermore, the documentation states:

This function uses the same syntax as %history for input ranges, then saves the lines to the filename you specify.

This allows for example, to reference older sessions, such as

%save current_session ~0/
%save previous_session ~1/

Look at the videos on the presentation page to get a quick overview of the features.

SQL query with avg and group by

As I understand, you want the average value for each id at each pass. The solution is

SELECT id, pass, avg(value) FROM data_r1
GROUP BY id, pass;

Make git automatically remove trailing whitespace before committing

I'd rather leave this task to your favorite editor.

Just set a command to remove trailing spaces when saving.

What are Runtime.getRuntime().totalMemory() and freeMemory()?

To understand it better, run this following program (in jdk1.7.x) :

$ java -Xms1025k -Xmx1025k -XshowSettings:vm  MemoryTest

This will print jvm options and the used, free, total and maximum memory available in jvm.

public class MemoryTest {    
    public static void main(String args[]) {
                System.out.println("Used Memory   :  " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) + " bytes");
                System.out.println("Free Memory   : " + Runtime.getRuntime().freeMemory() + " bytes");
                System.out.println("Total Memory  : " + Runtime.getRuntime().totalMemory() + " bytes");
                System.out.println("Max Memory    : " + Runtime.getRuntime().maxMemory() + " bytes");            
        }
}

Getting list of parameter names inside python function

If you also want the values you can use the inspect module

import inspect

def func(a, b, c):
    frame = inspect.currentframe()
    args, _, _, values = inspect.getargvalues(frame)
    print 'function name "%s"' % inspect.getframeinfo(frame)[2]
    for i in args:
        print "    %s = %s" % (i, values[i])
    return [(i, values[i]) for i in args]

>>> func(1, 2, 3)
function name "func"
    a = 1
    b = 2
    c = 3
[('a', 1), ('b', 2), ('c', 3)]

How to send post request to the below post method using postman rest client

The Interface of Postman is changing acccording to the updates.

So You can get full information about postman can get Here.

https://www.getpostman.com/docs/requests

Update all objects in a collection using LINQ

There is no built-in extension method to do this. Although defining one is fairly straight forward. At the bottom of the post is a method I defined called Iterate. It can be used like so

collection.Iterate(c => { c.PropertyToSet = value;} );

Iterate Source

public static void Iterate<T>(this IEnumerable<T> enumerable, Action<T> callback)
{
    if (enumerable == null)
    {
        throw new ArgumentNullException("enumerable");
    }

    IterateHelper(enumerable, (x, i) => callback(x));
}

public static void Iterate<T>(this IEnumerable<T> enumerable, Action<T,int> callback)
{
    if (enumerable == null)
    {
        throw new ArgumentNullException("enumerable");
    }

    IterateHelper(enumerable, callback);
}

private static void IterateHelper<T>(this IEnumerable<T> enumerable, Action<T,int> callback)
{
    int count = 0;
    foreach (var cur in enumerable)
    {
        callback(cur, count);
        count++;
    }
}

Use jQuery to hide a DIV when the user clicks outside of it

Even sleaker:

$("html").click(function(){ 
    $(".wrapper:visible").hide();
});

MySQL Incorrect datetime value: '0000-00-00 00:00:00'

Make the sql mode non strict

if using laravel go to config->database, the go to mysql settings and make the strict mode false

What is the problem with shadowing names defined in outer scopes?

It looks like it is 100% a pytest code pattern.

See:

pytest fixtures: explicit, modular, scalable

I had the same problem with it, and this is why I found this post ;)

# ./tests/test_twitter1.py
import os
import pytest

from mylib import db
# ...

@pytest.fixture
def twitter():
    twitter_ = db.Twitter()
    twitter_._debug = True
    return twitter_

@pytest.mark.parametrize("query,expected", [
    ("BANCO PROVINCIAL", 8),
    ("name", 6),
    ("castlabs", 42),
])
def test_search(twitter: db.Twitter, query: str, expected: int):

    for query in queries:
        res = twitter.search(query)
        print(res)
        assert res

And it will warn with This inspection detects shadowing names defined in outer scopes.

To fix that, just move your twitter fixture into ./tests/conftest.py

# ./tests/conftest.py
import pytest

from syntropy import db


@pytest.fixture
def twitter():
    twitter_ = db.Twitter()
    twitter_._debug = True
    return twitter_

And remove the twitter fixture, like in ./tests/test_twitter2.py:

# ./tests/test_twitter2.py
import os
import pytest

from mylib import db
# ...

@pytest.mark.parametrize("query,expected", [
    ("BANCO PROVINCIAL", 8),
    ("name", 6),
    ("castlabs", 42),
])
def test_search(twitter: db.Twitter, query: str, expected: int):

    for query in queries:
        res = twitter.search(query)
        print(res)
        assert res

This will be make happy for QA, PyCharm and everyone.

Support for the experimental syntax 'classProperties' isn't currently enabled

{
    "presets": [
        "@babel/preset-env",
        "@babel/preset-react"
    ],
    "plugins": [
        [
          "@babel/plugin-proposal-class-properties"
        ]
    ]
}

replace your .babelrc file with above code. it fixed the issue for me.

How can I group data with an Angular filter?

If you need that in js code. You can use injected method of angula-filter lib. Like this.

function controller($scope, $http, groupByFilter) {     

   var groupedData = groupByFilter(originalArray, 'groupPropName');

}

https://github.com/a8m/angular-filter/wiki/Common-Questions#inject-filters

Add an element to an array in Swift

In Swift 4.1 and Xcode 9.4.1

We can add objects to Array basically in Two ways

let stringOne = "One"
let strigTwo = "Two"
let stringThree = "Three"
var array:[String] = []//If your array is string type

Type 1)

//To append elements at the end
array.append(stringOne)
array.append(stringThree)

Type 2)

//To add elements at specific index
array.insert(strigTwo, at: 1)

If you want to add two arrays

var array1 = [1,2,3,4,5]
let array2 = [6,7,8,9]

let array3 = array1+array2
print(array3)
array1.append(contentsOf: array2)
print(array1)

How to write the code for the back button?

You need to tell the browser you are using javascript:

<a href="javascript:history.back(1)">Back</a> 

Also, your input element seems out of place in your code.

Bash scripting missing ']'

You're missing a space after "p1":

if [ -s "p1" ];

Using LINQ to group by multiple properties and sum

Use the .Select() after grouping:

var agencyContracts = _agencyContractsRepository.AgencyContracts
    .GroupBy(ac => new
                   {
                       ac.AgencyContractID, // required by your view model. should be omited
                                            // in most cases because group by primary key
                                            // makes no sense.
                       ac.AgencyID,
                       ac.VendorID,
                       ac.RegionID
                   })
    .Select(ac => new AgencyContractViewModel
                   {
                       AgencyContractID = ac.Key.AgencyContractID,
                       AgencyId = ac.Key.AgencyID,
                       VendorId = ac.Key.VendorID,
                       RegionId = ac.Key.RegionID,
                       Amount = ac.Sum(acs => acs.Amount),
                       Fee = ac.Sum(acs => acs.Fee)
                   });

How can I get (query string) parameters from the URL in Next.js?

Use router-hook.

You can use the useRouter hook in any component in your application.

https://nextjs.org/docs/api-reference/next/router#userouter

pass Param

import Link from "next/link";

<Link href={{ pathname: '/search', query: { keyword: 'this way' } }}><a>path</a></Link>
Or
import Router from 'next/router'

Router.push({
    pathname: '/search',
    query: { keyword: 'this way' },
})

In Component

import { useRouter } from 'next/router'

export default () => {
  const router = useRouter()
  console.log(router.query);

  ...
}

Parse time of format hh:mm:ss

String time = "12:32:22";
String[] values = time.split(":");

This will take your time and split it where it sees a colon and put the value in an array, so you should have 3 values after this.

Then loop through string array and convert each one. (with Integer.parseInt)

Difference between two lists

var third = first.Except(second);

(you can also call ToList() after Except(), if you don't like referencing lazy collections.)

The Except() method compares the values using the default comparer, if the values being compared are of base data types, such as int, string, decimal etc.

Otherwise the comparison will be made by object address, which is probably not what you want... In that case, make your custom objects implement IComparable (or implement a custom IEqualityComparer and pass it to the Except() method).

git clone through ssh

Git 101:

git is a decentralized version control system. You do not necessary need a server to get up and running with git. Still you might want to do that as it looks cool, right? (It's also useful if you want to work on a single project from multiple computers.)

So to get a "server" running you need to run git init --bare <your_project>.git as this will create an empty repository, which you can then import on your machines without having to muck around in config files in your .git dir.

After this you could clone the repo on your clients as it is supposed to work, but I found that some clients (namely git-gui) will fail to clone a repo that is completely empty. To work around this you need to run cd <your_project>.git && touch <some_random_file> && git add <some_random_file> && git commit && git push origin master. (Note that you might need to configure your username and email for that machine's git if you hadn't done so in the past. The actual commands to run will be in the error message you get so I'll just omit them.)

So at this point you can clone the repository to any machine simply by running git clone <user>@<server>:<relative_path><your_project>.git. (As others have pointed out you might need to prefix it with ssh:// if you use the absolute path.) This assumes that you can already log in from your client to the server. (You'll also get bonus points for setting up a config file and keys for ssh, if you intend to push a lot of stuff to the remote server.)

Some relevant links:
This pretty much tells you what you need to know.
And this is for those who know the basic workings of git but sometimes forget the exact syntax.

How to check permissions of a specific directory?

You can also use the stat command if you want detailed information on a file/directory. (I precise this as you say you are learning ^^)

How to name an object within a PowerPoint slide?

Yes. Click on the object (textbox, shape, etc.) to select the object and in the Drawing Tools | Format tab, click on Selection Pane in the Arrange group. From there, you'll see names of objects - you can double click (or press F2) on any name and rename it. By deselecting it, it becomes renamed. You can also get to this from the Home tab -> Drawing group -> Arrange drop-down -> Selection pane or by pressing ALT + F10.

Center a H1 tag inside a DIV

<div id="AlertDiv" style="width:600px;height:400px;border:SOLID 1px;">
    <h1 style="width:100%;height:10%;text-align:center;position:relative;top:40%;">Yes</h1>
</div>

You can try the code here:

http://htmledit.squarefree.com/

Tooltip on image

You can use the standard HTML title attribute of image for this:

<img src="source of image" alt="alternative text" title="this will be displayed as a tooltip"/>

jquery if div id has children

if ( $('#myfav').children().length > 0 ) {
     // do something
}

This should work. The children() function returns a JQuery object that contains the children. So you just need to check the size and see if it has at least one child.

Android Animation Alpha

The "setStartOffset" should be smaller, else animation starts at view alpha 0.xf and waits for start offset before animating to 1f. Hope the following code helps.

AlphaAnimation animation1 = new AlphaAnimation(0.1f, 1f);

animation1.setDuration(1000);
animation1.setStartOffset(50);

animation1.setFillAfter(true);

view.setVisibility(View.VISIBLE);

view.startAnimation(animation1);

socket programming multiple client to one server

This is the echo server handling multiple clients... Runs fine and good using Threads

// echo server
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;


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


    Socket s=null;
    ServerSocket ss2=null;
    System.out.println("Server Listening......");
    try{
        ss2 = new ServerSocket(4445); // can also use static final PORT_NUM , when defined

    }
    catch(IOException e){
    e.printStackTrace();
    System.out.println("Server error");

    }

    while(true){
        try{
            s= ss2.accept();
            System.out.println("connection Established");
            ServerThread st=new ServerThread(s);
            st.start();

        }

    catch(Exception e){
        e.printStackTrace();
        System.out.println("Connection Error");

    }
    }

}

}

class ServerThread extends Thread{  

    String line=null;
    BufferedReader  is = null;
    PrintWriter os=null;
    Socket s=null;

    public ServerThread(Socket s){
        this.s=s;
    }

    public void run() {
    try{
        is= new BufferedReader(new InputStreamReader(s.getInputStream()));
        os=new PrintWriter(s.getOutputStream());

    }catch(IOException e){
        System.out.println("IO error in server thread");
    }

    try {
        line=is.readLine();
        while(line.compareTo("QUIT")!=0){

            os.println(line);
            os.flush();
            System.out.println("Response to Client  :  "+line);
            line=is.readLine();
        }   
    } catch (IOException e) {

        line=this.getName(); //reused String line for getting thread name
        System.out.println("IO Error/ Client "+line+" terminated abruptly");
    }
    catch(NullPointerException e){
        line=this.getName(); //reused String line for getting thread name
        System.out.println("Client "+line+" Closed");
    }

    finally{    
    try{
        System.out.println("Connection Closing..");
        if (is!=null){
            is.close(); 
            System.out.println(" Socket Input Stream Closed");
        }

        if(os!=null){
            os.close();
            System.out.println("Socket Out Closed");
        }
        if (s!=null){
        s.close();
        System.out.println("Socket Closed");
        }

        }
    catch(IOException ie){
        System.out.println("Socket Close Error");
    }
    }//end finally
    }
}

Also here is the code for the client.. Just execute this code for as many times as you want to create multiple client..

// A simple Client Server Protocol .. Client for Echo Server

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;

public class NetworkClient {

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


    InetAddress address=InetAddress.getLocalHost();
    Socket s1=null;
    String line=null;
    BufferedReader br=null;
    BufferedReader is=null;
    PrintWriter os=null;

    try {
        s1=new Socket(address, 4445); // You can use static final constant PORT_NUM
        br= new BufferedReader(new InputStreamReader(System.in));
        is=new BufferedReader(new InputStreamReader(s1.getInputStream()));
        os= new PrintWriter(s1.getOutputStream());
    }
    catch (IOException e){
        e.printStackTrace();
        System.err.print("IO Exception");
    }

    System.out.println("Client Address : "+address);
    System.out.println("Enter Data to echo Server ( Enter QUIT to end):");

    String response=null;
    try{
        line=br.readLine(); 
        while(line.compareTo("QUIT")!=0){
                os.println(line);
                os.flush();
                response=is.readLine();
                System.out.println("Server Response : "+response);
                line=br.readLine();

            }



    }
    catch(IOException e){
        e.printStackTrace();
    System.out.println("Socket read Error");
    }
    finally{

        is.close();os.close();br.close();s1.close();
                System.out.println("Connection Closed");

    }

}
}

How to get a particular date format ('dd-MMM-yyyy') in SELECT query SQL Server 2008 R2

I Think this is the best way to do it.

REPLACE(CONVERT(NVARCHAR,CAST(WeekEnding AS DATETIME), 106), ' ', '-')

Because you do not have to use varchar(11) or varchar(10) that can make problem in future.

How do I get a background location update every n minutes in my iOS application?

Here is what I use:

import Foundation
import CoreLocation
import UIKit

class BackgroundLocationManager :NSObject, CLLocationManagerDelegate {

    static let instance = BackgroundLocationManager()
    static let BACKGROUND_TIMER = 150.0 // restart location manager every 150 seconds
    static let UPDATE_SERVER_INTERVAL = 60 * 60 // 1 hour - once every 1 hour send location to server

    let locationManager = CLLocationManager()
    var timer:NSTimer?
    var currentBgTaskId : UIBackgroundTaskIdentifier?
    var lastLocationDate : NSDate = NSDate()

    private override init(){
        super.init()
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyKilometer
        locationManager.activityType = .Other;
        locationManager.distanceFilter = kCLDistanceFilterNone;
        if #available(iOS 9, *){
            locationManager.allowsBackgroundLocationUpdates = true
        }

        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.applicationEnterBackground), name: UIApplicationDidEnterBackgroundNotification, object: nil)
    }

    func applicationEnterBackground(){
        FileLogger.log("applicationEnterBackground")
        start()
    }

    func start(){
        if(CLLocationManager.authorizationStatus() == CLAuthorizationStatus.AuthorizedAlways){
            if #available(iOS 9, *){
                locationManager.requestLocation()
            } else {
                locationManager.startUpdatingLocation()
            }
        } else {
                locationManager.requestAlwaysAuthorization()
        }
    }
    func restart (){
        timer?.invalidate()
        timer = nil
        start()
    }

    func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
        switch status {
        case CLAuthorizationStatus.Restricted:
            //log("Restricted Access to location")
        case CLAuthorizationStatus.Denied:
            //log("User denied access to location")
        case CLAuthorizationStatus.NotDetermined:
            //log("Status not determined")
        default:
            //log("startUpdatintLocation")
            if #available(iOS 9, *){
                locationManager.requestLocation()
            } else {
                locationManager.startUpdatingLocation()
            }
        }
    }
    func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

        if(timer==nil){
            // The locations array is sorted in chronologically ascending order, so the
            // last element is the most recent
            guard let location = locations.last else {return}

            beginNewBackgroundTask()
            locationManager.stopUpdatingLocation()
            let now = NSDate()
            if(isItTime(now)){
                //TODO: Every n minutes do whatever you want with the new location. Like for example sendLocationToServer(location, now:now)
            }
        }
    }

    func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
        CrashReporter.recordError(error)

        beginNewBackgroundTask()
        locationManager.stopUpdatingLocation()
    }

    func isItTime(now:NSDate) -> Bool {
        let timePast = now.timeIntervalSinceDate(lastLocationDate)
        let intervalExceeded = Int(timePast) > BackgroundLocationManager.UPDATE_SERVER_INTERVAL
        return intervalExceeded;
    }

    func sendLocationToServer(location:CLLocation, now:NSDate){
        //TODO
    }

    func beginNewBackgroundTask(){
        var previousTaskId = currentBgTaskId;
        currentBgTaskId = UIApplication.sharedApplication().beginBackgroundTaskWithExpirationHandler({
            FileLogger.log("task expired: ")
        })
        if let taskId = previousTaskId{
            UIApplication.sharedApplication().endBackgroundTask(taskId)
            previousTaskId = UIBackgroundTaskInvalid
        }

        timer = NSTimer.scheduledTimerWithTimeInterval(BackgroundLocationManager.BACKGROUND_TIMER, target: self, selector: #selector(self.restart),userInfo: nil, repeats: false)
    }
}

I start the tracking in AppDelegate like that:

BackgroundLocationManager.instance.start()

How to tune Tomcat 5.5 JVM Memory settings without using the configuration program

If you'd start Tomcat manually (not as service), then the CATALINA_OPTS environment variable is the way to go. If you'd start it as a service, then the settings are probably stored somewhere in the registry. I have Tomcat 6 installed in my machine and I found the settings at the HKLM\SOFTWARE\Apache Software Foundation\Procrun 2.0\Tomcat6\Parameters\Java key.

Installing tensorflow with anaconda in windows

This is what I did for Installing Anaconda Python 3.6 version and Tensorflow on Window 10 64bit.And It was success!

  1. Go to https://www.continuum.io/downloads to download Anaconda Python 3.6 version for Window 64bit.

  2. Create a conda environment named tensorflow by invoking the following command:

    C:> conda create -n tensorflow

  3. Activate the conda environment by issuing the following command:

    C:> activate tensorflow (tensorflow)C:> # Your prompt should change

  4. Go to http://www.lfd.uci.edu/~gohlke/pythonlibs/enter code here download “tensorflow-1.0.1-cp36-cp36m-win_amd64.whl”. (For my case, the file will be located in “C:\Users\Joshua\Downloads” once after downloaded)

  5. Install the Tensorflow by using the following command:

    (tensorflow)C:>pip install C:\Users\Joshua\Downloads\ tensorflow-1.0.1-cp36-cp36m-win_amd64.whl

This is what I got after the installing: enter image description here

  1. Validate installation by entering following command in your Python environment:

    import tensorflow as tf hello = tf.constant('Hello, TensorFlow!') sess = tf.Session() print(sess.run(hello))

If the output you got is 'Hello, TensorFlow!',that means you have successfully install your Tensorflow.

milliseconds to time in javascript

Simplest Way

let getTime = (Time)=>{
    let Hours = Time.getHours();
    let Min = Time.getMinutes();
    let Sec = Time.getSeconds();

    return `Current time ${Hours} : ${Min} : ${Sec}`;
}

console.log(getTime(new Date()));

How do I install Python packages on Windows?

Upgrade the pip via command prompt ( Python Directory )

D:\Python 3.7.2>python -m pip install --upgrade pip

Now you can install the required Module

D:\Python 3.7.2>python -m pip install <<yourModuleName>>

How to redirect on another page and pass parameter in url from table?

Set the user name as data-username attribute to the button and also a class:

HTML

<input type="button" name="theButton" value="Detail" class="btn" data-username="{{result['username']}}" />

JS

$(document).on('click', '.btn', function() {

    var name = $(this).data('username');        
    if (name != undefined && name != null) {
        window.location = '/player_detail?username=' + name;
    }
});?

EDIT:

Also, you can simply check for undefined && null using:

$(document).on('click', '.btn', function() {

    var name = $(this).data('username');        
    if (name) {
        window.location = '/player_detail?username=' + name;
    }
});?

As, mentioned in this answer

if (name) {            
}

will evaluate to true if value is not:

  • null
  • undefined
  • NaN
  • empty string ("")
  • 0
  • false

The above list represents all possible falsy values in ECMA/Javascript.

How to stop docker under Linux

if you have no systemctl and started the docker daemon by:

sudo service docker start

you can stop it by:

sudo service docker stop

How to find a value in an excel column by vba code Cells.Find

Just for sake of completeness, you can also use the same technique above with excel tables.

In the example below, I'm looking of a text in any cell of a Excel Table named "tblConfig", place in the sheet named Config that normally is set to be hidden. I'm accepting the defaults of the Find method.

Dim list As ListObject
Dim config As Worksheet
Dim cell as Range


Set config = Sheets("Config")
Set list = config.ListObjects("tblConfig")

'search in any cell of the data range of excel table
Set cell = list.DataBodyRange.Find(searchTerm)

If cell Is Nothing Then
    'when information is not found
Else
    'when information is found
End If

Real time face detection OpenCV, Python

Your line:

img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) 

will draw a rectangle in the image, but the return value will be None, so img changes to None and cannot be drawn.

Try

cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) 

nginx error connect to php5-fpm.sock failed (13: Permission denied)

Simple but works..

listen.owner = nginx
listen.group = nginx

chown nginx:nginx /var/run/php-fpm/php-fpm.sock

How can I remove space (margin) above HTML header?

Try:

h1 {
    margin-top: 0;
}

You're seeing the effects of margin collapsing.

Android : difference between invisible and gone?

From Documentation you can say that

View.GONE This view is invisible, and it doesn't take any space for layout purposes.

View.INVISIBLE This view is invisible, but it still takes up space for layout purposes.


Lets clear the idea with some pictures.

Assume that you have three buttons, like below

enter image description here

Now if you set visibility of Button Two as invisible (View.INVISIBLE), then output will be

enter image description here

And when you set visibility of Button Two as gone (View.GONE) then output will be

enter image description here

Hope this will clear your doubts.

Make a link use POST instead of GET

As mentioned in many posts, this is not directly possible, but an easy and successful way is as follows: First, we put a form in the body of our html page, which does not have any buttons for the submit, and also its inputs are hidden. Then we use a javascript function to get the data and ,send the form. One of the advantages of this method is to redirect to other pages, which depends on the server-side code. The code is as follows: and now in anywhere you need an to be in "POST" method:

<script type="text/javascript" language="javascript">
function post_link(data){

    $('#post_form').find('#form_input').val(data);
    $('#post_form').submit();
};
</script>

   <form id="post_form" action="anywhere/you/want/" method="POST">
 {% csrf_token %}
    <input id="form_input" type="hidden" value="" name="form_input">
</form>

<a href="javascript:{}" onclick="javascript:post_link('data');">post link is ready</a>

Read input stream twice

You can wrap input stream with PushbackInputStream. PushbackInputStream allows to unread ("write back") bytes which were already read, so you can do like this:

public class StreamTest {
  public static void main(String[] args) throws IOException {
    byte[] bytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

    InputStream originalStream = new ByteArrayInputStream(bytes);

    byte[] readBytes = getBytes(originalStream, 3);
    printBytes(readBytes); // prints: 1 2 3

    readBytes = getBytes(originalStream, 3);
    printBytes(readBytes); // prints: 4 5 6

    // now let's wrap it with PushBackInputStream

    originalStream = new ByteArrayInputStream(bytes);

    InputStream wrappedStream = new PushbackInputStream(originalStream, 10); // 10 means that maximnum 10 characters can be "written back" to the stream

    readBytes = getBytes(wrappedStream, 3);
    printBytes(readBytes); // prints 1 2 3

    ((PushbackInputStream) wrappedStream).unread(readBytes, 0, readBytes.length);

    readBytes = getBytes(wrappedStream, 3);
    printBytes(readBytes); // prints 1 2 3


  }

  private static byte[] getBytes(InputStream is, int howManyBytes) throws IOException {
    System.out.print("Reading stream: ");

    byte[] buf = new byte[howManyBytes];

    int next = 0;
    for (int i = 0; i < howManyBytes; i++) {
      next = is.read();
      if (next > 0) {
        buf[i] = (byte) next;
      }
    }
    return buf;
  }

  private static void printBytes(byte[] buffer) throws IOException {
    System.out.print("Reading stream: ");

    for (int i = 0; i < buffer.length; i++) {
      System.out.print(buffer[i] + " ");
    }
    System.out.println();
  }


}

Please note that PushbackInputStream stores internal buffer of bytes so it really creates a buffer in memory which holds bytes "written back".

Knowing this approach we can go further and combine it with FilterInputStream. FilterInputStream stores original input stream as a delegate. This allows to create new class definition which allows to "unread" original data automatically. The definition of this class is following:

public class TryReadInputStream extends FilterInputStream {
  private final int maxPushbackBufferSize;

  /**
  * Creates a <code>FilterInputStream</code>
  * by assigning the  argument <code>in</code>
  * to the field <code>this.in</code> so as
  * to remember it for later use.
  *
  * @param in the underlying input stream, or <code>null</code> if
  *           this instance is to be created without an underlying stream.
  */
  public TryReadInputStream(InputStream in, int maxPushbackBufferSize) {
    super(new PushbackInputStream(in, maxPushbackBufferSize));
    this.maxPushbackBufferSize = maxPushbackBufferSize;
  }

  /**
   * Reads from input stream the <code>length</code> of bytes to given buffer. The read bytes are still avilable
   * in the stream
   *
   * @param buffer the destination buffer to which read the data
   * @param offset  the start offset in the destination <code>buffer</code>
   * @aram length how many bytes to read from the stream to buff. Length needs to be less than
   *        <code>maxPushbackBufferSize</code> or IOException will be thrown
   *
   * @return number of bytes read
   * @throws java.io.IOException in case length is
   */
  public int tryRead(byte[] buffer, int offset, int length) throws IOException {
    validateMaxLength(length);

    // NOTE: below reading byte by byte instead of "int bytesRead = is.read(firstBytes, 0, maxBytesOfResponseToLog);"
    // because read() guarantees to read a byte

    int bytesRead = 0;

    int nextByte = 0;

    for (int i = 0; (i < length) && (nextByte >= 0); i++) {
      nextByte = read();
      if (nextByte >= 0) {
        buffer[offset + bytesRead++] = (byte) nextByte;
      }
    }

    if (bytesRead > 0) {
      ((PushbackInputStream) in).unread(buffer, offset, bytesRead);
    }

    return bytesRead;

  }

  public byte[] tryRead(int maxBytesToRead) throws IOException {
    validateMaxLength(maxBytesToRead);

    ByteArrayOutputStream baos = new ByteArrayOutputStream(); // as ByteArrayOutputStream to dynamically allocate internal bytes array instead of allocating possibly large buffer (if maxBytesToRead is large)

    // NOTE: below reading byte by byte instead of "int bytesRead = is.read(firstBytes, 0, maxBytesOfResponseToLog);"
    // because read() guarantees to read a byte

    int nextByte = 0;

    for (int i = 0; (i < maxBytesToRead) && (nextByte >= 0); i++) {
      nextByte = read();
      if (nextByte >= 0) {
        baos.write((byte) nextByte);
      }
    }

    byte[] buffer = baos.toByteArray();

    if (buffer.length > 0) {
      ((PushbackInputStream) in).unread(buffer, 0, buffer.length);
    }

    return buffer;

  }

  private void validateMaxLength(int length) throws IOException {
    if (length > maxPushbackBufferSize) {
      throw new IOException(
        "Trying to read more bytes than maxBytesToRead. Max bytes: " + maxPushbackBufferSize + ". Trying to read: " +
        length);
    }
  }

}

This class has two methods. One for reading into existing buffer (defintion is analogous to calling public int read(byte b[], int off, int len) of InputStream class). Second which returns new buffer (this may be more effective if the size of buffer to read is unknown).

Now let's see our class in action:

public class StreamTest2 {
  public static void main(String[] args) throws IOException {
    byte[] bytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

    InputStream originalStream = new ByteArrayInputStream(bytes);

    byte[] readBytes = getBytes(originalStream, 3);
    printBytes(readBytes); // prints: 1 2 3

    readBytes = getBytes(originalStream, 3);
    printBytes(readBytes); // prints: 4 5 6

    // now let's use our TryReadInputStream

    originalStream = new ByteArrayInputStream(bytes);

    InputStream wrappedStream = new TryReadInputStream(originalStream, 10);

    readBytes = ((TryReadInputStream) wrappedStream).tryRead(3); // NOTE: no manual call to "unread"(!) because TryReadInputStream handles this internally
    printBytes(readBytes); // prints 1 2 3

    readBytes = ((TryReadInputStream) wrappedStream).tryRead(3); 
    printBytes(readBytes); // prints 1 2 3

    readBytes = ((TryReadInputStream) wrappedStream).tryRead(3);
    printBytes(readBytes); // prints 1 2 3

    // we can also call normal read which will actually read the bytes without "writing them back"
    readBytes = getBytes(wrappedStream, 3);
    printBytes(readBytes); // prints 1 2 3

    readBytes = getBytes(wrappedStream, 3);
    printBytes(readBytes); // prints 4 5 6

    readBytes = ((TryReadInputStream) wrappedStream).tryRead(3); // now we can try read next bytes
    printBytes(readBytes); // prints 7 8 9

    readBytes = ((TryReadInputStream) wrappedStream).tryRead(3); 
    printBytes(readBytes); // prints 7 8 9


  }



}

Set CSS property in Javascript?

For most styles do this:

var obj = document.createElement('select');
obj.style.width= "100px";

For styles that have hyphens in the name do this instead:

var obj = document.createElement('select');
obj.style["-webkit-background-size"] = "100px"

How to access html form input from asp.net code behind

Simplest way IMO is to include an ID and runat server tag on all your elements.

<div id="MYDIV" runat="server" />

Since it sounds like these are dynamically inserted controls, you might appreciate FindControl().

Android Device not recognized by adb

  1. Download and install Moborobo software on your computer.
  2. Connect your device with USB debugging through USB cable.
  3. Now open moborobo and it will connect to your android.
  4. Stay connected, now your device should recognize as adb devices and get listed.

Are nested try/except blocks in Python a good programming practice?

According to the documentation, it is better to handle multiple exceptions through tuples or like this:

import sys

try:
    f = open('myfile.txt')
    s = f.readline()
    i = int(s.strip())
except IOError as e:
    print "I/O error({0}): {1}".format(e.errno, e.strerror)
except ValueError:
    print "Could not convert data to an integer."
except:
    print "Unexpected error: ", sys.exc_info()[0]
    raise

How to break out of while loop in Python?

Walrus operator (assignment expressions added to python 3.8) and while-loop-else-clause can do it more pythonic:

myScore = 0
while ans := input("Roll...").lower() == "r":
    # ... do something
else:
    print("Now I'll see if I can break your score...")

how do you insert null values into sql server

If you're using SSMS (or old school Enterprise Manager) to edit the table directly, press CTRL+0 to add a null.

take(1) vs first()

Tip: Only use first() if:

  • You consider zero items emitted to be an error condition (eg. completing before emitting) AND if there’s a greater than 0% chance of error you handling it gracefully
  • OR You know 100% that the source observable will emit 1+ items (so can never throw).

If there are zero emissions and you are not explicitly handling it (with catchError) then that error will get propagated up, possibly cause an unexpected problem somewhere else and can be quite tricky to track down - especially if it's coming from an end user.

You're safer off using take(1) for the most part provided that:

  • You're OK with take(1) not emitting anything if the source completes without an emission.
  • You don't need to use an inline predicate (eg. first(x => x > 10) )

Note: You can use a predicate with take(1) like this: .pipe( filter(x => x > 10), take(1) ). There is no error with this if nothing is ever greater than 10.

What about single()

If you want to be even stricter, and disallow two emissions you can use single() which errors if there are zero or 2+ emissions. Again you'd need to handle errors in that case.

Tip: Single can occasionally be useful if you want to ensure your observable chain isn't doing extra work like calling an http service twice and emitting two observables. Adding single to the end of the pipe will let you know if you made such a mistake. I'm using it in a 'task runner' where you pass in a task observable that should only emit one value, so I pass the response through single(), catchError() to guarantee good behavior.


Why not always use first() instead of take(1) ?

aka. How can first potentially cause more errors?

If you have an observable that takes something from a service and then pipes it through first() you should be fine most of the time. But if someone comes along to disable the service for whatever reason - and changes it to emit of(null) or NEVER then any downstream first() operators would start throwing errors.

Now I realize that might be exactly what you want - hence why this is just a tip. The operator first appealed to me because it sounded slightly less 'clumsy' than take(1) but you need to be careful about handling errors if there's ever a chance of the source not emitting. Will entirely depend on what you're doing though.


If you have a default value (constant):

Consider also .pipe(defaultIfEmpty(42), first()) if you have a default value that should be used if nothing is emitted. This would of course not raise an error because first would always receive a value.

Note that defaultIfEmpty is only triggered if the stream is empty, not if the value of what is emitted is null.

System.Data.OracleClient requires Oracle client software version 8.1.7

Why not use this: dotConnect for Oracle (formerly known as OraDirect .NET)?

It can be configured to not require an Oracle Client at all.

We have been using this in both Windows Services and ASP.NET Web Services and it works like a charm.

How can I format the output of a bash command in neat columns

Since AIX doesn't have a "column" command, I created the simplistic script below. It would be even shorter without the doc & input edits... :)

#!/usr/bin/perl
#       column.pl: convert STDIN to multiple columns on STDOUT
#       Usage: column.pl column-width number-of-columns  file...
#
$width = shift;
($width ne '') or die "must give column-width and number-of-columns\n";
$columns = shift;
($columns ne '') or die "must give number-of-columns\n";
($x = $width) =~ s/[^0-9]//g;
($x eq $width) or die "invalid column-width: $width\n";
($x = $columns) =~ s/[^0-9]//g;
($x eq $columns) or die "invalid number-of-columns: $columns\n";

$w = $width * -1; $c = $columns;
while (<>) {
        chomp;
        if ( $c-- > 1 ) {
                printf "%${w}s", $_;
                next;
        }
        $c = $columns;
        printf "%${w}s\n", $_;
}
print "\n";

Remove a data connection from an Excel 2010 spreadsheet in compatibility mode

I had the same problem. Get the warning. Went to Data connections and deleted connection. Save, close reopen. Still get the warning. I use a xp/vista menu plugin for classic menus. I found under data, get external data, properties, uncheck the save query definition. Save close and reopen. That seemed to get rid of the warning. Just removing the connection does not work. You have to get rid of the query.

Use jQuery to change an HTML tag?

Here's an extension that will do it all, on as many elements in as many ways...

Example usage:

keep existing class and attributes:

$('div#change').replaceTag('<span>', true);

or

Discard existing class and attributes:

$('div#change').replaceTag('<span class=newclass>', false);

or even

replace all divs with spans, copy classes and attributes, add extra class name

$('div').replaceTag($('<span>').addClass('wasDiv'), true);

Plugin Source:

$.extend({
    replaceTag: function (currentElem, newTagObj, keepProps) {
        var $currentElem = $(currentElem);
        var i, $newTag = $(newTagObj).clone();
        if (keepProps) {//{{{
            newTag = $newTag[0];
            newTag.className = currentElem.className;
            $.extend(newTag.classList, currentElem.classList);
            $.extend(newTag.attributes, currentElem.attributes);
        }//}}}
        $currentElem.wrapAll($newTag);
        $currentElem.contents().unwrap();
        // return node; (Error spotted by Frank van Luijn)
        return this; // Suggested by ColeLawrence
    }
});

$.fn.extend({
    replaceTag: function (newTagObj, keepProps) {
        // "return" suggested by ColeLawrence
        return this.each(function() {
            jQuery.replaceTag(this, newTagObj, keepProps);
        });
    }
});

len() of a numpy array in python

You can transpose the array if you want to get the length of the other dimension.

len(np.array([[2,3,1,0], [2,3,1,0], [3,2,1,1]]).T)

How does strtok() split the string into tokens in C?

The first time you call it, you provide the string to tokenize to strtok. And then, to get the following tokens, you just give NULL to that function, as long as it returns a non NULL pointer.

The strtok function records the string you first provided when you call it. (Which is really dangerous for multi-thread applications)

Change a Django form field to a hidden field

For normal form you can do

class MyModelForm(forms.ModelForm):
    slug = forms.CharField(widget=forms.HiddenInput())

If you have model form you can do the following

class MyModelForm(forms.ModelForm):
    class Meta:
        model = TagStatus
        fields = ('slug', 'ext')
        widgets = {'slug': forms.HiddenInput()}

You can also override __init__ method

class Myform(forms.Form):
    def __init__(self, *args, **kwargs):
        super(Myform, self).__init__(*args, **kwargs)
        self.fields['slug'].widget = forms.HiddenInput()

When should iteritems() be used instead of items()?

dict.iteritems was removed because dict.items now does the thing dict.iteritems did in python 2.x and even improved it a bit by making it an itemview.

How to thoroughly purge and reinstall postgresql on ubuntu?

Steps that worked for me on Ubuntu 8.04.2 to remove postgres 8.3

  1. List All Postgres related packages

    dpkg -l | grep postgres
    
    ii  postgresql                            8.3.17-0ubuntu0.8.04.1           object-relational SQL database (latest versi
    ii  postgresql-8.3                        8.3.9-0ubuntu8.04                object-relational SQL database, version 8.3
    ii  postgresql-client                     8.3.9-0ubuntu8.04                front-end programs for PostgreSQL (latest ve
    ii  postgresql-client-8.3                 8.3.9-0ubuntu8.04                front-end programs for PostgreSQL 8.3
    ii  postgresql-client-common              87ubuntu2                        manager for multiple PostgreSQL client versi
    ii  postgresql-common                     87ubuntu2                        PostgreSQL database-cluster manager
    ii  postgresql-contrib                    8.3.9-0ubuntu8.04                additional facilities for PostgreSQL (latest
    ii  postgresql-contrib-8.3                8.3.9-0ubuntu8.04                additional facilities for PostgreSQL
    
  2. Remove all above listed

    sudo apt-get --purge remove postgresql postgresql-8.3  postgresql-client  postgresql-client-8.3 postgresql-client-common postgresql-common  postgresql-contrib postgresql-contrib-8.3
    
  3. Remove the following folders

    sudo rm -rf /var/lib/postgresql/
    sudo rm -rf /var/log/postgresql/
    sudo rm -rf /etc/postgresql/
    

Test if object implements interface

Using the is or as operators is the correct way if you know the interface type at compile time and have an instance of the type you are testing. Something that no one else seems to have mentioned is Type.IsAssignableFrom:

if( typeof(IMyInterface).IsAssignableFrom(someOtherType) )
{
}

I think this is much neater than looking through the array returned by GetInterfaces and has the advantage of working for classes as well.

Open S3 object as a string with Boto3

This isn't in the boto3 documentation. This worked for me:

object.get()["Body"].read()

object being an s3 object: http://boto3.readthedocs.org/en/latest/reference/services/s3.html#object

How can I add numbers in a Bash script?

Use the $(( )) arithmetic expansion.

num=$(( $num + $metab ))

See Chapter 13. Arithmetic Expansion for more information.

Datetime current year and month in Python

Try this solution:

from datetime import datetime

currentSecond= datetime.now().second
currentMinute = datetime.now().minute
currentHour = datetime.now().hour

currentDay = datetime.now().day
currentMonth = datetime.now().month
currentYear = datetime.now().year

How can one grab a stack trace in C?

For Windows check the StackWalk64() API (also on 32bit Windows). For UNIX you should use the OS' native way to do it, or fallback to glibc's backtrace(), if availabe.

Note however that taking a Stacktrace in native code is rarely a good idea - not because it is not possible, but because you're usally trying to achieve the wrong thing.

Most of the time people try to get a stacktrace in, say, an exceptional circumstance, like when an exception is caught, an assert fails or - worst and most wrong of them all - when you get a fatal "exception" or signal like a segmentation violation.

Considering the last issue, most of the APIs will require you to explicitly allocate memory or may do it internally. Doing so in the fragile state in which your program may be currently in, may acutally make things even worse. For example, the crash report (or coredump) will not reflect the actual cause of the problem, but your failed attempt to handle it).

I assume you're trying to achive that fatal-error-handling thing, as most people seem to try that when it comes to getting a stacktrace. If so, I would rely on the debugger (during development) and letting the process coredump in production (or mini-dump on windows). Together with proper symbol-management, you should have no trouble figuring the causing instruction post-mortem.

What is the advantage of using REST instead of non-REST HTTP?

One advantage is that, we can non-sequentially process XML documents and unmarshal XML data from different sources like InputStream object, a URL, a DOM node...

Drawing a line/path on Google Maps

public class MainActivity extends FragmentActivity  {


  List<Overlay> mapOverlays;
  GeoPoint point1, point2;
  LocationManager locManager;
  Drawable drawable;
  Document document;
  GMapV2GetRouteDirection v2GetRouteDirection;
  LatLng fromPosition;
  LatLng toPosition;
  GoogleMap mGoogleMap;
  MarkerOptions markerOptions;
  Location location ;
  @Override
  protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        v2GetRouteDirection = new GMapV2GetRouteDirection();
      SupportMapFragment supportMapFragment = (SupportMapFragment) getSupportFragmentManager()
        .findFragmentById(R.id.map);
        mGoogleMap = supportMapFragment.getMap();

        // Enabling MyLocation in Google Map
        mGoogleMap.setMyLocationEnabled(true);
        mGoogleMap.getUiSettings().setZoomControlsEnabled(true);
        mGoogleMap.getUiSettings().setCompassEnabled(true);
        mGoogleMap.getUiSettings().setMyLocationButtonEnabled(true);
        mGoogleMap.getUiSettings().setAllGesturesEnabled(true);
        mGoogleMap.setTrafficEnabled(true);
        mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(12));
        markerOptions = new MarkerOptions();
        fromPosition = new LatLng(11.663837, 78.147297);
        toPosition = new LatLng(11.723512, 78.466287);
        GetRouteTask getRoute = new GetRouteTask();
        getRoute.execute();
  }
  /**
   *
   * @author VIJAYAKUMAR M
   * This class Get Route on the map
   *
   */
  private class GetRouteTask extends AsyncTask<String, Void, String> {

        private ProgressDialog Dialog;
        String response = "";
        @Override
        protected void onPreExecute() {
              Dialog = new ProgressDialog(MainActivity.this);
              Dialog.setMessage("Loading route...");
              Dialog.show();
        }

        @Override
        protected String doInBackground(String... urls) {
              //Get All Route values
                         document = v2GetRouteDirection.getDocument(fromPosition, toPosition,          GMapV2GetRouteDirection.MODE_DRIVING);
                    response = "Success";
              return response;

        }

        @Override
        protected void onPostExecute(String result) {
              mGoogleMap.clear();
              if(response.equalsIgnoreCase("Success")){
              ArrayList<LatLng> directionPoint = v2GetRouteDirection.getDirection(document);
              PolylineOptions rectLine = new PolylineOptions().width(10).color(
                          Color.RED);

              for (int i = 0; i < directionPoint.size(); i++) {
                    rectLine.add(directionPoint.get(i));
              }
              // Adding route on the map
              mGoogleMap.addPolyline(rectLine);
              markerOptions.position(toPosition);
              markerOptions.draggable(true);
              mGoogleMap.addMarker(markerOptions);

              }

              Dialog.dismiss();
        }
  }
  @Override
  protected void onStop() {
        super.onStop();
        finish();
    }
 }

Route Helper class

 public class GMapV2GetRouteDirection {
  public final static String MODE_DRIVING = "driving";
  public final static String MODE_WALKING = "walking";

  public GMapV2GetRouteDirection() { }

  public Document getDocument(LatLng start, LatLng end, String mode) {
    String url = "http://maps.googleapis.com/maps/api/directions/xml?"
            + "origin=" + start.latitude + "," + start.longitude 
            + "&destination=" + end.latitude + "," + end.longitude
            + "&sensor=false&units=metric&mode=driving";

    try {
        HttpClient httpClient = new DefaultHttpClient();
        HttpContext localContext = new BasicHttpContext();
        HttpPost httpPost = new HttpPost(url);
        HttpResponse response = httpClient.execute(httpPost, localContext);
        InputStream in = response.getEntity().getContent();
        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document doc = builder.parse(in);
        return doc;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
  }

  public String getDurationText (Document doc) {
    NodeList nl1 = doc.getElementsByTagName("duration");
    Node node1 = nl1.item(0);
    NodeList nl2 = node1.getChildNodes();
    Node node2 = nl2.item(getNodeIndex(nl2, "text"));
    Log.i("DurationText", node2.getTextContent());
    return node2.getTextContent();
 }

 public int getDurationValue (Document doc) {
    NodeList nl1 = doc.getElementsByTagName("duration");
    Node node1 = nl1.item(0);
    NodeList nl2 = node1.getChildNodes();
    Node node2 = nl2.item(getNodeIndex(nl2, "value"));
    Log.i("DurationValue", node2.getTextContent());
    return Integer.parseInt(node2.getTextContent());
  }

  public String getDistanceText (Document doc) {
    NodeList nl1 = doc.getElementsByTagName("distance");
    Node node1 = nl1.item(0);
    NodeList nl2 = node1.getChildNodes();
    Node node2 = nl2.item(getNodeIndex(nl2, "text"));
    Log.i("DistanceText", node2.getTextContent());
    return node2.getTextContent();
  }

  public int getDistanceValue (Document doc) {
    NodeList nl1 = doc.getElementsByTagName("distance");
    Node node1 = nl1.item(0);
    NodeList nl2 = node1.getChildNodes();
    Node node2 = nl2.item(getNodeIndex(nl2, "value"));
    Log.i("DistanceValue", node2.getTextContent());
    return Integer.parseInt(node2.getTextContent());
  }

  public String getStartAddress (Document doc) {
    NodeList nl1 = doc.getElementsByTagName("start_address");
    Node node1 = nl1.item(0);
    Log.i("StartAddress", node1.getTextContent());
    return node1.getTextContent();
  }

  public String getEndAddress (Document doc) {
    NodeList nl1 = doc.getElementsByTagName("end_address");
    Node node1 = nl1.item(0);
    Log.i("StartAddress", node1.getTextContent());
    return node1.getTextContent();
  }

  public String getCopyRights (Document doc) {
    NodeList nl1 = doc.getElementsByTagName("copyrights");
    Node node1 = nl1.item(0);
    Log.i("CopyRights", node1.getTextContent());
    return node1.getTextContent();
  }

   public ArrayList<LatLng> getDirection (Document doc) {
    NodeList nl1, nl2, nl3;
    ArrayList<LatLng> listGeopoints = new ArrayList<LatLng>();
    nl1 = doc.getElementsByTagName("step");
    if (nl1.getLength() > 0) {
        for (int i = 0; i < nl1.getLength(); i++) {
            Node node1 = nl1.item(i);
            nl2 = node1.getChildNodes();

            Node locationNode = nl2.item(getNodeIndex(nl2, "start_location"));
            nl3 = locationNode.getChildNodes();
            Node latNode = nl3.item(getNodeIndex(nl3, "lat"));
            double lat = Double.parseDouble(latNode.getTextContent());
            Node lngNode = nl3.item(getNodeIndex(nl3, "lng"));
            double lng = Double.parseDouble(lngNode.getTextContent());
            listGeopoints.add(new LatLng(lat, lng));

            locationNode = nl2.item(getNodeIndex(nl2, "polyline"));
            nl3 = locationNode.getChildNodes();
            latNode = nl3.item(getNodeIndex(nl3, "points"));
            ArrayList<LatLng> arr = decodePoly(latNode.getTextContent());
            for(int j = 0 ; j < arr.size() ; j++) {
                listGeopoints.add(new LatLng(arr.get(j).latitude, arr.get(j).longitude));
            }

            locationNode = nl2.item(getNodeIndex(nl2, "end_location"));
            nl3 = locationNode.getChildNodes();
            latNode = nl3.item(getNodeIndex(nl3, "lat"));
            lat = Double.parseDouble(latNode.getTextContent());
            lngNode = nl3.item(getNodeIndex(nl3, "lng"));
            lng = Double.parseDouble(lngNode.getTextContent());
            listGeopoints.add(new LatLng(lat, lng));
        }
    }

    return listGeopoints;
 }

 private int getNodeIndex(NodeList nl, String nodename) {
    for(int i = 0 ; i < nl.getLength() ; i++) {
        if(nl.item(i).getNodeName().equals(nodename))
            return i;
    }
    return -1;
 }

 private ArrayList<LatLng> decodePoly(String encoded) {
    ArrayList<LatLng> poly = new ArrayList<LatLng>();
    int index = 0, len = encoded.length();
    int lat = 0, lng = 0;
    while (index < len) {
        int b, shift = 0, result = 0;
        do {
            b = encoded.charAt(index++) - 63;
            result |= (b & 0x1f) << shift;
            shift += 5;
        } while (b >= 0x20);
        int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
        lat += dlat;
        shift = 0;
        result = 0;
        do {
            b = encoded.charAt(index++) - 63;
            result |= (b & 0x1f) << shift;
            shift += 5;
        } while (b >= 0x20);
        int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
        lng += dlng;

        LatLng position = new LatLng((double) lat / 1E5, (double) lng / 1E5);
        poly.add(position);
    }
    return poly;
  }
 }

How to display table data more clearly in oracle sqlplus

You can set the line size as per the width of the window and set wrap off using the following command.

set linesize 160;
set wrap off;

I have used 160 as per my preference you can set it to somewhere between 100 - 200 and setting wrap will not your data and it will display the data properly.

Importing text file into excel sheet

There are many ways you can import Text file to the current sheet. Here are three (including the method that you are using above)

  1. Using a QueryTable
  2. Open the text file in memory and then write to the current sheet and finally applying Text To Columns if required.
  3. If you want to use the method that you are currently using then after you open the text file in a new workbook, simply copy it over to the current sheet using Cells.Copy

Using a QueryTable

Here is a simple macro that I recorded. Please amend it to suit your needs.

Sub Sample()
    With ActiveSheet.QueryTables.Add(Connection:= _
        "TEXT;C:\Sample.txt", Destination:=Range("$A$1") _
        )
        .Name = "Sample"
        .FieldNames = True
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .PreserveFormatting = True
        .RefreshOnFileOpen = False
        .RefreshStyle = xlInsertDeleteCells
        .SavePassword = False
        .SaveData = True
        .AdjustColumnWidth = True
        .RefreshPeriod = 0
        .TextFilePromptOnRefresh = False
        .TextFilePlatform = 437
        .TextFileStartRow = 1
        .TextFileParseType = xlDelimited
        .TextFileTextQualifier = xlTextQualifierDoubleQuote
        .TextFileConsecutiveDelimiter = False
        .TextFileTabDelimiter = True
        .TextFileSemicolonDelimiter = False
        .TextFileCommaDelimiter = True
        .TextFileSpaceDelimiter = False
        .TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1)
        .TextFileTrailingMinusNumbers = True
        .Refresh BackgroundQuery:=False
    End With
End Sub

Open the text file in memory

Sub Sample()
    Dim MyData As String, strData() As String

    Open "C:\Sample.txt" For Binary As #1
    MyData = Space$(LOF(1))
    Get #1, , MyData
    Close #1
    strData() = Split(MyData, vbCrLf)
End Sub

Once you have the data in the array you can export it to the current sheet.

Using the method that you are already using

Sub Sample()
    Dim wbI As Workbook, wbO As Workbook
    Dim wsI As Worksheet

    Set wbI = ThisWorkbook
    Set wsI = wbI.Sheets("Sheet1") '<~~ Sheet where you want to import

    Set wbO = Workbooks.Open("C:\Sample.txt")

    wbO.Sheets(1).Cells.Copy wsI.Cells

    wbO.Close SaveChanges:=False
End Sub

FOLLOWUP

You can use the Application.GetOpenFilename to choose the relevant file. For example...

Sub Sample()
    Dim Ret

    Ret = Application.GetOpenFilename("Prn Files (*.prn), *.prn")

    If Ret <> False Then
        With ActiveSheet.QueryTables.Add(Connection:= _
        "TEXT;" & Ret, Destination:=Range("$A$1"))

            '~~> Rest of the code

        End With
    End If
End Sub

List of <p:ajax> events

I've got the list in debug mode; first I saw the point at which the error was thrown

javax.faces.view.facelets.TagException: /showcase/partial_submit.xhtml @26,36 Event:changed is not supported. org.primefaces.component.behavior.ajax.AjaxBehaviorHandler.applyAttachedObject(AjaxBehaviorHandler.java:179) org.primefaces.component.behavior.ajax.AjaxBehaviorHandler.apply(AjaxBehaviorHandler.java:157)

and then I debugged AjaxBehaviorHandler

enter image description here

so if you want discover the right list of supported event, you can generate an error (using an event name that is wrong), and follow this way

Change background color of edittext in android

The color you are using is white "#ffffff" is white so try a different one change in the values if you want until you get your need from this link Color Codes and it should go fine

How do I analyze a .hprof file?

Just get the Eclipse Memory Analyzer. There's nothing better out there and it's free.

JHAT is only usable for "toy applications"

Simulate low network connectivity for Android

There's a simple way of testing low speeds on a real device that seems to have been overlooked. It does require a Mac and an ethernet (or other wired) network connection.

Turn on Wifi sharing on the Mac, turning your computer into a Wifi hotspot, connect your device to this. Use Netlimiter/Charles Proxy or Network Link Conditioner (which you may have already installed) to control the speeds.

For more details and to understand what sort of speeds you should test on check out: http://opensignal.com/blog/2016/02/05/go-slow-how-why-to-test-apps-on-poor-connections/

Rotate image with javascript

No need for jQuery and lot's of CSS anymore (Note that some browsers need extra CSS)

Kind of what @Abinthaha posted, but pure JS, without the need of jQuery.

_x000D_
_x000D_
let rotateAngle = 90;_x000D_
_x000D_
function rotate(image) {_x000D_
  image.setAttribute("style", "transform: rotate(" + rotateAngle + "deg)");_x000D_
  rotateAngle = rotateAngle + 90;_x000D_
}
_x000D_
#rotater {_x000D_
  transition: all 0.3s ease;_x000D_
  border: 0.0625em solid black;_x000D_
  border-radius: 3.75em;_x000D_
}
_x000D_
<img id="rotater" onclick="rotate(this)" src="https://upload.wikimedia.org/wikipedia/en/e/e0/Iron_Man_bleeding_edge.jpg"/>
_x000D_
_x000D_
_x000D_

Overlaying histograms with ggplot2 in R

Using @joran's sample data,

ggplot(dat, aes(x=xx, fill=yy)) + geom_histogram(alpha=0.2, position="identity")

note that the default position of geom_histogram is "stack."

see "position adjustment" of this page:

docs.ggplot2.org/current/geom_histogram.html

Get list from pandas DataFrame column headers

Did some quick tests, and perhaps unsurprisingly the built-in version using dataframe.columns.values.tolist() is the fastest:

In [1]: %timeit [column for column in df]
1000 loops, best of 3: 81.6 µs per loop

In [2]: %timeit df.columns.values.tolist()
10000 loops, best of 3: 16.1 µs per loop

In [3]: %timeit list(df)
10000 loops, best of 3: 44.9 µs per loop

In [4]: % timeit list(df.columns.values)
10000 loops, best of 3: 38.4 µs per loop

(I still really like the list(dataframe) though, so thanks EdChum!)

gdb: "No symbol table is loaded"

First of all, what you have is a fully compiled program, not an object file, so drop the .o extension. Now, pay attention to what the error message says, it tells you exactly how to fix your problem: "No symbol table is loaded. Use the "file" command."

(gdb) exec-file test
(gdb) b 2
No symbol table is loaded.  Use the "file" command.
(gdb) file test
Reading symbols from /home/user/test/test...done.
(gdb) b 2
Breakpoint 1 at 0x80483ea: file test.c, line 2.
(gdb) 

Or just pass the program on the command line.

$ gdb test
GNU gdb (GDB) 7.4
Copyright (C) 2012 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
[...]
Reading symbols from /home/user/test/test...done.
(gdb) b 2
Breakpoint 1 at 0x80483ea: file test.c, line 2.
(gdb) 

What is function overloading and overriding in php?

PHP 5.x.x does not support overloading this is why PHP is not fully OOP.

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

A 'quick-and-dirty' approach is to download the wiki HTML pages using the wget utility, instead of cloning it. For example, this is how I downloaded the Hystrix wiki from GitHub (I'm using Ubuntu Linux):

 $ wget -e robots=off -nH -E -H -k -K -p https://github.com/Netflix/Hystrix/wiki
 $ wget -e robots=off -nH -E -H -k -K -I "Netflix/Hystrix/wiki" -r -l 1 https://github.com/Netflix/Hystrix/wiki

The first call will download the wiki entry page and all its dependencies. The second one will call all sub-pages on it. You can browse now the wiki by opening Netflix/Hystrix/wiki.1.html.

Note that both calls to wget are necessary. If you just run the second one then you will miss some dependencies required to show the pages properly.

Multiple GitHub Accounts & SSH Config

In my case none of the solutions above solved my issue, but ssh-agent does. Basically, I did the following:

  1. Generate key pair using ssh-keygen shown below. It will generate a key pair (in this example .\keyfile and .\keyfile.pub)

    ssh-keygen -t rsa -b 4096 -C "yourname@yourdomain" -f keyfile

  2. Upload keyfile.pub to the git provider

  3. Start ssh-agent on your machine (you can check with ps -ef | grep ssh-agent to see if it is running already)
  4. Run ssh-add .\keyfile to add credentials
  5. Now you can run git clone git@provider:username/project.git

How can I do a case insensitive string comparison?

How about using StringComparison.CurrentCultureIgnoreCase instead?

Check if an excel cell exists on another worksheet in a column - and return the contents of a different column

You can use following formulas.

For Excel 2007 or later:

=IFERROR(VLOOKUP(D3,List!A:C,3,FALSE),"No Match")

For Excel 2003:

=IF(ISERROR(MATCH(D3,List!A:A, 0)), "No Match", VLOOKUP(D3,List!A:C,3,FALSE))

Note, that

  • I'm using List!A:C in VLOOKUP and returns value from column ? 3
  • I'm using 4th argument for VLOOKUP equals to FALSE, in that case VLOOKUP will only find an exact match, and the values in the first column of List!A:C do not need to be sorted (opposite to case when you're using TRUE).

Setting log level of message at runtime in slf4j

It is not possible to specify a log level in sjf4j 1.x out of the box. But there is hope for slf4j 2.0 to fix the issue. In 2.0 it might look like this:

// POTENTIAL 2.0 SOLUTION
import org.slf4j.helpers.Util;
import static org.slf4j.spi.LocationAwareLogger.*;

// does not work with slf4j 1.x
Util.log(logger, DEBUG_INT, "hello world!");

In the meanwhile, for slf4j 1.x, you can use this workaround:

Copy this class into your classpath:

import org.slf4j.Logger;
import java.util.function.Function;

public enum LogLevel {

    TRACE(l -> l::trace, Logger::isTraceEnabled),
    DEBUG(l -> l::debug, Logger::isDebugEnabled),
    INFO(l -> l::info, Logger::isInfoEnabled),
    WARN(l -> l::warn, Logger::isWarnEnabled),
    ERROR(l -> l::error, Logger::isErrorEnabled);

    interface LogMethod {
        void log(String format, Object... arguments);
    }

    private final Function<Logger, LogMethod> logMethod;
    private final Function<Logger, Boolean> isEnabledMethod;

    LogLevel(Function<Logger, LogMethod> logMethod, Function<Logger, Boolean> isEnabledMethod) {
        this.logMethod = logMethod;
        this.isEnabledMethod = isEnabledMethod;
    }

    public LogMethod prepare(Logger logger) {
        return logMethod.apply(logger);
    }

    public boolean isEnabled(Logger logger) {
        return isEnabledMethod.apply(logger);
    }
}

Then you can use it like this:

Logger logger = LoggerFactory.getLogger(Application.class);

LogLevel level = LogLevel.ERROR;
level.prepare(logger).log("It works!"); // just message, without parameter
level.prepare(logger).log("Hello {}!", "world"); // with slf4j's parameter replacing

try {
    throw new RuntimeException("Oops");
} catch (Throwable t) {
    level.prepare(logger).log("Exception", t);
}

if (level.isEnabled(logger)) {
    level.prepare(logger).log("logging is enabled");
}

This will output a log like this:

[main] ERROR Application - It works!
[main] ERROR Application - Hello world!
[main] ERROR Application - Exception
java.lang.RuntimeException: Oops
    at Application.main(Application.java:14)
[main] ERROR Application - logging is enabled

Is it worth it?

  • Pro It keeps the source code location (class names, method names, line numbers will point to your code)
  • Pro You can easily define variables, parameters and return types as LogLevel
  • Pro Your business code stays short and easy to read, and no additional dependencies required.

The source code as minimal example is hosted on GitHub.

How to make bootstrap 3 fluid layout without horizontal scrollbar

Apply to the body seems to get rid of the horizontal scrollbar

overflow-x: hidden;

Embedding DLLs in a compiled executable

I highly recommend to use Costura.Fody - by far the best and easiest way to embed resources in your assembly. It's available as NuGet package.

Install-Package Costura.Fody

After adding it to the project, it will automatically embed all references that are copied to the output directory into your main assembly. You might want to clean the embedded files by adding a target to your project:

Install-CleanReferencesTarget

You'll also be able to specify whether to include the pdb's, exclude certain assemblies, or extracting the assemblies on the fly. As far as I know, also unmanaged assemblies are supported.

Update

Currently, some people are trying to add support for DNX.

Update 2

For the lastest Fody version, you will need to have MSBuild 16 (so Visual Studio 2019). Fody version 4.2.1 will do MSBuild 15. (reference: Fody is only supported on MSBuild 16 and above. Current version: 15)

You are trying to add a non-nullable field 'new_field' to userprofile without a default

One option is to declare a default value for 'new_field':

new_field = models.CharField(max_length=140, default='DEFAULT VALUE')

another option is to declare 'new_field' as a nullable field:

new_field = models.CharField(max_length=140, null=True)

If you decide to accept 'new_field' as a nullable field you may want to accept 'no input' as valid input for 'new_field'. Then you have to add the blank=True statement as well:

new_field = models.CharField(max_length=140, blank=True, null=True)

Even with null=True and/or blank=True you can add a default value if necessary:

new_field = models.CharField(max_length=140, default='DEFAULT VALUE', blank=True, null=True)

Location of ini/config files in linux/unix?

You should adhere your application to the XDG Base Directory Specification. Most answers here are either obsolete or wrong.

Your application should store and load data and configuration files to/from the directories pointed by the following environment variables:

  • $XDG_DATA_HOME (default: "$HOME/.local/share"): user-specific data files.
  • $XDG_CONFIG_HOME (default: "$HOME/.config"): user-specific configuration files.
  • $XDG_DATA_DIRS (default: "/usr/local/share/:/usr/share/"): precedence-ordered set of system data directories.
  • $XDG_CONFIG_DIRS (default: "/etc/xdg"): precedence-ordered set of system configuration directories.
  • $XDG_CACHE_HOME (default: "$HOME/.cache"): user-specific non-essential data files.

You should first determine if the file in question is:

  1. A configuration file ($XDG_CONFIG_HOME:$XDG_CONFIG_DIRS);
  2. A data file ($XDG_DATA_HOME:$XDG_DATA_DIRS); or
  3. A non-essential (cache) file ($XDG_CACHE_HOME).

It is recommended that your application put its files in a subdirectory of the above directories. Usually, something like $XDG_DATA_DIRS/<application>/filename or $XDG_DATA_DIRS/<vendor>/<application>/filename.

When loading, you first try to load the file from the user-specific directories ($XDG_*_HOME) and, if failed, from system directories ($XDG_*_DIRS). When saving, save to user-specific directories only (since the user probably won't have write access to system directories).

For other, more user-oriented directories, refer to the XDG User Directories Specification. It defines directories for the Desktop, downloads, documents, videos, etc.

How to convert DataSet to DataTable

Here is my solution:

DataTable datatable = (DataTable)dataset.datatablename;

Yarn: How to upgrade yarn version using terminal?

yarn policies set-version

Use the above command in powershell to upgrade your current yarn version to Latest.It will download the latest yarn release

Generating CSV file for Excel, how to have a newline inside a value

You could use keyboard shortcut ALT+Enter.

  1. Select the cell you wish to edit
  2. enter edit mode either by double clicking it or pressing F2 3.Press Alt+enter. This will create a new line in cell

How to read existing text files without defining path

As your project is a console project you can pass the path to the text files that you want to read via the string[] args

static void Main(string[] args)
{
}

Within Main you can check if arguments are passed

if (args.Length == 0){ System.Console.WriteLine("Please enter a parameter");}

Extract an argument

string fileToRead = args[0];

Nearly all languages support the concept of argument passing and follow similar patterns to C#.

For more C# specific see http://msdn.microsoft.com/en-us/library/vstudio/cb20e19t.aspx

Setting a divs background image to fit its size?

You can achieve this with the background-size property, which is now supported by most browsers.

To scale the background image to fit inside the div:

background-size: contain;

To scale the background image to cover the whole div:

background-size: cover;

"Could not load type [Namespace].Global" causing me grief

Check the Build Action of Global.asax.cs. It should be set to Compile.

In Solution Explorer, Right-click Global.asax.cs and go to Properties. In the Properties pane, set the Build Action (while not debugging).

It seems that VS 2008 does not always add the .asax(.cs) files correctly by default.

CSS Margin: 0 is not setting to 0

It seems that nobody actually read your question and looked at your source code. Here's the answer you all have been waiting for:

#header_content p {
    margin-top: 0;
}

jsFiddle

How to uncheck checked radio button

Radio buttons are meant to be required options... If you want them to be unchecked, use a checkbox, there is no need to complicate things and allow users to uncheck a radio button; removing the JQuery allows you to select from one of them

Change default timeout for mocha

By default Mocha will read a file named test/mocha.opts that can contain command line arguments. So you could create such a file that contains:

--timeout 5000

Whenever you run Mocha at the command line, it will read this file and set a timeout of 5 seconds by default.

Another way which may be better depending on your situation is to set it like this in a top level describe call in your test file:

describe("something", function () {
    this.timeout(5000); 

    // tests...
});

This would allow you to set a timeout only on a per-file basis.

You could use both methods if you want a global default of 5000 but set something different for some files.


Note that you cannot generally use an arrow function if you are going to call this.timeout (or access any other member of this that Mocha sets for you). For instance, this will usually not work:

describe("something", () => {
    this.timeout(5000); //will not work

    // tests...
});

This is because an arrow function takes this from the scope the function appears in. Mocha will call the function with a good value for this but that value is not passed inside the arrow function. The documentation for Mocha says on this topic:

Passing arrow functions (“lambdas”) to Mocha is discouraged. Due to the lexical binding of this, such functions are unable to access the Mocha context.

Python interpreter error, x takes no arguments (1 given)

Your updateVelocity() method is missing the explicit self parameter in its definition.

Should be something like this:

def updateVelocity(self):    
    for x in range(0,len(self.velocity)):
        self.velocity[x] = 2*random.random()*(self.pbestx[x]-self.current[x]) + 2 \
          * random.random()*(self.gbest[x]-self.current[x])

Your other methods (except for __init__) have the same problem.

Bootstrap $('#myModal').modal('show') is not working

<div class="modal fade" id="myModal" aria-hidden="true">
   ...
   ...
</div>

Note: Remove fade class from the div and enjoy it should be worked

os.path.dirname(__file__) returns empty

Because os.path.abspath = os.path.dirname + os.path.basename does not hold. we rather have

os.path.dirname(filename) + os.path.basename(filename) == filename

Both dirname() and basename() only split the passed filename into components without taking into account the current directory. If you want to also consider the current directory, you have to do so explicitly.

To get the dirname of the absolute path, use

os.path.dirname(os.path.abspath(__file__))

AngularJS - Access to child scope

One possible workaround is inject the child controller in the parent controller using a init function.

Possible implementation:

<div ng-controller="ParentController as parentCtrl">
   ...

    <div ng-controller="ChildController as childCtrl" 
         ng-init="ChildCtrl.init()">
       ...
    </div>
</div>

Where in ChildController you have :

app.controller('ChildController',
    ['$scope', '$rootScope', function ($scope, $rootScope) {
    this.init = function() {
         $scope.parentCtrl.childCtrl = $scope.childCtrl;
         $scope.childCtrl.test = 'aaaa';
    };

}])

So now in the ParentController you can use :

app.controller('ParentController',
    ['$scope', '$rootScope', 'service', function ($scope, $rootScope, service) {

    this.save = function() {
        service.save({
            a:  $scope.parentCtrl.ChildCtrl.test
        });
     };

}])

Important:
To work properly you have to use the directive ng-controller and rename each controller using as like i did in the html eg.

Tips:
Use the chrome plugin ng-inspector during the process. It's going to help you to understand the tree.

How to know Hive and Hadoop versions from command prompt?

Use the below command to get hive version

hive --service version

Python ValueError: too many values to unpack

Iterating over a dictionary object itself actually gives you an iterator over its keys. Python is trying to unpack keys, which you get from m.type + m.purity into (m, k).

My crystal ball says m.type and m.purity are both strings, so your keys are also strings. Strings are iterable, so they can be unpacked; but iterating over the string gives you an iterator over its characters. So whenever m.type + m.purity is more than two characters long, you have too many values to unpack. (And whenever it's shorter, you have too few values to unpack.)

To fix this, you can iterate explicitly over the items of the dict, which are the (key, value) pairs that you seem to be expecting. But if you only want the values, then just use the values.

(In 2.x, itervalues, iterkeys, and iteritems are typically a better idea; the non-iter versions create a new list object containing the values/keys/items. For large dictionaries and trivial tasks within the iteration, this can be a lot slower than the iter versions which just set up an iterator.)

Cannot change column used in a foreign key constraint

The type and definition of foreign key field and reference must be equal. This means your foreign key disallows changing the type of your field.

One solution would be this:

LOCK TABLES 
    favorite_food WRITE,
    person WRITE;

ALTER TABLE favorite_food
    DROP FOREIGN KEY fk_fav_food_person_id,
    MODIFY person_id SMALLINT UNSIGNED;

Now you can change you person_id

ALTER TABLE person MODIFY person_id SMALLINT UNSIGNED AUTO_INCREMENT;

recreate foreign key

ALTER TABLE favorite_food
    ADD CONSTRAINT fk_fav_food_person_id FOREIGN KEY (person_id)
          REFERENCES person (person_id);

UNLOCK TABLES;

EDIT: Added locks above, thanks to comments

You have to disallow writing to the database while you do this, otherwise you risk data integrity problems.

I've added a write lock above

All writing queries in any other session than your own ( INSERT, UPDATE, DELETE ) will wait till timeout or UNLOCK TABLES; is executed

http://dev.mysql.com/doc/refman/5.5/en/lock-tables.html

EDIT 2: OP asked for a more detailed explanation of the line "The type and definition of foreign key field and reference must be equal. This means your foreign key disallows changing the type of your field."

From MySQL 5.5 Reference Manual: FOREIGN KEY Constraints

Corresponding columns in the foreign key and the referenced key must have similar internal data types inside InnoDB so that they can be compared without a type conversion. The size and sign of integer types must be the same. The length of string types need not be the same. For nonbinary (character) string columns, the character set and collation must be the same.

Replacing from match to end-of-line

Use this, two<anything any number of times><end of line>

's/two.*$/BLAH/g'

How can I implement custom Action Bar with custom buttons in Android?

Please write following code in menu.xml file:

<menu xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:my_menu_tutorial_app="http://schemas.android.com/apk/res-auto"
      xmlns:tools="http://schemas.android.com/tools"
      tools:context="com.example.mymenus.menu_app.MainActivity">
<item android:id="@+id/item_one"
      android:icon="@drawable/menu_icon"
      android:orderInCategory="l01"
      android:title="Item One"
      my_menu_tutorial_app:showAsAction="always">
      <!--sub-menu-->
      <menu>
          <item android:id="@+id/sub_one"
                android:title="Sub-menu item one" />
          <item android:id="@+id/sub_two"
                android:title="Sub-menu item two" />
      </menu>

Also write this java code in activity class file:

public boolean onOptionsItemSelected(MenuItem item)
{
    super.onOptionsItemSelected(item);
    Toast.makeText(this, "Menus item selected: " +
        item.getTitle(), Toast.LENGTH_SHORT).show();
    switch (item.getItemId())
    {
        case R.id.sub_one:
            isItemOneSelected = true;
            supportInvalidateOptionsMenu();
            return true;
        case MENU_ITEM + 1:
            isRemoveItem = true;
            supportInvalidateOptionsMenu();
            return true;
        default:
            return false;
    }
}

This is the easiest way to display menus in action bar.

Define: What is a HashSet?

    1. A HashSet holds a set of objects, but in a way that it allows you to easily and quickly determine whether an object is already in the set or not. It does so by internally managing an array and storing the object using an index which is calculated from the hashcode of the object. Take a look here

    2. HashSet is an unordered collection containing unique elements. It has the standard collection operations Add, Remove, Contains, but since it uses a hash-based implementation, these operations are O(1). (As opposed to List for example, which is O(n) for Contains and Remove.) HashSet also provides standard set operations such as union, intersection, and symmetric difference. Take a look here

  1. There are different implementations of Sets. Some make insertion and lookup operations super fast by hashing elements. However, that means that the order in which the elements were added is lost. Other implementations preserve the added order at the cost of slower running times.

The HashSet class in C# goes for the first approach, thus not preserving the order of elements. It is much faster than a regular List. Some basic benchmarks showed that HashSet is decently faster when dealing with primary types (int, double, bool, etc.). It is a lot faster when working with class objects. So that point is that HashSet is fast.

The only catch of HashSet is that there is no access by indices. To access elements you can either use an enumerator or use the built-in function to convert the HashSet into a List and iterate through that. Take a look here

How and when to use SLEEP() correctly in MySQL?

If you don't want to SELECT SLEEP(1);, you can also DO SLEEP(1); It's useful for those situations in procedures where you don't want to see output.

e.g.

SELECT ...
DO SLEEP(5);
SELECT ...

CSS Animation onClick

_x000D_
_x000D_
var  abox = document.getElementsByClassName("box")[0];_x000D_
function allmove(){_x000D_
        abox.classList.remove("move-ltr");_x000D_
        abox.classList.remove("move-ttb");_x000D_
       abox.classList.toggle("move");_x000D_
}_x000D_
function ltr(){_x000D_
        abox.classList.remove("move");_x000D_
        abox.classList.remove("move-ttb");_x000D_
       abox.classList.toggle("move-ltr");_x000D_
}_x000D_
function ttb(){_x000D_
       abox.classList.remove("move-ltr");_x000D_
       abox.classList.remove("move");_x000D_
       abox.classList.toggle("move-ttb");_x000D_
}
_x000D_
.box {_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
  background: red;_x000D_
  position: relative;_x000D_
}_x000D_
.move{_x000D_
  -webkit-animation: moveall 5s;_x000D_
  animation: moveall 5s;_x000D_
}_x000D_
.move-ltr{_x000D_
   -webkit-animation: moveltr 5s;_x000D_
  animation: moveltr 5s;_x000D_
}_x000D_
.move-ttb{_x000D_
    -webkit-animation: movettb 5s;_x000D_
  animation: movettb 5s;_x000D_
}_x000D_
@keyframes moveall {_x000D_
  0%   {left: 0px; top: 0px;}_x000D_
  25%  {left: 200px; top: 0px;}_x000D_
  50%  {left: 200px; top: 200px;}_x000D_
  75%  {left: 0px; top: 200px;}_x000D_
  100% {left: 0px; top: 0px;}_x000D_
}_x000D_
@keyframes moveltr {_x000D_
  0%   { left: 0px; top: 0px;}_x000D_
  50%  {left: 200px; top: 0px;}_x000D_
  100% {left: 0px; top: 0px;}_x000D_
}_x000D_
@keyframes movettb {_x000D_
  0%   {left: 0px; top: 0px;}_x000D_
  50%  {top: 200px;left: 0px;}_x000D_
  100% {left: 0px; top: 0px;}_x000D_
}
_x000D_
<div class="box"></div>_x000D_
<button onclick="allmove()">click</button>_x000D_
<button onclick="ltr()">click</button>_x000D_
<button onclick="ttb()">click</button>
_x000D_
_x000D_
_x000D_

Subset dataframe by multiple logical conditions of rows to remove

And also

library(dplyr)
data %>% filter(!v1 %in% c("b", "d", "e"))

or

data %>% filter(v1 != "b" & v1 != "d" & v1 != "e")

or

data %>% filter(v1 != "b", v1 != "d", v1 != "e")

Since the & operator is implied by the comma.

Calculating moving average

EDIT: took great joy in adding the side parameter, for a moving average (or sum, or ...) of e.g. the past 7 days of a Date vector.


For people just wanting to calculate this themselves, it's nothing more than:

# x = vector with numeric data
# w = window length
y <- numeric(length = length(x))

for (i in seq_len(length(x))) {
  ind <- c((i - floor(w / 2)):(i + floor(w / 2)))
  ind <- ind[ind %in% seq_len(length(x))]
  y[i] <- mean(x[ind])
}

y

But it gets fun to make it independent of mean(), so you can calculate any 'moving' function!

# our working horse:
moving_fn <- function(x, w, fun, ...) {
  # x = vector with numeric data
  # w = window length
  # fun = function to apply
  # side = side to take, (c)entre, (l)eft or (r)ight
  # ... = parameters passed on to 'fun'
  y <- numeric(length(x))
  for (i in seq_len(length(x))) {
    if (side %in% c("c", "centre", "center")) {
      ind <- c((i - floor(w / 2)):(i + floor(w / 2)))
    } else if (side %in% c("l", "left")) {
      ind <- c((i - floor(w) + 1):i)
    } else if (side %in% c("r", "right")) {
      ind <- c(i:(i + floor(w) - 1))
    } else {
      stop("'side' must be one of 'centre', 'left', 'right'", call. = FALSE)
    }
    ind <- ind[ind %in% seq_len(length(x))]
    y[i] <- fun(x[ind], ...)
  }
  y
}

# and now any variation you can think of!
moving_average <- function(x, w = 5, side = "centre", na.rm = FALSE) {
  moving_fn(x = x, w = w, fun = mean, side = side, na.rm = na.rm)
}

moving_sum <- function(x, w = 5, side = "centre", na.rm = FALSE) {
  moving_fn(x = x, w = w, fun = sum, side = side, na.rm = na.rm)
}

moving_maximum <- function(x, w = 5, side = "centre", na.rm = FALSE) {
  moving_fn(x = x, w = w, fun = max, side = side, na.rm = na.rm)
}

moving_median <- function(x, w = 5, side = "centre", na.rm = FALSE) {
  moving_fn(x = x, w = w, fun = median, side = side, na.rm = na.rm)
}

moving_Q1 <- function(x, w = 5, side = "centre", na.rm = FALSE) {
  moving_fn(x = x, w = w, fun = quantile, side = side, na.rm = na.rm, 0.25)
}

moving_Q3 <- function(x, w = 5, side = "centre", na.rm = FALSE) {
  moving_fn(x = x, w = w, fun = quantile, side = side, na.rm = na.rm, 0.75)
}

Git: can't undo local changes (error: path ... is unmerged)

This worked perfectly for me:

$ git reset -- foo/bar.txt
$ git checkout foo/bar.txt

What does the "assert" keyword do?

It ensures that the expression returns true. Otherwise, it throws a java.lang.AssertionError.

http://java.sun.com/docs/books/jls/third_edition/html/statements.html#14.10

How to get the last day of the month?

The easiest & most reliable way I've found so Far is as:

from datetime import datetime
import calendar
days_in_month = calendar.monthrange(2020, 12)[1]
end_dt = datetime(2020, 12, days_in_month)

Failed to load resource: the server responded with a status of 404 (Not Found) css

you have defined the public dir in app root/public

app.use(express.static(__dirname + '/public')); 

so you have to use:

./css/main.css

How to validate array in Laravel?

The below code working for me on array coming from ajax call .

  $form = $request->input('form');
  $rules = array(
            'facebook_account' => 'url',
            'youtube_account' => 'url',
            'twitter_account' => 'url',
            'instagram_account' => 'url',
            'snapchat_account' => 'url',
            'website' => 'url',
        );
        $validation = Validator::make($form, $rules);

        if ($validation->fails()) {
            return Response::make(['error' => $validation->errors()], 400);
        }

declaring a priority_queue in c++ with a custom comparator

You should declare a class Compare and overload operator() for it like this:

class Foo
{

};

class Compare
{
public:
    bool operator() (Foo, Foo)
    {
        return true;
    }
};

int main()
{
    std::priority_queue<Foo, std::vector<Foo>, Compare> pq;
    return 0;
}

Or, if you for some reasons can't make it as class, you could use std::function for it:

class Foo
{

};

bool Compare(Foo, Foo)
{
    return true;
}

int main()
{
    std::priority_queue<Foo, std::vector<Foo>, std::function<bool(Foo, Foo)>> pq(Compare);
    return 0;
}

Postgres password authentication fails

Assuming, that you have root access on the box you can do:

sudo -u postgres psql

If that fails with a database "postgres" does not exists this block.

sudo -u postgres psql template1

Then sudo nano /etc/postgresql/11/main/pg_hba.conf file

local   all         postgres                          ident

For newer versions of PostgreSQL ident actually might be peer.

Inside the psql shell you can give the DB user postgres a password:

ALTER USER postgres PASSWORD 'newPassword';

Maven error :Perhaps you are running on a JRE rather than a JDK?

If the above solutions doesn't work then try to place java path before maven in path of environment variable. It worked for me.

%JAVA_HOME%\bin

C:\Program Files\apache-maven-3.6.1-bin\apache-maven-3.6.1\bin

Error installing mysql2: Failed to build gem native extension

You are getting this problem because you have not install MySql. Before install mysql2 gem. Install MySQL. After that mysql2 gem will install.

How to create User/Database in script for Docker Postgres

You can use this commands:

docker exec -it yournamecontainer psql -U postgres -c "CREATE DATABASE mydatabase ENCODING 'LATIN1' TEMPLATE template0 LC_COLLATE 'C' LC_CTYPE 'C';"

docker exec -it yournamecontainer psql -U postgres -c "GRANT ALL PRIVILEGES ON DATABASE postgres TO postgres;"

Spring: return @ResponseBody "ResponseEntity<List<JSONObject>>"

Now I return Object. I don't know better solution, but it works.

@RequestMapping(value="", method=RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody ResponseEntity<Object> getAll() {
    List<Entity> entityList = entityManager.findAll();

    List<JSONObject> entities = new ArrayList<JSONObject>();
    for (Entity n : entityList) {
        JSONObject Entity = new JSONObject();
        entity.put("id", n.getId());
        entity.put("address", n.getAddress());
        entities.add(entity);
    }
    return new ResponseEntity<Object>(entities, HttpStatus.OK);
}

Find where python is installed (if it isn't default dir)

  1. First search for PYTHON IDLE from search bar
  2. Open the IDLE and use below commands.

    import sys print(sys.path)

  3. It will give you the path where the python.exe is installed. For eg: C:\Users\\...\python.exe

  4. Add the same path to system environment variable.

In Python, how do I determine if an object is iterable?

I've been studying this problem quite a bit lately. Based on that my conclusion is that nowadays this is the best approach:

from collections.abc import Iterable   # drop `.abc` with Python 2.7 or lower

def iterable(obj):
    return isinstance(obj, Iterable)

The above has been recommended already earlier, but the general consensus has been that using iter() would be better:

def iterable(obj):
    try:
        iter(obj)
    except Exception:
        return False
    else:
        return True

We've used iter() in our code as well for this purpose, but I've lately started to get more and more annoyed by objects which only have __getitem__ being considered iterable. There are valid reasons to have __getitem__ in a non-iterable object and with them the above code doesn't work well. As a real life example we can use Faker. The above code reports it being iterable but actually trying to iterate it causes an AttributeError (tested with Faker 4.0.2):

>>> from faker import Faker
>>> fake = Faker()
>>> iter(fake)    # No exception, must be iterable
<iterator object at 0x7f1c71db58d0>
>>> list(fake)    # Ooops
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/.../site-packages/faker/proxy.py", line 59, in __getitem__
    return self._factory_map[locale.replace('-', '_')]
AttributeError: 'int' object has no attribute 'replace'

If we'd use insinstance(), we wouldn't accidentally consider Faker instances (or any other objects having only __getitem__) to be iterable:

>>> from collections.abc import Iterable
>>> from faker import Faker
>>> isinstance(Faker(), Iterable)
False

Earlier answers commented that using iter() is safer as the old way to implement iteration in Python was based on __getitem__ and the isinstance() approach wouldn't detect that. This may have been true with old Python versions, but based on my pretty exhaustive testing isinstance() works great nowadays. The only case where isinstance() didn't work but iter() did was with UserDict when using Python 2. If that's relevant, it's possible to use isinstance(item, (Iterable, UserDict)) to get that covered.

Check if a key exists inside a json object

function to check undefined and null objects

function elementCheck(objarray, callback) {
        var list_undefined = "";
        async.forEachOf(objarray, function (item, key, next_key) {
            console.log("item----->", item);
            console.log("key----->", key);
            if (item == undefined || item == '') {
                list_undefined = list_undefined + "" + key + "!!  ";
                next_key(null);
            } else {
                next_key(null);
            }
        }, function (next_key) {
            callback(list_undefined);
        })
    }

here is an easy way to check whether object sent is contain undefined or null

var objarray={
"passenger_id":"59b64a2ad328b62e41f9050d",
"started_ride":"1",
"bus_id":"59b8f920e6f7b87b855393ca",
"route_id":"59b1333c36a6c342e132f5d5",
"start_location":"",
"stop_location":""
}
elementCheck(objarray,function(list){
console.log("list");
)

How do you set the width of an HTML Helper TextBox in ASP.NET MVC?

Don't use the length parameter as it will not work with all browsers. The best way is to set a style on the input tag.

<input style="width:100px" />

Change the jquery show()/hide() animation?

Use slidedown():

$("test").slideDown("slow");

HTML SELECT - Change selected option by VALUE using JavaScript

You can select the value using javascript:

document.getElementById('sel').value = 'bike';

DEMO

Python: converting a list of dictionaries to json

import json

list = [{'id': 123, 'data': 'qwerty', 'indices': [1,10]}, {'id': 345, 'data': 'mnbvc', 'indices': [2,11]}]

Write to json File:

with open('/home/ubuntu/test.json', 'w') as fout:
    json.dump(list , fout)

Read Json file:

with open(r"/home/ubuntu/test.json", "r") as read_file:
    data = json.load(read_file)
print(data)
#list = [{'id': 123, 'data': 'qwerty', 'indices': [1,10]}, {'id': 345, 'data': 'mnbvc', 'indices': [2,11]}]

Change the background color of a row in a JTable

This is basically as simple as repainting the table. I haven't found a way to selectively repaint just one row/column/cell however.

In this example, clicking on the button changes the background color for a row and then calls repaint.

public class TableTest {
    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        final Color[] rowColors = new Color[] {
                randomColor(), randomColor(), randomColor()
        };
        final JTable table = new JTable(3, 3);
        table.setDefaultRenderer(Object.class, new TableCellRenderer() {
            @Override
            public Component getTableCellRendererComponent(JTable table,
                    Object value, boolean isSelected, boolean hasFocus,
                    int row, int column) {
                JPanel pane = new JPanel();
                pane.setBackground(rowColors[row]);
                return pane;
            }
        });
        frame.setLayout(new BorderLayout());

        JButton btn = new JButton("Change row2's color");
        btn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                rowColors[1] = randomColor();
                table.repaint();
            }
        });

        frame.add(table, BorderLayout.NORTH);
        frame.add(btn, BorderLayout.SOUTH);
        frame.pack();
        frame.setVisible(true);
    }

    private static Color randomColor() {
        Random rnd = new Random();
        return new Color(rnd.nextInt(256),
                rnd.nextInt(256), rnd.nextInt(256));
    }
}

null vs empty string in Oracle

This is because Oracle internally changes empty string to NULL values. Oracle simply won't let insert an empty string.

On the other hand, SQL Server would let you do what you are trying to achieve.

There are 2 workarounds here:

  1. Use another column that states whether the 'description' field is valid or not
  2. Use some dummy value for the 'description' field where you want it to store empty string. (i.e. set the field to be 'stackoverflowrocks' assuming your real data will never encounter such a description value)

Both are, of course, stupid workarounds :)

Exception: Can't bind to 'ngFor' since it isn't a known native property

Just to cover one more case when I was getting the same error and the reason was using in instead of of in iterator

Wrong way let file in files

Correct way let file of files

jquery ajax function not working

you need to prevent the default behavior of your form when submitting

by adding this:

$("#postcontent").on('submit' , function(e) {

  e.preventDefault();

  //then the rest of your code
}

Difference between `Optional.orElse()` and `Optional.orElseGet()`

First of all check the declaration of both the methods.

1) OrElse: Execute logic and pass result as argument.

public T orElse(T other) {    
 return value != null ? value : other;
}

2) OrElseGet: Execute logic if value inside the optional is null

public T orElseGet(Supplier<? extends T> other) {
  return value != null ? value : other.get(); 
}

Some explanation on above declaration: The argument of “Optional.orElse” always gets executed irrespective of the value of the object in optional (null, empty or with value). Always consider the above-mentioned point in mind while using “Optional.orElse”, otherwise use of “Optional.orElse” can be very risky in the following situation.

Risk-1) Logging Issue: If content inside orElse contains any log statement: In this case, you will end up logging it every time.

Optional.of(getModel())
   .map(x -> {
      //some logic
   })
  .orElse(getDefaultAndLogError());

getDefaultAndLogError() {
  log.error("No Data found, Returning default");
  return defaultValue;
}

Risk-2) Performance Issue: If content inside orElse is time-intensive: Time intensive content can be any i/o operations DB call, API call, file reading. If we put such content in orElse(), the system will end up executing a code of no use.

Optional.of(getModel())
   .map(x -> //some logic)
   .orElse(getDefaultFromDb());

getDefaultFromDb() {
   return dataBaseServe.getDefaultValue(); //api call, db call.
}

Risk-3) Illegal State or Bug Issue: If content inside orElse is mutating some object state: We might be using the same object at another place let say inside Optional.map function and it can put us in a critical bug.

List<Model> list = new ArrayList<>();
Optional.of(getModel())
  .map(x -> {
  })
  .orElse(get(list));

get(List < String > list) {
   log.error("No Data found, Returning default");
   list.add(defaultValue);
   return defaultValue;
}

Then, When can we go with orElse()? Prefer using orElse when the default value is some constant object, enum. In all above cases we can go with Optional.orElseGet() (which only executes when Optional contains non empty value)instead of Optional.orElse(). Why?? In orElse, we pass default result value, but in orElseGet we pass Supplier and method of Supplier only executes if the value in Optional is null.

Key takeaways from this:

  1. Do not use “Optional.orElse” if it contains any log statement.
  2. Do not use “Optional.orElse” if it contains time-intensive logic.
  3. Do not use “Optional.orElse” if it is mutating some object state.
  4. Use “Optional.orElse” if we have to return a constant, enum.
  5. Prefer “Optional.orElseGet” in the situations mentioned in 1,2 and 3rd points.

I have explained this in point-2 (“Optional.map/Optional.orElse” != “if/else”) my medium blog. Use Java8 as a programmer not as a coder

Convert varchar dd/mm/yyyy to dd/mm/yyyy datetime

You can do like this:

SELECT convert(datetime, convert(date, '27-09-2013', 103), 103) 

How to convert Strings to and from UTF8 byte arrays in Java

If you are using 7-bit ASCII or ISO-8859-1 (an amazingly common format) then you don't have to create a new java.lang.String at all. It's much much more performant to simply cast the byte into char:

Full working example:

for (byte b : new byte[] { 43, 45, (byte) 215, (byte) 247 }) {
    char c = (char) b;
    System.out.print(c);
}

If you are not using extended-characters like Ä, Æ, Å, Ç, Ï, Ê and can be sure that the only transmitted values are of the first 128 Unicode characters, then this code will also work for UTF-8 and extended ASCII (like cp-1252).

Numpy - Replace a number with NaN

A[A==NDV]=numpy.nan

A==NDV will produce a boolean array that can be used as an index for A

How to make a TextBox accept only alphabetic characters?

you can try following code that alert at the time of key press event

private void tbOwnerName_KeyPress(object sender, KeyPressEventArgs e)
    {

        //===================to accept only charactrs & space/backspace=============================================

        if (e.Handled = !(char.IsLetter(e.KeyChar) || e.KeyChar == (char)Keys.Back || e.KeyChar == (char)Keys.Space))
        {
            e.Handled = true;
            base.OnKeyPress(e);
            MessageBox.Show("enter characters only");
        }

How to create Haar Cascade (.xml file) to use in OpenCV?

If you are interested to detect simple IR light blob through haar cascade, it will be very odd to do. Because simple IR blob does not have enough features to be trained through opencv like other objects (face, eyes,nose etc). Because IR is just a simple light having only one feature of brightness in my point of view. But if you want to learn how to train a classifier following link will help you alot.

http://note.sonots.com/SciSoftware/haartraining.html

And if you just want to detect IR blob, then you have two more possibilities, one is you go for DIP algorithms to detect bright region and the other one which I recommend you is you can use an IR cam which just pass the IR blob and you can detect easily the IR blob by using opencv blob functiuons. If you think an IR cam is expansive, you can make simple webcam to an IR cam by removing IR blocker (if any) and add visible light blocker i.e negative film, floppy material or any other. You can check the following link to convert simple webcam to IR cam.

http://www.metacafe.com/watch/385098/transform_your_webcam_into_an_infrared_cam/

How to tell if a JavaScript function is defined

typeof callback === "function"

Check if registry key exists using VBScript

Simplest way avoiding RegRead and error handling tricks. Optional friendly consts for the registry:

Const HKEY_CLASSES_ROOT   = &H80000000
Const HKEY_CURRENT_USER   = &H80000001
Const HKEY_LOCAL_MACHINE  = &H80000002
Const HKEY_USERS          = &H80000003
Const HKEY_CURRENT_CONFIG = &H80000005

Then check with:

Set oReg = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\default:StdRegProv")

If oReg.EnumKey(HKEY_LOCAL_MACHINE, "SYSTEM\Example\Key\", "", "") = 0 Then
  MsgBox "Key Exists"
Else
  MsgBox "Key Not Found"
End If

IMPORTANT NOTES FOR THE ABOVE:

  • There are 4 parameters being passed to EnumKey, not the usual 3.
  • Equals zero means the key EXISTS.
  • The slash after key name is optional and not required.

Using iText to convert HTML to PDF

I think this is exactly what you were looking for

http://today.java.net/pub/a/today/2007/06/26/generating-pdfs-with-flying-saucer-and-itext.html

http://code.google.com/p/flying-saucer

Flying Saucer's primary purpose is to render spec-compliant XHTML and CSS 2.1 to the screen as a Swing component. Though it was originally intended for embedding markup into desktop applications (things like the iTunes Music Store), Flying Saucer has been extended work with iText as well. This makes it very easy to render XHTML to PDFs, as well as to images and to the screen. Flying Saucer requires Java 1.4 or higher.

Test for non-zero length string in Bash: [ -n "$var" ] or [ "$var" ]

An alternative and perhaps more transparent way of evaluating an empty environment variable is to use...

  if [ "x$ENV_VARIABLE" != "x" ] ; then
      echo 'ENV_VARIABLE contains something'
  fi

How does Java handle integer underflows and overflows and how would you check for it?

By default, Java's int and long math silently wrap around on overflow and underflow. (Integer operations on other integer types are performed by first promoting the operands to int or long, per JLS 4.2.2.)

As of Java 8, java.lang.Math provides addExact, subtractExact, multiplyExact, incrementExact, decrementExact and negateExact static methods for both int and long arguments that perform the named operation, throwing ArithmeticException on overflow. (There's no divideExact method -- you'll have to check the one special case (MIN_VALUE / -1) yourself.)

As of Java 8, java.lang.Math also provides toIntExact to cast a long to an int, throwing ArithmeticException if the long's value does not fit in an int. This can be useful for e.g. computing the sum of ints using unchecked long math, then using toIntExact to cast to int at the end (but be careful not to let your sum overflow).

If you're still using an older version of Java, Google Guava provides IntMath and LongMath static methods for checked addition, subtraction, multiplication and exponentiation (throwing on overflow). These classes also provide methods to compute factorials and binomial coefficients that return MAX_VALUE on overflow (which is less convenient to check). Guava's primitive utility classes, SignedBytes, UnsignedBytes, Shorts and Ints, provide checkedCast methods for narrowing larger types (throwing IllegalArgumentException on under/overflow, not ArithmeticException), as well as saturatingCast methods that return MIN_VALUE or MAX_VALUE on overflow.

Best way to unselect a <select> in jQuery?

Set a id in your select, like:
<select id="foo" size="2">

Then you can use:
$("#foo").prop("selectedIndex", 0).change();

Building a fat jar using maven

You can use the maven-shade-plugin.

After configuring the shade plugin in your build the command mvn package will create one single jar with all dependencies merged into it.

javascript multiple OR conditions in IF statement

because the OR operator will return true if any one of the conditions is true, and in your code there are two conditions that are true.

How to style components using makeStyles and still have lifecycle methods in Material UI?

I used withStyles instead of makeStyle

EX :

import { withStyles } from '@material-ui/core/styles';
import React, {Component} from "react";

const useStyles = theme => ({
        root: {
           flexGrow: 1,
         },
  });

class App extends Component {
       render() {
                const { classes } = this.props;
                return(
                    <div className={classes.root}>
                       Test
                </div>
                )
          }
} 

export default withStyles(useStyles)(App)

How to remove empty lines with or without whitespace in Python

My version:

while '' in all_lines:
    all_lines.pop(all_lines.index(''))

Google maps API V3 - multiple markers on exact same spot

I used this alongside jQuery and it does the job:

var map;
var markers = [];
var infoWindow;

function initialize() {
    var center = new google.maps.LatLng(-29.6833300, 152.9333300);

    var mapOptions = {
        zoom: 5,
        center: center,
        panControl: false,
        zoomControl: false,
        mapTypeControl: false,
        scaleControl: false,
        streetViewControl: false,
        overviewMapControl: false,
        mapTypeId: google.maps.MapTypeId.ROADMAP
      }


    map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

    $.getJSON('jsonbackend.php', function(data) {
        infoWindow = new google.maps.InfoWindow();

        $.each(data, function(key, val) {
            if(val['LATITUDE']!='' && val['LONGITUDE']!='')
            {                
                // Set the coordonates of the new point
                var latLng = new google.maps.LatLng(val['LATITUDE'],val['LONGITUDE']);

                //Check Markers array for duplicate position and offset a little
                if(markers.length != 0) {
                    for (i=0; i < markers.length; i++) {
                        var existingMarker = markers[i];
                        var pos = existingMarker.getPosition();
                        if (latLng.equals(pos)) {
                            var a = 360.0 / markers.length;
                            var newLat = pos.lat() + -.00004 * Math.cos((+a*i) / 180 * Math.PI);  //x
                            var newLng = pos.lng() + -.00004 * Math.sin((+a*i) / 180 * Math.PI);  //Y
                            var latLng = new google.maps.LatLng(newLat,newLng);
                        }
                    }
                }

                // Initialize the new marker
                var marker = new google.maps.Marker({map: map, position: latLng, title: val['TITLE']});

                // The HTML that is shown in the window of each item (when the icon it's clicked)
                var html = "<div id='iwcontent'><h3>"+val['TITLE']+"</h3>"+
                "<strong>Address: </strong>"+val['ADDRESS']+", "+val['SUBURB']+", "+val['STATE']+", "+val['POSTCODE']+"<br>"+
                "</div>";

                // Binds the infoWindow to the point
                bindInfoWindow(marker, map, infoWindow, html);

                // Add the marker to the array
                markers.push(marker);
            }
        });

        // Make a cluster with the markers from the array
        var markerCluster = new MarkerClusterer(map, markers, { zoomOnClick: true, maxZoom: 15, gridSize: 20 });
    });
}

function markerOpen(markerid) {
    map.setZoom(22);
    map.panTo(markers[markerid].getPosition());
    google.maps.event.trigger(markers[markerid],'click');
    switchView('map');
}

google.maps.event.addDomListener(window, 'load', initialize);

Code for a simple JavaScript countdown timer?

Here is another one if anyone needs one for minutes and seconds:

    var mins = 10;  //Set the number of minutes you need
    var secs = mins * 60;
    var currentSeconds = 0;
    var currentMinutes = 0;
    /* 
     * The following line has been commented out due to a suggestion left in the comments. The line below it has not been tested. 
     * setTimeout('Decrement()',1000);
     */
    setTimeout(Decrement,1000); 

    function Decrement() {
        currentMinutes = Math.floor(secs / 60);
        currentSeconds = secs % 60;
        if(currentSeconds <= 9) currentSeconds = "0" + currentSeconds;
        secs--;
        document.getElementById("timerText").innerHTML = currentMinutes + ":" + currentSeconds; //Set the element id you need the time put into.
        if(secs !== -1) setTimeout('Decrement()',1000);
    }

How to merge two json string in Python?

Assuming a and b are the dictionaries you want to merge:

c = {key: value for (key, value) in (a.items() + b.items())}

To convert your string to python dictionary you use the following:

import json
my_dict = json.loads(json_str)

Update: full code using strings:

# test cases for jsonStringA and jsonStringB according to your data input
jsonStringA = '{"error_1395946244342":"valueA","error_1395952003":"valueB"}'
jsonStringB = '{"error_%d":"Error Occured on machine %s in datacenter %s on the %s of process %s"}' % (timestamp_number, host_info, local_dc, step, c)

# now we have two json STRINGS
import json
dictA = json.loads(jsonStringA)
dictB = json.loads(jsonStringB)

merged_dict = {key: value for (key, value) in (dictA.items() + dictB.items())}

# string dump of the merged dict
jsonString_merged = json.dumps(merged_dict)

But I have to say that in general what you are trying to do is not the best practice. Please read a bit on python dictionaries.


Alternative solution:

jsonStringA = get_my_value_as_string_from_somewhere()
errors_dict = json.loads(jsonStringA)

new_error_str = "Error Ocurred in datacenter %s blah for step %s blah" % (datacenter, step)
new_error_key = "error_%d" % (timestamp_number)

errors_dict[new_error_key] = new_error_str

# and if I want to export it somewhere I use the following
write_my_dict_to_a_file_as_string(json.dumps(errors_dict))

And actually you can avoid all these if you just use an array to hold all your errors.

Entity Framework vs LINQ to SQL

There are a number of obvious differences outlined in that article @lars posted, but short answer is:

  • L2S is tightly coupled - object property to specific field of database or more correctly object mapping to a specific database schema
  • L2S will only work with SQL Server (as far as I know)
  • EF allows mapping a single class to multiple tables
  • EF will handle M-M relationships
  • EF will have ability to target any ADO.NET data provider

The original premise was L2S is for Rapid Development, and EF for more "enterprisey" n-tier applications, but that is selling L2S a little short.

Get the full URL in PHP

My favorite cross platform method for finding the current URL is:

$url = (isset($_SERVER['HTTPS']) ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

Replace Multiple String Elements in C#

this will be more efficient:

public static class StringExtension
{
    public static string clean(this string s)
    {
        return new StringBuilder(s)
              .Replace("&", "and")
              .Replace(",", "")
              .Replace("  ", " ")
              .Replace(" ", "-")
              .Replace("'", "")
              .Replace(".", "")
              .Replace("eacute;", "é")
              .ToString()
              .ToLower();
    }
}

Why does Git say my master branch is "already up to date" even though it is not?

As the other posters say, pull merges changes from upstream into your repository. If you want to replace what is in your repository with what is in upstream, you have several options. Off the cuff, I'd go with

git checkout HEAD^1  # Get off your repo's master.. doesn't matter where you go, so just go back one commit
git branch -d master  # Delete your repo's master branch
git checkout -t upstream/master  # Check out upstream's master into a local tracking branch of the same name

What is the difference between CMD and ENTRYPOINT in a Dockerfile?

The official documentation of Dockerfile best practices does a great job explaining the differences. Dockerfile best practices

CMD:

The CMD instruction should be used to run the software contained by your image, along with any arguments. CMD should almost always be used in the form of CMD ["executable", "param1", "param2"…]. Thus, if the image is for a service, such as Apache and Rails, you would run something like CMD ["apache2","-DFOREGROUND"]. Indeed, this form of the instruction is recommended for any service-based image.

ENTRYPOINT:

The best use for ENTRYPOINT is to set the image’s main command, allowing that image to be run as though it was that command (and then use CMD as the default flags).

How does autowiring work in Spring?

Keep in mind that you must enable the @Autowired annotation by adding element <context:annotation-config/> into the spring configuration file. This will register the AutowiredAnnotationBeanPostProcessor which takes care the processing of annotation.

And then you can autowire your service by using the field injection method.

public class YourController{

 @Autowired
 private UserService userService; 

}

I found this from the post Spring @autowired annotation

Giving graphs a subtitle in matplotlib

I don't think there is anything built-in, but you can do it by leaving more space above your axes and using figtext:

axes([.1,.1,.8,.7])
figtext(.5,.9,'Foo Bar', fontsize=18, ha='center')
figtext(.5,.85,'Lorem ipsum dolor sit amet, consectetur adipiscing elit',fontsize=10,ha='center')

ha is short for horizontalalignment.

How should I validate an e-mail address?

For regex lovers, the very best (e.g. consistant with RFC 822) email's pattern I ever found since now is the following (before PHP supplied filters). I guess it's easy to translate this into Java - for those playing with API < 8 :

private static function email_regex_pattern() {
// Source:  http://www.iamcal.com/publish/articles/php/parsing_email
$qtext = '[^\\x0d\\x22\\x5c\\x80-\\xff]';
$dtext = '[^\\x0d\\x5b-\\x5d\\x80-\\xff]';
$atom = '[^\\x00-\\x20\\x22\\x28\\x29\\x2c\\x2e\\x3a-\\x3c'.
    '\\x3e\\x40\\x5b-\\x5d\\x7f-\\xff]+';
$quoted_pair = '\\x5c[\\x00-\\x7f]';
$domain_literal = "\\x5b($dtext|$quoted_pair)*\\x5d";
$quoted_string = "\\x22($qtext|$quoted_pair)*\\x22";
$domain_ref = $atom;
$sub_domain = "($domain_ref|$domain_literal)";
$word = "($atom|$quoted_string)";
$domain = "$sub_domain(\\x2e$sub_domain)*";
$local_part = "$word(\\x2e$word)*";
$pattern = "!^$local_part\\x40$domain$!";
return $pattern ;
}

How to execute a .sql script from bash

If you want to run a script to a database:

mysql -u user -p data_base_name_here < db.sql

What is the use of ByteBuffer in Java?

In Android you can create shared buffer between C++ and Java (with directAlloc method) and manipulate it in both sides.

IOException: Too many open files

Don't know the nature of your app, but I have seen this error manifested multiple times because of a connection pool leak, so that would be worth checking out. On Linux, socket connections consume file descriptors as well as file system files. Just a thought.

How to discard all changes made to a branch?

git reset --hard can help you if you want to throw away everything since your last commit

How to list records with date from the last 10 days?

My understanding from my testing (and the PostgreSQL dox) is that the quotes need to be done differently from the other answers, and should also include "day" like this:

SELECT Table.date
  FROM Table 
  WHERE date > current_date - interval '10 day';

Demonstrated here (you should be able to run this on any Postgres db):

SELECT DISTINCT current_date, 
                current_date - interval '10' day, 
                current_date - interval '10 days' 
  FROM pg_language;

Result:

2013-03-01  2013-03-01 00:00:00 2013-02-19 00:00:00

pandas convert some columns into rows

Use set_index with stack for MultiIndex Series, then for DataFrame add reset_index with rename:

df1 = (df.set_index(["location", "name"])
         .stack()
         .reset_index(name='Value')
         .rename(columns={'level_2':'Date'}))
print (df1)
  location  name        Date  Value
0        A  test    Jan-2010     12
1        A  test    Feb-2010     20
2        A  test  March-2010     30
3        B   foo    Jan-2010     18
4        B   foo    Feb-2010     20
5        B   foo  March-2010     25

How to drop SQL default constraint without knowing its name?

Rob Farley's blog post might be of help:

Something like:

 declare @table_name nvarchar(256)
 declare @col_name nvarchar(256)
 set @table_name = N'Department'
 set @col_name = N'ModifiedDate'

 select t.name, c.name, d.name, d.definition
 from 
     sys.tables t
     join sys.default_constraints d on d.parent_object_id = t.object_id
     join sys.columns c on c.object_id = t.object_id
                           and c.column_id = d.parent_column_id
 where 
     t.name = @table_name
     and c.name = @col_name