Programs & Examples On #Kermit

Kermit is a data transfer protocol, commonly used in the early days of the internet.

Why am I getting a "401 Unauthorized" error in Maven?

Also had 401's from Nexus. Having tried all the suggestions above and more without success I eventually found that it was a Jenkins setting that was in error.

In the Jenkins configuration for the failing project, we have a section in the 'Post Build' actions entitled 'Deploy Artifacts To Maven Repository'. This has a 'Repository ID' field which was set to the wrong value. It has to be the same as the repository ID in settings.xml for Jenkins to read the user and password fields:

Jenkins Project Configuration

      <id>snapshot-repository</id>  <!-- must match this -->

Append data to a POST NSURLRequest

The previous posts about forming POST requests are largely correct (add the parameters to the body, not the URL). But if there is any chance of the input data containing any reserved characters (e.g. spaces, ampersand, plus sign), then you will want to handle these reserved characters. Namely, you should percent-escape the input.

//create body of the request

NSString *userid = ...
NSString *encodedUserid = [self percentEscapeString:userid];
NSString *postString    = [NSString stringWithFormat:@"userid=%@", encodedUserid];
NSData   *postBody      = [postString dataUsingEncoding:NSUTF8StringEncoding];

//initialize a request from url

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPBody:postBody];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];

//initialize a connection from request, any way you want to, e.g.

NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];

Where the precentEscapeString method is defined as follows:

- (NSString *)percentEscapeString:(NSString *)string
    NSString *result = CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                                                 (CFStringRef)@" ",
    return [result stringByReplacingOccurrencesOfString:@" " withString:@"+"];

Note, there was a promising NSString method, stringByAddingPercentEscapesUsingEncoding (now deprecated), that does something very similar, but resist the temptation to use that. It handles some characters (e.g. the space character), but not some of the others (e.g. the + or & characters).

The contemporary equivalent is stringByAddingPercentEncodingWithAllowedCharacters, but, again, don't be tempted to use URLQueryAllowedCharacterSet, as that also allows + and & pass unescaped. Those two characters are permitted within the broader "query", but if those characters appear within a value within a query, they must escaped. Technically, you can either use URLQueryAllowedCharacterSet to build a mutable character set and remove a few of the characters that they've included in there, or build your own character set from scratch.

For example, if you look at Alamofire's parameter encoding, they take URLQueryAllowedCharacterSet and then remove generalDelimitersToEncode (which includes the characters #, [, ], and @, but because of a historical bug in some old web servers, neither ? nor /) and subDelimitersToEncode (i.e. !, $, &, ', (, ), *, +, ,, ;, and =). This is correct implementation (though you could debate the removal of ? and /), though pretty convoluted. Perhaps CFURLCreateStringByAddingPercentEscapes is more direct/efficient.

diff to output only the file names

From the diff man page:

-q   Report only whether the files differ, not the details of the differences.
-r   When comparing directories, recursively compare any subdirectories found.

Example command:

diff -qr dir1 dir2

Example output (depends on locale):

$ ls dir1 dir2
same-file  different  only-1

same-file  different  only-2
$ diff -qr dir1 dir2
Files dir1/different and dir2/different differ
Only in dir1: only-1
Only in dir2: only-2

What are some resources for getting started in operating system development?

I wish there was one place to get all of the info about developing your own OS. The closest to come to that is OS Dev Wiki and Forums. They offer a ton of good information regarding the setup, development, and device hardware information.

Also there are some great tutorials at BoneFide, I've used the getting started tutorial by Bran, and am now looking at a more recent one based on his called Roll your own toy UNIX-clone OS.

I second checking out: "Operating Systems : Design and Implementation"

And if you want to develop on Windows, check out jolson's blog post.

Edit: For development on windows using Visual Studio, check out BrokenThorn's guide or OSDev's wiki.

100% Min Height CSS layout

I agree with Levik as the parent container is set to 100% if you have sidebars and want them to fill the space to meet up with the footer you cannot set them to 100% because they will be 100 percent of the parent height as well which means that the footer ends up getting pushed down when using the clear function.

Think of it this way if your header is say 50px height and your footer is 50px height and the content is just autofitted to the remaining space say 100px for example and the page container is 100% of this value its height will be 200px. Then when you set the sidebar height to 100% it is then 200px even though it is supposed to fit snug in between the header and footer. Instead it ends up being 50px + 200px + 50px so the page is now 300px because the sidebars are set to the same height as the page container. There will be a big white space in the contents of the page.

I am using internet Explorer 9 and this is what I am getting as the effect when using this 100% method. I havent tried it in other browsers and I assume that it may work in some of the other options. but it will not be universal.

How to remove outliers in boxplot in R?

See ?boxplot for all the help you need.

 outline: if ‘outline’ is not true, the outliers are not drawn (as
          points whereas S+ uses lines).


And for extending the range of the whiskers and suppressing the outliers inside this range:

   range: this determines how far the plot whiskers extend out from the
          box.  If ‘range’ is positive, the whiskers extend to the most
          extreme data point which is no more than ‘range’ times the
          interquartile range from the box. A value of zero causes the
          whiskers to extend to the data extremes.

# change the value of range to change the whisker length

Plot 3D data in R

I use the lattice package for almost everything I plot in R and it has a corresponing plot to persp called wireframe. Let data be the way Sven defined it.

wireframe(z ~ x * y, data=data)

wireframe plot

Or how about this (modification of fig 6.3 in Deepanyan Sarkar's book):

p <- wireframe(z ~ x * y, data=data)
npanel <- c(4, 2)
rotx <- c(-50, -80)
rotz <- seq(30, 300, length = npanel[1]+1)
update(p[rep(1, prod(npanel))], layout = npanel,
    panel = function(..., screen) {
        panel.wireframe(..., screen = list(z = rotz[current.column()],
                                           x = rotx[current.row()]))

Multiple wireframe plots using panel and update

Update: Plotting surfaces with OpenGL

Since this post continues to draw attention I want to add the OpenGL way to make 3-d plots too (as suggested by @tucson below). First we need to reformat the dataset from xyz-tripplets to axis vectors x and y and a matrix z.

x <- 1:5/10
y <- 1:5
z <- x %o% y
z <- z + .2*z*runif(25) - .1*z

persp3d(x, y, z, col="skyblue")


This image can be freely rotated and scaled using the mouse, or modified with additional commands, and when you are happy with it you save it using rgl.snapshot.


Passing event and argument to v-on in Vue.js

You can also do something like this...

<input @input="myHandler('foo', 'bar', ...arguments)">

Evan You himself recommended this technique in one post on Vue forum. In general some events may emit more than one argument. Also as documentation states internal variable $event is meant for passing original DOM event.

What's the difference between ViewData and ViewBag?

Internally ViewBag properties are stored as name/value pairs in the ViewData dictionary.

Note: in most pre-release versions of MVC 3, the ViewBag property was named the ViewModel as noted in this snippet from MVC 3 release notes:

(edited 10-8-12) It was suggested I post the source of this info I posted, here is the source:

MVC 2 controllers support a ViewData property that enables you to pass data to a view template using a late-bound dictionary API. In MVC 3, you can also use somewhat simpler syntax with the ViewBag property to accomplish the same purpose. For example, instead of writing ViewData["Message"]="text", you can write ViewBag.Message="text". You do not need to define any strongly-typed classes to use the ViewBag property. Because it is a dynamic property, you can instead just get or set properties and it will resolve them dynamically at run time. Internally, ViewBag properties are stored as name/value pairs in the ViewData dictionary. (Note: in most pre-release versions of MVC 3, the ViewBag property was named the ViewModel property.)

How to ignore the certificate check when ssl

Mention has been made that before .NET 4.5 the property on the request to access its ServicePointManager was not available.

Here is .NET 4.0 code that will give you access to the ServicePoint on a per-request basis. It doesn't give you access to the per-request callback, but it should let you find out more details about the problem. Just access the scvPoint.Certificate (or ClientCertificate if you prefer) properties.

WebRequest request = WebRequest.Create(uri);

// oddity: these two .Address values are not necessarily the same!
//  The service point appears to be related to the .Host, not the Uri itself.
//  So, check the .Host vlaues before fussing in the debugger.
ServicePoint svcPoint = ServicePointManager.FindServicePoint(uri);
if (null != svcPoint)
    if (!request.RequestUri.Host.Equals(svcPoint.Address.Host, StringComparison.OrdinalIgnoreCase))
        Debug.WriteLine(".Address              == " + request.RequestUri.ToString());
        Debug.WriteLine(".ServicePoint.Address == " + svcPoint.Address.ToString());
    Debug.WriteLine(".IssuerName           == " + svcPoint.Certificate.GetIssuerName());

Difference between request.getSession() and request.getSession(true)

request.getSession() is just a convenience method. It does exactly the same as request.getSession(true).

How do I check if a file exists in Java?

I would recommend using isFile() instead of exists(). Most of the time you are looking to check if the path points to a file not only that it exists. Remember that exists() will return true if your path points to a directory.

new File("path/to/file.txt").isFile();

new File("C:/").exists() will return true but will not allow you to open and read from it as a file.

How to restrict the selectable date ranges in Bootstrap Datepicker?

Most answers and explanations are not to explain what is a valid string of endDate or startDate. Danny gave us two useful example.

    startDate: '-2m',
    endDate: '+2d'

But why?let's take a look at the source code at bootstrap-datetimepicker.js. There are some code begin line 1343 tell us how does it work.

if (/^[-+]\d+[dmwy]([\s,]+[-+]\d+[dmwy])*$/.test(date)) {
            var part_re = /([-+]\d+)([dmwy])/,
                parts = date.match(/([-+]\d+)([dmwy])/g),
                part, dir;
            date = new Date();
            for (var i = 0; i < parts.length; i++) {
                part = part_re.exec(parts[i]);
                dir = parseInt(part[1]);
                switch (part[2]) {
                    case 'd':
                        date.setUTCDate(date.getUTCDate() + dir);
                    case 'm':
                        date =, date, dir);
                    case 'w':
                        date.setUTCDate(date.getUTCDate() + dir * 7);
                    case 'y':
                        date =, date, dir);
            return UTCDate(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds(), 0);

There are four kinds of expressions.

  • w means week
  • m means month
  • y means year
  • d means day

Look at the regular expression ^[-+]\d+[dmwy]([\s,]+[-+]\d+[dmwy])*$. You can do more than these -0d or +1m.

Try harder like startDate:'+1y,-2m,+0d,-1w'.And the separator , could be one of [\f\n\r\t\v,]

How to get a substring between two strings in PHP?

  function getBetween($content,$start,$end){
    $r = explode($start, $content);
    if (isset($r[1])){
        $r = explode($end, $r[1]);
        return $r[0];
    return '';


  $content = "Try to find the guy in the middle with this function!";
  $start = "Try to find ";
  $end = " with this function!";
  $output = getBetween($content,$start,$end);
  echo $output;

This will return "the guy in the middle".

How to manually install a pypi module without pip/easy_install?

  1. Download the package
  2. unzip it if it is zipped
  3. cd into the directory containing
  4. If there are any installation instructions contained in documentation contianed herein, read and follow the instructions OTHERWISE
  5. type in python install

You may need administrator privileges for step 5. What you do here thus depends on your operating system. For example in Ubuntu you would say sudo python install

EDIT- thanks to kwatford (see first comment)

To bypass the need for administrator privileges during step 5 above you may be able to make use of the --user flag. In this way you can install the package only for the current user.

The docs say:

Files will be installed into subdirectories of site.USER_BASE (written as userbase hereafter). This scheme installs pure Python modules and extension modules in the same location (also known as site.USER_SITE). Here are the values for UNIX, including Mac OS X:

More details can be found here:

PhpMyAdmin not working on localhost

enter image description here

I was getting the Object not found error as shown in the screen shot while clicking the phpmyadmin link. Apache and SQL server had got started from the xampp console.

Solution: I uninstalled and installed again after deleting all the files and folders of xampp from C drive. Also, this time, I installed just the Apache and the SQL server. After this, phpmyadmin link started to work.


What is the point of WORKDIR on Dockerfile?

Be careful where you set WORKDIR because it can affect the continuous integration flow. For example, setting it to /home/circleci/project will cause error something like .ssh or whatever is the remote circleci is doing at setup time.

jQuery UI 1.10: dialog and zIndex option

Add zIndex property to dialog object:

 zIndex: 10000

How to get the ActionBar height?

This helper method should come in handy for someone. Example: int actionBarSize = getThemeAttributeDimensionSize(this, android.R.attr.actionBarSize);

public static int getThemeAttributeDimensionSize(Context context, int attr)
    TypedArray a = null;
        a = context.getTheme().obtainStyledAttributes(new int[] { attr });
        return a.getDimensionPixelSize(0, 0);
        if(a != null){

How do I make WRAP_CONTENT work on a RecyclerView

i suggest you to put the recyclerview in any other layout (Relative layout is preferable). Then change recyclerview's height/width as match parent to that layout and set the parent layout's height/width as wrap content. it works for me

How to split long commands over multiple lines in PowerShell

You can use the backtick operator:

& "C:\Program Files\IIS\Microsoft Web Deploy\msdeploy.exe" `
    -verb:sync `
    -source:contentPath="c:\workspace\xxx\master\Build\_PublishedWebsites\xxx.Web" `

That's still a little too long for my taste, so I'd use some well-named variables:

$msdeployPath = "C:\Program Files\IIS\Microsoft Web Deploy\msdeploy.exe"
$verbArg = '-verb:sync'
$sourceArg = '-source:contentPath="c:\workspace\xxx\master\Build\_PublishedWebsites\xxx.Web"'
$destArg = '-dest:contentPath="c:\websites\xxx\wwwroot\,computerName=,username=administrator,password=xxx"'

& $msdeployPath $verbArg $sourceArg $destArg

Android: I am unable to have ViewPager WRAP_CONTENT

I based my answer on Daniel López Lacalle and this post The problem with Daniel's answer is that in some cases my children had a height of zero. The solution was to unfortunately measure twice.

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    int mode = MeasureSpec.getMode(heightMeasureSpec);
    // Unspecified means that the ViewPager is in a ScrollView WRAP_CONTENT.
    // At Most means that the ViewPager is not in a ScrollView WRAP_CONTENT.
    if (mode == MeasureSpec.UNSPECIFIED || mode == MeasureSpec.AT_MOST) {
        // super has to be called in the beginning so the child views can be initialized.
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int height = 0;
        for (int i = 0; i < getChildCount(); i++) {
            View child = getChildAt(i);
            child.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
            int h = child.getMeasuredHeight();
            if (h > height) height = h;
        heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
    // super has to be called again so the new specs are treated as exact measurements
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);

This also lets you set a height on the ViewPager if you so want to or just wrap_content.

How to populate/instantiate a C# array with a single value?

I am a bit surprised noone has made the very simple, yet ultra fast, SIMD version:

  public static void PopulateSimd<T>(T[] array, T value) where T : struct
     var vector = new Vector<T>(value);
     var i = 0;
     var s = Vector<T>.Count;
     var l = array.Length & ~(s-1);
     for (; i < l; i += s) vector.CopyTo(array, i);
     for (; i < array.Length; i++) array[i] = value;

Benchmark: (Number are for Framework 4.8, but Core3.1 is statistically the same)

|     Method |       N |           Mean |          Error |        StdDev | Ratio | RatioSD |
|----------- |-------- |---------------:|---------------:|--------------:|------:|--------:|
| DarthGizka |      10 |      25.975 ns |      1.2430 ns |     0.1924 ns |  1.00 |    0.00 |
|       Simd |      10 |       3.438 ns |      0.4427 ns |     0.0685 ns |  0.13 |    0.00 |
|            |         |                |                |               |       |         |
| DarthGizka |     100 |      81.155 ns |      3.8287 ns |     0.2099 ns |  1.00 |    0.00 |
|       Simd |     100 |      12.178 ns |      0.4547 ns |     0.0704 ns |  0.15 |    0.00 |
|            |         |                |                |               |       |         |
| DarthGizka |    1000 |     201.138 ns |      8.9769 ns |     1.3892 ns |  1.00 |    0.00 |
|       Simd |    1000 |     100.397 ns |      4.0965 ns |     0.6339 ns |  0.50 |    0.00 |
|            |         |                |                |               |       |         |
| DarthGizka |   10000 |   1,292.660 ns |     38.4965 ns |     5.9574 ns |  1.00 |    0.00 |
|       Simd |   10000 |   1,272.819 ns |     68.5148 ns |    10.6027 ns |  0.98 |    0.01 |
|            |         |                |                |               |       |         |
| DarthGizka |  100000 |  16,156.106 ns |    366.1133 ns |    56.6564 ns |  1.00 |    0.00 |
|       Simd |  100000 |  17,627.879 ns |  1,589.7423 ns |   246.0144 ns |  1.09 |    0.02 |
|            |         |                |                |               |       |         |
| DarthGizka | 1000000 | 176,625.870 ns | 32,235.9957 ns | 1,766.9637 ns |  1.00 |    0.00 |
|       Simd | 1000000 | 186,812.920 ns | 18,069.1517 ns | 2,796.2212 ns |  1.07 |    0.01 |

As can be seen, it is much faster at <10000 elements, and only slightly slower beyond that.

Ignore files that have already been committed to a Git repository

Thanks to your answer, I was able to write this little one-liner to improve it. I ran it on my .gitignore and repo, and had no issues, but if anybody sees any glaring problems, please comment. This should git rm -r --cached from .gitignore:

cat $(git rev-parse --show-toplevel)/.gitIgnore | sed "s/\/$//" | grep -v "^#" | xargs -L 1 -I {} find $(git rev-parse --show-toplevel) -name "{}" | xargs -L 1 git rm -r --cached

Note that you'll get a lot of fatal: pathspec '<pathspec>' did not match any files. That's just for the files which haven't been modified.

How to update npm

Tried the options above on Ubuntu 14.04, but they would constantly produce this error:

npm ERR! tar pack Error reading /root/tmp/npm-15864/1465947804069-0.4854120113886893/package

Then found this solution online:

1) Clean the cache of npm first:

sudo npm cache clean -f

2) Install n module of npm:

sudo npm install -g n

3) Begin the installation by selecting the version of node to install: stable or latest, we will use stable here:

sudo n stable

4) Check the version of node:

node -v

5) Check the version of npm:

npm -v

Apply multiple functions to multiple groupby columns

This is a twist on 'exans' answer that uses Named Aggregations. It's the same but with argument unpacking which allows you to still pass in a dictionary to the agg function.

The named aggs are a nice feature, but at first glance might seem hard to write programmatically since they use keywords, but it's actually simple with argument/keyword unpacking.

animals = pd.DataFrame({'kind': ['cat', 'dog', 'cat', 'dog'],
                         'height': [9.1, 6.0, 9.5, 34.0],
                         'weight': [7.9, 7.5, 9.9, 198.0]})
agg_dict = {
    "min_height": pd.NamedAgg(column='height', aggfunc='min'),
    "max_height": pd.NamedAgg(column='height', aggfunc='max'),
    "average_weight": pd.NamedAgg(column='weight', aggfunc=np.mean)


The Result

      min_height  max_height  average_weight
cat          9.1         9.5            8.90
dog          6.0        34.0          102.75

Force hide address bar in Chrome on Android


this will help you but this javascript is may not work in all browsers

Failed to instantiate module [$injector:unpr] Unknown provider: $routeProvider

adding to scotty's answer:

Option 1: Either include this in your JS file:

<script src=""></script>

Option 2: or just use the URL to download 'angular-route.min.js' to your local.

and then (whatever option you choose) add this 'ngRoute' as dependency.

explained: var app = angular.module('myapp', ['ngRoute']);


Easy way to dismiss keyboard?

Subclass your textfields... and also textviews

In the subclass put this code..


    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dismissKeyBoard) name:KEYBOARD_DISMISS object:nil];


    [[NSNotificationCenter defaultCenter] removeObserver:self name:KEYBOARD_DISMISS object:nil];

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [self resignFirstResponder];

In the textfield delegates (similarly for textview delegates)

-(void)textFieldDidBeginEditing:(JCPTextField *)textField{
     [textField conformsToKeyboardDismissNotification];

- (void)textFieldDidEndEditing:(JCPTextField *)textField{
    [textField deConformsToKeyboardDismissNotification];

All set.. Now just post the notification from anywhere in your code. It will resign any keyboard.

SQL Server: Get data for only the past year

The other suggestions are good if you have "SQL only".

However I suggest, that - if possible - you calculate the date in your program and insert it as string in the SQL query.

At least for for big tables (i.e. several million rows, maybe combined with joins) that will give you a considerable speed improvement as the optimizer can work with that much better.

Communication between multiple docker-compose projects

The previous posts information is correct, but it does not have details on how to link containers, which should be connected as "external_links".

Hope this example make more clear to you:

  • Suppose you have app1/docker-compose.yml, with two services (svc11 and svc12), and app2/docker-compose.yml with two more services (svc21 and svc22) and suppose you need to connect in a crossed fashion:

  • svc11 needs to connect to svc22's container

  • svc21 needs to connect to svc11's container.

So the configuration should be like this:

this is app1/docker-compose.yml:

version: '2'
        container_name: container11
            - default # this network
            - app2_default # external network
            - container22:container22
       container_name: container12

    default: # this network (app1)
        driver: bridge
    app2_default: # external network (app2)
        external: true

this is app2/docker-compose.yml:

version: '2'
        container_name: container21
            - default # this network (app2)
            - app1_default # external network (app1)
            - container11:container11
       container_name: container22

    default: # this network (app2)
        driver: bridge
    app1_default: # external network (app1)
        external: true

What is unexpected T_VARIABLE in PHP?

In my case it was an issue of the PHP version.

The .phar file I was using was not compatible with PHP 5.3.9. Switching interpreter to PHP 7 did fix it.

How to match a line not containing a word

This should work:


If you only wanted to exclude it from the beginning of the line (I know you don't, but just FYI), you could use this:


Edit (by request): Why this pattern works

The (?!...) syntax is a negative lookahead, which I've always found tough to explain. Basically, it means "whatever follows this point must not match the regular expression /PART/." The site I've linked explains this far better than I can, but I'll try to break this down:

^         #Start matching from the beginning of the string.    
(?!PART)  #This position must not be followed by the string "PART".
.         #Matches any character except line breaks (it will include those in single-line mode).
$         #Match all the way until the end of the string.

The ((?!xxx).)* idiom is probably hardest to understand. As we saw, (?!PART) looks at the string ahead and says that whatever comes next can't match the subpattern /PART/. So what we're doing with ((?!xxx).)* is going through the string letter by letter and applying the rule to all of them. Each character can be anything, but if you take that character and the next few characters after it, you'd better not get the word PART.

The ^ and $ anchors are there to demand that the rule be applied to the entire string, from beginning to end. Without those anchors, any piece of the string that didn't begin with PART would be a match. Even PART itself would have matches in it, because (for example) the letter A isn't followed by the exact string PART.

Since we do have ^ and $, if PART were anywhere in the string, one of the characters would match (?=PART). and the overall match would fail. Hope that's clear enough to be helpful.

Map a network drive to be used by a service

There is a good answer here:

I.e. You can use a symbolic link, e.g.

mklink /D C:\myLink \\\c$

LinearLayout not expanding inside a ScrollView

All the answers here didn't work (completely) for me. Just to recap what we wanna do for a complete answer: We have a ScrollView, supposedly filling the device's viewport, thus we set fillViewport to "true" in the layout xml. Then, inside the ScrollView, we have a LinearLayout containing everything else, and that LinearLayout should be at least as high as its parent ScrollView, so stuff that's supposed to be on the bottom (of the LinearLayout) is actually, as we want it, at the bottom of the screen (or at the bottom of the ScrollView, in case the LinearLayout's content has more hight than the screen.

Example activity_main.xml layout:

...content which might or might not be higher than screen height...

Then, in the activity's onCreate, we "wait" for the LinearLayout's layouting to be done (implying it's parent's layouting is also already done) and then set it's minimum height to the ScrollView's height. Thus it also works in case the ScrollView does not occupy the whole screen height. Whether you call .post(...) on the ScrollView or the inner LinearLayout should not make that much of a difference, if one doesn't work for you, try the other.

public class MainActivity extends AppCompatActivity {

@Override // Activity
protected void onCreate(Bundle savedInstanceState) {

    LinearLayout linearLayoutWrapper = findViewById(;

    ... -> {

Sadly, it's not an xml-only solution, but it works well enough for me, hope it also helps some other tortured android dev scouring the interwebs in search for a solution to this problem ;D

Add button to a layout programmatically

If you just have included a layout file at the beginning of onCreate() inside setContentView and want to get this layout to add new elements programmatically try this:

ViewGroup linearLayout = (ViewGroup) findViewById(;

then you can create a new Button for example and just add it:

Button bt = new Button(this);
bt.setText("A Button");
bt.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, 

Detect end of ScrollView

I found a simple way to detect this :

       .addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
            public void onScrollChanged() {
                if (scrollView.getChildAt(0).getBottom()
                     <= (scrollView.getHeight() + scrollView.getScrollY())) {
                    //scroll view is at bottom
                } else {
                    //scroll view is not at bottom
  • Doesn't need to custom ScrollView.
  • Scrollview can host only one direct child, so scrollView.getChildAt(0) is okay.
  • This solution is right even the height of direct child of scroll view is match_parent or wrap_content.

Setting a property with an EventTrigger

Stopping the Storyboard can be done in the code behind, or the xaml, depending on where the need comes from.

If the EventTrigger is moved outside of the button, then we can go ahead and target it with another EventTrigger that will tell the storyboard to stop. When the storyboard is stopped in this manner it will not revert to the previous value.

Here I've moved the Button.Click EventTrigger to a surrounding StackPanel and added a new EventTrigger on the the CheckBox.Click to stop the Button's storyboard when the CheckBox is clicked. This lets us check and uncheck the CheckBox when it is clicked on and gives us the desired unchecking behavior from the button as well.

    <StackPanel x:Name="myStackPanel">

        <CheckBox x:Name="myCheckBox"
                  Content="My CheckBox" />

        <Button Content="Click to Uncheck"
                x:Name="myUncheckButton" />

        <Button Content="Click to check the box in code."
                Click="OnClick" />


            <EventTrigger RoutedEvent="Button.Click"
                    <BeginStoryboard x:Name="myBeginStoryboard">
                        <Storyboard x:Name="myStoryboard">
                            <BooleanAnimationUsingKeyFrames Storyboard.TargetName="myCheckBox"
                                <DiscreteBooleanKeyFrame KeyTime="00:00:00"
                                                         Value="False" />

            <EventTrigger RoutedEvent="CheckBox.Click"
                    <StopStoryboard BeginStoryboardName="myBeginStoryboard" />


To stop the storyboard in the code behind, we will have to do something slightly different. The third button provides the method where we will stop the storyboard and set the IsChecked property back to true through code.

We can't call myStoryboard.Stop() because we did not begin the Storyboard through the code setting the isControllable parameter. Instead, we can remove the Storyboard. To do this we need the FrameworkElement that the storyboard exists on, in this case our StackPanel. Once the storyboard is removed, we can once again set the IsChecked property with it persisting to the UI.

    private void OnClick(object sender, RoutedEventArgs e)
        myCheckBox.IsChecked = true;

How to install libusb in Ubuntu

This should work:

# apt-get install libusb-1.0-0-dev

Javamail Could not convert socket to TLS GMail

props.put("", "");

PostgreSQL - SQL state: 42601 syntax error

Your function would work like this:

CREATE OR REPLACE FUNCTION prc_tst_bulk(sql text)
RETURNS TABLE (name text, rowcount integer) AS 

WITH v_tb_person AS (' || sql || $x$)
SELECT name, count(*)::int FROM v_tb_person WHERE nome LIKE '%a%' GROUP BY name
SELECT name, count(*)::int FROM v_tb_person WHERE gender = 1 GROUP BY name$x$;

$$ LANGUAGE plpgsql;


SELECT * FROM prc_tst_bulk($$SELECT a AS name, b AS nome, c AS gender FROM tbl$$)
  • You cannot mix plain and dynamic SQL the way you tried to do it. The whole statement is either all dynamic or all plain SQL. So I am building one dynamic statement to make this work. You may be interested in the chapter about executing dynamic commands in the manual.

  • The aggregate function count() returns bigint, but you had rowcount defined as integer, so you need an explicit cast ::int to make this work

  • I use dollar quoting to avoid quoting hell.

However, is this supposed to be a honeypot for SQL injection attacks or are you seriously going to use it? For your very private and secure use, it might be ok-ish - though I wouldn't even trust myself with a function like that. If there is any possible access for untrusted users, such a function is a loaded footgun. It's impossible to make this secure.

Craig (a sworn enemy of SQL injection!) might get a light stroke, when he sees what you forged from his piece of code in the answer to your preceding question. :)

The query itself seems rather odd, btw. But that's beside the point here.

In Java, how to append a string more efficiently?

- Each time you append or do any modification with it, it creates a new String object.

- So use append() method of StringBuilder(If thread safety is not important), else use StringBuffer(If thread safety is important.), that will be efficient way to do it.

How to test an SQL Update statement before running it?

Run select query on same table with all where conditions you are applying in update query.

Clearing content of text file using php

This would truncate the file:

$fh = fopen( 'filelist.txt', 'w' );

In clear.php, redirect to the caller page by making use of $_SERVER['HTTP_REFERER'] value.

Simple PHP form: Attachment to email (code golf)

Just for fun I thought I'd knock it up. It ended up being trickier than I thought because I went in not fully understanding how the boundary part works, eventually I worked out that the starting and ending '--' were significant and off it went.

        //The form has been submitted, prep a nice thank you message
        $output = '<h1>Thanks for your file and message!</h1>';
        //Set the form flag to no display (cheap way!)
        $flags = 'style="display:none;"';

        //Deal with the email
        $to = '[email protected]';
        $subject = 'a file for you';

        $message = strip_tags($_POST['message']);
        $attachment = chunk_split(base64_encode(file_get_contents($_FILES['file']['tmp_name'])));
        $filename = $_FILES['file']['name'];

        $boundary =md5(date('r', time())); 

        $headers = "From: [email protected]\r\nReply-To: [email protected]";
        $headers .= "\r\nMIME-Version: 1.0\r\nContent-Type: multipart/mixed; boundary=\"_1_$boundary\"";

        $message="This is a multi-part message in MIME format.

Content-Type: multipart/alternative; boundary=\"_2_$boundary\"

Content-Type: text/plain; charset=\"iso-8859-1\"
Content-Transfer-Encoding: 7bit


Content-Type: application/octet-stream; name=\"$filename\" 
Content-Transfer-Encoding: base64 
Content-Disposition: attachment 


        mail($to, $subject, $message, $headers);
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">


<?php echo $output; ?>

<form enctype="multipart/form-data" action="<?php echo $_SERVER['PHP_SELF'];?>" method="post" <?php echo $flags;?>>
<p><label for="message">Message</label> <textarea name="message" id="message" cols="20" rows="8"></textarea></p>
<p><label for="file">File</label> <input type="file" name="file" id="file"></p>
<p><input type="submit" name="submit" id="submit" value="send"></p>

Very barebones really, and obviously the using inline CSS to hide the form is a bit cheap and you'd almost certainly want a bit more feedback to the user! Also, I'd probably spend a bit more time working out what the actual Content-Type for the file is, rather than cheating and using application/octet-stream but that part is quite as interesting.

How to skip over an element in .map()?

To extrapolate on Felix Kling's comment, you can use .filter() like this:

var sources = (img) {
  if(img.src.split('.').pop() === "json") { // if extension is .json
    return null; // skip
  } else {
    return img.src;

That will remove falsey values from the array that is returned by .map()

You could simplify it further like this:

var sources = (img) {
  if(img.src.split('.').pop() !== "json") { // if extension is .json
    return img.src;

Or even as a one-liner using an arrow function, object destructuring and the && operator:

var sources ={ src }) => src.split('.').pop() !== "json" && src).filter(Boolean);

How do I restart my C# WinForm Application?

public static void appReloader()
        //Start a new instance of the current program

        //close the current application process

Application.ExecutablePath returns your aplication .exe file path Please follow the order of calls. You might want to place it in a try-catch clause.

Retrieving the text of the selected <option> in <select> element


java : convert float to String and String to float

Float to string - String.valueOf()

float amount=100.00f;
String strAmount=String.valueOf(amount);
// or  Float.toString(float)

String to Float - Float.parseFloat()

String strAmount="100.20";
float amount=Float.parseFloat(strAmount)
// or  Float.valueOf(string)

How to output git log with the first line only?

You can define a global alias so you can invoke a short log in a more comfortable way:

git config --global alias.slog "log --pretty=oneline --abbrev-commit"

Then you can call it using git slog (it even works with autocompletion if you have it enabled).

Why does calling sumr on a stream with 50 tuples not complete

sumr is implemented in terms of foldRight:

 final def sumr(implicit A: Monoid[A]): A = F.foldRight(self, 

foldRight is not always tail recursive, so you can overflow the stack if the collection is too long. See Why foldRight and reduceRight are NOT tail recursive? for some more discussion of when this is or isn't true.

Jenkins fails when running "service start jenkins"

ERROR: Linux / Centos:

Job for jenkins.service failed because the control process exited with error code. See "systemctl status jenkins.service" and "journalctl -xe" for details.


  • Edit the Jenkins init file by doing

    sudo vi /etc/init.d/jenkins
  • Add your own Java path, for example:

  • Restart the service:

    sudo service jenkins start
    sudo service jenkins status
    sudo service jenkins stop

What are the differences between char literals '\n' and '\r' in Java?

\n is for unix
\r is for mac (before OS X)
\r\n is for windows format

you can also take System.getProperty("line.separator")

it will give you the appropriate to your OS

How do I update/upsert a document in Mongoose?

//Here is my code to it... work like ninj

router.param('contractor', function(req, res, next, id) {
  var query = Contractors.findById(id);

  query.exec(function (err, contractor){
    if (err) { return next(err); }
    if (!contractor) { return next(new Error("can't find contractor")); }

    req.contractor = contractor;
    return next();

router.get('/contractors/:contractor/save', function(req, res, next) {

    contractor = req.contractor ;
    contractor.update({'_id':contractor._id},{upsert: true},function(err,contractor){
            return next(); 
    return res.json(contractor); 


Difference between ProcessBuilder and Runtime.exec()

Look at how Runtime.getRuntime().exec() passes the String command to the ProcessBuilder. It uses a tokenizer and explodes the command into individual tokens, then invokes exec(String[] cmdarray, ......) which constructs a ProcessBuilder.

If you construct the ProcessBuilder with an array of strings instead of a single one, you'll get to the same result.

The ProcessBuilder constructor takes a String... vararg, so passing the whole command as a single String has the same effect as invoking that command in quotes in a terminal:

shell$ "command with args"

mysqli_fetch_array while loop columns

I think this would be a more simpler way of outputting your results.

Sorry for using my own data should be easy to replace .

$query = "SELECT * FROM category ";

$result = mysqli_query($connection, $query);

    while($row = mysqli_fetch_assoc($result))
        $cat_id = $row['cat_id'];
        $cat_title = $row['cat_title'];

        echo $cat_id . " " . $cat_title  ."<br>";

This would output :

  • -ID Title
  • -1 Gary
  • -2 John
  • -3 Michaels

What are the minimum margins most printers can handle?

Every printer is different but 0.25" (6.35 mm) is a safe bet.

Detect click inside/outside of element with single event handler

For bootstrap 4 this works for me.

$(document).on('click', function(e) {
    $('[data-toggle="popover"],[data-original-title]').each(function() {
        if (!$(this).is( && $(this).has( === 0 && $('.popover').has( === 0) {

working demo on jsfiddle link:

What does the ELIFECYCLE Node.js error mean?

When running Webpack build I was getting similar error because node doesn't understand async await keywords on older versions. I added webpack babel-plugin-transform-async-to-generator and it was solved. This replaces them with promises.

Creating a textarea with auto-resize

I know I'm late to this party but the simplest solution I've come across is to split your text area content on new line characters and update the rows for the textarea element.

<textarea id="my-text-area"></textarea>

  $(function() {
    const txtArea = $('#my-text-area')
    const val = txtArea.val()
    const rowLength = val.split('\n')
    txtArea.attr('rows', rowLength)

Finding the average of an array using JS

answer to your 1. question:

for ( var i = 0; i < grades.length; i ++){
    var avg = (grades[i] / grades.length) * grades.length

avg is declared in each loop. Thus, at the end of the loop, avg has the value of the last item in the array : 68 *5 / 5

Write-back vs Write-Through caching?

Write-back and write-through describe policies when a write hit occurs, that is when the cache has the requested information. In these examples, we assume a single processor is writing to main memory with a cache.

Write-through: The information is written to the cache and memory, and the write finishes when both have finished. This has the advantage of being simpler to implement, and the main memory is always consistent (in sync) with the cache (for the uniprocessor case - if some other device modifies main memory, then this policy is not enough), and a read miss never results in writes to main memory. The obvious disadvantage is that every write hit has to do two writes, one of which accesses slower main memory.

Write-back: The information is written to a block in the cache. The modified cache block is only written to memory when it is replaced (in effect, a lazy write). A special bit for each cache block, the dirty bit, marks whether or not the cache block has been modified while in the cache. If the dirty bit is not set, the cache block is "clean" and a write miss does not have to write the block to memory.

The advantage is that writes can occur at the speed of the cache, and if writing within the same block only one write to main memory is needed (when the previous block is being replaced). The disadvantages are that this protocol is harder to implement, main memory can be not consistent (not in sync) with the cache, and reads that result in replacement may cause writes of dirty blocks to main memory.

The policies for a write miss are detailed in my first link.

These protocols don't take care of the cases with multiple processors and multiple caches, as is common in modern processors. For this, more complicated cache coherence mechanisms are required. Write-through caches have simpler protocols since a write to the cache is immediately reflected in memory.

Good resources:

ADB server version (36) doesn't match this client (39) {Not using Genymotion}

I think you have multiple adb server running, genymotion could be one of them, but also Xamarin - Visual studio for mac OS could be running an adb server, closing Visual studio worked for me

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

Please add attribute useLegacyV2RuntimeActivationPolicy="true" in your applications app.config file.

Old Value

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

New Value

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

It will solve your problem.

How can you get the Manifest Version number from the App's (Layout) XML variables?

Late to the game, but you can do it without @string/xyz by using ?android:attr

    <!-- or -->

SQLSTATE[HY093]: Invalid parameter number: parameter was not defined

I had the same error. My issue was using the wrong parameter name when binding.

Notice :tokenHash in the query, but :token_hash when binding. Fixing one or the other resolves the error in this instance.

// Prepare DB connection
$sql = 'INSERT INTO rememberedlogins (token_hash,user_id,expires_at)
        VALUES (:tokenHash,:user_id,:expires_at)';
$db = static::getDB();
$stmt = $db->prepare($sql);

// Bind values

Is it possible to have empty RequestParam values use the defaultValue?

You can set RequestParam, using generic class Integer instead of int, it will resolve your issue.

   @RequestParam(value= "i", defaultValue = "20") Integer i

intellij incorrectly saying no beans of type found for autowired repository

Putting @Component or @configuration in your bean config file seems to work, ie something like:

public class MyApplicationContext {
    public DirectoryScanner scanner() {
        return new WatchServiceDirectoryScanner("/tmp/myDir");

public class MyApplicationContext {
    public DirectoryScanner scanner() {
        return new WatchServiceDirectoryScanner("/tmp/myDir");

How to add spacing between columns?

Bootstrap col slightly use some spaces both left and right. I have just added a block element like div and set border for the differences. also adding some extra padding or margin in that extra div will work perfectly..

<link href="" rel="stylesheet"/>


<div class="container">
    <div class="row">
        <div class="col-6 ">
            <div class="border border-danger ">
                <h2 class="text-center">1</h2>
        <div class="col-6">
            <div class="border border-warning">
                <h2 class="text-center">2</h2>

How to convert string to char array in C++?

Simplest way I can think of doing it is:

string temp = "cat";
char tab2[1024];
strcpy(tab2, temp.c_str());

For safety, you might prefer:

string temp = "cat";
char tab2[1024];
strncpy(tab2, temp.c_str(), sizeof(tab2));
tab2[sizeof(tab2) - 1] = 0;

or could be in this fashion:

string temp = "cat";
char * tab2 = new char [temp.length()+1];
strcpy (tab2, temp.c_str());

MatPlotLib: Multiple datasets on the same scatter plot

I don't know, it works fine for me. Exact commands:

import scipy, pylab
ax = pylab.subplot(111)
ax.scatter(scipy.randn(100), scipy.randn(100), c='b')
ax.scatter(scipy.randn(100), scipy.randn(100), c='r')

What is the color code for transparency in CSS?

There is no transparency component of the color hex string. There is opacity, which is a float from 0.0 to 1.0.

How to set x axis values in matplotlib python?

The scaling on your example figure is a bit strange but you can force it by plotting the index of each x-value and then setting the ticks to the data points:

import matplotlib.pyplot as plt
x = [0.00001,0.001,0.01,0.1,0.5,1,5]
# create an index for each tick position
xi = list(range(len(x)))
y = [0.945,0.885,0.893,0.9,0.996,1.25,1.19]
# plot the index for the x-values
plt.plot(xi, y, marker='o', linestyle='--', color='r', label='Square') 
plt.xticks(xi, x)

How to find controls in a repeater header or footer

You can take a reference on the control on the ItemCreated event, and then use it later.

SQL UPDATE with sub-query that references the same table in MySQL

Abstract example with clearer table and column names:

UPDATE tableName t1
INNER JOIN tableName t2 ON t2.ref_column = t1.ref_column
SET t1.column_to_update = t2.column_desired_value

As suggested by @Nico

Hope this help someone.

Apache SSL Configuration Error (SSL Connection Error)

I was getting the same error in chrome (and different one in Firefox, IE). Also in error.log i was getting [error] [client cli.ent.ip.add] Invalid method in request \x16\x03 Following the instructions form this site I changed my configuration FROM:


   ServerAdmin [email protected]

   SSLEngine On
   SSLCertificateFile conf/ssl/ssl.crt
   SSLCertificateKeyFile conf/ssl/ssl.key


<VirtualHost _default_:443>

   ServerAdmin [email protected]

   SSLEngine On
   SSLCertificateFile conf/ssl/ssl.crt
   SSLCertificateKeyFile conf/ssl/ssl.key

Now it's working fine :)

Using `window.location.hash.includes` throws “Object doesn't support property or method 'includes'” in IE11

I'm using ReactJs and used import 'core-js/es6/string'; at the start of index.js to solve my problem.

I'm also using import 'react-app-polyfill/ie11'; to support running React in IE11.


This package includes polyfills for various browsers. It includes minimum requirements and commonly used language features used by Create React App projects.

How to create a new branch from a tag?

I have resolve the problem as below 1. Get the tag from your branch 2. Write below command

Example: git branch <Hotfix branch> <TAG>
    git branch hotfix_4.4.3 v4.4.3
    git checkout hotfix_4.4.3

or you can do with other command

git checkout -b <Hotfix branch> <TAG>
-b stands for creating new branch to local 

once you ready with your hotfix branch, It's time to move that branch to github, you can do so by writing below command

git push --set-upstream origin hotfix_4.4.3

Creating composite primary key in SQL Server

How about this:

ALTER TABLE dbo.testRequest
PRIMARY KEY (wardNo, BHTNo, TestID) 

Dynamic constant assignment

Ruby doesn't like that you are assigning the constant inside of a method because it risks re-assignment. Several SO answers before me give the alternative of assigning it outside of a method--but in the class, which is a better place to assign it.

How can I convert a stack trace to a string?

if you are using Java 8, try this

you can find the code for getStackTrace() function provided by as :

public StackTraceElement[] getStackTrace() {
    return getOurStackTrace().clone();

and for StackTraceElement, it provides toString() as follows:

public String toString() {
    return getClassName() + "." + methodName +
        (isNativeMethod() ? "(Native Method)" :
         (fileName != null && lineNumber >= 0 ?
          "(" + fileName + ":" + lineNumber + ")" :
          (fileName != null ?  "("+fileName+")" : "(Unknown Source)")));

So just join the StackTraceElement with "\n".

Why are unnamed namespaces used and what are their benefits?

Unnamed namespaces are a utility to make an identifier translation unit local. They behave as if you would choose a unique name per translation unit for a namespace:

namespace unique { /* empty */ }
using namespace unique;
namespace unique { /* namespace body. stuff in here */ }

The extra step using the empty body is important, so you can already refer within the namespace body to identifiers like ::name that are defined in that namespace, since the using directive already took place.

This means you can have free functions called (for example) help that can exist in multiple translation units, and they won't clash at link time. The effect is almost identical to using the static keyword used in C which you can put in in the declaration of identifiers. Unnamed namespaces are a superior alternative, being able to even make a type translation unit local.

namespace { int a1; }
static int a2;

Both a's are translation unit local and won't clash at link time. But the difference is that the a1 in the anonymous namespace gets a unique name.

Read the excellent article at comeau-computing Why is an unnamed namespace used instead of static? ( mirror).

how to stop Javascript forEach?

    var f = "how to stop Javascript forEach?".split(' ');
    f.forEach(function (a,b){;
        if (a == 'stop') {
            console.warn("\tposition: \'stop\'["+(b+1)+"] \r\n\tall length: " + (f.length)); 
            f.length = 0; //<--!!!

Batch File; List files in directory, only filenames?

1.Open notepad

2.Create new file

3.type bellow line

dir /b > fileslist.txt

4.Save "list.bat"

Thats it. now you can copy & paste this "list.bat" file any of your folder location and double click it, it will create a "fileslist.txt" along with that directory folder and file name list.

Sample Output: enter image description here

Note: If you want create file name list along with sub folder, then you can create batch file with bellow code.

dir /b /s > fileslist.txt

Separating class code into a header and cpp file

Basically a modified syntax of function declaration/definitions:


class A2DD
  int gx;
  int gy;

  A2DD(int x,int y);

  int getSum();


A2DD::A2DD(int x,int y)
  gx = x;
  gy = y;

int A2DD::getSum()
  return gx + gy;

How do I call a SQL Server stored procedure from PowerShell?

Consider calling osql.exe (the command line tool for SQL Server) passing as parameter a text file written for each line with the call to the stored procedure.

SQL Server provides some assemblies that could be of use with the name SMO that have seamless integration with PowerShell. Here is an article on that.

There are API methods to execute stored procedures that I think are worth being investigated. Here a startup example:

When saving, how can you check if a field has changed?

Here is another way of doing it.

class Parameter(models.Model):

    def __init__(self, *args, **kwargs):
        super(Parameter, self).__init__(*args, **kwargs)
        self.__original_value = self.value

    def clean(self,*args,**kwargs):
        if self.__original_value == self.value:

    def save(self,*args,**kwargs):
        return super(Parameter, self).save(*args, **kwargs)
        self.__original_value = self.value

    key = models.CharField(max_length=24, db_index=True, unique=True)
    value = models.CharField(max_length=128)

As per documentation: validating objects

"The second step full_clean() performs is to call Model.clean(). This method should be overridden to perform custom validation on your model. This method should be used to provide custom model validation, and to modify attributes on your model if desired. For instance, you could use it to automatically provide a value for a field, or to do validation that requires access to more than a single field:"

How can I run a php without a web server?

You can use these kind of programs to emulate an apache web server and run PHP on your computer:

How can I get the actual video URL of a YouTube live stream?

You need to get the HLS m3u8 playlist files from the video's manifest. There are ways to do this by hand, but for simplicity I'll be using the youtube-dl tool to get this information. I'll be using this live stream as an example:

First, get the formats of the video:

?  ~ youtube-dl --list-formats\?v\=_Gtc-GtLlTk
[youtube] _Gtc-GtLlTk: Downloading webpage
[youtube] _Gtc-GtLlTk: Downloading video info webpage
[youtube] Downloading multifeed video (_Gtc-GtLlTk, aflWCT1tYL0) - add --no-playlist to just download video _Gtc-GtLlTk
[download] Downloading playlist: Southwest Florida Eagle Cam
[youtube] playlist Southwest Florida Eagle Cam: Collected 2 video ids (downloading 2 of them)
[download] Downloading video 1 of 2
[youtube] _Gtc-GtLlTk: Downloading webpage
[youtube] _Gtc-GtLlTk: Downloading video info webpage
[youtube] _Gtc-GtLlTk: Extracting video information
[youtube] _Gtc-GtLlTk: Downloading formats manifest
[youtube] _Gtc-GtLlTk: Downloading DASH manifest
[info] Available formats for _Gtc-GtLlTk:
format code  extension  resolution note
140          m4a        audio only DASH audio  144k , m4a_dash container, mp4a.40.2@128k (48000Hz)
160          mp4        256x144    DASH video  124k , avc1.42c00b, 30fps, video only
133          mp4        426x240    DASH video  258k , avc1.4d4015, 30fps, video only
134          mp4        640x360    DASH video  646k , avc1.4d401e, 30fps, video only
135          mp4        854x480    DASH video 1171k , avc1.4d401f, 30fps, video only
136          mp4        1280x720   DASH video 2326k , avc1.4d401f, 30fps, video only
137          mp4        1920x1080  DASH video 4347k , avc1.640028, 30fps, video only
151          mp4        72p        HLS , h264, aac  @ 24k
132          mp4        240p       HLS , h264, aac  @ 48k
92           mp4        240p       HLS , h264, aac  @ 48k
93           mp4        360p       HLS , h264, aac  @128k
94           mp4        480p       HLS , h264, aac  @128k
95           mp4        720p       HLS , h264, aac  @256k
96           mp4        1080p      HLS , h264, aac  @256k (best)
[download] Downloading video 2 of 2
[youtube] aflWCT1tYL0: Downloading webpage
[youtube] aflWCT1tYL0: Downloading video info webpage
[youtube] aflWCT1tYL0: Extracting video information
[youtube] aflWCT1tYL0: Downloading formats manifest
[youtube] aflWCT1tYL0: Downloading DASH manifest
[info] Available formats for aflWCT1tYL0:
format code  extension  resolution note
140          m4a        audio only DASH audio  144k , m4a_dash container, mp4a.40.2@128k (48000Hz)
160          mp4        256x144    DASH video  124k , avc1.42c00b, 30fps, video only
133          mp4        426x240    DASH video  258k , avc1.4d4015, 30fps, video only
134          mp4        640x360    DASH video  646k , avc1.4d401e, 30fps, video only
135          mp4        854x480    DASH video 1171k , avc1.4d401f, 30fps, video only
136          mp4        1280x720   DASH video 2326k , avc1.4d401f, 30fps, video only
151          mp4        72p        HLS , h264, aac  @ 24k
132          mp4        240p       HLS , h264, aac  @ 48k
92           mp4        240p       HLS , h264, aac  @ 48k
93           mp4        360p       HLS , h264, aac  @128k
94           mp4        480p       HLS , h264, aac  @128k
95           mp4        720p       HLS , h264, aac  @256k (best)
[download] Finished downloading playlist: Southwest Florida Eagle Cam

In this case, there are two videos because the live stream contains two cameras. From here, we need to get the HLS URL for a specific stream. Use -f to pass in the format you would like to watch, and -g to get that stream's URL:

?  ~ youtube-dl -f 95 -g\?v\=_Gtc-GtLlTk,9410706,9416126,9418581,9420452,9422596,9422780,9423059,9423661,9423662,9425349,9425959,9426661,9426720,9427325,9428422,9429306/upn/xmL7zNht848/mt/1456412649/ip/,ipbits,expire,id,itag,source,requiressl,ratebypass,live,cmbypass,gir,dg_shard,hls_chunk_host,playlist_type,gcr,pmbypass,mm,mn,ms,mv,pl/signature/7E48A727654105FF82E158154FCBA7569D52521B.1FA117183C664F00B7508DDB81274644F520C27F/key/dg_yt0/playlist/index.m3u8,9410706,9416126,9418581,9420452,9422596,9422780,9423059,9423661,9423662,9425349,9425959,9426661,9426720,9427325,9428422,9429306/mt/1456412649/ip/,ipbits,expire,id,itag,source,requiressl,ratebypass,live,cmbypass,gir,dg_shard,hls_chunk_host,pmbypass,playlist_type,gcr,mm,mn,ms,mv,pl/signature/4E83CD2DB23C2331CE349CE9AFE806C8293A01ED.880FD2E253FAC8FA56FAA304C78BD1D62F9D22B4/key/dg_yt0/playlist/index.m3u8

These are your HLS m3u8 playlists, one for each camera associated with the live stream.

Without youtube-dl, your flow might look like this:

Take your video id and make a GET request to the get_video_info endpoint:


In the response, the hlsvp value will be the link to the m3u8 HLS playlist:

How do you remove a specific revision in the git history?

If all you want to do is remove the changes made in revision 3, you might want to use git revert.

Git revert simply creates a new revision with changes that undo all of the changes in the revision you are reverting.

What this means, is that you retain information about both the unwanted commit, and the commit that removes those changes.

This is probably a lot more friendly if it's at all possible the someone has pulled from your repository in the mean time, since the revert is basically just a standard commit.

Adjust width of input field to its input

You would like to change the size attribute as the text changes.

# react

const resizeInput = (e) => {'size', || 1);

  size={(propertyInput.current && propertyInput.current.value.length) || 1}


How to convert hex to rgb using Java?

The easiest way:

// 0000FF
public static Color hex2Rgb(String colorStr) {
    return new Color(Integer.valueOf(colorStr, 16));

Visual Studio 2017 does not have Business Intelligence Integration Services/Projects

SSIS Integration with Visual Studio 2017 available from Aug 2017.

SSIS designer is now available for Visual Studio 2017! ARCHIVE

I installed in July 2018 and appears working fine. See Download link

How to check command line parameter in ".bat" file?

The short answer - use square brackets:

if [%1]==[] goto :blank

or (when you need to handle quoted args, see the Edit below):

if [%~1]==[] goto :blank

Why? you might ask. Well, just as Jeremiah Willcock mentioned: - they use that! OK, but what's wrong with the quotes?

Again, short answer: they are "magical" - sometimes double (double) quotes get converted to a single (double) quote. And they need to match, for a start.

Consider this little script:

@rem argq.bat
@echo off

if "%1"=="" goto :done
echo %1
goto :loop

echo Done.

Let's test it:

C:\> argq bla bla

Seems to work. But now, lets switch to second gear:

C:\> argq "bla bla"
bla""=="" was unexpected at this time.

Boom This didn't evaluate to true, neither did it evaluate to false. The script DIED. If you were supposed to turn off the reactor somewhere down the line, well - tough luck. You now will die like Harry Daghlian.

You may think - OK, the arguments can't contain quotes. If they do, this happens. Wrong Here's some consolation:

C:\> argq ""bla bla""

Oh yeah. Don't worry - sometimes this will work.

Let's try another script:

@rem args.bat
@echo off

if [%1]==[] goto :done
echo %1
goto :loop

echo Done.

You can test yourself, that it works OK for the above cases. This is logical - quotes have nothing to do with brackets, so there's no magic here. But what about spicing the args up with brackets?

D:\>args ]bla bla[

D:\>args [bla bla]

No luck there. The brackets just can't choke cmd.exe's parser.

Let's go back to the evil quotes for a moment. The problem was there, when the argument ended with a quote:

D:\>argq "bla1 bla2"
bla2""=="" was unexpected at this time.

What if I pass just:

D:\>argq bla2"
The syntax of the command is incorrect.

The script won't run at all. Same for args.bat:

D:\>args bla2"
The syntax of the command is incorrect.

But what do I get, when the number of "-characters "matches" (i.e. - is even), in such a case:

D:\>args bla2" "bla3
bla2" "bla3

NICE - I hope you learned something about how .bat files split their command line arguments (HINT: *It's not exactly like in bash). The above argument contains a space. But the quotes are not stripped automatically.

And argq? How does it react to that? Predictably:

D:\>argq bla2" "bla3
"bla3"=="" was unexpected at this time.

So - think before you say: "Know what? Just use quotes. [Because, to me, this looks nicer]".


Recently, there were comments about this answer - well, sqare brackets "can't handle" passing quoted arguments and treating them just as if they weren't quoted.

The syntax:

if "%~1"=="" (...)

Is not some newly found virtue of the double quotes, but a display of a neat feature of stripping quotes from the argument variable, if the first and last character is a double quote.

This "technology" works just as well with square brackets:

if [%~1]==[] (...)

It was a useful thing to point this out, so I also upvote the new answer.

Finally, double quote fans, does an argument of the form "" exist in your book, or is it blank? Just askin' ;)

powerpoint loop a series of animation

Unfortunately you're probably done with the animation and presentation already. In the hopes this answer can help future questioners, however, this blog post has a walkthrough of steps that can loop a single slide as a sort of sub-presentation.

First, click Slide Show > Set Up Show.

Put a checkmark to Loop continuously until 'Esc'.

Click Ok. Now, Click Slide Show > Custom Shows. Click New.

Select the slide you are looping, click Add. Click Ok and Close.

Click on the slide you are looping. Click Slide Show > Slide Transition. Under Advance slide, put a checkmark to Automatically After. This will allow the slide to loop automatically. Do NOT Apply to all slides.

Right click on the thumbnail of the current slide, select Hide Slide.

Now, you will need to insert a new slide just before the slide you are looping. On the new slide, insert an action button. Set the hyperlink to the custom show you have created. Put a checkmark on "Show and Return"

This has worked for me.

Python-equivalent of short-form "if" in C++

My cryptic version...

a = ['123', '456'][b == True]

An invalid XML character (Unicode: 0xc) was found

public String stripNonValidXMLCharacters(String in) {
    StringBuffer out = new StringBuffer(); // Used to hold the output.
    char current; // Used to reference the current character.

    if (in == null || ("".equals(in))) return ""; // vacancy test.
    for (int i = 0; i < in.length(); i++) {
        current = in.charAt(i); // NOTE: No IndexOutOfBoundsException caught here; it should not happen.
        if ((current == 0x9) ||
            (current == 0xA) ||
            (current == 0xD) ||
            ((current >= 0x20) && (current <= 0xD7FF)) ||
            ((current >= 0xE000) && (current <= 0xFFFD)) ||
            ((current >= 0x10000) && (current <= 0x10FFFF)))
    return out.toString();

Obtain form input fields using jQuery?

Here is another solution, this way you can fetch all data about the form and use it in a serverside call or something.

$('.form').on('submit', function( e )){ 
   var form = $( this ), // this will resolve to the form submitted
       action = form.attr( 'action' ),
         type = form.attr( 'method' ),
         data = {};

     // Make sure you use the 'name' field on the inputs you want to grab. 
   form.find( '[name]' ).each( function( i , v ){
      var input = $( this ), // resolves to current input element.
          name = input.attr( 'name' ),
          value = input.val();
      data[name] = value;

  // Code which makes use of 'data'.


You can then use this with ajax calls:

function sendRequest(action, type, data) {
            url: action,
           type: type,
           data: data
       .done(function( returnedHtml ) {
           $( "#responseDiv" ).append( returnedHtml );
       .fail(function() {
           $( "#responseDiv" ).append( "This failed" );

Hope this is of any use for any of you :)

Why do I get a "Null value was assigned to a property of primitive type setter of" error message when using HibernateCriteriaBuilder in Grails

@Dinh Nhat, your setter method looks wrong because you put a primitive type there again and it should be:

public void setClient_os_id(Integer clientOsId) {
client_os_id = clientOsId;

JPA mapping: "QuerySyntaxException: foobar is not mapped..."

There is also another possible source of this error. In some J2EE / web containers (in my experience under Jboss 7.x and Tomcat 7.x) You have to add each class You want to use as a hibernate Entity into the file persistence.xml as


In case of jboss this concerns every entity class (local - i.e. within the project You are developing or in a library). In case of Tomcat 7.x this concerns only entity classes within libraries.

Gridview with two columns and auto resized images

another simple approach with modern built-in stuff like PercentRelativeLayout is now available for new users who hit this problem. thanks to android team for release this item.

< xmlns:android=""

<FrameLayout xmlns:android=""

        android:scaleType="centerCrop" />

        android:textColor="@android:color/white" />


and for better performance you can use some stuff like picasso image loader which help you to fill whole width of every image parents. for example in your adapter you should use this:

int width= context.getResources().getDisplayMetrics().widthPixels;
            .load("some url")

now you dont need CustomImageView Class anymore.

P.S i recommend to use ImageView in place of Type Int in class Item.

hope this help..

oracle.jdbc.driver.OracleDriver ClassNotFoundException

java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver

Just add the ojdbc14.jar to your classpath.

The following are the steps that are given below to add ojdbc14.jar in eclipse:

1) Inside your project

2) Libraries

3) Right click on JRE System Library

4) Build Path

5) Select Configure Build Path

6) Click on Add external JARs...

7) C:\oraclexe\app\oracle\product\10.2.0\server\jdbc\lib

8) Here you will get ojdbc14.jar

9) select here

10) open

11) ok

save and run the program you will get output.

Making an API call in Python with an API that requires a bearer token

It just means it expects that as a key in your header data

import requests
endpoint = ".../api/ip"
data = {"ip": ""}
headers = {"Authorization": "Bearer MYREALLYLONGTOKENIGOT"}

print(, data=data, headers=headers).json())

What exactly are iterator, iterable, and iteration?

The above answers are great, but as most of what I've seen, don't stress the distinction enough for people like me.

Also, people tend to get "too Pythonic" by putting definitions like "X is an object that has __foo__() method" before. Such definitions are correct--they are based on duck-typing philosophy, but the focus on methods tends to get between when trying to understand the concept in its simplicity.

So I add my version.

In natural language,

  • iteration is the process of taking one element at a time in a row of elements.

In Python,

  • iterable is an object that is, well, iterable, which simply put, means that it can be used in iteration, e.g. with a for loop. How? By using iterator. I'll explain below.

  • ... while iterator is an object that defines how to actually do the iteration--specifically what is the next element. That's why it must have next() method.

Iterators are themselves also iterable, with the distinction that their __iter__() method returns the same object (self), regardless of whether or not its items have been consumed by previous calls to next().

So what does Python interpreter think when it sees for x in obj: statement?

Look, a for loop. Looks like a job for an iterator... Let's get one. ... There's this obj guy, so let's ask him.

"Mr. obj, do you have your iterator?" (... calls iter(obj), which calls obj.__iter__(), which happily hands out a shiny new iterator _i.)

OK, that was easy... Let's start iterating then. (x = ... x =

Since Mr. obj succeeded in this test (by having certain method returning a valid iterator), we reward him with adjective: you can now call him "iterable Mr. obj".

However, in simple cases, you don't normally benefit from having iterator and iterable separately. So you define only one object, which is also its own iterator. (Python does not really care that _i handed out by obj wasn't all that shiny, but just the obj itself.)

This is why in most examples I've seen (and what had been confusing me over and over), you can see:

class IterableExample(object):

    def __iter__(self):
        return self

    def next(self):

instead of

class Iterator(object):
    def next(self):

class Iterable(object):
    def __iter__(self):
        return Iterator()

There are cases, though, when you can benefit from having iterator separated from the iterable, such as when you want to have one row of items, but more "cursors". For example when you want to work with "current" and "forthcoming" elements, you can have separate iterators for both. Or multiple threads pulling from a huge list: each can have its own iterator to traverse over all items. See @Raymond's and @glglgl's answers above.

Imagine what you could do:

class SmartIterableExample(object):

    def create_iterator(self):
        # An amazingly powerful yet simple way to create arbitrary
        # iterator, utilizing object state (or not, if you are fan
        # of functional), magic and nuclear waste--no kittens hurt.
        pass    # don't forget to add the next() method

    def __iter__(self):
        return self.create_iterator()


  • I'll repeat again: iterator is not iterable. Iterator cannot be used as a "source" in for loop. What for loop primarily needs is __iter__() (that returns something with next()).

  • Of course, for is not the only iteration loop, so above applies to some other constructs as well (while...).

  • Iterator's next() can throw StopIteration to stop iteration. Does not have to, though, it can iterate forever or use other means.

  • In the above "thought process", _i does not really exist. I've made up that name.

  • There's a small change in Python 3.x: next() method (not the built-in) now must be called __next__(). Yes, it should have been like that all along.

  • You can also think of it like this: iterable has the data, iterator pulls the next item

Disclaimer: I'm not a developer of any Python interpreter, so I don't really know what the interpreter "thinks". The musings above are solely demonstration of how I understand the topic from other explanations, experiments and real-life experience of a Python newbie.

Split an NSString to access one particular piece

I have formatted the nice solution provided by JeremyP above into a more generic reusable function below:

///Return an ARRAY containing the exploded chunk of strings
+(NSArray*)explodeString:(NSString*)stringToBeExploded WithDelimiter:(NSString*)delimiter
    return [stringToBeExploded componentsSeparatedByString: delimiter];

How to preview selected image in input type="file" in popup using jQuery?

You can use URL.createObjectURL

    function img_pathUrl(input){
        $('#img_url')[0].src = (window.URL ? URL : webkitURL).createObjectURL(input.files[0]);
#img_url {
  background: #ddd;
  height: 90px;
  display: block;
<script src=""></script>
<img src="" id="img_url" alt="your image">
<input type="file" id="img_file" onChange="img_pathUrl(this);">

How to send a “multipart/form-data” POST in Android with Volley

I might be wrong on this but I think you need to implement your own for this because the default ones (HurlStack if version > Gingerbread or HttpClientStack) don't deal with multipart/form-data.


And indeed I was wrong. I was able to do it using MultipartEntity in Request like this:

public class MultipartRequest extends Request<String> {

    private MultipartEntity entity = new MultipartEntity();

    private static final String FILE_PART_NAME = "file";
    private static final String STRING_PART_NAME = "text";

    private final Response.Listener<String> mListener;
    private final File mFilePart;
    private final String mStringPart;

    public MultipartRequest(String url, Response.ErrorListener errorListener, Response.Listener<String> listener, File file, String stringPart)
        super(Method.POST, url, errorListener);

        mListener = listener;
        mFilePart = file;
        mStringPart = stringPart;

    private void buildMultipartEntity()
        entity.addPart(FILE_PART_NAME, new FileBody(mFilePart));
            entity.addPart(STRING_PART_NAME, new StringBody(mStringPart));
        catch (UnsupportedEncodingException e)

    public String getBodyContentType()
        return entity.getContentType().getValue();

    public byte[] getBody() throws AuthFailureError
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        catch (IOException e)
            VolleyLog.e("IOException writing to ByteArrayOutputStream");
        return bos.toByteArray();

    protected Response<String> parseNetworkResponse(NetworkResponse response)
        return Response.success("Uploaded", getCacheEntry());

    protected void deliverResponse(String response)

It's pretty raw but I tried it with an image and a simple string and it works. The response is a placeholder, doesn't make much sense to return a Response String in this case. I had problems using apache httpmime to use MultipartEntity so I used this don't know if there's a better way. Hope it helps.


You can use httpmime without using httpclientandroidlib, the only dependency is httpcore.

How to create an Array, ArrayList, Stack and Queue in Java?

I am guessing you're confused with the parameterization of the types:

// This works, because there is one class/type definition in the parameterized <> field
ArrayList<String> myArrayList = new ArrayList<String>(); 

// This doesn't work, as you cannot use primitive types here
ArrayList<char> myArrayList = new ArrayList<char>();

In SQL, is UPDATE always faster than DELETE+INSERT?

One command on the same row should always be faster than two on that same row. So the UPDATE only would be better.

EDIT set up the table:

create table YourTable
(YourName  varchar(50)  primary key
,Tag int

insert into YourTable values ('first value',1)

run this, which takes 1 second on my system (sql server 2005):

declare @x int
declare @y int
select @x=0,@y=0
UPDATE YourTable set YourName='new name'
while @x<10000
    Set @x=@x+1
    update YourTable set YourName='new name' where YourName='new name'
    SET @y=@y+@@ROWCOUNT
print @y

run this, which took 2 seconds on my system:

declare @x int
declare @y int
select @x=0,@y=0
while @x<10000
    Set @x=@x+1
    DELETE YourTable WHERE YourName='new name'
    insert into YourTable values ('new name',1)
    SET @y=@y+@@ROWCOUNT
print @y

How to check model string property for null in a razor view

Try this first, you may be passing a Null Model:

@if (Model != null && !String.IsNullOrEmpty(Model.ImageName))
    <label for="Image">Change picture</label>
    <label for="Image">Add picture</label>

Otherise, you can make it even neater with some ternary fun! - but that will still error if your model is Null.

<label for="Image">@(String.IsNullOrEmpty(Model.ImageName) ? "Add" : "Change") picture</label>

Calculating time difference in Milliseconds

Since Java 1.5, you can get a more precise time value with System.nanoTime(), which obviously returns nanoseconds instead.

There is probably some caching going on in the instances when you get an immediate result.

Using Python's list index() method on a list of tuples or objects?

Python's list.index(x) returns index of the first occurrence of x in the list. So we can pass objects returned by list compression to get their index.

>>> tuple_list = [("pineapple", 5), ("cherry", 7), ("kumquat", 3), ("plum", 11)]
>>> [tuple_list.index(t) for t in tuple_list if t[1] == 7]
>>> [tuple_list.index(t) for t in tuple_list if t[0] == 'kumquat']

With the same line, we can also get the list of index in case there are multiple matched elements.

>>> tuple_list = [("pineapple", 5), ("cherry", 7), ("kumquat", 3), ("plum", 11), ("banana", 7)]
>>> [tuple_list.index(t) for t in tuple_list if t[1] == 7]
[1, 4]

jQuery date/time picker

Not jQuery, but it works well for a calendar with time: JavaScript Date Time Picker.

I just bound the click event to pop it up:

$(".arrival-date").click(function() {
    NewCssCal($(this).attr('id'), 'mmddyyyy', 'dropdown', true, 12);

Find files in created between a date range

Explanation: Use unix command find with -ctime (creation time) flag

The find utility recursively descends the directory tree for each path listed, evaluating an expression (composed of the 'primaries' and 'operands') in terms of each file in the tree.

Solution: According to documenation

-ctime n[smhdw]
             If no units are specified, this primary evaluates to true if the difference
             between the time of last change of file status information and the time find
             was started, rounded up to the next full 24-hour period, is n 24-hour peri-

             If units are specified, this primary evaluates to true if the difference
             between the time of last change of file status information and the time find
             was started is exactly n units.  Please refer to the -atime primary descrip-
             tion for information on supported time units.

Formula: find <path> -ctime +[number][timeMeasurement] -ctime -[number][timeMeasurment]


1.Find everything that were created after 1 week ago ago and before 2 weeks ago

find / -ctime +1w -ctime -2w

2.Find all javascript files (.js) in current directory that were created between 1 day ago to 3 days ago

find . -name "*\.js" -type f -ctime +1d -ctime -3d

Email Address Validation in Android on EditText

try this

public static final Pattern EMAIL_ADDRESS_PATTERN = Pattern.compile(

              "[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}" +
              "\\@" +
              "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}" +
              "(" +
              "\\." +
              "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25}" +

and in tne edit text

final String emailText = email.getText().toString();

How to SELECT by MAX(date)?

This should do it:

SELECT report_id, computer_id, date_entered
FROM reports AS a
WHERE date_entered = (
    SELECT MAX(date_entered)
    FROM reports AS b
    WHERE a.report_id = b.report_id
      AND a.computer_id = b.computer_id

"installation of package 'FILE_PATH' had non-zero exit status" in R

I have had the same problem with a specific package in R and the solution was I should install in the ubuntu terminal libcurl. Look at the information that appears above explaining to us that curl package has error installation.

I knew this about the message:

Configuration failed because libcurl was not found. Try installing:
 * deb: libcurl4-openssl-dev (Debian, Ubuntu, etc)
 * rpm: libcurl-devel (Fedora, CentOS, RHEL)
 * csw: libcurl_dev (Solaris)
If libcurl is already installed, check that 'pkg-config' is in your
PATH and PKG_CONFIG_PATH contains a libcurl.pc file. If pkg-config
is unavailable you can set INCLUDE_DIR and LIB_DIR manually via:
R CMD INSTALL --configure-vars='INCLUDE_DIR=... LIB_DIR=...'

To install it I used the net command:

sudo apt-get install libcurl4-openssl-dev

Sometimes we can not install a specific package in R because we have problems with packages that must be installed previously as curl package. To know if we should install it we should check the warning errors such as: installation of package ‘curl’ had non-zero exit status.

I hope I have been helpful

angularjs ng-style: background-image isn't working

It is possible to parse dynamic values in a couple of way.

Interpolation with double-curly braces:


String concatenation:

ng-style="{'background-image': 'url(' + myBackgroundUrl + ')'}"

ES6 template literals:

ng-style="{'background-image': `url(${myBackgroundUrl})`}"

Java method: Finding object in array list given a known attribute value

You have to loop through the entire array, there's no changing that. You can however, do it a little easier

for (Dog dog : list) {
  if (dog.getId() == id) {
    return dog; //gotcha!
return null; // dog not found.

or without the new for loop

for (int i = 0; i < list.size(); i++) {
  if (list.get(i).getId() == id) {
    return list.get(i);

How to set radio button selected value using jquery

You can do more elegantly.

function RadionButtonSelectedValueSet(name, SelectedValue) {
    $('input[name="' + name+ '"]').val([SelectedValue]);

How do I launch the Android emulator from the command line?

Here you can check the options to execute this command via command-line:

emulator -avd avd_name [-option [value]] ... [-qemu args]

For example, I use it like this below:

emulator -avd ICS_ARM -wipe-data -no-boot-anim -cpu-delay 0

How do I get the SelectedItem or SelectedIndex of ListView in

ListView returns collections of selected items and indices through the SelectedItems and SelectedIndices properties. Note that these collections are empty, if no item is currently selected (lst.SelectedItems.Count = 0). The first item that is selected is lst.SelectedItems(0). The index of this item in the Items collection is lst.SelectedIndices(0). So basically


is the same as


You can also use check boxes. Set CheckBoxes to True for this. Through the CheckedItems and CheckedIndices properties you can see which items are checked.

Move the most recent commit(s) to a new branch with Git

This doesn't "move" them in the technical sense but it has the same effect:

A--B--C  (branch-foo)
 \    ^-- I wanted them here!
   D--E--F--G  (branch-bar)
      ^--^--^-- Opps wrong branch!

While on branch-bar:
$ git reset --hard D # remember the SHAs for E, F, G (or E and G for a range)

A--B--C  (branch-foo)
   D-(E--F--G) detached
   ^-- (branch-bar)

Switch to branch-foo
$ git cherry-pick E..G

A--B--C--E'--F'--G' (branch-foo)
 \   E--F--G detached (This can be ignored)
  \ /
   D--H--I (branch-bar)

Now you won't need to worry about the detached branch because it is basically
like they are in the trash can waiting for the day it gets garbage collected.
Eventually some time in the far future it will look like:

A--B--C--E'--F'--G'--L--M--N--... (branch-foo)
   D--H--I--J--K--.... (branch-bar)

Embed website into my site

Put content from other site in iframe

<iframe src="/othersiteurl" width="100%" height="300">
  <p>Your browser does not support iframes.</p>

Sample database for exercise

If you want a big database of real data to play with, you could sign up for the Netflix Prize contest and get access to their data, which is pretty large (a few gigs of entries).

3rd party edit

The URL above does not contain the dataset anylonger (october 2016). The wikipedia page about the Netflix Prize reports that a law suit was settled regarding privacy concerns.

How do I get a Cron like scheduler in Python?

I don't know if something like that already exists. It would be easy to write your own with time, datetime and/or calendar modules, see

The only concern for a python solution is that your job needs to be always running and possibly be automatically "resurrected" after a reboot, something for which you do need to rely on system dependent solutions.

How to install multiple python packages at once using pip

You can install packages listed in a text file called requirements file. For example, if you have a file called req.txt containing the following text:


and you issue at the command line:

pip install -r req.txt

pip will install packages listed in the file at the specific revisions.

How to set the height and the width of a textfield in Java?


add the above lines ( f is a JFrame or a Container where you have added the JTestField )

But try to learn 'LayoutManager' in java ; refer to other answers for the links of the tutorials .Or try This

How to post SOAP Request from PHP

You might want to look here and here.

A Little code example from the first link:

// include the SOAP classes
// define parameter array (ISBN number)
$param = array('isbn'=>'0385503954');
// define path to server application
$serverpath ='';
//define method namespace
// create client object
$client = new soapclient($serverpath);
// make the call
$price = $client->call('getPrice',$param,$namespace);
// if a fault occurred, output error info
if (isset($fault)) {
        print "Error: ". $fault;
else if ($price == -1) {
        print "The book is not in the database.";
} else {
        // otherwise output the result
        print "The price of book number ". $param[isbn] ." is $". $price;
// kill object

Writing a large resultset to an Excel file using POI

You can using SXSSFWorkbook implementation of Workbook, if you use style in your excel ,You can caching style by Flyweight Pattern to improve your performance. enter image description here

Create a CSS rule / class with jQuery at runtime

You can use insertRule if you don't need to support IE < 9, according to dottoro. There's a bit of cross browser code over there as well.

document.styleSheets[0].insertRule('#my-window {\
    position: fixed;\
    z-index: 102;\
}', 0)

WordPress is giving me 404 page not found for all pages except the homepage

I just changed the permalink to 'month and day'of all the posts by ging to setting>permalink.

Now all posts are open and working fine.

Again, I renamed to all posts to its actual permalink. Its again working fine.

This method worked for me :-)

PHP code to convert a MySQL query to CSV

Look at the documentation regarding the SELECT ... INTO OUTFILE syntax.

SELECT a,b,a+b INTO OUTFILE '/tmp/result.txt'
  FROM test_table;

Pandas: how to change all the values of a column?

As @DSM points out, you can do this more directly using the vectorised string methods:


Or using extract (assuming there is only one set of digits of length 4 somewhere in each string):


An alternative slightly more flexible way, might be to use apply (or equivalently map) to do this:

df['Date'] = df['Date'].apply(lambda x: int(str(x)[-4:]))
             #  converts the last 4 characters of the string to an integer

The lambda function, is taking the input from the Date and converting it to a year.
You could (and perhaps should) write this more verbosely as:

def convert_to_year(date_in_some_format):
    date_as_string = str(date_in_some_format)  # cast to string
    year_as_string = date_in_some_format[-4:] # last four characters
    return int(year_as_string)

df['Date'] = df['Date'].apply(convert_to_year)

Perhaps 'Year' is a better name for this column...

Multi-select dropdown list in ASP.NET

Try this server control which inherits directly from CheckBoxList (free, open source):

How to make a website secured with https

Try making a boot directory in PHP, as in

$privacy = ['BOOTSTRAP_CONFIG'];
$shell   = ['BOOTSTRAP_OUTPUT'];
enter code here
if $ip == $privacy {
function $privacy int $ip = "https://";
} endif {
echo $shell

Thats mainly it!

Twitter Bootstrap Form File Element Upload Button

It's included in Jasny's fork of bootstrap.

A simple upload button can be created using

<span class="btn btn-file">Upload<input type="file" /></span>

With the fileupload plugin you can create more advanced widgets. Have a look at

I get Access Forbidden (Error 403) when setting up new alias

Apache 2.4 virtual hosts hack

1.In http.conf specify the ports , below “Listen”

Listen 80
Listen 4000
Listen 7000
Listen 9000
  1. In httpd-vhosts.conf

    <VirtualHost *:80>
    ServerAdmin [email protected]
    DocumentRoot "C:/Users/Vikas/Documents/NetBeansProjects/slider_website_hitesh/public_html"  
    ErrorLog "logs/"
    CustomLog "logs/" common
    <Directory "C:/Users/Vikas/Documents/NetBeansProjects/slider_website_hitesh/public_html">
    Allow from all
    Require all granted

    this is 2nd virtual host

    <VirtualHost *:80>
    ServerAdmin [email protected]
    DocumentRoot "E:/dabkick_git/DabKickWebsite"
    ErrorLog "logs/"
    CustomLog "logs/" common
    <Directory "E:/dabkick_git/DabKickWebsite">
     Allow from all
     Require all granted
  2. In hosts.ics file of windows os “C:\Windows\System32\drivers\etc\host.ics”             localhost    type your “domain names” in the browser it will ping the particular folder specified in the documentRoot path

5.if you want to access those files in a particular port then replace 80 in httpd-vhosts.conf with port numbers like below and restart apache

   <VirtualHost *:4000>
ServerAdmin [email protected]
DocumentRoot "C:/Users/Vikas/Documents/NetBeansProjects/slider_website_hitesh/public_html"
ErrorLog "logs/"
CustomLog "logs/" common

<Directory "C:/Users/Vikas/Documents/NetBeansProjects/slider_website_hitesh/public_html">
Allow from all
Require all granted


this is the 2nd vhost

<VirtualHost *:7000>
ServerAdmin [email protected]
DocumentRoot "E:/dabkick_git/DabKickWebsite"
ErrorLog "logs/"
CustomLog "logs/" common

<Directory "E:/dabkick_git/DabKickWebsite">
Allow from all
Require all granted

Note: for port number given virtual hosts you have to ping in browser like “” or “

6.After doing all those changes you have to save the files and restart apache respectively.

"dd/mm/yyyy" date format in excel through vba

I got it

Cells(1, 1).Value = StartDate
Cells(1, 1).NumberFormat = "dd/mm/yyyy"

Basically, I need to set the cell format, instead of setting the date.

Is it possible to cherry-pick a commit from another git repository?

Here's an example of the remote-fetch-merge.

cd /home/you/projectA
git remote add projectB /home/you/projectB
git fetch projectB

Then you can:

git cherry-pick <first_commit>..<last_commit>

or you could even merge the whole branch

git merge projectB/master

How to connect to LocalDB in Visual Studio Server Explorer?

Use SQL Server Object Explorer (SSOX) Instead

Unlike the other answers, this approach uses:
- No special commands.
- No complicated configurations.
Just use the SQL Server Object Explorer

It's pretty straightforward...

  • From the View menu, open SQL Server Object Explorer.


  • Right click on the {YourTableName} table > View Designer



How to add property to object in PHP >= 5.3 strict mode without generating error

Yes, is possible to dynamically add properties to a PHP object.

This is useful when a partial object is received from javascript.


var myObject = { name = "myName" };
$.ajax({ type: "POST", url: "index.php",
    data: myObject, dataType: "json",
    contentType: "application/json;charset=utf-8"
    if( >= 0 ) { /* the id property has dynamically added on server side via PHP */ }

PHP side:

$requestString = file_get_contents('php://input');
$myObject = json_decode($requestString); // same object as was sent in the ajax call
$myObject->id = 30; // This will dynamicaly add the id property to the myObject object

OR JUST SEND A DUMMY PROPERTY from javascript that you will fill in PHP.

get the value of DisplayName attribute

Assuming property as PropertyInfo type, you can do this in one single line:

property.GetCustomAttributes(typeof(DisplayNameAttribute), true).Cast<DisplayNameAttribute>().Single().DisplayName

How to plot a very simple bar chart (Python, Matplotlib) using input *.txt file?

You're talking about histograms, but this doesn't quite make sense. Histograms and bar charts are different things. An histogram would be a bar chart representing the sum of values per year, for example. Here, you just seem to be after bars.

Here is a complete example from your data that shows a bar of for each required value at each date:

import pylab as pl
import datetime

data = """0 14-11-2003
1 15-03-1999
12 04-12-2012
33 09-05-2007
44 16-08-1998
55 25-07-2001
76 31-12-2011
87 25-06-1993
118 16-02-1995
119 10-02-1981
145 03-05-2014"""

values = []
dates = []

for line in data.split("\n"):
    x, y = line.split()
    dates.append(datetime.datetime.strptime(y, "%d-%m-%Y").date())

fig = pl.figure()
ax = pl.subplot(111), values, width=100)

You need to parse the date with strptime and set the x-axis to use dates (as described in this answer).

If you're not interested in having the x-axis show a linear time scale, but just want bars with labels, you can do this instead:

fig = pl.figure()
ax = pl.subplot(111), values)

EDIT: Following comments, for all the ticks, and for them to be centred, pass the range to set_ticks (and move them by half the bar width):

fig = pl.figure()
ax = pl.subplot(111)
width=0.8, values, width=width)
ax.set_xticks(np.arange(len(dates)) + width/2)
ax.set_xticklabels(dates, rotation=90)

How do I divide in the Linux console?

I also had the same problem. It's easy to divide integer numbers but decimal numbers are not that easy. if you have 2 numbers like 3.14 and 2.35 and divide the numbers then, the code will be Division=echo 3.14 / 2.35 | bc echo "$Division" the quotes are different. Don't be confused, it's situated just under the esc button on your keyboard. THE ONLY DIFFERENCE IS THE | bc and also here echo works as an operator for the arithmetic calculations in stead of printing. So, I had added echo "$Division" for printing the value. Let me know if it works for you. Thank you.

Resizing a button

Use inline styles:

<div class="button" style="width:60px;height:100px;">This is a button</div>


git rebase merge conflict

Note: with Git 2.14.x/2.15 (Q3 2017), the git rebase message in case of conflicts will be clearer.

See commit 5fdacc1 (16 Jul 2017) by William Duclot (williamdclt).
(Merged by Junio C Hamano -- gitster -- in commit 076eeec, 11 Aug 2017)

rebase: make resolve message clearer for inexperienced users


When you have resolved this problem, run "git rebase --continue".
If you prefer to skip this patch, run "git rebase --skip" instead.
To check out the original branch and stop rebasing, run "git rebase --abort"


Resolve all conflicts manually, 
mark them as resolved with git add/rm <conflicted_files>
then run "git rebase --continue".

You can instead skip this commit: run "git rebase --skip".
To abort and get back to the state before "git rebase", run "git rebase --abort".')

The git UI can be improved by addressing the error messages to those they help: inexperienced and casual git users.
To this intent, it is helpful to make sure the terms used in those messages can be understood by this segment of users, and that they guide them to resolve the problem.

In particular, failure to apply a patch during a git rebase is a common problem that can be very destabilizing for the inexperienced user.
It is important to lead them toward the resolution of the conflict (which is a 3-steps process, thus complex) and reassure them that they can escape a situation they can't handle with "--abort".
This commit answer those two points by detailing the resolution process and by avoiding cryptic git linguo.

SFTP file transfer using Java JSch


sftp("file:/C:/home/file.txt", "ssh://user:pass@host/home");
sftp("ssh://user:pass@host/home/file.txt", "file:/C:/home");


ECMAScript 6 class destructor

You have to manually "destruct" objects in JS. Creating a destroy function is common in JS. In other languages this might be called free, release, dispose, close, etc. In my experience though it tends to be destroy which will unhook internal references, events and possibly propagates destroy calls to child objects as well.

WeakMaps are largely useless as they cannot be iterated and this probably wont be available until ECMA 7 if at all. All WeakMaps let you do is have invisible properties detached from the object itself except for lookup by the object reference and GC so that they don't disturb it. This can be useful for caching, extending and dealing with plurality but it doesn't really help with memory management for observables and observers. WeakSet is a subset of WeakMap (like a WeakMap with a default value of boolean true).

There are various arguments on whether to use various implementations of weak references for this or destructors. Both have potential problems and destructors are more limited.

Destructors are actually potentially useless for observers/listeners as well because typically the listener will hold references to the observer either directly or indirectly. A destructor only really works in a proxy fashion without weak references. If your Observer is really just a proxy taking something else's Listeners and putting them on an observable then it can do something there but this sort of thing is rarely useful. Destructors are more for IO related things or doing things outside of the scope of containment (IE, linking up two instances that it created).

The specific case that I started looking into this for is because I have class A instance that takes class B in the constructor, then creates class C instance which listens to B. I always keep the B instance around somewhere high above. A I sometimes throw away, create new ones, create many, etc. In this situation a Destructor would actually work for me but with a nasty side effect that in the parent if I passed the C instance around but removed all A references then the C and B binding would be broken (C has the ground removed from beneath it).

In JS having no automatic solution is painful but I don't think it's easily solvable. Consider these classes (pseudo):

function Filter(stream) {
    stream.on('data', function() {
        this.emit('data', data.toString().replace('somenoise', '')); // Pretend chunks/multibyte are not a problem.
Filter.prototype.__proto__ = EventEmitter.prototype;
function View(df, stream) {
    df.on('data', function(data) {
        stream.write(data.toUpper()); // Shout.

On a side note, it's hard to make things work without anonymous/unique functions which will be covered later.

In a normal case instantiation would be as so (pseudo):

var df = new Filter(stdin),
    v1 = new View(df, stdout),
    v2 = new View(df, stderr);

To GC these normally you would set them to null but it wont work because they've created a tree with stdin at the root. This is basically what event systems do. You give a parent to a child, the child adds itself to the parent and then may or may not maintain a reference to the parent. A tree is a simple example but in reality you may also find yourself with complex graphs albeit rarely.

In this case, Filter adds a reference to itself to stdin in the form of an anonymous function which indirectly references Filter by scope. Scope references are something to be aware of and that can be quite complex. A powerful GC can do some interesting things to carve away at items in scope variables but that's another topic. What is critical to understand is that when you create an anonymous function and add it to something as a listener to ab observable, the observable will maintain a reference to the function and anything the function references in the scopes above it (that it was defined in) will also be maintained. The views do the same but after the execution of their constructors the children do not maintain a reference to their parents.

If I set any or all of the vars declared above to null it isn't going to make a difference to anything (similarly when it finished that "main" scope). They will still be active and pipe data from stdin to stdout and stderr.

If I set them all to null it would be impossible to have them removed or GCed without clearing out the events on stdin or setting stdin to null (assuming it can be freed like this). You basically have a memory leak that way with in effect orphaned objects if the rest of the code needs stdin and has other important events on it prohibiting you from doing the aforementioned.

To get rid of df, v1 and v2 I need to call a destroy method on each of them. In terms of implementation this means that both the Filter and View methods need to keep the reference to the anonymous listener function they create as well as the observable and pass that to removeListener.

On a side note, alternatively you can have an obserable that returns an index to keep track of listeners so that you can add prototyped functions which at least to my understanding should be much better on performance and memory. You still have to keep track of the returned identifier though and pass your object to ensure that the listener is bound to it when called.

A destroy function adds several pains. First is that I would have to call it and free the reference:

df = v1 = v2 = null;

This is a minor annoyance as it's a bit more code but that is not the real problem. When I hand these references around to many objects. In this case when exactly do you call destroy? You cannot simply hand these off to other objects. You'll end up with chains of destroys and manual implementation of tracking either through program flow or some other means. You can't fire and forget.

An example of this kind of problem is if I decide that View will also call destroy on df when it is destroyed. If v2 is still around destroying df will break it so destroy cannot simply be relayed to df. Instead when v1 takes df to use it, it would need to then tell df it is used which would raise some counter or similar to df. df's destroy function would decrease than counter and only actually destroy if it is 0. This sort of thing adds a lot of complexity and adds a lot that can go wrong the most obvious of which is destroying something while there is still a reference around somewhere that will be used and circular references (at this point it's no longer a case of managing a counter but a map of referencing objects). When you're thinking of implementing your own reference counters, MM and so on in JS then it's probably deficient.

If WeakSets were iterable, this could be used:

function Observable() { = {open: new WeakSet(), close: new WeakSet()};
Observable.prototype.on = function(type, f) {[type].add(f);
Observable.prototype.emit = function(type, ...args) {[type].forEach(f => f(...args));
}; = function(type, f) {[type].delete(f);

In this case the owning class must also keep a token reference to f otherwise it will go poof.

If Observable were used instead of EventListener then memory management would be automatic in regards to the event listeners.

Instead of calling destroy on each object this would be enough to fully remove them:

df = v1 = v2 = null;

If you didn't set df to null it would still exist but v1 and v2 would automatically be unhooked.

There are two problems with this approach however.

Problem one is that it adds a new complexity. Sometimes people do not actually want this behaviour. I could create a very large chain of objects linked to each other by events rather than containment (references in constructor scopes or object properties). Eventually a tree and I would only have to pass around the root and worry about that. Freeing the root would conveniently free the entire thing. Both behaviours depending on coding style, etc are useful and when creating reusable objects it's going to be hard to either know what people want, what they have done, what you have done and a pain to work around what has been done. If I use Observable instead of EventListener then either df will need to reference v1 and v2 or I'll have to pass them all if I want to transfer ownership of the reference to something else out of scope. A weak reference like thing would mitigate the problem a little by transferring control from Observable to an observer but would not solve it entirely (and needs check on every emit or event on itself). This problem can be fixed I suppose if the behaviour only applies to isolated graphs which would complicate the GC severely and would not apply to cases where there are references outside the graph that are in practice noops (only consume CPU cycles, no changes made).

Problem two is that either it is unpredictable in certain cases or forces the JS engine to traverse the GC graph for those objects on demand which can have a horrific performance impact (although if it is clever it can avoid doing it per member by doing it per WeakMap loop instead). The GC may never run if memory usage does not reach a certain threshold and the object with its events wont be removed. If I set v1 to null it may still relay to stdout forever. Even if it does get GCed this will be arbitrary, it may continue to relay to stdout for any amount of time (1 lines, 10 lines, 2.5 lines, etc).

The reason WeakMap gets away with not caring about the GC when non-iterable is that to access an object you have to have a reference to it anyway so either it hasn't been GCed or hasn't been added to the map.

I am not sure what I think about this kind of thing. You're sort of breaking memory management to fix it with the iterable WeakMap approach. Problem two can also exist for destructors as well.

All of this invokes several levels of hell so I would suggest to try to work around it with good program design, good practices, avoiding certain things, etc. It can be frustrating in JS however because of how flexible it is in certain aspects and because it is more naturally asynchronous and event based with heavy inversion of control.

There is one other solution that is fairly elegant but again still has some potentially serious hangups. If you have a class that extends an observable class you can override the event functions. Add your events to other observables only when events are added to yourself. When all events are removed from you then remove your events from children. You can also make a class to extend your observable class to do this for you. Such a class could provide hooks for empty and non-empty so in a since you would be Observing yourself. This approach isn't bad but also has hangups. There is a complexity increase as well as performance decrease. You'll have to keep a reference to object you observe. Critically, it also will not work for leaves but at least the intermediates will self destruct if you destroy the leaf. It's like chaining destroy but hidden behind calls that you already have to chain. A large performance problem is with this however is that you may have to reinitialise internal data from the Observable everytime your class becomes active. If this process takes a very long time then you might be in trouble.

If you could iterate WeakMap then you could perhaps combine things (switch to Weak when no events, Strong when events) but all that is really doing is putting the performance problem on someone else.

There are also immediate annoyances with iterable WeakMap when it comes to behaviour. I mentioned briefly before about functions having scope references and carving. If I instantiate a child that in the constructor that hooks the listener 'console.log(param)' to parent and fails to persist the parent then when I remove all references to the child it could be freed entirely as the anonymous function added to the parent references nothing from within the child. This leaves the question of what to do about parent.weakmap.add(child, (param) => console.log(param)). To my knowledge the key is weak but not the value so weakmap.add(object, object) is persistent. This is something I need to reevaluate though. To me that looks like a memory leak if I dispose all other object references but I suspect in reality it manages that basically by seeing it as a circular reference. Either the anonymous function maintains an implicit reference to objects resulting from parent scopes for consistency wasting a lot of memory or you have behaviour varying based on circumstances which is hard to predict or manage. I think the former is actually impossible. In the latter case if I have a method on a class that simply takes an object and adds console.log it would be freed when I clear the references to the class even if I returned the function and maintained a reference. To be fair this particular scenario is rarely needed legitimately but eventually someone will find an angle and will be asking for a HalfWeakMap which is iterable (free on key and value refs released) but that is unpredictable as well (obj = null magically ending IO, f = null magically ending IO, both doable at incredible distances).

How can I lock a file using java (if possible)

If you can use Java NIO (JDK 1.4 or greater), then I think you're looking for java.nio.channels.FileChannel.lock()


How to include CSS file in Symfony 2 and Twig?

You are doing everything right, except passing your bundle path to asset() function.

According to documentation - in your example this should look like below:

{{ asset('bundles/webshome/css/main.css') }}

Tip: you also can call assets:install with --symlink key, so it will create symlinks in web folder. This is extremely useful when you often apply js or css changes (in this way your changes, applied to src/YouBundle/Resources/public will be immediately reflected in web folder without need to call assets:install again):

app/console assets:install web --symlink

Also, if you wish to add some assets in your child template, you could call parent() method for the Twig block. In your case it would be like this:

{% block stylesheets %}
    {{ parent() }}

    <link href="{{ asset('bundles/webshome/css/main.css') }}" rel="stylesheet">
{% endblock %}

java.lang.ClassNotFoundException: org.eclipse.core.runtime.adaptor.EclipseStarter

check jar files in your project which are mentioned in config.ini if not proper then install manually and then follow the following steps:

  1. Select your product configuration file, right-click on it and select Run As Run Configurations
  2. Select "Validate plug-ins prior to launching". This will check if you have all required plug-ins in your run configuration. If this check reports that some plug-ins are missing, try clicking the "Add Required-Plug-Ins" button. Also make sure to define all dependencies in your product. And your application start running

SQL - Query to get server's IP address

You can get the[hostname]\[instancename] by:


To get only the hostname when you have hostname\instance name format:

SELECT LEFT(ltrim(rtrim(@@ServerName)), Charindex('\', ltrim(rtrim(@@ServerName))) -1)

Alternatively as @GilM pointed out:


You can get the actual IP address using this:

create Procedure sp_get_ip_address (@ip varchar(40) out)
Declare @ipLine varchar(200)
Declare @pos int
set nocount on
          set @ip = NULL
          Create table #temp (ipLine varchar(200))
          Insert #temp exec master..xp_cmdshell 'ipconfig'
          select @ipLine = ipLine
          from #temp
          where upper (ipLine) like '%IP ADDRESS%'
          if (isnull (@ipLine,'***') != '***')
                set @pos = CharIndex (':',@ipLine,1);
                set @ip = rtrim(ltrim(substring (@ipLine , 
               @pos + 1 ,
                len (@ipLine) - @pos)))
drop table #temp
set nocount off

declare @ip varchar(40)
exec sp_get_ip_address @ip out
print @ip

Source of the SQL script.

Selenium Webdriver move mouse to Point

I am using JavaScript but some of the principles are common I am sure.

The code I am using is as follows:

    var s = new webdriver.ActionSequence(d);

the driver = d. The location = l is simply {x:300,y:500) - it is just an offset.

What I found during my testing was that I could not make it work without using the method to find an existing element first, using that at a basis from where to locate my click.

I suspect the figures in the locate are a bit more difficult to predict than I thought.

It is an old post but this response may help other newcomers like me.

Converting a string to a date in JavaScript

use this format....

//get current date in javascript

  var currentDate = new Date();

// for getting a date from a textbox as string format

   var newDate=document.getElementById("<%=textBox1.ClientID%>").value;

// convert this date to date time

   var MyDate = new Date(newDate);

Initialize a vector array of strings

If you are using cpp11 (enable with the -std=c++0x flag if needed), then you can simply initialize the vector like this:

// static std::vector<std::string> v;
v = {"haha", "hehe"};

Making Enter key on an HTML form submit instead of activating button

Try this, if enter key was pressed you can capture it like this for example, I developed an answer the other day html button specify selected, see if this helps.

Specify the forms name as for example yourFormName then you should be able to submit the form without having focus on the form.

document.onkeypress = keyPress;

function keyPress(e){
  var x = e || window.event;
  var key = (x.keyCode || x.which);
  if(key == 13 || key == 3){
   //  myFunc1();

Suppress Scientific Notation in Numpy When Creating Array From Nested List

for 1D and 2D arrays you can use np.savetxt to print using a specific format string:

>>> import sys
>>> x = numpy.arange(20).reshape((4,5))
>>> numpy.savetxt(sys.stdout, x, '%5.2f')
 0.00  1.00  2.00  3.00  4.00
 5.00  6.00  7.00  8.00  9.00
10.00 11.00 12.00 13.00 14.00
15.00 16.00 17.00 18.00 19.00

Your options with numpy.set_printoptions or numpy.array2string in v1.3 are pretty clunky and limited (for example no way to suppress scientific notation for large numbers). It looks like this will change with future versions, with numpy.set_printoptions(formatter=..) and numpy.array2string(style=..).

How to view .img files?

OSFMount , MagicDisc , Gizmo Director/Gizmo Drive , The Takeaway .

All these work well on .img files

What is the correct way of reading from a TCP socket in C/C++?

Where are you allocating memory for your buffer? The line where you invoke bzero invokes undefined behavior since buffer does not point to any valid region of memory.

char *buffer = new char[ BUFFER_SIZE ];
// do processing

// don't forget to release
delete[] buffer;

How do you create a foreign key relationship in a SQL Server CE (Compact Edition) Database?

You need to create a query (in Visual Studio, right-click on the DB connection -> New Query) and execute the following SQL:


To verify that your foreign key was created, execute the following SQL:


Credit to E Jensen (

Interface/enum listing standard mime-type constants

From :

staticjava.lang.String APPLICATION_ATOM_XML             "application/atom+xml"
staticMediaType        APPLICATION_ATOM_XML_TYPE        "application/atom+xml"
staticjava.lang.String APPLICATION_FORM_URLENCODED      "application/x-www-form-urlencoded"
staticMediaType        APPLICATION_FORM_URLENCODED_TYPE "application/x-www-form-urlencoded"
staticjava.lang.String APPLICATION_JSON                 "application/json"
staticMediaType        APPLICATION_JSON_TYPE            "application/json"
staticjava.lang.String APPLICATION_OCTET_STREAM         "application/octet-stream"
staticMediaType        APPLICATION_OCTET_STREAM_TYPE    "application/octet-stream"
staticjava.lang.String APPLICATION_SVG_XML              "application/svg+xml"
staticMediaType        APPLICATION_SVG_XML_TYPE         "application/svg+xml"
staticjava.lang.String APPLICATION_XHTML_XML            "application/xhtml+xml"
staticMediaType        APPLICATION_XHTML_XML_TYPE       "application/xhtml+xml"
staticjava.lang.String APPLICATION_XML                  "application/xml"
staticMediaType        APPLICATION_XML_TYPE             "application/xml"
staticjava.lang.String MEDIA_TYPE_WILDCARD              The value of a type or subtype wildcard: "*"
staticjava.lang.String MULTIPART_FORM_DATA              "multipart/form-data"
staticMediaType        MULTIPART_FORM_DATA_TYPE         "multipart/form-data"
staticjava.lang.String TEXT_HTML                        "text/html"
staticMediaType        TEXT_HTML_TYPE                   "text/html"
staticjava.lang.String TEXT_PLAIN                       "text/plain"
staticMediaType        TEXT_PLAIN_TYPE                  "text/plain"
staticjava.lang.String TEXT_XML                         "text/xml"
staticMediaType        TEXT_XML_TYPE                    "text/xml"
staticjava.lang.String WILDCARD                         "*/*"
staticMediaType        WILDCARD_TYPE                    "*/*"

How do you move a file?

If you are moving folders via Repository Browser, then there is no Move option on right-click; the only way is to drag and drop.

How to resolve "Waiting for Debugger" message?

Rebooting the phone was the solution for me.

Binary search (bisection) in Python

Why not look at the code for bisect_left/right and adapt it to suit your purpose.

like this:

def binary_search(a, x, lo=0, hi=None):
    if hi is None:
        hi = len(a)
    while lo < hi:
        mid = (lo+hi)//2
        midval = a[mid]
        if midval < x:
            lo = mid+1
        elif midval > x: 
            hi = mid
            return mid
    return -1

Add ArrayList to another ArrayList in java

The problem you have is caused that you use the same ArrayList NodeList over all iterations in main for loop. Each iterations NodeList is enlarged by new elements.

  1. After first loop, NodeList has 5 elements (PropertyStart,a,b,c,PropertyEnd) and list has 1 element (NodeList: (PropertyStart,a,b,c,PropertyEnd))

  2. After second loop NodeList has 10 elements (PropertyStart,a,b,c,PropertyEnd,PropertyStart,d,e,f,PropertyEnd) and list has 2 elements (NodeList (with 10 elements), NodeList (with 10 elements))

To get you expectations you must replace



List childrenList = new ArrayList(nodes);

PS. Your code is not readable, keep Java code conventions to have readble code. For example is hard to recognize if NodeList is a class or object

Cycles in family tree software

Potential legal implications aside, it certainly seems that you need to treat a 'node' on a family tree as a predecessor-person rather than assuming that the node can be the-one-and-only person.

Have the tree node include a person as well as the successors - and then you can have another node deeper down the tree that includes the same person with different successors.

Good tool to visualise database schema?

Have you tried the arrange > auto arrange function in MySQL Workbench. It may save you from manually moving the tables around.

How to fix Ora-01427 single-row subquery returns more than one row in select?

The only subquery appears to be this - try adding a ROWNUM limit to the where to be sure:

         AND C.I_EMPID = A.I_EMPID)

You do need to investigate why this isn't unique, however - e.g. the employee might have had more than one C.I_COMPENSATEDDATE on the matched date.

For performance reasons, you should also see if the lookup subquery can be rearranged into an inner / left join, i.e.

            ' ',
            '') AS WORKDATE,
          AND C.I_EMPID = A.I_EMPID

What does the fpermissive flag do?

A common case for simply setting -fpermissive and not sweating it exists: the thoroughly-tested and working third-party library that won't compile on newer compiler versions without -fpermissive. These libraries exist, and are very likely not the application developer's problem to solve, nor in the developer's schedule budget to do it.

Set -fpermissive and move on in that case.

Is it possible to create a temporary table in a View and drop it after select?

You can achieve what you are trying to do, using a Stored Procedure which returns a query result. Views are not suitable / developed for operations like this one.

How can I represent a range in Java?

import java.util.Arrays;

class Soft{
    public static void main(String[] args){
        int[] nums=range(9, 12);
    static int[] range(int low, int high){
        int[] a=new int[high-low];
        for(int i=0,j=low;i<high-low;i++,j++){
        return a;


My code is similar to Python`s range :)

What is HTTP "Host" header?

I would always recommend going to the authoritative source when trying to understand the meaning and purpose of HTTP headers.

The "Host" header field in a request provides the host and port
information from the target URI, enabling the origin server to
distinguish among resources while servicing requests for multiple
host names on a single IP address.

How to use operator '-replace' in PowerShell to replace strings of texts with special characters and replace successfully

In your example, you prepended your source string with AccountKey= but not your target string.

$c = $c -replace 'AccountKey=eKkij32jGEIYIEqAR5RjkKgf4OTiMO6SAyF68HsR/Zd/KXoKvSdjlUiiWyVV2+OUFOrVsd7jrzhldJPmfBBpQA==','AccountKey=DdOegAhDmLdsou6Ms6nPtP37bdw6EcXucuT47lf9kfClA6PjGTe3CfN+WVBJNWzqcQpWtZf10tgFhKrnN48lXA=='

By not including that in the target string, the resulting string will remove AccountKey= instead of replacing it. You correctly do this with the AccountName= example, which seems to support this conclusion since it is not giving you any problems. If you really mean to have that prepended, then this may resolve your issue.

How to add a scrollbar to an HTML5 table?

I first tried the accepted answer by Mr Green, but I found my columns didn't align, that float:left seems very suspicious. When I went from no scollbar to scrollbar -- my table body shifted a few pixels and I lost alignment.



.width50px {
    width: 100px !important;

.width100px {
    width: 100px !important;

.fixed_headers {
    width: 100%;
    table-layout: fixed;
    border-collapse: collapse;

th {
    padding: 5px;
    text-align: left;

td {
    padding: 5px;
    text-align: left;

thead, tr 
    display: block;
    position: relative;

tbody {
    display: block;
    overflow: auto;
    width: 100%;
    height: 500px;

.tableColumnHeader {
    height: 50px;
    font-weight: bold;

.lime {
    background-color: lime;

How to write UTF-8 in a CSV file

For python2 you can use this code before csv_writer.writerows(rows)
This code will NOT convert integers to utf-8 strings

def encode_rows_to_utf8(rows):
    encoded_rows = []
    for row in rows:
        encoded_row = []
        for value in row:
            if isinstance(value, basestring):
                value = unicode(value).encode("utf-8")
    return encoded_rows

How to change heatmap.2 color range in R?

I think you need to set symbreaks = FALSE That should allow for asymmetrical color scales. Read error: ssl=0x9524b800: I/O error during system call, Connection reset by peer

I was experiencing this error on Android 5.1.1 devices sending network requests using okhttp/4.0.0-RC1. Setting header Content-Length: <sizeof response> on the server side resolved the issue.

How do I add 1 day to an NSDate?

NSDateComponents *dayComponent = [[[NSDateComponents alloc] init] autorelease]; = 1;

NSCalendar *theCalendar = [NSCalendar currentCalendar];
dateToBeIncremented = [theCalendar dateByAddingComponents:dayComponent toDate:dateToBeIncremented options:0];

Ok - I thought this was going to work for me. However, if you use it to add a day to the 31st March 2013, it'll return a date that has only 23 hours added to it. It may well actually have the 24, but using in calculations has only 23:00 hours added.

Similarly, if you blast forward to 28th Oct 2013, the code adds 25 hours resulting in a date time of 2013-10-28 01:00:00.

In order to add a day I was doing the thing at the top, adding the:

NSDate *newDate1 = [now dateByAddingTimeInterval:60*60*24*daysToAdd];

Complicated, principally due to daylight saving.

How do I move a file from one location to another in Java?

myFile.renameTo(new File("/the/new/place/newName.file"));

File#renameTo does that (it can not only rename, but also move between directories, at least on the same file system).

Renames the file denoted by this abstract pathname.

Many aspects of the behavior of this method are inherently platform-dependent: The rename operation might not be able to move a file from one filesystem to another, it might not be atomic, and it might not succeed if a file with the destination abstract pathname already exists. The return value should always be checked to make sure that the rename operation was successful.

If you need a more comprehensive solution (such as wanting to move the file between disks), look at Apache Commons FileUtils#moveFile

How to increase Java heap space for a tomcat app

Your change may well be working. Does your application need a lot of memory - the stack trace shows some Image related features.

I'm guessing that the error either happens right away, with a large file, or happens later after several requests.

If the error happens right away, then you can increase memory still further, or investigate find out why so much memory is needed for one file.

If the error happens after several requests, then you could have a memory leak - where objects are not being reclaimed by the garbage collector. Using a tool like JProfiler can help you monitor how much memory is being used by your VM and can help you see what is using that memory and why objects are not being reclaimed by the garbage collector.

How to format a DateTime in PowerShell

Very informative answer from @stej, but here is a short answer: Among other options, you have 3 simple options to format [System.DateTime] stored in a variable:

  1. Pass the variable to the Get-Date cmdlet: Get-Date -Format "HH:mm" $date

  2. Use toString() method: $date.ToString("HH:mm")

  3. Use Composite formatting: "{0:HH:mm}" -f $date

Find all elements with a certain attribute value in jquery

You can use partial value of an attribute to detect a DOM element using (^) sign. For example you have divs like this:

<div id="abc_1"></div>
<div id="abc_2"></div>
<div id="xyz_3"></div>
<div id="xyz_4"></div>...

You can use the code:

var abc = $('div[id^=abc]')

This will return a DOM array of divs which have id starting with abc:

<div id="abc_1"></div>
<div id="abc_2"></div>

Here is the demo:

How to use router.navigateByUrl and router.navigate in Angular

In addition to the provided answer, there are more details to navigate. From the function's comments:

 * Navigate based on the provided array of commands and a starting point.
 * If no starting route is provided, the navigation is absolute.
 * Returns a promise that:
 * - resolves to 'true' when navigation succeeds,
 * - resolves to 'false' when navigation fails,
 * - is rejected when an error happens.
 * ### Usage
 * ```
 * router.navigate(['team', 33, 'user', 11], {relativeTo: route});
 * // Navigate without updating the URL
 * router.navigate(['team', 33, 'user', 11], {relativeTo: route, skipLocationChange: true});
 * ```
 * In opposite to `navigateByUrl`, `navigate` always takes a delta that is applied to the current
 * URL.

The Router Guide has more details on programmatic navigation.

The target ... overrides the `OTHER_LDFLAGS` build setting defined in `Pods/Pods.xcconfig

This definitely works most of the time:

Go to your target Build Settings -> Other linker flags -> double click . Add $(inherited) to a new line.

If you have problem with " overrides the GCC_PREPROCESSOR_DEFINITIONS build setting defined in..." then you must add $(inherited) to your target Build Settings -> Preprocessor Macros

How to make String.Contains case insensitive?

You can use:

if (myString1.IndexOf("AbC", StringComparison.OrdinalIgnoreCase) >=0) {

This works with any .NET version.

How do I search for an object by its ObjectId in the mongo console?

If you're using Node.js:

> var ObjectId = require('mongodb').ObjectId; 
> var id = req.params.gonderi_id;       
> var o_id = new ObjectId(id);
> db.test.find({_id:o_id})

Edit: corrected to new ObjectId(id), not new ObjectID(id)

"starting Tomcat server 7 at localhost has encountered a prob"

Open the terminal in ubuntu (ctrl+shift+t)
sudo gedit /etc/tomcat7/server.xml

change the default port in the server.xml,from 8080 to anything like 8081,8181,8008. Then save the file .

Now the project will work nicely without any interruption.

How to terminate a Python script

You can also use simply exit().

Keep in mind that sys.exit(), exit(), quit(), and os._exit(0) kill the Python interpreter. Therefore, if it appears in a script called from another script by execfile(), it stops execution of both scripts.

See "Stop execution of a script called with execfile" to avoid this.

The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead

  1. Why is this happening?

    The entire ext/mysql PHP extension, which provides all functions named with the prefix mysql_, was officially deprecated in PHP v5.5.0 and removed in PHP v7.

    It was originally introduced in PHP v2.0 (November 1997) for MySQL v3.20, and no new features have been added since 2006. Coupled with the lack of new features are difficulties in maintaining such old code amidst complex security vulnerabilities.

    The manual has contained warnings against its use in new code since June 2011.

  2. How can I fix it?

    As the error message suggests, there are two other MySQL extensions that you can consider: MySQLi and PDO_MySQL, either of which can be used instead of ext/mysql. Both have been in PHP core since v5.0, so if you're using a version that is throwing these deprecation errors then you can almost certainly just start using them right away—i.e. without any installation effort.

    They differ slightly, but offer a number of advantages over the old extension including API support for transactions, stored procedures and prepared statements (thereby providing the best way to defeat SQL injection attacks). PHP developer Ulf Wendel has written a thorough comparison of the features. has an excellent tutorial on migrating from ext/mysql to PDO.

  3. I understand that it's possible to suppress deprecation errors by setting error_reporting in php.ini to exclude E_DEPRECATED:

    error_reporting = E_ALL ^ E_DEPRECATED

    What will happen if I do that?

    Yes, it is possible to suppress such error messages and continue using the old ext/mysql extension for the time being. But you really shouldn't do this—this is a final warning from the developers that the extension may not be bundled with future versions of PHP (indeed, as already mentioned, it has been removed from PHP v7). Instead, you should take this opportunity to migrate your application now, before it's too late.

    Note also that this technique will suppress all E_DEPRECATED messages, not just those to do with the ext/mysql extension: therefore you may be unaware of other upcoming changes to PHP that would affect your application code. It is, of course, possible to only suppress errors that arise on the expression at issue by using PHP's error control operator—i.e. prepending the relevant line with @—however this will suppress all errors raised by that expression, not just E_DEPRECATED ones.

What should you do?

  • You are starting a new project.

    There is absolutely no reason to use ext/mysql—choose one of the other, more modern, extensions instead and reap the rewards of the benefits they offer.

  • You have (your own) legacy codebase that currently depends upon ext/mysql.

    It would be wise to perform regression testing: you really shouldn't be changing anything (especially upgrading PHP) until you have identified all of the potential areas of impact, planned around each of them and then thoroughly tested your solution in a staging environment.

    • Following good coding practice, your application was developed in a loosely integrated/modular fashion and the database access methods are all self-contained in one place that can easily be swapped out for one of the new extensions.

      Spend half an hour rewriting this module to use one of the other, more modern, extensions; test thoroughly. You can later introduce further refinements to reap the rewards of the benefits they offer.

    • The database access methods are scattered all over the place and cannot easily be swapped out for one of the new extensions.

      Consider whether you really need to upgrade to PHP v5.5 at this time.

      You should begin planning to replace ext/mysql with one of the other, more modern, extensions in order that you can reap the rewards of the benefits they offer; you might also use it as an opportunity to refactor your database access methods into a more modular structure.

      However, if you have an urgent need to upgrade PHP right away, you might consider suppressing deprecation errors for the time being: but first be sure to identify any other deprecation errors that are also being thrown.

  • You are using a third party project that depends upon ext/mysql.

    Consider whether you really need to upgrade to PHP v5.5 at this time.

    Check whether the developer has released any fixes, workarounds or guidance in relation to this specific issue; or, if not, pressure them to do so by bringing this matter to their attention. If you have an urgent need to upgrade PHP right away, you might consider suppressing deprecation errors for the time being: but first be sure to identify any other deprecation errors that are also being thrown.

    It is absolutely essential to perform regression testing.

What is the minimum length of a valid international phone number?

The minimum length is 4 for Saint Helena (Format: +290 XXXX) and Niue (Format: +683 XXXX).

Add padding to HTML text input field

<input class="form-control search-query input_style" placeholder="Search…"  name="" title="Search for:" type="text">


How to add a named sheet at the end of all Excel sheets?

Try switching the order of your code. You must create the worksheet first in order to name it.

Private Sub CreateSheet()
    Dim ws As Worksheet
    Set ws = Sheets.Add(After:=Sheets(Sheets.Count))
    ws.Name = "Tempo"
End Sub


C programming: Dereferencing pointer to incomplete type error

The reason why you're getting that error is because you've declared your struct as:

struct {
 char name[32];
 int  size;
 int  start;
 int  popularity;
} stasher_file;

This is not declaring a stasher_file type. This is declaring an anonymous struct type and is creating a global instance named stasher_file.

What you intended was:

struct stasher_file {
 char name[32];
 int  size;
 int  start;
 int  popularity;

But note that while Brian R. Bondy's response wasn't correct about your error message, he's right that you're trying to write into the struct without having allocated space for it. If you want an array of pointers to struct stasher_file structures, you'll need to call malloc to allocate space for each one:

struct stasher_file *newFile = malloc(sizeof *newFile);
if (newFile == NULL) {
   /* Failure handling goes here. */
strncpy(newFile->name, name, 32);
newFile->size = size;

(BTW, be careful when using strncpy; it's not guaranteed to NUL-terminate.)

Working with select using AngularJS's ng-options

I'm learning AngularJS and was struggling with selection as well. I know this question is already answered, but I wanted to share some more code nevertheless.

In my test I have two listboxes: car makes and car models. The models list is disabled until some make is selected. If selection in makes listbox is later reset (set to 'Select Make') then the models listbox becomes disabled again AND its selection is reset as well (to 'Select Model'). Makes are retrieved as a resource while models are just hard-coded.

Makes JSON:

{"code": "0", "name": "Select Make"},
{"code": "1", "name": "Acura"},
{"code": "2", "name": "Audi"}


angular.module('makeServices', ['ngResource']).
factory('Make', function($resource){
    return $resource('makes.json', {}, {
        query: {method:'GET', isArray:true}

HTML file:

<div ng:controller="MakeModelCtrl">
  <select id="makeListBox"
      ng-options="make.code as for make in makes"

  <select id="modelListBox"
     ng-options="model.code as for model in models">


function MakeModelCtrl($scope)
    $scope.makeNotSelected = true;
    $scope.make = {selected: "0"};
    $scope.makes = Make.query({}, function (makes) {
         $scope.make = {selected: makes[0].code};

    $scope.makeChanged = function(selectedMakeCode) {
        $scope.makeNotSelected = !selectedMakeCode;
        if ($scope.makeNotSelected)
            $scope.model = {selected: "0"};

    $scope.models = [
      {code:"0", name:"Select Model"},
      {code:"1", name:"Model1"},
      {code:"2", name:"Model2"}
    $scope.model = {selected: "0"};

Android Dialog: Removing title bar


dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); //before     

Ansible: deploy on multiple hosts in the same time

In my case I needed the configuration stage to be blocking as a whole, but execute each role in parallel. I've tackled this issue using the following code:

echo webserver loadbalancer database | tr ' ' '\n' \
| xargs -I % -P 3 bash -c 'ansible-playbook $1.yml' -- %

the -P 3 argument in xargs makes sure that all the commands are ran in parallel, each command executes the respective playbook and the command as a whole blocks until all parts are finished.