Programs & Examples On #Business objects sdk

A software development kit (SDK) to access users and groups, folders and objects, and services provided by BusinessObjects Enterprise. Includes Java, .Net, COM, SOAP, and REST versions.

How can I get an int from stdio in C?

The typical way is with scanf:

int input_value;

scanf("%d", &input_value);

In most cases, however, you want to check whether your attempt at reading input succeeded. scanf returns the number of items it successfully converted, so you typically want to compare the return value against the number of items you expected to read. In this case you're expecting to read one item, so:

if (scanf("%d", &input_value) == 1)
    // it succeeded
else
    // it failed

Of course, the same is true of all the scanf family (sscanf, fscanf and so on).

Is iterating ConcurrentHashMap values thread safe?

What does it mean?

That means that each iterator you obtain from a ConcurrentHashMap is designed to be used by a single thread and should not be passed around. This includes the syntactic sugar that the for-each loop provides.

What happens if I try to iterate the map with two threads at the same time?

It will work as expected if each of the threads uses it's own iterator.

What happens if I put or remove a value from the map while iterating it?

It is guaranteed that things will not break if you do this (that's part of what the "concurrent" in ConcurrentHashMap means). However, there is no guarantee that one thread will see the changes to the map that the other thread performs (without obtaining a new iterator from the map). The iterator is guaranteed to reflect the state of the map at the time of it's creation. Futher changes may be reflected in the iterator, but they do not have to be.

In conclusion, a statement like

for (Object o : someConcurrentHashMap.entrySet()) {
    // ...
}

will be fine (or at least safe) almost every time you see it.

Using a SELECT statement within a WHERE clause

The principle of subqueries is not at all bad, but I don't think that you should use it in your example. If I understand correctly you want to get the maximum score for each date. In this case you should use a GROUP BY.

How to split/partition a dataset into training and test datasets for, e.g., cross validation?

As sklearn.cross_validation module was deprecated, you can use:

import numpy as np
from sklearn.model_selection import train_test_split
X, y = np.arange(10).reshape((5, 2)), range(5)

X_trn, X_tst, y_trn, y_tst = train_test_split(X, y, test_size=0.2, random_state=42)

Maven2 property that indicates the parent directory

I've found a solution to solve this problem: use ${parent.relativePath}

<parent>
    <artifactId>xxx</artifactId>
    <groupId>xxx</groupId>
    <version>1.0-SNAPSHOT</version>
    <relativePath>..</relativePath>
</parent>
<build>
    <filters>
        <filter>${parent.relativePath}/src/main/filters/filter-${env}.properties</filter>
    </filters>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <filtering>true</filtering>
        </resource>
    </resources>
</build>

Matrix multiplication in OpenCV

You say that the matrices are the same dimensions, and yet you are trying to perform matrix multiplication on them. Multiplication of matrices with the same dimension is only possible if they are square. In your case, you get an assertion error, because the dimensions are not square. You have to be careful when multiplying matrices, as there are two possible meanings of multiply.

Matrix multiplication is where two matrices are multiplied directly. This operation multiplies matrix A of size [a x b] with matrix B of size [b x c] to produce matrix C of size [a x c]. In OpenCV it is achieved using the simple * operator:

C = A * B

Element-wise multiplication is where each pixel in the output matrix is formed by multiplying that pixel in matrix A by its corresponding entry in matrix B. The input matrices should be the same size, and the output will be the same size as well. This is achieved using the mul() function:

output = A.mul(B);

How to encode URL parameters?

With PHP

echo urlencode("http://www.image.com/?username=unknown&password=unknown");

Result

http%3A%2F%2Fwww.image.com%2F%3Fusername%3Dunknown%26password%3Dunknown

With Javascript:

var myUrl = "http://www.image.com/?username=unknown&password=unknown";
var encodedURL= "http://www.foobar.com/foo?imageurl=" + encodeURIComponent(myUrl);

DEMO: http://jsfiddle.net/Lpv53/

Java, how to compare Strings with String Arrays

If I understand your question correctly, it appears you want to know the following:

How do I check if my String array contains usercode, the String that was just inputted?

See here for a similar question. It quotes solutions that have been pointed out by previous answers. I hope this helps.

how to print float value upto 2 decimal place without rounding off

The only easy way to do this is to use snprintf to print to a buffer that's long enough to hold the entire, exact value, then truncate it as a string. Something like:

char buf[2*(DBL_MANT_DIG + DBL_MAX_EXP)];
snprintf(buf, sizeof buf, "%.*f", (int)sizeof buf, x);
char *p = strchr(buf, '.'); // beware locale-specific radix char, though!
p[2+1] = 0;
puts(buf);

How to insert a file in MySQL database?

You need to use BLOB, there's TINY, MEDIUM, LONG, and just BLOB, as with other types, choose one according to your size needs.

TINYBLOB 255
BLOB 65535
MEDIUMBLOB 16777215
LONGBLOB 4294967295
(in bytes)

The insert statement would be fairly normal. You need to read the file using fread and then addslashes to it.

Case Statement Equivalent in R

As of data.table v1.13.0 you can use the function fcase() (fast-case) to do SQL-like CASE operations (also similar to dplyr::case_when()):

require(data.table)

dt <- data.table(name = c('cow','pig','eagle','pigeon','cow','eagle'))
dt[ , category := fcase(name %in% c('cow', 'pig'), 'mammal',
                        name %in% c('eagle', 'pigeon'), 'bird') ]

How to set a timer in android

yes java's timer can be used, but as the question asks for better way (for mobile). Which is explained Here.


For the sake of StackOverflow:

Since Timer creates a new thread it may be considered heavy,

if all you need is to get is a call back while the activity is running a Handler can be used in conjunction with a

Runnable:

private final int interval = 1000; // 1 Second
private Handler handler = new Handler();
private Runnable runnable = new Runnable(){
    public void run() {
        Toast.makeText(MyActivity.this, "C'Mom no hands!", Toast.LENGTH_SHORT).show();
    }
};
...
handler.postAtTime(runnable, System.currentTimeMillis()+interval);
handler.postDelayed(runnable, interval);

or a Message

private final int EVENT1 = 1; 
private Handler handler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {         
        case Event1:
            Toast.makeText(MyActivity.this, "Event 1", Toast.LENGTH_SHORT).show();
            break;

        default:
            Toast.makeText(MyActivity.this, "Unhandled", Toast.LENGTH_SHORT).show();
            break;
        }
    }
};

...

Message msg = handler.obtainMessage(EVENT1);
handler.sendMessageAtTime(msg, System.currentTimeMillis()+interval);
handler.sendMessageDelayed(msg, interval);

on a side note this approach can be used, if you want to run a piece of code in the UI thread from an another thread.

if you need to get a call back even if your activity is not running then, you can use an AlarmManager

Differences between action and actionListener

TL;DR:

The ActionListeners (there can be multiple) execute in the order they were registered BEFORE the action

Long Answer:

A business action typically invokes an EJB service and if necessary also sets the final result and/or navigates to a different view if that is not what you are doing an actionListener is more appropriate i.e. for when the user interacts with the components, such as h:commandButton or h:link they can be handled by passing the name of the managed bean method in actionListener attribute of a UI Component or to implement an ActionListener interface and pass the implementation class name to actionListener attribute of a UI Component.

How to make all controls resize accordingly proportionally when window is maximized?

Well, it's fairly simple to do.

On the window resize event handler, calculate how much the window has grown/shrunk, and use that fraction to adjust 1) Height, 2) Width, 3) Canvas.Top, 4) Canvas.Left properties of all the child controls inside the canvas.

Here's the code:

private void window1_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            myCanvas.Width = e.NewSize.Width;
            myCanvas.Height = e.NewSize.Height;

            double xChange = 1, yChange = 1;

            if (e.PreviousSize.Width != 0)
            xChange = (e.NewSize.Width/e.PreviousSize.Width);

            if (e.PreviousSize.Height != 0)
            yChange = (e.NewSize.Height / e.PreviousSize.Height);

            foreach (FrameworkElement fe in myCanvas.Children )
            {   
                /*because I didn't want to resize the grid I'm having inside the canvas in this particular instance. (doing that from xaml) */            
                if (fe is Grid == false)
                {
                    fe.Height = fe.ActualHeight * yChange;
                    fe.Width = fe.ActualWidth * xChange;

                    Canvas.SetTop(fe, Canvas.GetTop(fe) * yChange);
                    Canvas.SetLeft(fe, Canvas.GetLeft(fe) * xChange);

                }
            }
        }

The ResourceConfig instance does not contain any root resource classes

I had the same issue with trying to run the webapp from an eclipse project. As soon I copied the .class files to /WEB-INF/classes it worked perfectly.

Hosting a Maven repository on github

If you have only aar or jar file itself, or just don't want to use plugins - I've created a simple shell script. You can achieve the same with it - publishing your artifacts to Github and use it as public Maven repo.

Java converting Image to BufferedImage

If you are getting back a sun.awt.image.ToolkitImage, you can cast the Image to that, and then use getBufferedImage() to get the BufferedImage.

So instead of your last line of code where you are casting you would just do:

BufferedImage buffered = ((ToolkitImage) image).getBufferedImage();

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

I actually had this identical issue with the inverse solution. I had upgraded a .NET project to .NET 4.0 and then reverted back to .NET 3.5. The app.config in my project continued to have the following which was causing the above error in question:

<startup>
  <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
</startup>

The solution to solve the error for this was to revert it back to the proper 2.0 reference as follows:

<startup>
  <supportedRuntime version="v2.0.50727"/>
</startup>

So if a downgrade is producing the above error, you might need to back up the .NET Framework supported version.

contenteditable change events

non jQuery quick and dirty answer:

function setChangeListener (div, listener) {

    div.addEventListener("blur", listener);
    div.addEventListener("keyup", listener);
    div.addEventListener("paste", listener);
    div.addEventListener("copy", listener);
    div.addEventListener("cut", listener);
    div.addEventListener("delete", listener);
    div.addEventListener("mouseup", listener);

}

var div = document.querySelector("someDiv");

setChangeListener(div, function(event){
    console.log(event);
});

Text not wrapping inside a div element

Might benefit you to be aware of another option, word-wrap: break-word;

The difference here is that words that can completely fit on 1 line will do that, vs. being forced to break simply because there is no more real estate on the line the word starts on.

See the fiddle for an illustration http://jsfiddle.net/Jqkcp/

Move SQL data from one table to another

Try this

INSERT INTO TABLE2 (Cols...) SELECT Cols... FROM TABLE1 WHERE Criteria

Then

DELETE FROM TABLE1 WHERE Criteria

How can I find the first occurrence of a sub-string in a python string?

verse = "If you can keep your head when all about you\n Are losing theirs and blaming it on you,\nIf you can trust yourself when all men doubt you,\n But make allowance for their doubting too;\nIf you can wait and not be tired by waiting,\n Or being lied about, don’t deal in lies,\nOr being hated, don’t give way to hating,\n And yet don’t look too good, nor talk too wise:"

enter code here

print(verse)
#1. What is the length of the string variable verse?
verse_length = len(verse)
print("The length of verse is: {}".format(verse_length))
#2. What is the index of the first occurrence of the word 'and' in verse?
index = verse.find("and")
print("The index of the word 'and' in verse is {}".format(index))

Android Studio - Gradle sync project failed

I know this is an old thread but I ended up here with the same issue.

I solved it by comparing the dependencies classpath in the build.gradle script(Project) to the installed version.

The error message was pointing to the following folder

C:\Program Files\Android\android-studio3 preview\gradle\m2repository\com\android\tools\build\gradle

It turned out that the alpha2 version was installed but the classpath was still pointing to alpaha1. A simple change to the classpath ('com.android.tools.build:gradle:3.0.0-alpha2') was all that was needed.

This may not help everyone, but I do hope it help most people out.

Add legend to ggplot2 line plot

I really like the solution proposed by @Brian Diggs. However, in my case, I create the line plots in a loop rather than giving them explicitly because I do not know apriori how many plots I will have. When I tried to adapt the @Brian's code I faced some problems with handling the colors correctly. Turned out I needed to modify the aesthetic functions. In case someone has the same problem, here is the code that worked for me.

I used the same data frame as @Brian:

data <- structure(list(month = structure(c(1317452400, 1317538800, 1317625200, 1317711600, 
                                       1317798000, 1317884400, 1317970800, 1318057200, 
                                       1318143600, 1318230000, 1318316400, 1318402800, 
                                       1318489200, 1318575600, 1318662000, 1318748400, 
                                       1318834800, 1318921200, 1319007600, 1319094000), 
                                     class = c("POSIXct", "POSIXt"), tzone = ""),
                   TempMax = c(26.58, 27.78, 27.9, 27.44, 30.9, 30.44, 27.57, 25.71, 
                               25.98, 26.84, 33.58, 30.7, 31.3, 27.18, 26.58, 26.18, 
                               25.19, 24.19, 27.65, 23.92), 
                   TempMed = c(22.88, 22.87, 22.41, 21.63, 22.43, 22.29, 21.89, 20.52,
                                 19.71, 20.73, 23.51, 23.13, 22.95, 21.95, 21.91, 20.72, 
                                 20.45, 19.42, 19.97, 19.61), 
                   TempMin = c(19.34, 19.14, 18.34, 17.49, 16.75, 16.75, 16.88, 16.82, 
                               14.82, 16.01, 16.88, 17.55, 16.75, 17.22, 19.01, 16.95, 
                               17.55, 15.21, 14.22, 16.42)), 
              .Names = c("month", "TempMax", "TempMed", "TempMin"), 
              row.names = c(NA, 20L), class = "data.frame")  

In my case, I generate my.cols and my.names dynamically, but I don't want to make things unnecessarily complicated so I give them explicitly here. These three lines make the ordering of the legend and assigning colors easier.

my.cols <- heat.colors(3, alpha=1)
my.names <- c("TempMin", "TempMed", "TempMax")
names(my.cols) <- my.names

And here is the plot:

p <-  ggplot(data, aes(x = month))

for (i in 1:3){
  p <- p + geom_line(aes_(y = as.name(names(data[i+1])), colour = 
colnames(data[i+1])))#as.character(my.names[i])))
}
p + scale_colour_manual("", 
                        breaks = as.character(my.names),
                        values = my.cols)
p

enter image description here

Custom Authentication in ASP.Net-Core

Creating custom authentication in ASP.NET Core can be done in a variety of ways. If you want to build off existing components (but don't want to use identity), checkout the "Security" category of docs on docs.asp.net. https://docs.asp.net/en/latest/security/index.html

Some articles you might find helpful:

Using Cookie Middleware without ASP.NET Identity

Custom Policy-Based Authorization

And of course, if that fails or docs aren't clear enough, the source code is at https://github.com/dotnet/aspnetcore/tree/master/src/Security which includes some samples.

Jasmine.js comparing arrays

just for the record you can always compare using JSON.stringify

const arr = [1,2,3]; expect(JSON.stringify(arr)).toBe(JSON.stringify([1,2,3])); expect(JSON.stringify(arr)).toEqual(JSON.stringify([1,2,3]));

It's all meter of taste, this will also work for complex literal objects

Returning an array using C

In your case, you are creating an array on the stack and once you leave the function scope, the array will be deallocated. Instead, create a dynamically allocated array and return a pointer to it.

char * returnArray(char *arr, int size) {
    char *new_arr = malloc(sizeof(char) * size);
    for(int i = 0; i < size; ++i) {
        new_arr[i] = arr[i];
    }
    return new_arr;
}

int main() {

    char arr[7]= {1,0,0,0,0,1,1};
    char *new_arr = returnArray(arr, 7);

    // don't forget to free the memory after you're done with the array
    free(new_arr);

}

Adding maven nexus repo to my pom.xml

From maven setting reference, you can not put your username/password in a pom.xml

The repositories for download and deployment are defined by the repositories and distributionManagement elements of the POM. However, certain settings such as username and password should not be distributed along with the pom.xml. This type of information should exist on the build server in the settings.xml.

You can first add a repository in your pom and then add the username/password in the $MAVEN_HOME/conf/settings.xml:

  <servers>
    <server>
        <id>my-internal-site</id>
        <username>yourUsername</username>
        <password>yourPassword</password>
    </server>
  </servers>

Insert null/empty value in sql datetime column by default

you can use like this:

string Log_In_Val = (Convert.ToString(attenObj.Log_In) == "" ? "Null" + "," : "'" + Convert.ToString(attenObj.Log_In) + "',");

Returning a value from callback function in Node.js

If what you want is to get your code working without modifying too much. You can try this solution which gets rid of callbacks and keeps the same code workflow:

Given that you are using Node.js, you can use co and co-request to achieve the same goal without callback concerns.

Basically, you can do something like this:

function doCall(urlToCall) {
  return co(function *(){
    var response = yield urllib.request(urlToCall, { wd: 'nodejs' }); // This is co-request.                             
    var statusCode = response.statusCode;
    finalData = getResponseJson(statusCode, data.toString());
    return finalData;
  });
}

Then,

var response = yield doCall(urlToCall); // "yield" garuantees the callback finished.
console.log(response) // The response will not be undefined anymore.

By doing this, we wait until the callback function finishes, then get the value from it. Somehow, it solves your problem.

How to clear a textbox once a button is clicked in WPF?

You wouldn't have to put it in the button click hander. If you were, then you'd assign your text box a name (x:Name) in your view and then use the generated member of the same name in the code behind to set the Text property.

If you were avoiding code behind, then you would investigate the MVVM design pattern and data binding, and bind a property on your view model to the text box's Text property.

How to delete specific columns with VBA?

To answer the question How to delete specific columns in vba for excel. I use Array as below.

sub del_col()

dim myarray as variant
dim i as integer

myarray = Array(10, 9, 8)'Descending to Ascending
For i = LBound(myarray) To UBound(myarray)
    ActiveSheet.Columns(myarray(i)).EntireColumn.Delete
Next i

end sub

Python how to exit main function

If you don't feel like importing anything, you can try:

raise SystemExit, 0

What is a non-capturing group in regular expressions?

You can use capturing groups to organize and parse an expression. A non-capturing group has the first benefit, but doesn't have the overhead of the second. You can still say a non-capturing group is optional, for example.

Say you want to match numeric text, but some numbers could be written as 1st, 2nd, 3rd, 4th,... If you want to capture the numeric part, but not the (optional) suffix you can use a non-capturing group.

([0-9]+)(?:st|nd|rd|th)?

That will match numbers in the form 1, 2, 3... or in the form 1st, 2nd, 3rd,... but it will only capture the numeric part.

What is the difference between document.location.href and document.location?

document.location is a synonym for window.location that has been deprecated for almost as long as JavaScript has existed. Don't use it.

location is a structured object, with properties corresponding to the parts of the URL. location.href is the whole URL in a single string. Assigning a string to either is defined to cause the same kind of navigation, so take your pick.

I consider writing to location.href = something to be marginally better as it's slightly more explicit about what it's doing. You generally want to avoid just location = something as it looks misleadingly like a variable assignment. window.location = something is fine though.

c++ parse int from string

You can use boost::lexical_cast:

#include <iostream>
#include <boost/lexical_cast.hpp>

int main( int argc, char* argv[] ){
std::string s1 = "10";
std::string s2 = "abc";
int i;

   try   {
      i = boost::lexical_cast<int>( s1 );
   }
   catch( boost::bad_lexical_cast & e ){
      std::cout << "Exception caught : " << e.what() << std::endl;
   }

   try   {
      i = boost::lexical_cast<int>( s2 );
   }
   catch( boost::bad_lexical_cast & e ){
      std::cout << "Exception caught : " << e.what() << std::endl;
   }

   return 0;
}

When should I use GET or POST method? What's the difference between them?

You should use POST if there is a lot of data, or sort-of sensitive information (really sensitive stuff needs a secure connection as well).

Use GET if you want people to be able to bookmark your page, because all the data is included with the bookmark.

Just be careful of people hitting REFRESH with the GET method, because the data will be sent again every time without warning the user (POST sometimes warns the user about resending data).

How are "mvn clean package" and "mvn clean install" different?

What clean does (common in both the commands) - removes all files generated by the previous build


Coming to the difference between the commands package and install, you first need to understand the lifecycle of a maven project


These are the default life cycle phases in maven

  • validate - validate the project is correct and all necessary information is available
  • compile - compile the source code of the project
  • test - test the compiled source code using a suitable unit testing framework. These tests should not require the code be packaged or deployed
  • package - take the compiled code and package it in its distributable format, such as a JAR.
  • verify - run any checks on results of integration tests to ensure quality criteria are met
  • install - install the package into the local repository, for use as a dependency in other projects locally
  • deploy - done in the build environment, copies the final package to the remote repository for sharing with other developers and projects.

How Maven works is, if you run a command for any of the lifecycle phases, it executes each default life cycle phase in order, before executing the command itself.

order of execution

validate >> compile >> test (optional) >> package >> verify >> install >> deploy

So when you run the command mvn package, it runs the commands for all lifecycle phases till package

validate >> compile >> test (optional) >> package

And as for mvn install, it runs the commands for all lifecycle phases till install, which includes package as well

validate >> compile >> test (optional) >> package >> verify >> install


So, effectively what it means is, install commands does everything that package command does and some more (install the package into the local repository, for use as a dependency in other projects locally)

Source: Maven lifecycle reference

Return Max Value of range that is determined by an Index & Match lookup

You don't need an index match formula. You can use this array formula. You have to press CTL + SHIFT + ENTER after you enter the formula.

=MAX(IF((A1:A6=A10)*(B1:B6=B10),C1:F6))

SNAPSHOT

enter image description here

how do I use an enum value on a switch statement in C++

You can use an enumerated value just like an integer:

myChoice c;

...

switch( c ) {
case EASY:
    DoStuff();
    break;
case MEDIUM:
    ...
}

How to pass a file path which is in assets folder to File(String path)?

Unless you unpack them, assets remain inside the apk. Accordingly, there isn't a path you can feed into a File. The path you've given in your question will work with/in a WebView, but I think that's a special case for WebView.

You'll need to unpack the file or use it directly.

If you have a Context, you can use context.getAssets().open("myfoldername/myfilename"); to open an InputStream on the file. With the InputStream you can use it directly, or write it out somewhere (after which you can use it with File).

Remove last characters from a string in C#. An elegant way?

You can use TrimEnd. It's efficient as well and looks clean.

"Name,".TrimEnd(',');

how to update spyder on anaconda

This worked for me: conda install --force-reinstall pyqt qt
Based on this

HTML5 Video not working in IE 11

I know this is old, but here is a additional thing if you still encounter problems with the solution above.

Just put in your <head> :

<meta http-equiv="X-UA-Compatible" content="IE=edge"> 

It will prevent IE to jump back to IE9 compatibility, thus breaking the video function. Worked for me, so if you still have problems, consider checking this out.

Alternatively you can add this in PHP :

header('x-ua-compatible: ie=edge');

Or in a .htaccess file:

header set X-UA-Compatible "IE=Edge"

How to convert integer timestamp to Python datetime

datetime.datetime.fromtimestamp() is correct, except you are probably having timestamp in miliseconds (like in JavaScript), but fromtimestamp() expects Unix timestamp, in seconds.

Do it like that:

>>> import datetime
>>> your_timestamp = 1331856000000
>>> date = datetime.datetime.fromtimestamp(your_timestamp / 1e3)

and the result is:

>>> date
datetime.datetime(2012, 3, 16, 1, 0)

Does it answer your question?

EDIT: J.F. Sebastian correctly suggested to use true division by 1e3 (float 1000). The difference is significant, if you would like to get precise results, thus I changed my answer. The difference results from the default behaviour of Python 2.x, which always returns int when dividing (using / operator) int by int (this is called floor division). By replacing the divisor 1000 (being an int) with the 1e3 divisor (being representation of 1000 as float) or with float(1000) (or 1000. etc.), the division becomes true division. Python 2.x returns float when dividing int by float, float by int, float by float etc. And when there is some fractional part in the timestamp passed to fromtimestamp() method, this method's result also contains information about that fractional part (as the number of microseconds).

Calculating Page Load Time In JavaScript

Why so complicated? When you can do:

var loadTime = window.performance.timing.domContentLoadedEventEnd- window.performance.timing.navigationStart;

If you need more times check out the window.performance object:

console.log(window.performance);

Will show you the timing object:

connectEnd                 Time when server connection is finished.
connectStart               Time just before server connection begins.
domComplete                Time just before document readiness completes.
domContentLoadedEventEnd   Time after DOMContentLoaded event completes.
domContentLoadedEventStart Time just before DOMContentLoaded starts.
domInteractive             Time just before readiness set to interactive.
domLoading                 Time just before readiness set to loading.
domainLookupEnd            Time after domain name lookup.
domainLookupStart          Time just before domain name lookup.
fetchStart                 Time when the resource starts being fetched.
loadEventEnd               Time when the load event is complete.
loadEventStart             Time just before the load event is fired.
navigationStart            Time after the previous document begins unload.
redirectCount              Number of redirects since the last non-redirect.
redirectEnd                Time after last redirect response ends.
redirectStart              Time of fetch that initiated a redirect.
requestStart               Time just before a server request.
responseEnd                Time after the end of a response or connection.
responseStart              Time just before the start of a response.
timing                     Reference to a performance timing object.
navigation                 Reference to performance navigation object.
performance                Reference to performance object for a window.
type                       Type of the last non-redirect navigation event.
unloadEventEnd             Time after the previous document is unloaded.
unloadEventStart           Time just before the unload event is fired.

Browser Support

More Info

How to save an image locally using Python whose URL address I already know?

Version for Python 3

I adjusted the code of @madprops for Python 3

# getem.py
# python2 script to download all images in a given url
# use: python getem.py http://url.where.images.are

from bs4 import BeautifulSoup
import urllib.request
import shutil
import requests
from urllib.parse import urljoin
import sys
import time

def make_soup(url):
    req = urllib.request.Request(url, headers={'User-Agent' : "Magic Browser"}) 
    html = urllib.request.urlopen(req)
    return BeautifulSoup(html, 'html.parser')

def get_images(url):
    soup = make_soup(url)
    images = [img for img in soup.findAll('img')]
    print (str(len(images)) + " images found.")
    print('Downloading images to current working directory.')
    image_links = [each.get('src') for each in images]
    for each in image_links:
        try:
            filename = each.strip().split('/')[-1].strip()
            src = urljoin(url, each)
            print('Getting: ' + filename)
            response = requests.get(src, stream=True)
            # delay to avoid corrupted previews
            time.sleep(1)
            with open(filename, 'wb') as out_file:
                shutil.copyfileobj(response.raw, out_file)
        except:
            print('  An error occured. Continuing.')
    print('Done.')

if __name__ == '__main__':
    get_images('http://www.wookmark.com')

Disable nginx cache for JavaScript files

I have the following Nginx virtual host(static content) for local development work to disable all browser caching:

    upstream testCom
        {
         server localhost:1338;
        }

    server
        {

            listen 80;
            server_name <your ip or domain>;
            location / {

            # proxy_cache   datacache;
            proxy_cache_key $scheme$host$request_method$request_uri;
            proxy_cache_valid       200     60m;
            proxy_cache_min_uses    1;
            proxy_cache_use_stale   updating;

            proxy_pass_header Server;
            proxy_set_header Host $http_host;
            proxy_redirect off;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Scheme $scheme;

            proxy_ignore_headers    Set-Cookie;

            userid          on;
            userid_name     __uid;
            userid_domain   <your ip or domain>;
            userid_path     /;
            userid_expires  max;
            userid_p3p      'policyref="/w3c/p3p.xml", CP="CUR ADM OUR NOR STA NID"';


            add_header Last-Modified $date_gmt;
            add_header Cache-Control 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0';
            if_modified_since off;
            expires off;
            etag off;

            proxy_pass http://testCom;
        }
    }

How to pull specific directory with git

After much looking for an answer, not finding, giving up, trying again and so on, I finally found a solution to this in another SO thread:

How to git-pull all but one folder

To copy-paste what's there:

git init
git remote add -f origin <url>
git config core.sparsecheckout true
echo <dir1>/ >> .git/info/sparse-checkout
echo <dir2>/ >> .git/info/sparse-checkout
echo <dir3>/ >> .git/info/sparse-checkout
git pull origin master

To do what OP wants (work on only one dir), just add that one dir to .git/info/sparse-checkout, when doing the steps above.

Many many thanks to @cforbish !

For div to extend full height

In case also setting the height of the html and the body to 100% makes everything messier for you as it did for me, the following worked for me:

height: calc(100vh - 33rem)

The - 33rem is the height of the elements coming after the one we want to take full height, i.e., 100vh. By subtracting the height, we will make sure there is no overflow and it will always be responsive (assuming we are working with rem instead of px).

Getting a list of all subdirectories in the current directory

I've had a similar question recently, and I found out that the best answer for python 3.6 (as user havlock added) is to use os.scandir. Since it seems there is no solution using it, I'll add my own. First, a non-recursive solution that lists only the subdirectories directly under the root directory.

def get_dirlist(rootdir):

    dirlist = []

    with os.scandir(rootdir) as rit:
        for entry in rit:
            if not entry.name.startswith('.') and entry.is_dir():
                dirlist.append(entry.path)

    dirlist.sort() # Optional, in case you want sorted directory names
    return dirlist

The recursive version would look like this:

def get_dirlist(rootdir):

    dirlist = []

    with os.scandir(rootdir) as rit:
        for entry in rit:
            if not entry.name.startswith('.') and entry.is_dir():
                dirlist.append(entry.path)
                dirlist += get_dirlist(entry.path)

    dirlist.sort() # Optional, in case you want sorted directory names
    return dirlist

keep in mind that entry.path wields the absolute path to the subdirectory. In case you only need the folder name, you can use entry.name instead. Refer to os.DirEntry for additional details about the entry object.

Include files from parent or other directory

You may interest in using php's inbuilt function realpath(). and passing a constant DIR

for example: $TargetDirectory = realpath(__DIR__."/../.."); //Will take you 2 folder's back

String realpath() :: Returns canonicalized absolute pathname ..

MySQL - ERROR 1045 - Access denied

I had the same error, but it was because password_expired was set to Y. You can fix that issue by following the same approach as the currently accepted answer, but instead executing the MySQL query:

UPDATE mysql.user SET password_expired = 'N' WHERE User='root';

How to convert timestamp to datetime in MySQL?

SELECT from_unixtime( UNIX_TIMESTAMP(fild_with_timestamp) ) from "your_table"
This work for me

Difference between & and && in Java?

& is bitwise AND operator comparing bits of each operand.
For example,

int a = 4;
int b = 7;
System.out.println(a & b); // prints 4
//meaning in an 32 bit system
// 00000000 00000000 00000000 00000100
// 00000000 00000000 00000000 00000111
// ===================================
// 00000000 00000000 00000000 00000100


&& is logical AND operator comparing boolean values of operands only. It takes two operands indicating a boolean value and makes a lazy evaluation on them.

What does value & 0xff do in Java?

From http://www.coderanch.com/t/236675/java-programmer-SCJP/certification/xff

The hex literal 0xFF is an equal int(255). Java represents int as 32 bits. It look like this in binary:

00000000 00000000 00000000 11111111

When you do a bit wise AND with this value(255) on any number, it is going to mask(make ZEROs) all but the lowest 8 bits of the number (will be as-is).

... 01100100 00000101 & ...00000000 11111111 = 00000000 00000101

& is something like % but not really.

And why 0xff? this in ((power of 2) - 1). All ((power of 2) - 1) (e.g 7, 255...) will behave something like % operator.

Then
In binary, 0 is, all zeros, and 255 looks like this:

00000000 00000000 00000000 11111111

And -1 looks like this

11111111 11111111 11111111 11111111

When you do a bitwise AND of 0xFF and any value from 0 to 255, the result is the exact same as the value. And if any value higher than 255 still the result will be within 0-255.

However, if you do:

-1 & 0xFF

you get

00000000 00000000 00000000 11111111, which does NOT equal the original value of -1 (11111111 is 255 in decimal).


Few more bit manipulation: (Not related to the question)

X >> 1 = X/2
X << 1 = 2X

Check any particular bit is set(1) or not (0) then

 int thirdBitTobeChecked =   1 << 2   (...0000100)
 int onWhichThisHasTobeTested = 5     (.......101)

 int isBitSet = onWhichThisHasTobeTested  & thirdBitTobeChecked;
 if(isBitSet > 0) {
  //Third Bit is set to 1 
 } 

Set(1) a particular bit

 int thirdBitTobeSet =   1 << 2    (...0000100)
 int onWhichThisHasTobeSet = 2     (.......010)
 onWhichThisHasTobeSet |= thirdBitTobeSet;

ReSet(0) a particular bit

int thirdBitTobeReSet =   ~(1 << 2)  ; //(...1111011)
int onWhichThisHasTobeReSet = 6      ;//(.....000110)
onWhichThisHasTobeReSet &= thirdBitTobeReSet;

XOR

Just note that if you perform XOR operation twice, will results the same value.

byte toBeEncrypted = 0010 0110
byte salt          = 0100 1011

byte encryptedVal  =  toBeEncrypted ^ salt == 0110 1101
byte decryptedVal  =  encryptedVal  ^ salt == 0010 0110 == toBeEncrypted :)

One more logic with XOR is

if     A (XOR) B == C (salt)
then   C (XOR) B == A
       C (XOR) A == B

The above is useful to swap two variables without temp like below

a = a ^ b; b = a ^ b; a = a ^ b;

OR

a ^= b ^= a ^= b;

How to divide flask app into multiple py files?

You can use simple trick which is import flask app variable from main inside another file, like:

test-routes.py

from __main__ import app

@app.route('/test', methods=['GET'])
def test():
    return 'it works!'

and in your main files, where you declared flask app, import test-routes, like:

app.py

from flask import Flask, request, abort

app = Flask(__name__)

# import declared routes
import test-routes

It works from my side.

How to switch from POST to GET in PHP CURL

Make sure that you're putting your query string at the end of your URL when doing a GET request.

$qry_str = "?x=10&y=20";
$ch = curl_init();

// Set query data here with the URL
curl_setopt($ch, CURLOPT_URL, 'http://example.com/test.php' . $qry_str); 

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 3);
$content = trim(curl_exec($ch));
curl_close($ch);
print $content;
With a POST you pass the data via the CURLOPT_POSTFIELDS option instead 
of passing it in the CURLOPT__URL.
-------------------------------------------------------------------------

$qry_str = "x=10&y=20";
curl_setopt($ch, CURLOPT_URL, 'http://example.com/test.php');  
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 3);

// Set request method to POST
curl_setopt($ch, CURLOPT_POST, 1);

// Set query data here with CURLOPT_POSTFIELDS
curl_setopt($ch, CURLOPT_POSTFIELDS, $qry_str);

$content = trim(curl_exec($ch));
curl_close($ch);
print $content;

Note from the curl_setopt() docs for CURLOPT_HTTPGET (emphasis added):

[Set CURLOPT_HTTPGET equal to] TRUE to reset the HTTP request method to GET.
Since GET is the default, this is only necessary if the request method has been changed.

Access-control-allow-origin with multiple domains

Look into the Thinktecture IdentityModel library -- it has full CORS support:

http://brockallen.com/2012/06/28/cors-support-in-webapi-mvc-and-iis-with-thinktecture-identitymodel/

And it can dynamically emit the ACA-Origin you want.

Convert A String (like testing123) To Binary In Java

You can also do this with the ol' good method :

String inputLine = "test123";
String translatedString = null;
char[] stringArray = inputLine.toCharArray();
for(int i=0;i<stringArray.length;i++){
      translatedString += Integer.toBinaryString((int) stringArray[i]);
}

How to prevent the "Confirm Form Resubmission" dialog?

Quick Answer

Use different methods to load the form and save/process form.

Example.

Login.php

Load login form at Login/index Validate login at Login/validate

On Success

Redirect the user to User/dashboard

On failure

Redirect the user to login/index

SSL "Peer Not Authenticated" error with HttpClient 4.1

This is thrown when

... the peer was not able to identify itself (for example; no certificate, the particular cipher suite being used does not support authentication, or no peer authentication was established during SSL handshaking) this exception is thrown.

Probably the cause of this exception (where is the stacktrace) will show you why this exception is thrown. Most likely the default keystore shipped with Java does not contain (and trust) the root certificate of the TTP that is being used.

The answer is to retrieve the root certificate (e.g. from your browsers SSL connection), import it into the cacerts file and trust it using keytool which is shipped by the Java JDK. Otherwise you will have to assign another trust store programmatically.

C# binary literals

If you look at the language feature implementation status of the .NET Compiler Platform ("Roslyn") you can clearly see that in C# 6.0 this is a planned feature, so in the next release we can do it in the usual way.

Binary literal status

How to clear textarea on click?

Try:

<input name="mytextbox" onfocus="if (this.value=='Please describe why') this.value = ''" type="text" value="Please Describe why">

Check if a number has a decimal place/is a whole number

Simple, but effective!

Math.floor(number) === number;

How to get index in Handlebars each helper?

In handlebar version 4.0 onwards,

{{#list array}}
  {{@index}} 
{{/list}}

How to vertically align label and input in Bootstrap 3?

None of these solutions worked for me. But I was able to get vertical centering by using <div class="form-row align-items-center"> for each form row, per the Bootstrap examples.

pycharm convert tabs to spaces automatically

For me it was having a file called ~/.editorconfig that was overriding my tab settings. I removed that (surely that will bite me again someday) but it fixed my pycharm issue

What's a decent SFTP command-line client for windows?

WinSCP can be called from batch file:

"C:\Program Files\WinSCP\WinSCP.exe" /console

Example commands:

option batch on 
option confirm off  
option transfer binary 
open sftp://username@hostname:port -hostkey="ssh-rsa " 

How to dynamically load a Python class

In Google App Engine there is a webapp2 function called import_string. For more info see here:https://webapp-improved.appspot.com/api/webapp2.html

So,

import webapp2
my_class = webapp2.import_string('my_package.my_module.MyClass')

For example this is used in the webapp2.Route where you can either use a handler or a string.

How to retrieve available RAM from Windows command line?

Try MemLog. It does the job perfectly and quickly.

Download via one of many mirrors, e.g. this one: SoftPedia page for MemLog.
(MemLog's author has a web site. But this is down some times. Wayback machine snapshot here.)

Example output:

C:\>memlog
2012/02/01,13:22:02,878956544,-1128333312,2136678400,2138578944,-17809408,2147352576

878956544 being the free memory

Measuring code execution time

Stopwatch measures time elapsed.

// Create new stopwatch
Stopwatch stopwatch = new Stopwatch();

// Begin timing
stopwatch.Start();

Threading.Thread.Sleep(500)

// Stop timing
stopwatch.Stop();

Console.WriteLine("Time elapsed: {0}", stopwatch.Elapsed);

Here is a DEMO.

using setTimeout on promise chain

If you are inside a .then() block and you want to execute a settimeout()

            .then(() => {
                console.log('wait for 10 seconds . . . . ');
                return new Promise(function(resolve, reject) { 
                    setTimeout(() => {
                        console.log('10 seconds Timer expired!!!');
                        resolve();
                    }, 10000)
                });
            })
            .then(() => {
                console.log('promise resolved!!!');

            })

output will as shown below

wait for 10 seconds . . . .
10 seconds Timer expired!!!
promise resolved!!!

Happy Coding!

How to loop over directories in Linux?

The technique I use most often is find | xargs. For example, if you want to make every file in this directory and all of its subdirectories world-readable, you can do:

find . -type f -print0 | xargs -0 chmod go+r
find . -type d -print0 | xargs -0 chmod go+rx

The -print0 option terminates with a NULL character instead of a space. The -0 option splits its input the same way. So this is the combination to use on files with spaces.

You can picture this chain of commands as taking every line output by find and sticking it on the end of a chmod command.

If the command you want to run as its argument in the middle instead of on the end, you have to be a bit creative. For instance, I needed to change into every subdirectory and run the command latemk -c. So I used (from Wikipedia):

find . -type d -depth 1 -print0 | \
    xargs -0 sh -c 'for dir; do pushd "$dir" && latexmk -c && popd; done' fnord

This has the effect of for dir $(subdirs); do stuff; done, but is safe for directories with spaces in their names. Also, the separate calls to stuff are made in the same shell, which is why in my command we have to return back to the current directory with popd.

Easy way to convert a unicode list to a list containing python strings?

Just json.dumps will fix the problem

json.dumps function actually converts all the unicode literals to string literals and it will be easy for us to load the data either in json file or csv file.

sample code:

import json
EmployeeList =  [u'1001', u'Karick', u'14-12-2020', u'1$']
result_list = json.dumps(EmployeeList)
print result_list

output: ["1001", "Karick", "14-12-2020", "1$"]

C++ [Error] no matching function for call to

You are trying to call DeckOfCards::shuffle with a deckOfCards parameter:

deckOfCards cardDeck; // create DeckOfCards object
cardDeck.shuffle(cardDeck); // shuffle the cards in the deck

But the method takes a vector<Card>&:

void deckOfCards::shuffle(vector<Card>& deck)

The compiler error messages are quite clear on this. I'll paraphrase the compiler as it talks to you.

Error:

[Error] no matching function for call to 'deckOfCards::shuffle(deckOfCards&)'

Paraphrased:

Hey, pal. You're trying to call a function called shuffle which apparently takes a single parameter of type reference-to-deckOfCards, but there is no such function.

Error:

[Note] candidate is:

In file included from main.cpp

[Note] void deckOfCards::shuffle(std::vector&)

Paraphrased:

I mean, maybe you meant this other function called shuffle, but that one takes a reference-tovector<something>.

Error:

[Note] no known conversion for argument 1 from 'deckOfCards' to 'std::vector&'

Which I'd be happy to call if I knew how to convert from a deckOfCards to a vector; but I don't. So I won't.

Constants in Objective-C

There is also one thing to mention. If you need a non global constant, you should use static keyword.

Example

// In your *.m file
static NSString * const kNSStringConst = @"const value";

Because of the static keyword, this const is not visible outside of the file.


Minor correction by @QuinnTaylor: static variables are visible within a compilation unit. Usually, this is a single .m file (as in this example), but it can bite you if you declare it in a header which is included elsewhere, since you'll get linker errors after compilation

How to read until end of file (EOF) using BufferedReader in Java?

With text files, maybe the EOF is -1 when using BufferReader.read(), char by char. I made a test with BufferReader.readLine()!=null and it worked properly.

Rename computer and join to domain in one step with PowerShell

You can just use Add-Computer, there is a parameter for "-NewName"

Example: Add-Computer -DomainName MYLAB.Local -ComputerName TARGETCOMPUTER -newname NewTARGETCOMPUTER

You might want to check also the parameter "-OPTIONS"

http://technet.microsoft.com/en-us/library/hh849798.aspx

Get exception description and stack trace which caused an exception, all as a string

For Python 3.5+:

So, you can get the stacktrace from your exception as from any other exception. Use traceback.TracebackException for it (just replace ex with your exception):

print("".join(traceback.TracebackException.from_exception(ex).format())

An extended example and other features to do this:

import traceback

try:
    1/0
except Exception as ex:
    print("".join(traceback.TracebackException.from_exception(ex).format()) == traceback.format_exc() == "".join(traceback.format_exception(type(ex), ex, ex.__traceback__))) # This is True !!
    print("".join(traceback.TracebackException.from_exception(ex).format()))

The output will be something like this:

True
Traceback (most recent call last):
  File "untidsfsdfsdftled.py", line 29, in <module>
    1/0
ZeroDivisionError: division by zero

jQuery Ajax simple call

You could also make the ajax call more generic, reusable, so you can call it from different CRUD(create, read, update, delete) tasks for example and treat the success cases from those calls.

makePostCall = function (url, data) { // here the data and url are not hardcoded anymore
   var json_data = JSON.stringify(data);

    return $.ajax({
        type: "POST",
        url: url,
        data: json_data,
        dataType: "json",
        contentType: "application/json;charset=utf-8"
    });
}

// and here a call example
makePostCall("index.php?action=READUSERS", {'city' : 'Tokio'})
    .success(function(data){
               // treat the READUSERS data returned
   })
    .fail(function(sender, message, details){
           alert("Sorry, something went wrong!");
  });

how to get rid of notification circle in right side of the screen?

This stuff comes from ES file explorer

Just go into this app > settings

Then there is an option that says logging floating window, you just need to disable that and you will get rid of this infernal bubble for good

Apache Tomcat Not Showing in Eclipse Server Runtime Environments

Scenario 1: You had Eclipse showing server and now after removing the particular version you want to configure at Eclipse a new local server instance. But you can not move further.

This happens due to reason Eclipse still looks for configured version of Tomcat directory, which directory is no longer there.

There is no need till LUNA to make fresh installation!

All we need is to REPLACE the new server run time environment into eclipse after removing old one, which is non-existent. Eclipse will

enter image description here

Class constructor type in typescript?

Like that:

class Zoo {
    AnimalClass: typeof Animal;

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

Or just:

class Zoo {
    constructor(public AnimalClass: typeof Animal ) {
        let Hector = new AnimalClass();
    }
}

typeof Class is the type of the class constructor. It's preferable to the custom constructor type declaration because it processes static class members properly.

Here's the relevant part of TypeScript docs. Search for the typeof. As a part of a TypeScript type annotation, it means "give me the type of the symbol called Animal" which is the type of the class constructor function in our case.

How to pass the -D System properties while testing on Eclipse?

You can use java System.properties, for using them from eclipse you could:

  1. Add -Dlabel="label_value" in the VM arguments of the test Run Configuration like this:

eclipse_vm_config

  1. Then run the test:

    import org.junit.Test;
    import static org.junit.Assert.assertEquals;
    
    public class Main {
        @Test
        public void test(){
            System.out.println(System.getProperty("label"));
            assertEquals("label_value", System.getProperty("label"));
        }
    }
    
  2. Finally it should pass the test and output this in the console:

    label_value
    

Force hide address bar in Chrome on Android

Check this has everything you need

http://www.html5rocks.com/en/mobile/fullscreen/

The Chrome team has recently implemented a feature that tells the browser to launch the page fullscreen when the user has added it to the home screen. It is similar to the iOS Safari model.

<meta name="mobile-web-app-capable" content="yes">

How to scale Docker containers in production

Panamax: Docker Management for Humans. panamax.io

Fig: Fast, isolated development environments using Docker. fig.sh

sed whole word search and replace

On Mac OS X, neither of these regex syntaxes work inside sed for matching whole words

  • \bmyWord\b
  • \<myWord\>

Hear me now and believe me later, this ugly syntax is what you need to use:

  • /[[:<:]]myWord[[:>:]]/

So, for example, to replace mint with minty for whole words only:

  • sed "s/[[:<:]]mint[[:>:]]/minty/g"

Source: re_format man page

Adding placeholder attribute using Jquery

This line of code might not work in IE 8 because of native support problems.

$(".hidden").attr("placeholder", "Type here to search");

You can try importing a JQuery placeholder plugin for this task. Simply import it to your libraries and initiate from the sample code below.

$('input, textarea').placeholder();

How to communicate between iframe and the parent site?

You can also use

postMessage(message, '*');

How to use a keypress event in AngularJS?

You can also apply it to a controller on a parent element. This example can be used to highlight a row in a table by pressing up/down arrow keys.

app.controller('tableCtrl', [ '$scope', '$element', function($scope, $element) {
  $scope.index = 0; // row index
  $scope.data = []; // array of items
  $scope.keypress = function(offset) {
    console.log('keypress', offset);
    var i = $scope.index + offset;
    if (i < 0) { i = $scope.data.length - 1; }
    if (i >= $scope.data.length) { i = 0; }
  };
  $element.bind("keydown keypress", function (event) {
    console.log('keypress', event, event.which);
    if(event.which === 38) { // up
      $scope.keypress(-1);
    } else if (event.which === 40) { // down
      $scope.keypress(1);
    } else {
      return;
    }
    event.preventDefault();
  });
}]);


<table class="table table-striped" ng-controller="tableCtrl">
<thead>
    <tr>
        <th ng-repeat="(key, value) in data[0]">{{key}}</th>
    </tr>
</thead>
<tbody>
    <tr ng-repeat="row in data track by $index" ng-click="draw($index)" ng-class="$index == index ? 'info' : ''">
        <td ng-repeat="(key, value) in row">{{value}}</td>
    </tr>
</tbody>
</table>

How to deserialize xml to object

The comments above are correct. You're missing the decorators. If you want a generic deserializer you can use this.

public static T DeserializeXMLFileToObject<T>(string XmlFilename)
{
    T returnObject = default(T);
    if (string.IsNullOrEmpty(XmlFilename)) return default(T);

    try
    {
        StreamReader xmlStream = new StreamReader(XmlFilename);
        XmlSerializer serializer = new XmlSerializer(typeof(T));
        returnObject = (T)serializer.Deserialize(xmlStream);
    }
    catch (Exception ex)
    {
        ExceptionLogger.WriteExceptionToConsole(ex, DateTime.Now);
    }
    return returnObject;
}

Then you'd call it like this:

MyObjType MyObj = DeserializeXMLFileToObject<MyObjType>(FilePath);

Async always WaitingForActivation

I had the same problem. The answers got me on the right track. So the problem is that functions marked with async don't return a task of the function itself as expected (but another continuation task of the function).

So its the "await"and "async" keywords that screws thing up. The simplest solution then is simply to remove them. Then it works as expected. As in:

static void Main(string[] args)
{
    Console.WriteLine("Foo called");
    var result = Foo(5);

    while (result.Status != TaskStatus.RanToCompletion)
    {
        Console.WriteLine("Thread ID: {0}, Status: {1}", Thread.CurrentThread.ManagedThreadId, result.Status);
        Task.Delay(100).Wait();
    }

    Console.WriteLine("Result: {0}", result.Result);
    Console.WriteLine("Finished.");
    Console.ReadKey(true);
}

private static Task<string> Foo(int seconds)
{
    return Task.Run(() =>
    {
        for (int i = 0; i < seconds; i++)
        {
            Console.WriteLine("Thread ID: {0}, second {1}.", Thread.CurrentThread.ManagedThreadId, i);
            Task.Delay(TimeSpan.FromSeconds(1)).Wait();
        }

        return "Foo Completed.";
    });
}

Which outputs:

Foo called
Thread ID: 1, Status: WaitingToRun
Thread ID: 3, second 0.
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 3, second 1.
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 3, second 2.
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 3, second 3.
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 3, second 4.
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Result: Foo Completed.
Finished.

MavenError: Failed to execute goal on project: Could not resolve dependencies In Maven Multimodule project

In my case I forgot it was packaging conflict jar vs pom. I forgot to write

<packaging>pom</packaging>

In every child pom.xml file

Use async await with Array.map

A solution using modern-async's map():

import { map } from 'modern-async'

...
const result = await map(myArray, async (v) => {
    ...
})

The advantage of using that library is that you can control the concurrency using mapLimit() or mapSeries().

How can I add a vertical scrollbar to my div automatically?

I'm not quite sure what you're attempting to use the div for, but this is an example with some random text.

Mr_Green gave the correct instructions when he said to add overflow-y: auto as that restricts it to vertical scrolling. This is a JSFiddle example:

JSFiddle

Why should C++ programmers minimize use of 'new'?

new() shouldn't be used as little as possible. It should be used as carefully as possible. And it should be used as often as necessary as dictated by pragmatism.

Allocation of objects on the stack, relying on their implicit destruction, is a simple model. If the required scope of an object fits that model then there's no need to use new(), with the associated delete() and checking of NULL pointers. In the case where you have lots of short-lived objects allocation on the stack should reduce the problems of heap fragmentation.

However, if the lifetime of your object needs to extend beyond the current scope then new() is the right answer. Just make sure that you pay attention to when and how you call delete() and the possibilities of NULL pointers, using deleted objects and all of the other gotchas that come with the use of pointers.

Is Spring annotation @Controller same as @Service?

I already answered similar question on here Here is the Link

No both are different.

@Service annotation have use for other purpose and @Controller use for other. Actually Spring @Component, @Service, @Repository and @Controller annotations are used for automatic bean detection using classpath scan in Spring framework, but it doesn't ,mean that all functionalities are same. @Service: It indicates annotated class is a Service component in the business layer.

@Controller: Annotated class indicates that it is a controller components, and mainly used at presentation layer.

Mongoose and multiple database in single node.js project

According to the fine manual, createConnection() can be used to connect to multiple databases.

However, you need to create separate models for each connection/database:

var conn      = mongoose.createConnection('mongodb://localhost/testA');
var conn2     = mongoose.createConnection('mongodb://localhost/testB');

// stored in 'testA' database
var ModelA    = conn.model('Model', new mongoose.Schema({
  title : { type : String, default : 'model in testA database' }
}));

// stored in 'testB' database
var ModelB    = conn2.model('Model', new mongoose.Schema({
  title : { type : String, default : 'model in testB database' }
}));

I'm pretty sure that you can share the schema between them, but you have to check to make sure.

Text to speech(TTS)-Android

Text to speech is built into Android 1.6+. Here is a simple example of how to do it.

TextToSpeech tts = new TextToSpeech(this, this);
tts.setLanguage(Locale.US);
tts.speak("Text to say aloud", TextToSpeech.QUEUE_ADD, null);

More info: http://android-developers.blogspot.com/2009/09/introduction-to-text-to-speech-in.html


Here are instructions on how to download sample code from the Android SDK Manager:

  1. Launch the Android SDK Manager.

    a. On Windows, double-click the SDK Manager.exe file at the root of the Android SDK directory.

    b. On Mac or Linux, open a terminal to the tools/ directory in the Android SDK, then execute android sdk.

  2. Expand the list of packages for the latest Android platform.

  3. Select and download Samples for SDK. When the download is complete, you can find the source code for all samples at this location:

/sdk/samples/android-version/

(i.e. \android-sdk-windows\samples\android-16\ApiDemos\src\com\example\android\apis\app\TextToSpeechActivity.java)

Change the color of a checked menu item in a navigation drawer

Well you can achieve this using Color State Resource. If you notice inside your NavigationView you're using

app:itemIconTint="@color/black"
app:itemTextColor="@color/primary_text"

Here instead of using @color/black or @color/primary_test, use a Color State List Resource. For that, first create a new xml (e.g drawer_item.xml) inside color directory (which should be inside res directory.) If you don't have a directory named color already, create one.

Now inside drawer_item.xml do something like this

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:color="checked state color" android:state_checked="true" />
    <item android:color="your default color" />
</selector>

Final step would be to change your NavigationView

<android.support.design.widget.NavigationView
    android:id="@+id/activity_main_navigationview"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    app:headerLayout="@layout/drawer_header"
    app:itemIconTint="@color/drawer_item"  // notice here
    app:itemTextColor="@color/drawer_item" // and here
    app:itemBackground="@android:color/transparent"// and here for setting the background color to tranparent
    app:menu="@menu/menu_drawer">

Like this you can use separate Color State List Resources for IconTint, ItemTextColor, ItemBackground.

Now when you set an item as checked (either in xml or programmatically), the particular item will have different color than the unchecked ones.

How do I cast a string to integer and have 0 in case of error in the cast with PostgreSQL?

I found the following code easy and working. Original answer is here https://www.postgresql.org/message-id/[email protected]

prova=> create table test(t text, i integer);
CREATE

prova=> insert into test values('123',123);
INSERT 64579 1

prova=> select cast(i as text),cast(t as int)from test;
text|int4
----+----
123| 123
(1 row)

hope it helps

How to get process ID of background process?

this is what I have done. Check it out, hope it can help.

#!/bin/bash
#
# So something to show.
echo "UNO" >  UNO.txt
echo "DOS" >  DOS.txt
#
# Initialize Pid List
dPidLst=""
#
# Generate background processes
tail -f UNO.txt&
dPidLst="$dPidLst $!"
tail -f DOS.txt&
dPidLst="$dPidLst $!"
#
# Report process IDs
echo PID=$$
echo dPidLst=$dPidLst
#
# Show process on current shell
ps -f
#
# Start killing background processes from list
for dPid in $dPidLst
do
        echo killing $dPid. Process is still there.
        ps | grep $dPid
        kill $dPid
        ps | grep $dPid
        echo Just ran "'"ps"'" command, $dPid must not show again.
done

Then just run it as: ./bgkill.sh with proper permissions of course

root@umsstd22 [P]:~# ./bgkill.sh
PID=23757
dPidLst= 23758 23759
UNO
DOS
UID        PID  PPID  C STIME TTY          TIME CMD
root      3937  3935  0 11:07 pts/5    00:00:00 -bash
root     23757  3937  0 11:55 pts/5    00:00:00 /bin/bash ./bgkill.sh
root     23758 23757  0 11:55 pts/5    00:00:00 tail -f UNO.txt
root     23759 23757  0 11:55 pts/5    00:00:00 tail -f DOS.txt
root     23760 23757  0 11:55 pts/5    00:00:00 ps -f
killing 23758. Process is still there.
23758 pts/5    00:00:00 tail
./bgkill.sh: line 24: 23758 Terminated              tail -f UNO.txt
Just ran 'ps' command, 23758 must not show again.
killing 23759. Process is still there.
23759 pts/5    00:00:00 tail
./bgkill.sh: line 24: 23759 Terminated              tail -f DOS.txt
Just ran 'ps' command, 23759 must not show again.
root@umsstd22 [P]:~# ps -f
UID        PID  PPID  C STIME TTY          TIME CMD
root      3937  3935  0 11:07 pts/5    00:00:00 -bash
root     24200  3937  0 11:56 pts/5    00:00:00 ps -f

SCCM 2012 application install "Failed" in client Software Center

The execmgr.log will show the commandline and ccmcache folder used for installation. Typically, required apps don't show on appenforce.log and some clients will have outdated appenforce or no ppenforce.log files. execmgr.log also shows required hidden uninstall actions as well.

You may want to save the blog link. I still reference it from time to time.

Format bytes to kilobytes, megabytes, gigabytes

function formatBytes($bytes, $precision = 2) { 
    $units = array('B', 'KB', 'MB', 'GB', 'TB'); 

    $bytes = max($bytes, 0); 
    $pow = floor(($bytes ? log($bytes) : 0) / log(1024)); 
    $pow = min($pow, count($units) - 1); 

    // Uncomment one of the following alternatives
    // $bytes /= pow(1024, $pow);
    // $bytes /= (1 << (10 * $pow)); 

    return round($bytes, $precision) . ' ' . $units[$pow]; 
} 

(Taken from php.net, there are many other examples there, but I like this one best :-)

Where is the .NET Framework 4.5 directory?

Whilst the above answers are correct its worth noting that MSBuild has changed and it no longer ships with the .net framework, it comes either stand alone or with visual studio. As a result it's binaries have moved... so the one you get under the 4.0.303619 directory is actually the old one!

I've just been caught out by this - I found automatic binding redirects were only working when running from VisualStudio but not when running msbuild from the command line... the clue was that binding redirects were added in VS 2013 (for that read .net framework 4.5). If you open up a vs command prompt you'll see it now gets it from program files as the other article mentions. Whereas I was using a batch file on my path which linked to the old version.

Version numbers

Under framework:

PS C:\Windows\Microsoft.NET\Framework\v4.0.30319> .\msbuild.exe -version
Microsoft (R) Build Engine version 4.0.30319.33440
[Microsoft .NET Framework, version 4.0.30319.34014]
Copyright (C) Microsoft Corporation. All rights reserved.

4.0.30319.33440PS C:\Windows\Microsoft.NET\Framework\v4.0.30319>

Under program files:

PS C:\Program Files (x86)\MSBuild\12.0\Bin> .\MSBuild.exe -version
Microsoft (R) Build Engine version 12.0.21005.1
[Microsoft .NET Framework, version 4.0.30319.34014]
Copyright (C) Microsoft Corporation. All rights reserved.

12.0.21005.1PS C:\Program Files (x86)\MSBuild\12.0\Bin>

When to use React "componentDidUpdate" method?

componentDidUpdate(prevProps){ 

    if (this.state.authToken==null&&prevProps.authToken==null) {
      AccountKit.getCurrentAccessToken()
      .then(token => {
        if (token) {
          AccountKit.getCurrentAccount().then(account => {
            this.setState({
              authToken: token,
              loggedAccount: account
            });
          });
        } else {
          console.log("No user account logged");
        }
      })
      .catch(e => console.log("Failed to get current access token", e));

    }
}

JavaScript - populate drop down list with array

Something like this should work:

var dropdown = document.getElementById("dropdown1");
if (dropdown) {
    for (var i=0; i < month.length;++i){    
        addOption(dropdown, month[i], month[i]);
    }
}

addOption = function(selectbox, text, value) {
    var optn = document.createElement("OPTION");
    optn.text = text;
    optn.value = value;
    selectbox.options.add(optn);  
}

You can refer to this article for more details:
http://www.plus2net.com/javascript_tutorial/list-adding.php

how to pass value from one php page to another using session

Solution using just POST - no $_SESSION

page1.php

<form action="page2.php" method="post">
    <textarea name="textarea1" id="textarea1"></textarea><br />
    <input type="submit" value="submit" />
</form>

page2.php

<?php
    // this page outputs the contents of the textarea if posted
    $textarea1 = ""; // set var to avoid errors
    if(isset($_POST['textarea1'])){
        $textarea1 = $_POST['textarea1']
    }
?>
<textarea><?php echo $textarea1;?></textarea>

Solution using $_SESSION and POST

page1.php

<?php

    session_start(); // needs to be before anything else on page to use $_SESSION
    $textarea1 = "";
    if(isset($_POST['textarea1'])){
        $_SESSION['textarea1'] = $_POST['textarea1'];
    }

?>


<form action="page1.php" method="post">
    <textarea name="textarea1" id="textarea1"></textarea><br />
    <input type="submit" value="submit" />
</form>
<br /><br />
<a href="page2.php">Go to page2</a>

page2.php

<?php
    session_start(); // needs to be before anything else on page to use $_SESSION
    // this page outputs the textarea1 from the session IF it exists
    $textarea1 = ""; // set var to avoid errors
    if(isset($_SESSION['textarea1'])){
        $textarea1 = $_SESSION['textarea1']
    }
?>
<textarea><?php echo $textarea1;?></textarea>

WARNING!!! - This contains no validation!!!

PHP preg_replace special characters

$newstr = preg_replace('/[^a-zA-Z0-9\']/', '_', "There wouldn't be any");
$newstr = str_replace("'", '', $newstr);

I put them on two separate lines to make the code a little more clear.

Note: If you're looking for Unicode support, see Filip's answer below. It will match all characters that register as letters in addition to A-z.

SQL Server - Return value after INSERT

Entity Framework performs something similar to gbn's answer:

DECLARE @generated_keys table([Id] uniqueidentifier)

INSERT INTO Customers(FirstName)
OUTPUT inserted.CustomerID INTO @generated_keys
VALUES('bob');

SELECT t.[CustomerID]
FROM @generated_keys AS g 
   JOIN dbo.Customers AS t 
   ON g.Id = t.CustomerID
WHERE @@ROWCOUNT > 0

The output results are stored in a temporary table variable, and then selected back to the client. Have to be aware of the gotcha:

inserts can generate more than one row, so the variable can hold more than one row, so you can be returned more than one ID

I have no idea why EF would inner join the ephemeral table back to the real table (under what circumstances would the two not match).

But that's what EF does.

SQL Server 2008 or newer only. If it's 2005 then you're out of luck.

Differences between Microsoft .NET 4.0 full Framework and Client Profile

What's new in .NET Framework 4 Client Profile RTM explains many of the differences:

When to use NET4 Client Profile and when to use NET4 Full Framework?
NET4 Client Profile:
Always target NET4 Client Profile for all your client desktop applications (including Windows Forms and WPF apps).

NET4 Full framework:
Target NET4 Full only if the features or assemblies that your app need are not included in the Client Profile. This includes:

  • If you are building Server apps. Such as:
    o ASP.Net apps
    o Server-side ASMX based web services
  • If you use legacy client scenarios. Such as:
    o Use System.Data.OracleClient.dll which is deprecated in NET4 and not included in the Client Profile.
    o Use legacy Windows Workflow Foundation 3.0 or 3.5 (WF3.0 , WF3.5)
  • If you targeting developer scenarios and need tool such as MSBuild or need access to design assemblies such as System.Design.dll

However, as stated on MSDN, this is not relevant for >=4.5:

Starting with the .NET Framework 4.5, the Client Profile has been discontinued and only the full redistributable package is available. Optimizations provided by the .NET Framework 4.5, such as smaller download size and faster deployment, have eliminated the need for a separate deployment package. The single redistributable streamlines the installation process and simplifies your app's deployment options.

Laravel - check if Ajax request

$request->wantsJson()

You can try $request->wantsJson() if $request->ajax() does not work

$request->ajax() works if your JavaScript library sets an X-Requested-With HTTP header.

By default Laravel set this header in js/bootstrap.js

window.axios = require('axios');

window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

In my case, I used a different frontend code and I had to put this header manually for $request->ajax() to work.

But $request->wantsJson() will check the axios query without the need for a header X-Requested-With:

// Determine if the current request is asking for JSON. This checks Content-Type equals application/json.
$request->wantsJson()
// or 
\Request::wantsJson() // not \Illuminate\Http\Request

Label axes on Seaborn Barplot

One can avoid the AttributeError brought about by set_axis_labels() method by using the matplotlib.pyplot.xlabel and matplotlib.pyplot.ylabel.

matplotlib.pyplot.xlabel sets the x-axis label while the matplotlib.pyplot.ylabel sets the y-axis label of the current axis.

Solution code:

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

fake = pd.DataFrame({'cat': ['red', 'green', 'blue'], 'val': [1, 2, 3]})
fig = sns.barplot(x = 'val', y = 'cat', data = fake, color = 'black')
plt.xlabel("Colors")
plt.ylabel("Values")
plt.title("Colors vs Values") # You can comment this line out if you don't need title
plt.show(fig)

Output figure:

enter image description here

Print all but the first three columns

Pretty much all the answers currently add either leading spaces, trailing spaces or some other separator issue. To select from the fourth field where the separator is whitespace and the output separator is a single space using awk would be:

awk '{for(i=4;i<=NF;i++)printf "%s",$i (i==NF?ORS:OFS)}' file

To parametrize the starting field you could do:

awk '{for(i=n;i<=NF;i++)printf "%s",$i (i==NF?ORS:OFS)}' n=4 file

And also the ending field:

awk '{for(i=n;i<=m=(m>NF?NF:m);i++)printf "%s",$i (i==m?ORS:OFS)}' n=4 m=10 file

How do you send an HTTP Get Web Request in Python?

You can use urllib2

import urllib2
content = urllib2.urlopen(some_url).read()
print content

Also you can use httplib

import httplib
conn = httplib.HTTPConnection("www.python.org")
conn.request("HEAD","/index.html")
res = conn.getresponse()
print res.status, res.reason
# Result:
200 OK

or the requests library

import requests
r = requests.get('https://api.github.com/user', auth=('user', 'pass'))
r.status_code
# Result:
200

Exception thrown in catch and finally clause

I think this solve the problem :

boolean allOk = false;
try{
  q();
  allOk = true;
} finally {
  try {
     is.close();
  } catch (Exception e) {
     if(allOk) {
       throw new SomeException(e);
     }
  }
}

How to get xdebug var_dump to show full object/array

I know this is late but it might be of some use:

echo "<pre>";
print_r($array);
echo "</pre>";

accessing a file using [NSBundle mainBundle] pathForResource: ofType:inDirectory:

When I drag files in, the "Add to targets" box seems to be un-ticked by default. If I leave it un-ticked then I have the problem described. Fix it by deleting the files then dragging them back in but making sure to tick "Add to targets". enter image description here

Python math module

In

from math import sqrt

Using sqrt(4) works perfectly well. You need to only use math.sqrt(4) when you just use "import math".

How can I uninstall npm modules in Node.js?

Sometimes npm uninstall -g packageName doesn’t work.

In this case you can delete package manually.

On Mac, go to folder /usr/local/lib/node_modules and delete the folder with the package you want. That's it. Check your list of globally installed packages with this command:

npm list -g --depth=0

How to install a specific version of package using Composer?

Suppose you want to install Laravel Collective. It's currently at version 6.x but you want version 5.8. You can run the following command:

composer require "laravelcollective/html":"^5.8.0"

A good example is shown here in the documentation: https://laravelcollective.com/docs/5.5/html

Android Studio - Unable to find valid certification path to requested target

Even though this question is very old, many must be facing the same issue, so I would like to state how I fixed this.

The problem is classpath 'com.android.tools.build:gradle:0.13.2' By above line in build.gradle you are asking it to find a particular version of gradle but this version is not there in your machine. The best it to change the above line to

classpath 'com.android.tools.build:gradle:+'

filter: progid:DXImageTransform.Microsoft.gradient is not working in ie7

Having seen your fiddle in the comments the issue is quite easy to fix. You just need to add overflow:auto or set a specific height to your div. Live example: http://jsfiddle.net/tw16/xRcXL/3/

.Tab{
    overflow:auto; /* add this */
    border:solid 1px #faa62a;
    border-bottom:none;
    padding:7px 10px;
    background:-moz-linear-gradient(center top , #FAD59F, #FA9907) repeat scroll 0 0 transparent;
    background:-webkit-gradient(linear, left top, left bottom, from(#fad59f), to(#fa9907));
    filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=#fad59f, endColorstr=#fa9907);    
    -ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#fad59f, endColorstr=#fa9907)";
}

How to delete all rows from all tables in a SQL Server database?

Note that TRUNCATE won't work if you have any referential integrity set.

In that case, this will work:

EXEC sp_MSForEachTable 'DISABLE TRIGGER ALL ON ?'
GO
EXEC sp_MSForEachTable 'ALTER TABLE ? NOCHECK CONSTRAINT ALL'
GO
EXEC sp_MSForEachTable 'DELETE FROM ?'
GO
EXEC sp_MSForEachTable 'ALTER TABLE ? CHECK CONSTRAINT ALL'
GO
EXEC sp_MSForEachTable 'ENABLE TRIGGER ALL ON ?'
GO

Edit: To be clear, the ? in the statements is a ?. It's replaced with the table name by the sp_MSForEachTable procedure.

Amazon S3 upload file and get URL

Below method uploads file in a particular folder in a bucket and return the generated url of the file uploaded.

private String uploadFileToS3Bucket(final String bucketName, final File file) {
    final String uniqueFileName = uploadFolder + "/" + file.getName();
    LOGGER.info("Uploading file with name= " + uniqueFileName);
    final PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, uniqueFileName, file);
    amazonS3.putObject(putObjectRequest);
    return ((AmazonS3Client) amazonS3).getResourceUrl(bucketName, uniqueFileName);
}

Print an integer in binary format in Java

System.out.println(Integer.toBinaryString(343));

How to check what version of jQuery is loaded?

I have found this to be the shortest and simplest way to check if jQuery is loaded:

if (window.jQuery) {
    // jQuery is available.

    // Print the jQuery version, e.g. "1.0.0":
    console.log(window.jQuery.fn.jquery);
}

This method is used by http://html5boilerplate.com and others.

How to show all shared libraries used by executables in Linux?

I found this post very helpful as I needed to investigate dependencies from a 3rd party supplied library (32 vs 64 bit execution path(s)).

I put together a Q&D recursing bash script based on the 'readelf -d' suggestion on a RHEL 6 distro.

It is very basic and will test every dependency every time even if it might have been tested before (i.e very verbose). Output is very basic too.

#! /bin/bash

recurse ()
# Param 1 is the nuumber of spaces that the output will be prepended with
# Param 2 full path to library
{
#Use 'readelf -d' to find dependencies
dependencies=$(readelf -d ${2} | grep NEEDED | awk '{ print $5 }' | tr -d '[]')
for d in $dependencies; do
   echo "${1}${d}"
   nm=${d##*/}
   #libstdc++ hack for the '+'-s
   nm1=${nm//"+"/"\+"}
   # /lib /lib64 /usr/lib and /usr/lib are searched
   children=$(locate ${d} | grep -E "(^/(lib|lib64|usr/lib|usr/lib64)/${nm1})")
   rc=$?
   #at least locate... didn't fail
   if [ ${rc} == "0" ] ; then
      #we have at least one dependency
      if [ ${#children[@]} -gt 0 ]; then
         #check the dependeny's dependencies
         for c in $children; do
          recurse "  ${1}" ${c}
         done
      else
         echo "${1}no children found"
      fi
   else
      echo "${1}locate failed for ${d}"
   fi
done
}
# Q&D -- recurse needs 2 params could/should be supplied from cmdline
recurse "" !!full path to library you want to investigate!!

redirect the output to a file and grep for 'found' or 'failed'

Use and modify, at your own risk of course, as you wish.

get selected value in datePicker and format it

$('#scheduleDate').datepicker({ dateFormat : 'dd, MM, yy'});

var dateFormat = $('#scheduleDate').datepicker('option', 'dd, MM, yy');

$('#scheduleDate').datepicker('option', 'dateFormat', 'dd, MM, yy');

var result = $('#scheduleDate').val();

alert('result: ' + result);

result: 20, April, 2012

Error: Address already in use while binding socket with address but the port number is shown free by `netstat`

I know its been a while since the question was asked but I was able to find a solution:

int sockfd;
int option = 1;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &option, sizeof(option));

This set the socket able to be reused immediately.

I apologize if this is "wrong". I'm not very experienced with sockets

How can I measure the similarity between two images?

Use a normalised colour histogram. (Read the section on applications here), they are commonly used in image retrieval/matching systems and are a standard way of matching images that is very reliable, relatively fast and very easy to implement.

Essentially a colour histogram will capture the colour distribution of the image. This can then be compared with another image to see if the colour distributions match.

This type of matching is pretty resiliant to scaling (once the histogram is normalised), and rotation/shifting/movement etc.

Avoid pixel-by-pixel comparisons as if the image is rotated/shifted slightly it may lead to a large difference being reported.

Histograms would be straightforward to generate yourself (assuming you can get access to pixel values), but if you don't feel like it, the OpenCV library is a great resource for doing this kind of stuff. Here is a powerpoint presentation that shows you how to create a histogram using OpenCV.

Run Function After Delay

This answer is just useful to understand how you can make delay using JQuery delay function.

Imagine you have an alert and you want to set the alert text then show the alert and after a few seconds hide it.

Here is the simple solution:

$(".alert-element").html("I'm the alert text").fadeIn(500).delay(5000).fadeOut(1000);

It is completely simple:

  1. .html() will change the text of .alert-element
  2. .fadeIn(500) will fade in after 500 milliseconds
  3. JQuery delay(5000) function will make 5000 milliseconds of delay before calling next function
  4. .fadeOut(1000) at the end of the statement will fade out the .alert-element

"Could not get any response" response when using postman with subdomain

When getting the following error, enter image description here

you need to do the following.

Step 1: In Postman, click the wrench icon, go to settings, then go to the Proxy tab.

Step 1 Wrench Icon > Settings > Proxy Tab

Step 2: Create a custom Proxy. This article explains how to create a custom proxy. After you create the custom Proxy, make sure you turn the Proxy toggle button to off. I put 61095 in for the proxy server and it worked for me.

enter image description here

Step 3 :

Success

Success

How can I pass a parameter to a t-sql script?

SQL*Plus uses &1, &2... &n to access the parameters.

Suppose you have the following script test.sql:

SET SERVEROUTPUT ON
SPOOL test.log
EXEC dbms_output.put_line('&1 &2');
SPOOL off

you could call this script like this for example:

$ sqlplus login/pw @test Hello World!

Edit:

In a UNIX script you would usually call a SQL script like this:

sqlplus /nolog << EOF
connect user/password@db
@test.sql Hello World!
exit
EOF

so that your login/password won't be visible with another session's ps

How to add/subtract dates with JavaScript?

All these functions for adding date are wrong. You are passing the wrong month to the Date function. More information about the problem : http://www.domdigger.com/blog/?p=9

Handling identity columns in an "Insert Into TABLE Values()" statement?

set identity_insert customer on
insert into Customer(id,Name,city,Salary) values(8,'bcd','Amritsar',1234)

where 'customer' is table name

Where/How to getIntent().getExtras() in an Android Fragment?

you can still use

String Item = getIntent().getExtras().getString("name");

in the fragment, you just need call getActivity() first:

String Item = getActivity().getIntent().getExtras().getString("name");

This saves you having to write some code.

How to do a SQL NOT NULL with a DateTime?

Just to rule out a possibility - it doesn't appear to have anything to do with the ANSI_NULLS option, because that controls comparing to NULL with the = and <> operators. IS [NOT] NULL works whether ANSI_NULLS is ON or OFF.

I've also tried this against SQL Server 2005 with isql, because ANSI_NULLS defaults to OFF when using DB-Library.

How to create an empty file with Ansible?

Changed if file not exists. Create empty file.

- name: create fake 'nologin' shell
  file:
    path: /etc/nologin
    state: touch
  register: p
  changed_when: p.diff.before.state == "absent"

AngularJS Directive Restrict A vs E

restrict is for defining the directive type, and it can be A (Attribute), C (Class), E (Element), and M (coMment) , let's assume that the name of the directive is Doc :

Type : Usage

A = <div Doc></div>

C = <div class="Doc"></div>

E = <Doc data="book_data"></Doc>

M = <!--directive:Doc -->

Why and how to fix? IIS Express "The specified port is in use"

For me only thing worked is removing the element containing my application name, path and binding info under </system.applicationHost> element in applicationhost file. To be found under C:\Users\yourUsername\Documents\IISExpress\config

Closed the the solution , deleted the bad site element , save the applicationhost file and close. Reopen the application/Website from Visual studio using Admin rights - Rebuilt and Run. Voila... A new port is auto assigned to your application which solves the purpose.

Can also be verified without running-- check the Properties window for the solution and URL will have new port number.

Python Pandas: How to read only first n rows of CSV files in?

If you only want to read the first 999,999 (non-header) rows:

read_csv(..., nrows=999999)

If you only want to read rows 1,000,000 ... 1,999,999

read_csv(..., skiprows=1000000, nrows=999999)

nrows : int, default None Number of rows of file to read. Useful for reading pieces of large files*

skiprows : list-like or integer Row numbers to skip (0-indexed) or number of rows to skip (int) at the start of the file

and for large files, you'll probably also want to use chunksize:

chunksize : int, default None Return TextFileReader object for iteration

pandas.io.parsers.read_csv documentation

Adding event listeners to dynamically added elements using jQuery

When adding new element with jquery plugin calls, you can do like the following:

$('<div>...</div>').hoverCard(function(){...}).appendTo(...)

How to play a local video with Swift?

U can setup AVPlayer in another way, that open for u full customization of your video Player screen

Swift 2.3

  1. Create UIView subclass for playing video (basically u can use any UIView object and only needed is AVPlayerLayer. I setup in this way because it much clearer for me)

    import AVFoundation
    import UIKit
    
    class PlayerView: UIView {
    
    override class func layerClass() -> AnyClass {
        return AVPlayerLayer.self
    }
    
    var player:AVPlayer? {
        set {
            if let layer = layer as? AVPlayerLayer {
                layer.player = player
            }
        }
        get {
            if let layer = layer as? AVPlayerLayer {
                return layer.player
            } else {
                return nil
            }
        }
    }
    }
    
  2. Setup your player

    import AVFoundation
    import Foundation
    
    protocol VideoPlayerDelegate {
        func downloadedProgress(progress:Double)
        func readyToPlay()
        func didUpdateProgress(progress:Double)
        func didFinishPlayItem()
        func didFailPlayToEnd()
    }
    
    let videoContext:UnsafeMutablePointer<Void> = nil
    
    class VideoPlayer : NSObject {
    
        private var assetPlayer:AVPlayer?
        private var playerItem:AVPlayerItem?
        private var urlAsset:AVURLAsset?
        private var videoOutput:AVPlayerItemVideoOutput?
    
        private var assetDuration:Double = 0
        private var playerView:PlayerView?
    
        private var autoRepeatPlay:Bool = true
        private var autoPlay:Bool = true
    
        var delegate:VideoPlayerDelegate?
    
        var playerRate:Float = 1 {
            didSet {
                if let player = assetPlayer {
                    player.rate = playerRate > 0 ? playerRate : 0.0
                }
            }
        }
    
        var volume:Float = 1.0 {
            didSet {
                if let player = assetPlayer {
                    player.volume = volume > 0 ? volume : 0.0
                }
            }
        }
    
        // MARK: - Init
    
        convenience init(urlAsset:NSURL, view:PlayerView, startAutoPlay:Bool = true, repeatAfterEnd:Bool = true) {
            self.init()
    
            playerView = view
            autoPlay = startAutoPlay
            autoRepeatPlay = repeatAfterEnd
    
            if let playView = playerView, let playerLayer = playView.layer as? AVPlayerLayer {
                playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
            }
            initialSetupWithURL(urlAsset)
            prepareToPlay()
        }
    
        override init() {
            super.init()
        }
    
        // MARK: - Public
    
        func isPlaying() -> Bool {
            if let player = assetPlayer {
                return player.rate > 0
            } else {
                return false
            }
        }
    
        func seekToPosition(seconds:Float64) {
            if let player = assetPlayer {
                pause()
                if let timeScale = player.currentItem?.asset.duration.timescale {
                    player.seekToTime(CMTimeMakeWithSeconds(seconds, timeScale), completionHandler: { (complete) in
                        self.play()
                    })
                }
            }
        }
    
        func pause() {
            if let player = assetPlayer {
                player.pause()
            }
        }
    
        func play() {
            if let player = assetPlayer {
                if (player.currentItem?.status == .ReadyToPlay) {
                    player.play()
                    player.rate = playerRate
                }
            }
        }
    
        func cleanUp() {
            if let item = playerItem {
                item.removeObserver(self, forKeyPath: "status")
                item.removeObserver(self, forKeyPath: "loadedTimeRanges")
            }
            NSNotificationCenter.defaultCenter().removeObserver(self)
            assetPlayer = nil
            playerItem = nil
            urlAsset = nil
        }
    
        // MARK: - Private
    
        private func prepareToPlay() {
            let keys = ["tracks"]
            if let asset = urlAsset {
                asset.loadValuesAsynchronouslyForKeys(keys, completionHandler: {
                    dispatch_async(dispatch_get_main_queue(), {
                        self.startLoading()
                    })
                })
            }
        }
    
        private func startLoading(){
            var error:NSError?
            guard let asset = urlAsset else {return}
            let status:AVKeyValueStatus = asset.statusOfValueForKey("tracks", error: &error)
    
            if status == AVKeyValueStatus.Loaded {
                assetDuration = CMTimeGetSeconds(asset.duration)
    
                let videoOutputOptions = [kCVPixelBufferPixelFormatTypeKey as String : Int(kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange)]
                videoOutput = AVPlayerItemVideoOutput(pixelBufferAttributes: videoOutputOptions)
                playerItem = AVPlayerItem(asset: asset)
    
                if let item = playerItem {
                    item.addObserver(self, forKeyPath: "status", options: .Initial, context: videoContext)
                    item.addObserver(self, forKeyPath: "loadedTimeRanges", options: [.New, .Old], context: videoContext)
    
                    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(playerItemDidReachEnd), name: AVPlayerItemDidPlayToEndTimeNotification, object: nil)
                    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(didFailedToPlayToEnd), name: AVPlayerItemFailedToPlayToEndTimeNotification, object: nil)
    
                    if let output = videoOutput {
                        item.addOutput(output)
    
                        item.audioTimePitchAlgorithm = AVAudioTimePitchAlgorithmVarispeed
                        assetPlayer = AVPlayer(playerItem: item)
    
                        if let player = assetPlayer {
                            player.rate = playerRate
                        }
    
                        addPeriodicalObserver()
                        if let playView = playerView, let layer = playView.layer as? AVPlayerLayer {
                            layer.player = assetPlayer
                            print("player created")
                        }
                    }
                }
            }        
        }
    
        private func addPeriodicalObserver() {
            let timeInterval = CMTimeMake(1, 1)
    
            if let player = assetPlayer {
                player.addPeriodicTimeObserverForInterval(timeInterval, queue: dispatch_get_main_queue(), usingBlock: { (time) in
                    self.playerDidChangeTime(time)
                })
            }
        }
    
        private func playerDidChangeTime(time:CMTime) {
            if let player = assetPlayer {
                let timeNow = CMTimeGetSeconds(player.currentTime())
                let progress = timeNow / assetDuration
    
                delegate?.didUpdateProgress(progress)
            }
        }
    
        @objc private func playerItemDidReachEnd() {
            delegate?.didFinishPlayItem()
    
            if let player = assetPlayer {
                player.seekToTime(kCMTimeZero)
                if autoRepeatPlay == true {
                    play()
                }
            }
        }
    
        @objc private func didFailedToPlayToEnd() {
            delegate?.didFailPlayToEnd()
        }
    
        private func playerDidChangeStatus(status:AVPlayerStatus) {
            if status == .Failed {
                print("Failed to load video")
            } else if status == .ReadyToPlay, let player = assetPlayer {
                volume = player.volume
                delegate?.readyToPlay()
    
                if autoPlay == true && player.rate == 0.0 {
                    play()
                }
            }
        }
    
        private func moviewPlayerLoadedTimeRangeDidUpdated(ranges:Array<NSValue>) {
            var maximum:NSTimeInterval = 0
            for value in ranges {
                let range:CMTimeRange = value.CMTimeRangeValue
                let currentLoadedTimeRange = CMTimeGetSeconds(range.start) + CMTimeGetSeconds(range.duration)
                if currentLoadedTimeRange > maximum {
                    maximum = currentLoadedTimeRange
                }
            }
            let progress:Double = assetDuration == 0 ? 0.0 : Double(maximum) / assetDuration
    
            delegate?.downloadedProgress(progress)
        }
    
        deinit {
            cleanUp()
        }
    
        private func initialSetupWithURL(url:NSURL) {
            let options = [AVURLAssetPreferPreciseDurationAndTimingKey : true]
            urlAsset = AVURLAsset(URL: url, options: options)
        }
    
        // MARK: - Observations
    
        override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
            if context == videoContext {
                if let key = keyPath {
                    if key == "status", let player = assetPlayer {
                        playerDidChangeStatus(player.status)
                    } else if key == "loadedTimeRanges", let item = playerItem {
                        moviewPlayerLoadedTimeRangeDidUpdated(item.loadedTimeRanges)
                    }
                }
            }
        }
    
    }
    
  3. Usage:

assume u have view

@IBOutlet private weak var playerView: PlayerView!
private var videoPlayer:VideoPlayer?

and in viewDidLoad()

    private func preparePlayer() {
        if let filePath = NSBundle.mainBundle().pathForResource("intro", ofType: "m4v") {
            let fileURL = NSURL(fileURLWithPath: filePath)
            videoPlayer = VideoPlayer(urlAsset: fileURL, view: playerView)
            if let player = videoPlayer {
                player.playerRate = 0.67
            }
        }
    }

Objective-C

PlayerView.h

    #import <AVFoundation/AVFoundation.h>
    #import <UIKit/UIKit.h>

    /*!
     @class PlayerView
     @discussion Represent View for playinv video. Layer - PlayerLayer
     @availability iOS 7 and Up
     */
    @interface PlayerView : UIView

    /*!
     @var player
     @discussion Player object
     */
    @property (strong, nonatomic) AVPlayer *player;

    @end

PlayerView.m

    #import "PlayerView.h"

    @implementation PlayerView

    #pragma mark - LifeCycle

    + (Class)layerClass
    {
        return [AVPlayerLayer class];
    }

    #pragma mark - Setter/Getter

    - (AVPlayer*)player
    {
        return [(AVPlayerLayer *)[self layer] player];
    }

    - (void)setPlayer:(AVPlayer *)player
    {
        [(AVPlayerLayer *)[self layer] setPlayer:player];
    }

    @end

VideoPlayer.h

    #import <AVFoundation/AVFoundation.h>
    #import <UIKit/UIKit.h>
    #import "PlayerView.h"

    /*!
     @protocol VideoPlayerDelegate
     @discussion Events from VideoPlayer
     */
    @protocol VideoPlayerDelegate <NSObject>

    @optional

    /*!
     @brief Called whenever time when progress of played item changed
     @param progress
     Playing progress
     */
    - (void)progressDidUpdate:(CGFloat)progress;

    /*!
     @brief Called whenever downloaded item progress changed
     @param progress
     Playing progress
     */
    - (void)downloadingProgress:(CGFloat)progress;

    /*!
     @brief Called when playing time changed
     @param time
     Playing progress
     */
    - (void)progressTimeChanged:(CMTime)time;

    /*!
     @brief Called when player finish play item
    */
    - (void)playerDidPlayItem;

    /*!
     @brief Called when player ready to play item
     */
    - (void)isReadyToPlay;

    @end

    /*!
     @class VideoPlayer
     @discussion Video Player
     @code
         self.videoPlayer = [[VideoPlayer alloc] initVideoPlayerWithURL:someURL playerView:self.playerView];
         [self.videoPlayer prepareToPlay];
         self.videoPlayer.delegate = self; //optional

         //after when required play item
         [self.videoPlayer play];
     @endcode
     */
    @interface VideoPlayer : NSObject

    /*!
     @var delegate
     @abstract Delegate for VideoPlayer
     @discussion Set object to this property for getting response and notifications from this class
     */
    @property (weak, nonatomic) id <VideoPlayerDelegate> delegate;

    /*!
     @var volume
     @discussion volume of played asset
     */
    @property (assign, nonatomic) CGFloat volume;

    /*!
     @var autoRepeat
     @discussion indicate whenever player should repeat content on finish playing
     */
    @property (assign, nonatomic) BOOL autoRepeat;

    /*!
     @brief Create player with asset URL
     @param urlAsset
     Source URL
     @result
     instance of VideoPlayer
     */
    - (instancetype)initVideoPlayerWithURL:(NSURL *)urlAsset;

    /*!
     @brief Create player with asset URL and configure selected view for showing result
     @param urlAsset
     Source URL
     @param view
     View on wchich result will be showed
     @result
     instance of VideoPlayer
     */
    - (instancetype)initVideoPlayerWithURL:(NSURL *)urlAsset playerView:(PlayerView *)view;

    /*!
     @brief Call this method after creating player to prepare player to play
    */
    - (void)prepareToPlay;

    /*!
     @brief Play item
     */
    - (void)play;
    /*!
     @brief Pause item
     */
    - (void)pause;
    /*!
     @brief Stop item
     */
    - (void)stop;

    /*!
     @brief Seek required position in item and pla if rquired
     @param progressValue
     % of position to seek
     @param isPlaying
     YES if player should start to play item implicity
     */
    - (void)seekPositionAtProgress:(CGFloat)progressValue withPlayingStatus:(BOOL)isPlaying;

    /*!
     @brief Player state
     @result
     YES - if playing, NO if not playing
     */
    - (BOOL)isPlaying;

    /*!
     @brief Indicate whenever player can provide CVPixelBufferRef frame from item
     @result
     YES / NO
     */
    - (BOOL)canProvideFrame;

    /*!
     @brief CVPixelBufferRef frame from item
     @result
     CVPixelBufferRef frame
     */
    - (CVPixelBufferRef)getCurrentFramePicture;

    @end

VideoPlayer.m

    #import "VideoPlayer.h"

    typedef NS_ENUM(NSUInteger, InternalStatus) {
        InternalStatusPreparation,
        InternalStatusReadyToPlay,
    };

    static const NSString *ItemStatusContext;

    @interface VideoPlayer()

    @property (strong, nonatomic) AVPlayer *assetPlayer;
    @property (strong, nonatomic) AVPlayerItem *playerItem;
    @property (strong, nonatomic) AVURLAsset *urlAsset;
    @property (strong, atomic) AVPlayerItemVideoOutput *videoOutput;

    @property (assign, nonatomic) CGFloat assetDuration;
    @property (strong, nonatomic) PlayerView *playerView;

    @property (assign, nonatomic) InternalStatus status;

    @end

    @implementation VideoPlayer

    #pragma mark - LifeCycle

    - (instancetype)initVideoPlayerWithURL:(NSURL *)urlAsset
    {
        if (self = [super init]) {
            [self initialSetupWithURL:urlAsset];
        }
        return self;
    }

    - (instancetype)initVideoPlayerWithURL:(NSURL *)urlAsset playerView:(PlayerView *)view
    {
        if (self = [super init]) {
            ((AVPlayerLayer *)view.layer).videoGravity = AVLayerVideoGravityResizeAspectFill;
            [self initialSetupWithURL:urlAsset playerView:view];
        }
        return self;
    }

    #pragma mark - Public

    - (void)play
    {
        if ((self.assetPlayer.currentItem) && (self.assetPlayer.currentItem.status == AVPlayerItemStatusReadyToPlay)) {
            [self.assetPlayer play];
        }
    }

    - (void)pause
    {
        [self.assetPlayer pause];
    }

    - (void)seekPositionAtProgress:(CGFloat)progressValue withPlayingStatus:(BOOL)isPlaying
    {
        [self.assetPlayer pause];
        int32_t timeScale = self.assetPlayer.currentItem.asset.duration.timescale;

        __weak typeof(self) weakSelf = self;
        [self.assetPlayer seekToTime:CMTimeMakeWithSeconds(progressValue, timeScale) completionHandler:^(BOOL finished) {
            DLog(@"SEEK To time %f - success", progressValue);
            if (isPlaying && finished) {
                [weakSelf.assetPlayer play];
            }
        }];
    }

    - (void)setPlayerVolume:(CGFloat)volume
    {
        self.assetPlayer.volume = volume > .0 ? MAX(volume, 0.7) : 0.0f;
        [self.assetPlayer play];
    }

    - (void)setPlayerRate:(CGFloat)rate
    {
        self.assetPlayer.rate = rate > .0 ? rate : 0.0f;
    }

    - (void)stop
    {
        [self.assetPlayer seekToTime:kCMTimeZero];
        self.assetPlayer.rate =.0f;
    }

    - (BOOL)isPlaying
    {
        return self.assetPlayer.rate > 0 ? YES : NO;
    }

    #pragma mark - Private

    - (void)initialSetupWithURL:(NSURL *)url
    {
        self.status = InternalStatusPreparation;
        [self setupPlayerWithURL:url];
    }

    - (void)initialSetupWithURL:(NSURL *)url playerView:(PlayerView *)view
    {
        [self setupPlayerWithURL:url];
        self.playerView = view;
    }

    - (void)setupPlayerWithURL:(NSURL *)url
    {
        NSDictionary *assetOptions = @{ AVURLAssetPreferPreciseDurationAndTimingKey : @YES };
        self.urlAsset = [AVURLAsset URLAssetWithURL:url options:assetOptions];
    }

    - (void)prepareToPlay
    {
        NSArray *keys = @[@"tracks"];
        __weak VideoPlayer *weakSelf = self;
        [weakSelf.urlAsset loadValuesAsynchronouslyForKeys:keys completionHandler:^{
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf startLoading];
            });
        }];
    }

    - (void)startLoading
    {
        NSError *error;
        AVKeyValueStatus status = [self.urlAsset statusOfValueForKey:@"tracks" error:&error];
        if (status == AVKeyValueStatusLoaded) {
            self.assetDuration = CMTimeGetSeconds(self.urlAsset.duration);
            NSDictionary* videoOutputOptions = @{ (id)kCVPixelBufferPixelFormatTypeKey : @(kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange)};
            self.videoOutput = [[AVPlayerItemVideoOutput alloc] initWithPixelBufferAttributes:videoOutputOptions];
            self.playerItem = [AVPlayerItem playerItemWithAsset: self.urlAsset];

            [self.playerItem addObserver:self
                              forKeyPath:@"status"
                                 options:NSKeyValueObservingOptionInitial
                                 context:&ItemStatusContext];
            [self.playerItem addObserver:self
                              forKeyPath:@"loadedTimeRanges"
                                 options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld
                                 context:&ItemStatusContext];
            [[NSNotificationCenter defaultCenter] addObserver:self
                                                     selector:@selector(playerItemDidReachEnd:)
                                                         name:AVPlayerItemDidPlayToEndTimeNotification
                                                       object:self.playerItem];
            [[NSNotificationCenter defaultCenter] addObserver:self
                                                     selector:@selector(didFailedToPlayToEnd)
                                                         name:AVPlayerItemFailedToPlayToEndTimeNotification
                                                       object:nil];

            [self.playerItem addOutput:self.videoOutput];
            self.assetPlayer = [AVPlayer playerWithPlayerItem:self.playerItem];
            [self addPeriodicalObserver];
            [((AVPlayerLayer *)self.playerView.layer) setPlayer:self.assetPlayer];
            DLog(@"Player created");
        } else {
            DLog(@"The asset's tracks were not loaded:\n%@", error.localizedDescription);
        }
    }

    #pragma mark - Observation

    - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
    {
        BOOL isOldKey = [change[NSKeyValueChangeNewKey] isEqual:change[NSKeyValueChangeOldKey]];

        if (!isOldKey) {
            if (context == &ItemStatusContext) {
                if ([keyPath isEqualToString:@"status"] && !self.status) {
                    if (self.assetPlayer.status == AVPlayerItemStatusReadyToPlay) {
                        self.status = InternalStatusReadyToPlay;
                    }
                    [self moviePlayerDidChangeStatus:self.assetPlayer.status];
                } else if ([keyPath isEqualToString:@"loadedTimeRanges"]) {
                    [self moviewPlayerLoadedTimeRangeDidUpdated:self.playerItem.loadedTimeRanges];
                }
            }
        }
    }

    - (void)moviePlayerDidChangeStatus:(AVPlayerStatus)status
    {
        if (status == AVPlayerStatusFailed) {
            DLog(@"Failed to load video");
        } else if (status == AVPlayerItemStatusReadyToPlay) {
            DLog(@"Player ready to play");
            self.volume = self.assetPlayer.volume;

            if (self.delegate && [self.delegate respondsToSelector:@selector(isReadyToPlay)]) {
                [self.delegate isReadyToPlay];
            }
        }
    }

    - (void)moviewPlayerLoadedTimeRangeDidUpdated:(NSArray *)ranges
    {
        NSTimeInterval maximum = 0;

        for (NSValue *value in ranges) {
            CMTimeRange range;
            [value getValue:&range];
            NSTimeInterval currenLoadedRangeTime = CMTimeGetSeconds(range.start) + CMTimeGetSeconds(range.duration);
            if (currenLoadedRangeTime > maximum) {
                maximum = currenLoadedRangeTime;
            }
        }
        CGFloat progress = (self.assetDuration == 0) ? 0 : maximum / self.assetDuration;
        if (self.delegate && [self.delegate respondsToSelector:@selector(downloadingProgress:)]) {
            [self.delegate downloadingProgress:progress];
        }
    }

    - (void)playerItemDidReachEnd:(NSNotification *)notification
    {
        if (self.delegate && [self.delegate respondsToSelector:@selector(playerDidPlayItem)]){
            [self.delegate playerDidPlayItem];
        }
        [self.assetPlayer seekToTime:kCMTimeZero];
        if (self.autoRepeat) {
            [self.assetPlayer play];
        }
    }

    - (void)didFailedToPlayToEnd
    {
        DLog(@"Failed play video to the end");
    }

    - (void)addPeriodicalObserver
    {
        CMTime interval = CMTimeMake(1, 1);
        __weak typeof(self) weakSelf = self;
        [self.assetPlayer addPeriodicTimeObserverForInterval:interval queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
            [weakSelf playerTimeDidChange:time];
        }];
    }

    - (void)playerTimeDidChange:(CMTime)time
    {
        double timeNow = CMTimeGetSeconds(self.assetPlayer.currentTime);
        if (self.delegate && [self.delegate respondsToSelector:@selector(progressDidUpdate:)]) {
            [self.delegate progressDidUpdate:(CGFloat) (timeNow / self.assetDuration)];
        }
    }

    #pragma mark - Notification

    - (void)setupAppNotification
    {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didEnterBackground) name:UIApplicationDidEnterBackgroundNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(willEnterForeground) name:UIApplicationWillEnterForegroundNotification object:nil];
    }

    - (void)didEnterBackground
    {
        [self.assetPlayer pause];
    }

    - (void)willEnterForeground
    {
        [self.assetPlayer pause];
    }

    #pragma mark - GetImagesFromVideoPlayer

    - (BOOL)canProvideFrame
    {
        return self.assetPlayer.status == AVPlayerItemStatusReadyToPlay;
    }

    - (CVPixelBufferRef)getCurrentFramePicture
    {
        CMTime currentTime = [self.videoOutput itemTimeForHostTime:CACurrentMediaTime()];
        if (self.delegate && [self.delegate respondsToSelector:@selector(progressTimeChanged:)]) {
            [self.delegate progressTimeChanged:currentTime];
        }
        if (![self.videoOutput hasNewPixelBufferForItemTime:currentTime]) {
            return 0;
        }
        CVPixelBufferRef buffer = [self.videoOutput copyPixelBufferForItemTime:currentTime itemTimeForDisplay:NULL];

        return buffer;
    }

    #pragma mark - CleanUp

    - (void)removeObserversFromPlayer
    {
        @try {
            [self.playerItem removeObserver:self forKeyPath:@"status"];
            [self.playerItem removeObserver:self forKeyPath:@"loadedTimeRanges"];
            [[NSNotificationCenter defaultCenter] removeObserver:self];
            [[NSNotificationCenter defaultCenter] removeObserver:self.assetPlayer];        
        }
        @catch (NSException *ex) {
            DLog(@"Cant remove observer in Player - %@", ex.description);
        }
    }

    - (void)cleanUp
    {
        [self removeObserversFromPlayer];

        self.assetPlayer.rate = 0;
        self.assetPlayer = nil;
        self.playerItem = nil;
        self.urlAsset = nil;
    }

    - (void)dealloc
    {
        [self cleanUp];    
    }

    @end

Off cause resource (video file) should have target membership setted to your project

enter image description here

Additional - link to perfect Apple Developer guide

Bootstrap 3 .col-xs-offset-* doesn't work?

instead of using col-md-offset-4 use instead offset-md-4, you no longer have to use col when you're offsetting. In your case use offset-xs-1 and this will work. make sure you've called the bootstrap.css folder into your html as follows .

How to get < span > value?

You need to change your code as below:-

<html>
<body>

<span id="span_Id">Click the button to display the content.</span>

<button onclick="displayDate()">Click Me</button>

<script>
function displayDate() {
   var span_Text = document.getElementById("span_Id").innerText;
   alert (span_Text);
}
</script>
</body>
</html>

After doing this you will get the tag value in alert.

Create line after text with css

Here is another, in my opinion even simpler solution using a flex wrapper:

HTML:

<div class="wrapper">
  <p>Text</p>
  <div class="line"></div>
</div>

CSS:

.wrapper {
  display: flex;
  align-items: center;
}

.line {
  border-top: 1px solid grey;
  flex-grow: 1;
  margin: 0 10px;
}

JSFiddle

Use string in switch case in java

String value = someMethod();
switch(0) {
default:
    if ("apple".equals(value)) {
        method1();
        break;
    }
    if ("carrot".equals(value)) {
        method2();
        break;
    }
    if ("mango".equals(value)) {
        method3();
        break;
    }
    if ("orance".equals(value)) {
        method4();
        break;
    }
}

Make first letter of a string upper case (with maximum performance)

Expanding on Carlos' question above, if you want to capitalize multiple sentences you may use this code:

    /// <summary>
    /// Capitalize first letter of every sentence. 
    /// </summary>
    /// <param name="inputSting"></param>
    /// <returns></returns>
    public string CapitalizeSentences (string inputSting)
    {
        string result = string.Empty;
        if (!string.IsNullOrEmpty(inputSting))
        {
            string[] sentences = inputSting.Split('.');

            foreach (string sentence in sentences)
            {
                result += string.Format ("{0}{1}.", sentence.First().ToString().ToUpper(), sentence.Substring(1)); 
            }
        }

        return result; 
    }

Regex for not empty and not whitespace

I ended up using something similar to the accepted answer, with minor modifications

(^$)|(\s+$)

Explanation by the Expresso

Select from 2 alternatives (^$)
    [1] A numbered captured group ^$
        Beginning of line ^
        End of line $
    [2] A numbered captured group (\s+$)
        Whitespace, one or more repetitions \s+
        End of line $

How to pass arguments to a Button command in Tkinter?

button = Tk.Button(master=frame, text='press', command=lambda: action(someNumber))

I believe should fix this

Chrome Uncaught Syntax Error: Unexpected Token ILLEGAL

I had the same error when multiline string included new line (\n) characters. Merging all lines into one (thus removing all new line characters) and sending it to a browser used to solve. But was very inconvenient to code.

Often could not understand why this was an issue in Chrome until I came across to a statement which said that the current version of JavaScript engine in Chrome doesn't support multiline strings which are wrapped in single quotes and have new line (\n) characters in them. To make it work, multiline string need to be wrapped in double quotes. Changing my code to this, resolved this issue.

I will try to find a reference to a standard or Chrome doc which proves this. Until then, try this solution and see if works for you as well.

PersistenceContext EntityManager injection NullPointerException

An entity manager can only be injected in classes running inside a transaction. In other words, it can only be injected in a EJB. Other classe must use an EntityManagerFactory to create and destroy an EntityManager.

Since your TestService is not an EJB, the annotation @PersistenceContext is simply ignored. Not only that, in JavaEE 5, it's not possible to inject an EntityManager nor an EntityManagerFactory in a JAX-RS Service. You have to go with a JavaEE 6 server (JBoss 6, Glassfish 3, etc).

Here's an example of injecting an EntityManagerFactory:

package com.test.service;

import java.util.*;
import javax.persistence.*;
import javax.ws.rs.*;

@Path("/service")
public class TestService {

    @PersistenceUnit(unitName = "test")
    private EntityManagerFactory entityManagerFactory;

    @GET
    @Path("/get")
    @Produces("application/json")
    public List get() {
        EntityManager entityManager = entityManagerFactory.createEntityManager();
        try {
            return entityManager.createQuery("from TestEntity").getResultList();
        } finally {
            entityManager.close();
        }
    }
}

The easiest way to go here is to declare your service as a EJB 3.1, assuming you're using a JavaEE 6 server.

Related question: Inject an EJB into JAX-RS (RESTful service)

How to output MySQL query results in CSV format?

mysql --batch, -B

Print results using tab as the column separator, with each row on a new line. With this option, mysql does not use the history file. Batch mode results in non-tabular output format and escaping of special characters. Escaping may be disabled by using raw mode; see the description for the --raw option.

This will give you a tab separated file. Since commas (or strings containing comma) are not escaped it is not straightforward to change the delimiter to comma.

Drop rows with all zeros in pandas data frame

I think this solution is the shortest :

df= df[df['ColName'] != 0]

Why use def main()?

Everyone else has already answered it, but I think I still have something else to add.

Reasons to have that if statement calling main() (in no particular order):

  • Other languages (like C and Java) have a main() function that is called when the program is executed. Using this if, we can make Python behave like them, which feels more familiar for many people.

  • Code will be cleaner, easier to read, and better organized. (yeah, I know this is subjective)

  • It will be possible to import that python code as a module without nasty side-effects.

  • This means it will be possible to run tests against that code.

  • This means we can import that code into an interactive python shell and test/debug/run it.

  • Variables inside def main are local, while those outside it are global. This may introduce a few bugs and unexpected behaviors.

But, you are not required to write a main() function and call it inside an if statement.

I myself usually start writing small throwaway scripts without any kind of function. If the script grows big enough, or if I feel putting all that code inside a function will benefit me, then I refactor the code and do it. This also happens when I write bash scripts.

Even if you put code inside the main function, you are not required to write it exactly like that. A neat variation could be:

import sys

def main(argv):
    # My code here
    pass

if __name__ == "__main__":
    main(sys.argv)

This means you can call main() from other scripts (or interactive shell) passing custom parameters. This might be useful in unit tests, or when batch-processing. But remember that the code above will require parsing of argv, thus maybe it would be better to use a different call that pass parameters already parsed.

In an object-oriented application I've written, the code looked like this:

class MyApplication(something):
    # My code here

if __name__ == "__main__":
    app = MyApplication()
    app.run()

So, feel free to write the code that better suits you. :)

How to create a byte array in C++?

Maybe you can leverage the std::bitset type available in C++11. It can be used to represent a fixed sequence of N bits, which can be manipulated by conventional logic.

#include<iostream>
#include<bitset>

class MissileLauncher {
 public:
  MissileLauncher() {}
  void show_bits() const {
    std::cout<<m_abc[2]<<", "<<m_abc[1]<<", "<<m_abc[0]<<std::endl;
  }

  bool toggle_a() {
    // toggles (i.e., flips) the value of `a` bit and returns the
    // resulting logical value
    m_abc[0].flip();
    return m_abc[0];
  }

  bool toggle_c() {
    // toggles (i.e., flips) the value of `c` bit and returns the
    // resulting logical value
    m_abc[2].flip();
    return m_abc[2];
  }

  bool matches(const std::bitset<3>& mask) {
    // tests whether all the bits specified in `mask` are turned on in
    // this instance's bitfield
    return ((m_abc & mask) == mask);
  }

 private:
  std::bitset<3> m_abc;
};

typedef std::bitset<3> Mask;
int main() {
  MissileLauncher ml;

  // notice that the bitset can be "built" from a string - this masks
  // can be made available as constants to test whether certain bits
  // or bit combinations are "on" or "off"
  Mask has_a("001");       // the zeroth bit
  Mask has_b("010");       // the first bit
  Mask has_c("100");       // the second bit
  Mask has_a_and_c("101"); // zeroth and second bits
  Mask has_all_on("111");  // all on!
  Mask has_all_off("000"); // all off!

  // I can even create masks using standard logic (in this case I use
  // the or "|" operator)
  Mask has_a_and_b = has_a | has_b;
  std::cout<<"This should be 011: "<<has_a_and_b<<std::endl;

  // print "true" and "false" instead of "1" and "0"
  std::cout<<std::boolalpha;

  std::cout<<"Bits, as created"<<std::endl;
  ml.show_bits();
  std::cout<<"is a turned on? "<<ml.matches(has_a)<<std::endl;
  std::cout<<"I will toggle a"<<std::endl;
  ml.toggle_a();
  std::cout<<"Resulting bits:"<<std::endl;
  ml.show_bits();  
  std::cout<<"is a turned on now? "<<ml.matches(has_a)<<std::endl;
  std::cout<<"are both a and c on? "<<ml.matches(has_a_and_c)<<std::endl;
  std::cout<<"Toggle c"<<std::endl;
  ml.toggle_c();
  std::cout<<"Resulting bits:"<<std::endl;
  ml.show_bits();    
  std::cout<<"are both a and c on now? "<<ml.matches(has_a_and_c)<<std::endl;  
  std::cout<<"but, are all bits on? "<<ml.matches(has_all_on)<<std::endl;
  return 0;
}

Compiling using gcc 4.7.2

g++ example.cpp -std=c++11

I get:

This should be 011: 011
Bits, as created
false, false, false
is a turned on? false
I will toggle a
Resulting bits:
false, false, true
is a turned on now? true
are both a and c on? false
Toggle c
Resulting bits:
true, false, true
are both a and c on now? true
but, are all bits on? false

Multi-character constant warnings

If you're happy you know what you're doing and can accept the portability problems, on GCC for example you can disable the warning on the command line:

-Wno-multichar

I use this for my own apps to work with AVI and MP4 file headers for similar reasons to you.

Python - converting a string of numbers into a list of int

You can also use list comprehension on splitted string

[ int(x) for x in example_string.split(',') ]

how to set ulimit / file descriptor on docker container the image tag is phusion/baseimage-docker

Here is what I did.

set ulimit -n 32000 in the file /etc/init.d/docker

and restart the docker service

docker run -ti node:latest /bin/bash

run this command to verify

user@4d04d06d5022:/# ulimit -a

should see this in the result

open files (-n) 32000

[user@ip ec2-user]# docker run -ti node /bin/bash
user@4d04d06d5022:/# ulimit -a
core file size          (blocks, -c) 0
data seg size           (kbytes, -d) unlimited
scheduling priority             (-e) 0
file size               (blocks, -f) unlimited
pending signals                 (-i) 58729
max locked memory       (kbytes, -l) 64
max memory size         (kbytes, -m) unlimited
open files                      (-n) 32000
pipe size            (512 bytes, -p) 8
POSIX message queues     (bytes, -q) 819200
real-time priority              (-r) 0
stack size              (kbytes, -s) 10240
cpu time               (seconds, -t) unlimited
max user processes              (-u) 58729
virtual memory          (kbytes, -v) unlimited
file locks                      (-x) unlimited

How do I filter an array with TypeScript in Angular 2?

You can check an example in Plunker over here plunker example filters

filter() {

    let storeId = 1;
    this.bookFilteredList = this.bookList
                                .filter((book: Book) => book.storeId === storeId);
    this.bookList = this.bookFilteredList; 
}

Curl command line for consuming webServices?

Wrong. That doesn't work for me.

For me this one works:

curl 
-H 'SOAPACTION: "urn:samsung.com:service:MainTVAgent2:1#CheckPIN"'   
-X POST 
-H 'Content-type: text/xml'   
-d @/tmp/pinrequest.xml 
192.168.1.5:52235/MainTVServer2/control/MainTVAgent2

Largest and smallest number in an array

It is a long time. Maybe like this:

    public int smallestValue(int[] values)
    {
        int smallest = int.MaxValue;

        for (int i = 0; i < values.Length; i++)
        {
            smallest = (values[i] < smallest ? values[i] : smallest);
        }

        return smallest;
    }


    public static int largestvalue(int[] values)
    {
        int largest = int.MinValue;

        for (int i = 0; i < values.Length; i++)
        {
            largest = (values[i] > largest ? values[i] : largest);
        }

        return largest;
    }

Error: Segmentation fault (core dumped)

In my case: I forgot to activate virtualenv

I installed "pip install example" in the wrong virtualenv

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

you must install

npm install @babel/core @babel/plugin-proposal-class-properties @babel/preset-env @babel/preset-react babel-loader

and

change entry and output


const path = require('path')        
module.exports = {
  entry: path.resolve(__dirname,'src', 'app.js'),
  output: {
    path: path.resolve(__dirname, "public","dist",'javascript'),
    filename: 'bundle.js'
  },
  module: {
    rules: [
      {
        test: /\.(jsx|js)$/,
        exclude: /node_modules/,
        use: [{
          loader: 'babel-loader',
          options: {
            presets: [
              ['@babel/preset-env', {
                "targets": "defaults"
              }],
              '@babel/preset-react'
            ],
            plugins: [
              "@babel/plugin-proposal-class-properties"
            ]
          }
        }]
      }
    ]
  }
}

Turn off warnings and errors on PHP and MySQL

Prepend functions with the '@' symbol to suppress certain errors, as opposed to turning off all error reporting.

More information: http://php.net/manual/en/language.operators.errorcontrol.php

PHP supports one error control operator: the at sign (@). When prepended to an expression in PHP, any error messages that might be generated by that expression will be ignored.

@fsockopen();

What is Teredo Tunneling Pseudo-Interface?

Unless you have some kind of really weird problem, keep it. The number of IPv6 sites is very small, but there are some and it will let you get to them even if you're at an IPv4 only location.

If it is causing you a problem, it's best to fix it. I've seen a number of people recommending removing it to solve problems. However, they're not actually solving the root cause of the issue. In all the cases I've seen, removing Teredo just happens to cause a side-effect that fixes their problem... :)

Change Toolbar color in Appcompat 21

For people who are using AppCompatActivity with Toolbar as white background. Do use this code.

Updated: December, 2017

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:theme="@style/ThemeOverlay.AppCompat.Light">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar_edit"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        app:popupTheme="@style/AppTheme.AppBarOverlay"
        app:title="Edit Your Profile"/>

</android.support.design.widget.AppBarLayout>

How to convert IPython notebooks to PDF and HTML?

You can do it by 1st converting the notebook into HTML and then into PDF format:

Following steps I have implemented on: OS: Ubuntu, Anaconda-Jupyter notebook, Python 3

1 Save Notebook in HTML format:

  1. Start the jupyter notebook that you want to save in HTML format. First save the notebook properly so that HTML file will have a latest saved version of your code/notebook.

  2. Run the following command from the notebook itself:

    !jupyter nbconvert --to html your_notebook_name.ipynb

After execution will create HTML version of your notebook and will save it in the current working directory. You will see one html file will be added into the current directory with your_notebook_name.html name

(your_notebook_name.ipynb --> your_notebook_name.html).

2 Save html as PDF:

  1. Now open that your_notebook_name.html file (click on it). It will be opened in a new tab of your browser.
  2. Now go to print option. From here you can save this file in pdf file format.

Note that from print option we also have the flexibility of selecting a portion of a notebook to save in pdf format.

Long Press in JavaScript?

You can check the time to identify Click or Long Press [jQuery]

function AddButtonEventListener() {
try {
    var mousedowntime;
    var presstime;
    $("button[id$='" + buttonID + "']").mousedown(function() {
        var d = new Date();
        mousedowntime = d.getTime();
    });
    $("button[id$='" + buttonID + "']").mouseup(function() {
        var d = new Date();
        presstime = d.getTime() - mousedowntime;
        if (presstime > 999/*You can decide the time*/) {
            //Do_Action_Long_Press_Event();
        }
        else {
            //Do_Action_Click_Event();
        }
    });
}
catch (err) {
    alert(err.message);
}
} 

Define preprocessor macro through CMake?

The other solution proposed on this page are useful some versions of Cmake < 3.3.2. Here the solution for the version I am using (i.e., 3.3.2). Check the version of your Cmake by using $ cmake --version and pick the solution that fits with your needs. The cmake documentation can be found on the official page.

With CMake version 3.3.2, in order to create

#define foo

I needed to use:

add_definitions(-Dfoo)   # <--------HERE THE NEW CMAKE LINE inside CMakeLists.txt
add_executable( ....)
target_link_libraries(....)

and, in order to have a preprocessor macro definition like this other one:

#define foo=5

the line is so modified:

add_definitions(-Dfoo=5)   # <--------HERE THE NEW CMAKE LINE inside CMakeLists.txt
add_executable( ....)
target_link_libraries(....)

Any good boolean expression simplifiers out there?

Try Logic Friday 1 It includes tools from the Univerity of California (Espresso and misII) and makes them usable with a GUI. You can enter boolean equations and truth tables as desired. It also features a graphical gate diagram input and output.

The minimization can be carried out two-level or multi-level. The two-level form yields a minimized sum of products. The multi-level form creates a circuit composed out of logical gates. The types of gates can be restricted by the user.

Your expression simplifies to C.

How to extract text from a PDF file?

The below code is a solution to the question in Python 3. Before running the code, make sure you have installed the PyPDF2 library in your environment. If not installed, open the command prompt and run the following command:

pip3 install PyPDF2

Solution Code:

import PyPDF2
pdfFileObject = open('sample.pdf', 'rb')
pdfReader = PyPDF2.PdfFileReader(pdfFileObject)
count = pdfReader.numPages
for i in range(count):
    page = pdfReader.getPage(i)
    print(page.extractText())

How to make a 3-level collapsing menu in Bootstrap?

Bootstrap 3 dropped native support for nested collapsing menus, but there's a way to re-enable it with a 3rd party script. It's called SmartMenus. It means adding three new resources to your page, but it seamlessly supports Bootstrap 3.x with multiple levels of menus for nested <ul>/<li> elements with class="dropdown-menu". It automatically displays the proper caret indicator as well.

<head>
   ...
   <script src=".../jquery.smartmenus.min.js"></script>
   <script src=".../jquery.smartmenus.bootstrap.min.js"></script>
   ...
   <link rel="stylesheet" href=".../jquery.smartmenus.bootstrap.min.css"/>
   ...
</head>

Here's a demo page: http://vadikom.github.io/smartmenus/src/demo/bootstrap-navbar-fixed-top.html

Change the color of glyphicons to blue in some- but not at all places using Bootstrap 2

You can do this as well, hopeit helps

<span style="color:black"><i class="glyphicon glyphicon-music"></i></span>

Truncate/round whole number in JavaScript?

Travis Pessetto's answer along with mozey's trunc2 function were the only correct answers, considering how JavaScript represents very small or very large floating point numbers in scientific notation.

For example, parseInt(-2.2043642353916286e-15) will not correctly parse that input. Instead of returning 0 it will return -2.

This is the correct (and imho the least insane) way to do it:

function truncate(number)
{
    return number > 0
         ? Math.floor(number)
         : Math.ceil(number);
}

How can I bind a background color in WPF/XAML?

Here you've got a copy-paste code:

class NameToBackgroundConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if(value.ToString() == "System")
            {
                return new SolidColorBrush(System.Windows.Media.Colors.Aqua);
            }else
            {
                return new SolidColorBrush(System.Windows.Media.Colors.Blue);
            }
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return null;
        }
    }

Javascript regular expression password validation having special characters

Use positive lookahead assertions:

var regularExpression = /^(?=.*[0-9])(?=.*[!@#$%^&*])[a-zA-Z0-9!@#$%^&*]{6,16}$/;

Without it, your current regex only matches that you have 6 to 16 valid characters, it doesn't validate that it has at least a number, and at least a special character. That's what the lookahead above is for.

  • (?=.*[0-9]) - Assert a string has at least one number;
  • (?=.*[!@#$%^&*]) - Assert a string has at least one special character.

How to fill the whole canvas with specific color?

Yes, fill in a Rectangle with a solid color across the canvas, use the height and width of the canvas itself:

_x000D_
_x000D_
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.fillStyle = "blue";
ctx.fillRect(0, 0, canvas.width, canvas.height);
_x000D_
canvas{ border: 1px solid black; }
_x000D_
<canvas width=300 height=150 id="canvas">
_x000D_
_x000D_
_x000D_

Compress images on client side before uploading

I just developed a javascript library called JIC to solve that problem. It allows you to compress jpg and png on the client side 100% with javascript and no external libraries required!

You can try the demo here : http://makeitsolutions.com/labs/jic and get the sources here : https://github.com/brunobar79/J-I-C

How to retrieve value from elements in array using jQuery?

jQuery collections have a built in iterator with .each:

$("input[name^='card']").each(function () {
   console.log($(this).val());
}

Configuring user and password with Git Bash

Try ssh-agent for installing the SSH key for use with Git. It should auto login after use of a passphrase.

How do you create a custom AuthorizeAttribute in ASP.NET Core?

As of this writing I believe this can be accomplished with the IClaimsTransformation interface in asp.net core 2 and above. I just implemented a proof of concept which is sharable enough to post here.

public class PrivilegesToClaimsTransformer : IClaimsTransformation
{
    private readonly IPrivilegeProvider privilegeProvider;
    public const string DidItClaim = "http://foo.bar/privileges/resolved";

    public PrivilegesToClaimsTransformer(IPrivilegeProvider privilegeProvider)
    {
        this.privilegeProvider = privilegeProvider;
    }

    public async Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
    {
        if (principal.Identity is ClaimsIdentity claimer)
        {
            if (claimer.HasClaim(DidItClaim, bool.TrueString))
            {
                return principal;
            }

            var privileges = await this.privilegeProvider.GetPrivileges( ... );
            claimer.AddClaim(new Claim(DidItClaim, bool.TrueString));

            foreach (var privilegeAsRole in privileges)
            {
                claimer.AddClaim(new Claim(ClaimTypes.Role /*"http://schemas.microsoft.com/ws/2008/06/identity/claims/role" */, privilegeAsRole));
            }
        }

        return principal;
    }
}

To use this in your Controller just add an appropriate [Authorize(Roles="whatever")] to your methods.

[HttpGet]
[Route("poc")]
[Authorize(Roles = "plugh,blast")]
public JsonResult PocAuthorization()
{
    var result = Json(new
    {
        when = DateTime.UtcNow,
    });

    result.StatusCode = (int)HttpStatusCode.OK;

    return result;
}

In our case every request includes an Authorization header that is a JWT. This is the prototype and I believe we will do something super close to this in our production system next week.

Future voters, consider the date of writing when you vote. As of today, this works on my machine.™ You will probably want more error handling and logging on your implementation.

Using request.setAttribute in a JSP page

Try

request.getSession().setAttribute("SUBFAMILY", subFam);
request.getSession().getAttribute("SUBFAMILY");

Create a string of variable length, filled with a repeated character

For Evergreen browsers, this will build a staircase based on an incoming character and the number of stairs to build.
function StairCase(character, input) {
    let i = 0;
    while (i < input) {
        const spaces = " ".repeat(input - (i+1));
        const hashes = character.repeat(i + 1);
        console.log(spaces + hashes);
        i++;
    }
}

//Implement
//Refresh the console
console.clear();
StairCase("#",6);   

You can also add a polyfill for Repeat for older browsers

    if (!String.prototype.repeat) {
      String.prototype.repeat = function(count) {
        'use strict';
        if (this == null) {
          throw new TypeError('can\'t convert ' + this + ' to object');
        }
        var str = '' + this;
        count = +count;
        if (count != count) {
          count = 0;
        }
        if (count < 0) {
          throw new RangeError('repeat count must be non-negative');
        }
        if (count == Infinity) {
          throw new RangeError('repeat count must be less than infinity');
        }
        count = Math.floor(count);
        if (str.length == 0 || count == 0) {
          return '';
        }
        // Ensuring count is a 31-bit integer allows us to heavily optimize the
        // main part. But anyway, most current (August 2014) browsers can't handle
        // strings 1 << 28 chars or longer, so:
        if (str.length * count >= 1 << 28) {
          throw new RangeError('repeat count must not overflow maximum string size');
        }
        var rpt = '';
        for (;;) {
          if ((count & 1) == 1) {
            rpt += str;
          }
          count >>>= 1;
          if (count == 0) {
            break;
          }
          str += str;
        }
        // Could we try:
        // return Array(count + 1).join(this);
        return rpt;
      }
    } 

What is a bus error?

I was getting a bus error when the root directory was at 100%.

How to overload __init__ method based on argument type?

You probably want the isinstance builtin function:

self.data = data if isinstance(data, list) else self.parse(data)

Java client certificates over HTTPS/SSL

Have you set the KeyStore and/or TrustStore System properties?

java -Djavax.net.ssl.keyStore=pathToKeystore -Djavax.net.ssl.keyStorePassword=123456

or from with the code

System.setProperty("javax.net.ssl.keyStore", pathToKeyStore);

Same with javax.net.ssl.trustStore

Web API optional parameters

I figured it out. I was using a bad example I found in the past of how to map query string to the method parameters.

In case anyone else needs it, in order to have optional parameters in a query string such as:

  • ~/api/products/filter?apc=AA&xpc=BB
  • ~/api/products/filter?sku=7199123

you would use:

[Route("products/filter/{apc?}/{xpc?}/{sku?}")]
public IHttpActionResult Get(string apc = null, string xpc = null, int? sku = null)
{ ... }

It seems odd to have to define default values for the method parameters when these types already have a default.

Python, HTTPS GET with basic authentication

requests.get(url, auth=requests.auth.HTTPBasicAuth(username=token, password=''))

If with token, password should be ''.

It works for me.

Import cycle not allowed

I just encountered this. You may be accessing a method/type from within the same package using the package name itself.

Here is an example to illustrate what I mean:

In foo.go:

// foo.go
package foo

func Foo() {...}

In foo_test.go:

// foo_test.go
package foo

// try to access Foo()
foo.Foo() // WRONG <== This was the issue. You are already in package foo, there is no need to use foo.Foo() to access Foo()
Foo() // CORRECT

How to change an Android app's name?

It depends what you want to do. I personally wanted to rename my project so it didn't say MainActivity at the top of the app and underneath the icon on my phone menu.

To do this I went into the Android Manifest.xml file and edited

<activity
        android:name=".MainActitivity"
        android:label="@string/title_activity_main" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

And edited the android:name=".Mynewname" and then edited the string title_activity_main in the strings.xml file to match the name.

Hope that helps!

MySQL error 1449: The user specified as a definer does not exist

I got the same error after updating mysql.

The error has been fixed after this command:

mysql_upgrade -u root

mysql_upgrade should be executed each time you upgrade MySQL. It checks all tables in all databases for incompatibilities with the current version of MySQL Server. If a table is found to have a possible incompatibility, it is checked. If any problems are found, the table is repaired. mysql_upgrade also upgrades the system tables so that you can take advantage of new privileges or capabilities that might have been added.

How do I convert a pandas Series or index to a Numpy array?

You can use df.index to access the index object and then get the values in a list using df.index.tolist(). Similarly, you can use df['col'].tolist() for Series.

iOS9 Untrusted Enterprise Developer with no option to trust

For iOS 9 beta 3,4 users. Since the option to view profiles is not viewable do the following from Xcode.

  1. Open Xcode 7.
  2. Go to window, devices.
  3. Select your device.
  4. Delete all of the profiles loaded on the device.
  5. Delete the old app on your device.
  6. Clean and rebuild the app to your device.

On iOS 9.1+ n iOS 9.2+ go to Settings -> General -> Device Management -> press the Profile -> Press Trust.