Programs & Examples On #Jadclipse

Multiple Errors Installing Visual Studio 2015 Community Edition

I did.

1) Stopped Avast Internet security.

2) uninstall all Microsoft C++ 2015 Redistributables.

3) install vs-2015 community.

installation finished.

thanks.

How to redirect docker container logs to a single file?

No need to redirect logs.

Docker by default store logs to one log file. To check log file path run command:

docker inspect --format='{{.LogPath}}' containername

/var/lib/docker/containers/f844a7b45ca5a9589ffaa1a5bd8dea0f4e79f0e2ff639c1d010d96afb4b53334/f844a7b45ca5a9589ffaa1a5bd8dea0f4e79f0e2ff639c1d010d96afb4b53334-json.log

Open that log file and analyse.

if you redirect logs then you will only get logs before redirection. you will not be able to see live logs.

EDIT:

To see live logs you can run below command

tail -f `docker inspect --format='{{.LogPath}}' containername`

Note:

This log file /var/lib/docker/containers/f844a7b45ca5a9589ffaa1a5bd8dea0f4e79f0e2ff639c1d010d96afb4b53334/f844a7b45ca5a9589ffaa1a5bd8dea0f4e79f0e2ff639c1d010d96afb4b53334-json.log will be created only if docker generating logs if there is no logs then this file will not be there. it is similar like sometime if we run command docker logs containername and it returns nothing. In that scenario this file will not be available.

Graph visualization library in JavaScript

JsVIS was pretty nice, but slow with larger graphs, and has been abandoned since 2007.

prefuse is a set of software tools for creating rich interactive data visualizations in Java. flare is an ActionScript library for creating visualizations that run in the Adobe Flash Player, abandoned since 2012.

How to list imported modules?

let say you've imported math and re:

>>import math,re

now to see the same use

>>print(dir())

If you run it before the import and after the import, one can see the difference.

How to make this Header/Content/Footer layout using CSS?

Try This

<!DOCTYPE html>

<html>

<head>

<title>Sticky Header and Footer</title>

<style type="text/css">

/* Reset body padding and margins */

body {
    margin:0;

    padding:0;
}

/* Make Header Sticky */

#header_container {

    background:#eee;

    border:1px solid #666;

    height:60px;

    left:0;

    position:fixed;

    width:100%;

    top:0;
}

#header {

    line-height:60px;

    margin:0 auto;

    width:940px;

    text-align:center;
}

/* CSS for the content of page. I am giving top and bottom padding of 80px to make sure the header and footer do not overlap the content.*/

#container {

    margin:0 auto;

    overflow:auto;

    padding:80px 0;

    width:940px;

}

#content {

}

/* Make Footer Sticky */

#footer_container {

    background:#eee;

    border:1px solid #666;

    bottom:0;

    height:60px;

    left:0;

    position:fixed;

    width:100%;
}

#footer {

    line-height:60px;

    margin:0 auto;

    width:940px;

    text-align:center;

}

</style>

</head>

<body>

<!-- BEGIN: Sticky Header -->
<div id="header_container">

    <div id="header">
        Header Content
    </div>

</div>
<!-- END: Sticky Header -->

<!-- BEGIN: Page Content -->
<div id="container">

    <div id="content">

            content
        <br /><br />
            blah blah blah..
        ...
    </div>

</div>
<!-- END: Page Content -->

<!-- BEGIN: Sticky Footer -->
<div id="footer_container">

    <div id="footer">

        Footer Content

    </div>

</div>

<!-- END: Sticky Footer -->

</body>

</html>

How to send POST request in JSON using HTTPClient in Android?

I recommend using this HttpURLConnectioninstead HttpGet. As HttpGet is already deprecated in Android API level 22.

HttpURLConnection httpcon;  
String url = null;
String data = null;
String result = null;
try {
  //Connect
  httpcon = (HttpURLConnection) ((new URL (url).openConnection()));
  httpcon.setDoOutput(true);
  httpcon.setRequestProperty("Content-Type", "application/json");
  httpcon.setRequestProperty("Accept", "application/json");
  httpcon.setRequestMethod("POST");
  httpcon.connect();

  //Write       
  OutputStream os = httpcon.getOutputStream();
  BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
  writer.write(data);
  writer.close();
  os.close();

  //Read        
  BufferedReader br = new BufferedReader(new InputStreamReader(httpcon.getInputStream(),"UTF-8"));

  String line = null; 
  StringBuilder sb = new StringBuilder();         

  while ((line = br.readLine()) != null) {  
    sb.append(line); 
  }         

  br.close();  
  result = sb.toString();

} catch (UnsupportedEncodingException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
} 

bootstrap.min.js:6 Uncaught Error: Bootstrap dropdown require Popper.js

I had this issue with an MVC project and here is how I fixed it.

  1. Open BundleConfig.cs
  2. Find :

    bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include("~/Scripts/bootstrap.js"));

    Change to:

    bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include("~/Scripts/bootstrap.bundle.min.js"));
    

This will set the bundle file to load. It is already in the correct order. You just have to make sure that you are rendering this bundle in your view.

Alternative Windows shells, besides CMD.EXE?

I am a fan of Cmder, a package including clink, conemu, msysgit, and some cosmetic enhancements.

http://cmder.net/

https://github.com/cmderdev/cmder

https://chocolatey.org/packages/Cmder

enter image description here

How to assign a value to a TensorFlow variable?

There is an easier approach:

x = tf.Variable(0)
x = x + 1
print x.eval()

How to activate the Bootstrap modal-backdrop?

Pretty strange, it should work out of the box as the ".modal-backdrop" class is defined top-level in the css.

<div class="modal-backdrop"></div>

Made a small demo: http://jsfiddle.net/PfBnq/

Check if input value is empty and display an alert

Also you can try this, if you want to focus on same text after error.

If you wants to show this error message in a paragraph then you can use this one:

 $(document).ready(function () {
    $("#submit").click(function () {
        if($('#selBooks').val() === '') {
            $("#Paragraph_id").text("Please select a book and then proceed.").show();
            $('#selBooks').focus();
            return false;
        }
    });
 });

How to replace all occurrences of a string in Javascript?

This is the fastest version that doesn't use regular expressions.

Revised jsperf

replaceAll = function(string, omit, place, prevstring) {
  if (prevstring && string === prevstring)
    return string;
  prevstring = string.replace(omit, place);
  return replaceAll(prevstring, omit, place, string)
}

It is almost twice as fast as the split and join method.

As pointed out in a comment here, this will not work if your omit variable contains place, as in: replaceAll("string", "s", "ss"), because it will always be able to replace another occurrence of the word.

There is another jsperf with variants on my recursive replace that go even faster (http://jsperf.com/replace-all-vs-split-join/12)!

  • Update July 27th 2017: It looks like RegExp now has the fastest performance in the recently released Chrome 59.

How to change the locale in chrome browser

[on hold: broken in Chrome 72; reported to work in Chrome 71]

The "Quick Language Switcher" extension may help too: https://chrome.google.com/webstore/detail/quick-language-switcher/pmjbhfmaphnpbehdanbjphdcniaelfie

The Quick Language Switcher extension allows the user to supersede the locale the browser is currently using in favor of the value chosen through the extension.

Set initial focus in an Android application

I found this worked best for me.

In AndroidManifest.xml <activity> element add android:windowSoftInputMode="stateHidden"

This always hides the keyboard when entering the activity.

how to format date in Component of angular 5

Another option can be using built in angular formatDate function. I am assuming that you are using reactive forms. Here todoDate is a date input field in template.

import {formatDate} from '@angular/common';

this.todoForm.controls.todoDate.setValue(formatDate(this.todo.targetDate, 'yyyy-MM-dd', 'en-US'));

What is wrong with this code that uses the mysql extension to fetch data from a database in PHP?

use this code

  while ($rows = mysql_fetch_array($query)):

   $name = $rows['Name'];
   $address = $rows['Address'];
   $email = $rows['Email'];
   $subject = $rows['Subject'];
   $comment = $rows['Comment'];

   echo "$name<br>$address<br>$email<br>$subject<br>$comment<br><br>";

   endwhile;

   ?>

What does the Visual Studio "Any CPU" target mean?

I think most of the important stuff has been said, but I just thought I'd add one thing: If you compile as Any CPU and run on an x64 platform, then you won't be able to load 32-bit DLL files, because your application wasn't started in WoW64, but those DLL files need to run there.

If you compile as x86, then the x64 system will run your application in WoW64, and you'll be able to load 32-bit DLL files.

So I think you should choose "Any CPU" if your dependencies can run in either environment, but choose x86 if you have 32-bit dependencies. This article from Microsoft explains this a bit:

/CLRIMAGETYPE (Specify Type of CLR Image)

Incidentally, this other Microsoft documentation agrees that x86 is usually a more portable choice:

Choosing x86 is generally the safest configuration for an app package since it will run on nearly every device. On some devices, an app package with the x86 configuration won't run, such as the Xbox or some IoT Core devices. However, for a PC, an x86 package is the safest choice and has the largest reach for device deployment. A substantial portion of Windows 10 devices continue to run the x86 version of Windows.

jQuery ui datepicker with Angularjs

I have almost exactly the same code as you and mine works.

Do you have jQueryUI.js included in the page?

There's a fiddle here

<input type="text" ng-model="date" jqdatepicker />
<br/>
{{ date }}


var datePicker = angular.module('app', []);

datePicker.directive('jqdatepicker', function () {
    return {
        restrict: 'A',
        require: 'ngModel',
         link: function (scope, element, attrs, ngModelCtrl) {
            element.datepicker({
                dateFormat: 'DD, d  MM, yy',
                onSelect: function (date) {
                    scope.date = date;
                    scope.$apply();
                }
            });
        }
    };
});

You'll also need the ng-app="app" somewhere in your HTML

How To Set Up GUI On Amazon EC2 Ubuntu server

So I follow first answer, but my vnc viewer gives me grey screen when I connect to it. And I found this Ask Ubuntu link to solve that.

The only difference with previous answer is you need to install these extra packages:

apt-get install gnome-panel gnome-settings-daemon metacity nautilus gnome-terminal

And use this ~/.vnc/xstartup file:

#!/bin/sh

export XKL_XMODMAP_DISABLE=1
unset SESSION_MANAGER
unset DBUS_SESSION_BUS_ADDRESS

[ -x /etc/vnc/xstartup ] && exec /etc/vnc/xstartup
[ -r $HOME/.Xresources ] && xrdb $HOME/.Xresources
xsetroot -solid grey
vncconfig -iconic &

gnome-panel &
gnome-settings-daemon &
metacity &
nautilus &
gnome-terminal &

Everything else is the same.

Tested on EC2 Ubuntu 14.04 LTS.

Howto: Clean a mysql InnoDB storage engine?

The InnoDB engine does not store deleted data. As you insert and delete rows, unused space is left allocated within the InnoDB storage files. Over time, the overall space will not decrease, but over time the 'deleted and freed' space will be automatically reused by the DB server.

You can further tune and manage the space used by the engine through an manual re-org of the tables. To do this, dump the data in the affected tables using mysqldump, drop the tables, restart the mysql service, and then recreate the tables from the dump files.

Modelling an elevator using Object-Oriented Analysis and Design

I've seen many variants of this problem. One of the main differences (that determines the difficulty) is whether there is some centralized attempt to have a "smart and efficient system" that would have load balancing (e.g., send more idle elevators to lobby in morning). If that is the case, the design will include a whole subsystem with really fun design.

A full design is obviously too much to present here and there are many altenatives. The breadth is also not clear. In an interview, they'll try to figure out how you would think. However, these are some of the things you would need:

  1. Representation of the central controller (assuming there is one).

  2. Representations of elevators

  3. Representations of the interface units of the elevator (these may be different from elevator to elevator). Obviously also call buttons on every floor, etc.

  4. Representations of the arrows or indicators on each floor (almost a "view" of the elevator model).

  5. Representation of a human and cargo (may be important for factoring in maximal loads)

  6. Representation of the building (in some cases, as certain floors may be blocked at times, etc.)

check android application is in foreground or not?

There is no global callback for this, but for each activity it is onStop(). You don't need to mess with an atomic int. Just have a global int with the number of started activities, in every activity increment it in onStart() and decrement it in onStop().

public class BaseActivity extends ActionBarActivity {
public static int count = 0;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}


@Override
protected void onStart() {
    super.onStart();
    count = count + 1;
    Log.d(TAG, "onStart" + count);
    if (count == 1) {

       Toast.makeText(getApplicationContext(), "online", Toast.LENGTH_SHORT).show();

    }

}



protected void onStop() {
    super.onStop();
    count = count - 1;
    if (count == 0) {

        Toast.makeText(getApplicationContext(), "offline", Toast.LENGTH_SHORT).show();

    }
}


}

How to call a method in MainActivity from another class?

You can make this method static.

public static void startChronometer(){
        mChronometer.start();
        showElapsedTime();
    } 

you can call this function in other class as below:

MainActivity.startChronometer();

OR

You can make an object of the main class in second class like,

MainActivity mActivity = new MainActivity();
mActivity.startChronometer();

What is the difference between ManualResetEvent and AutoResetEvent in .NET?

The short answer is yes. The most important difference is that an AutoResetEvent will only allow one single waiting thread to continue. A ManualResetEvent on the other hand will keep allowing threads, several at the same time even, to continue until you tell it to stop (Reset it).

Registry key Error: Java version has value '1.8', but '1.7' is required

just did this and it worked

HKLM > SOFTWARE > JavaSoft > Java Runtime Environment

just manually change current version to 1.7 .

lol ... but it worked!

Verify a method call using Moq

You're checking the wrong method. Moq requires that you Setup (and then optionally Verify) the method in the dependency class.

You should be doing something more like this:

class MyClassTest
{
    [TestMethod]
    public void MyMethodTest()
    {
        string action = "test";
        Mock<SomeClass> mockSomeClass = new Mock<SomeClass>();

        mockSomeClass.Setup(mock => mock.DoSomething());

        MyClass myClass = new MyClass(mockSomeClass.Object);
        myClass.MyMethod(action);

        // Explicitly verify each expectation...
        mockSomeClass.Verify(mock => mock.DoSomething(), Times.Once());

        // ...or verify everything.
        // mockSomeClass.VerifyAll();
    }
}

In other words, you are verifying that calling MyClass#MyMethod, your class will definitely call SomeClass#DoSomething once in that process. Note that you don't need the Times argument; I was just demonstrating its value.

Android offline documentation and sample codes

If you install the SDK, the offline documentation can be found in $ANDROID_SDK/docs/.

Golang append an item to a slice

Here is a nice implementation of append for slices. I guess its similar to what is going on under the hood:

package main

import "fmt"

func main() {
    slice1 := []int{0, 1, 2, 3, 4}
    slice2 := []int{55, 66, 77}
    fmt.Println(slice1)
    slice1 = Append(slice1, slice2...) // The '...' is essential!
    fmt.Println(slice1)
}

// Append ...
func Append(slice []int, items ...int) []int {
    for _, item := range items {
        slice = Extend(slice, item)
    }
    return slice
}

// Extend ...
func Extend(slice []int, element int) []int {
    n := len(slice)
    if n == cap(slice) {
        // Slice is full; must grow.
        // We double its size and add 1, so if the size is zero we still grow.
        newSlice := make([]int, len(slice), 2*len(slice)+1)
        copy(newSlice, slice)
        slice = newSlice
    }
    slice = slice[0 : n+1]
    slice[n] = element
    return slice
}

Chrome/jQuery Uncaught RangeError: Maximum call stack size exceeded

You can also get this error when you have an infinite loop. Make sure that you don't have any unending, recursive self references.

Run local python script on remote server

You can do it via ssh.

ssh [email protected] "python ./hello.py"

You can also edit the script in ssh using a textual editor or X11 forwarding.

How to amend older Git commit?

I've used another way for a few times. In fact, it is a manual git rebase -i and it is useful when you want to rearrange several commits including squashing or splitting some of them. The main advantage is that you don't have to decide about every commit's destiny at a single moment. You'll also have all Git features available during the process unlike during a rebase. For example, you can display the log of both original and rewritten history at any time, or even do another rebase!

I'll refer to the commits in the following way, so it's readable easily:

C # good commit after a bad one
B # bad commit
A # good commit before a bad one

Your history in the beginning looks like this:

x - A - B - C
|           |
|           master
|
origin/master

We'll recreate it to this way:

x - A - B*- C'
|           |
|           master
|
origin/master

Procedure

git checkout B       # get working-tree to the state of commit B
git reset --soft A   # tell Git that we are working before commit B
git checkout -b rewrite-history   # switch to a new branch for alternative history

Improve your old commit using git add (git add -i, git stash etc.) now. You can even split your old commit into two or more.

git commit           # recreate commit B (result = B*)
git cherry-pick C    # copy C to our new branch (result = C')

Intermediate result:

x - A - B - C 
|    \      |
|     \     master
|      \
|       B*- C'
|           |
|           rewrite-history
|
origin/master

Let's finish:

git checkout master
git reset --hard rewrite-history  # make this branch master

Or using just one command:

git branch -f master  # make this place the new tip of the master branch

That's it, you can push your progress now.

The last task is to delete the temporary branch:

git branch -d rewrite-history

Automapper missing type map configuration or unsupported mapping - Error

I created a new AutomapperProfile class. It extends Profile. We have over 100 projects in our solution. Many projects have an AutomapperProfile class, but this one was new to this existing project. However, I did find what I had to do to fix this issue for us. There is a Binding project. Within the Initialization there is this code:

var mappingConfig = new List<Action<IConfiguration>>();

// Initialize the Automapper Configuration for all Known Assemblies
mappingConfig.AddRange( new List<Action<IConfiguration>>
{
   ConfigureProfilesInAssemblyOfType<Application.Administration.AutomapperProfile>,
   //...

I had to add ConfigureProfilesInAssemblyOfType<MyNewNamespace.AutomapperProfile>

Note that ConfigureProfilesInAssemblyOfType looks like this:

    private static void ConfigureProfilesInAssemblyOfType<T>( IConfiguration configuration )
    {
        var log = LogProvider.Get( typeof (AutomapperConfiguration) );

        // The Automapper Profile Type
        var automapperProfileType = typeof (Profile);

        // The Assembly containing the type
        var assembly = typeof (T).Assembly;
        log.Debug( "Scanning " + assembly.FullName );

        // Configure any Profile classes found in the assembly containing the type.
        assembly.GetTypes()
            .Where( automapperProfileType.IsAssignableFrom ).ToList()
            .ForEach( x =>
            {
                log.Debug( "Adding Profile '" + x.FullName + "'" );
                configuration.AddProfile( Activator.CreateInstance( x ) as Profile );
            } );
    }

Best regards, -Jeff

How to create JSON object Node.js

The JavaScript Object() constructor makes an Object that you can assign members to.

myObj = new Object()
myObj.key = value;
myObj[key2] = value2;   // Alternative

What does <> mean in excel?

It means "not equal to" (as in, the values in cells E37-N37 are not equal to "", or in other words, they are not empty.)

Useful example of a shutdown hook in Java?

Shutdown Hooks are unstarted threads that are registered with Runtime.addShutdownHook().JVM does not give any guarantee on the order in which shutdown hooks are started.For more info refer http://techno-terminal.blogspot.in/2015/08/shutdown-hooks.html

How do I return JSON without using a template in Django?

Here's an example I needed for conditionally rendering json or html depending on the Request's Accept header

# myapp/views.py
from django.core import serializers                                                                                
from django.http import HttpResponse                                                                                  
from django.shortcuts import render                                                                                   
from .models import Event

def event_index(request):                                                                                             
    event_list = Event.objects.all()                                                                                  
    if request.META['HTTP_ACCEPT'] == 'application/json':                                                             
        response = serializers.serialize('json', event_list)                                                          
        return HttpResponse(response, content_type='application/json')                                                
    else:                                                                                                             
        context = {'event_list': event_list}                                                                          
        return render(request, 'polls/event_list.html', context)

you can test this with curl or httpie

$ http localhost:8000/event/
$ http localhost:8000/event/ Accept:application/json

note I opted not to use JsonReponse as that would reserialize the model unnecessarily.

Change values of select box of "show 10 entries" of jquery datatable

If you want to use 'lengthMenu' together with buttons(copy, export), you have to use this option dom: 'lBfrtip'. Here https://datatables.net/reference/option/dom you can find meaning of each symbol. For example, if you will use like this 'Bfrtip', lengthMenu will not appears.

How to change the DataTable Column Name?

Use this

dataTable.Columns["OldColumnName"].ColumnName = "NewColumnName";

How do I find where JDK is installed on my windows machine?

Script for 32/64 bit Windows.

@echo off

setlocal enabledelayedexpansion

::- Get the Java Version
set KEY="HKLM\SOFTWARE\JavaSoft\Java Runtime Environment"
set KEY64="HKLM\SOFTWARE\WOW6432Node\JavaSoft\Java Runtime Environment"
set VALUE=CurrentVersion
reg query %KEY% /v %VALUE% 2>nul || (
    set KEY=!KEY64!
    reg query !KEY! /v %VALUE% 2>nul || (
    echo JRE not installed 
    exit /b 1
)
)

set JRE_VERSION=
for /f "tokens=2,*" %%a in ('reg query %KEY% /v %VALUE% ^| findstr %VALUE%') do (
    set JRE_VERSION=%%b
)

echo JRE VERSION: %JRE_VERSION%

::- Get the JavaHome
set KEY="HKLM\SOFTWARE\JavaSoft\Java Runtime Environment\%JRE_VERSION%"
set KEY64="HKLM\SOFTWARE\WOW6432Node\JavaSoft\Java Runtime Environment\%JRE_VERSION%"
set VALUE=JavaHome
reg query %KEY% /v %VALUE% 2>nul || (
    set KEY=!KEY64!
    reg query !KEY! /v %VALUE% 2>nul || (
    echo JavaHome not installed
    exit /b 1
)
)

set JAVAHOME=
for /f "tokens=2,*" %%a in ('reg query %KEY% /v %VALUE% ^| findstr %VALUE%') do (
    set JAVAHOME=%%b
)

echo JavaHome: %JAVAHOME%

endlocal

Bash script to cd to directory with spaces in pathname

When working under Linux the syntax below is right:

cd ~/My\ Code

However when you're executing your file, use the syntax below:

$ . cdcode

(just '.' and not './')

How to create a testflight invitation code?

after you add the user for testing. the user should get an email. open that email by your iOS device, then click "Start testing" it will bring you to testFlight to download the app directly. If you open that email via computer, and then click "Start testing" it will show you another page which have the instruction of how to install the app. and that invitation code is on the last line. those All upper case letters is the code.

Python: TypeError: cannot concatenate 'str' and 'int' objects

The easiest and least confusing solution:

a = raw_input("Enter a: ")
b = raw_input("Enter b: ")
print "a + b as strings: %s" % a  + b
a = int(a)
b = int(b)
c = a + b
print "a + b as integers: %d" % c

I found this on http://freecodeszone.blogspot.com/

Django DateField default options

This is why you should always import the base datetime module: import datetime, rather than the datetime class within that module: from datetime import datetime.

The other mistake you have made is to actually call the function in the default, with the (). This means that all models will get the date at the time the class is first defined - so if your server stays up for days or weeks without restarting Apache, all elements will get same the initial date.

So the field should be:

import datetime
date = models.DateField(_("Date"), default=datetime.date.today)

Android Studio - Failed to notify project evaluation listener error

I enabled "Offline-Work" under File -> Settings ->Build,Deploy, Exec -> Gradle And this finally resolved the issue for me.

Array to Collection: Optimized code

You can try something like this:

List<String> list = new ArrayList<String>(Arrays.asList(array));

public ArrayList(Collection c)

Constructs a list containing the elements of the specified collection, in the order they are returned by the collection's iterator. The ArrayList instance has an initial capacity of 110% the size of the specified collection.

Taken from here

Difference between FetchType LAZY and EAGER in Java Persistence API?

EAGER loading of collections means that they are fetched fully at the time their parent is fetched. So if you have Course and it has List<Student>, all the students are fetched from the database at the time the Course is fetched.

LAZY on the other hand means that the contents of the List are fetched only when you try to access them. For example, by calling course.getStudents().iterator(). Calling any access method on the List will initiate a call to the database to retrieve the elements. This is implemented by creating a Proxy around the List (or Set). So for your lazy collections, the concrete types are not ArrayList and HashSet, but PersistentSet and PersistentList (or PersistentBag)

git returns http error 407 from proxy after CONNECT

Had the 407 error from Android Studio. Tried adding the proxy, but nothing happened. Found out that it was related to company certificate, so I exported the one from my browser and added it to Git.

Export From Web Browser

Internet Options > Content > Certificates > Export (Follow wizard, I chose format "Base 64 encoded X.509(.CER))

In Git Bash

git config --global http.sslCAInfo c:\Utilities\Certificates\my_certificate

The following page was useful https://blogs.msdn.microsoft.com/phkelley/2014/01/20/adding-a-corporate-or-self-signed-certificate-authority-to-git-exes-store/

To add the proxy, like the other threads I used

git config --global http.proxy proxy.company.net:8080
git config --global https.proxy proxy.company.net:8080

Using git to get just the latest revision

Use git clone with the --depth option set to 1 to create a shallow clone with a history truncated to the latest commit.

For example:

git clone --depth 1 https://github.com/user/repo.git

To also initialize and update any nested submodules, also pass --recurse-submodules and to clone them shallowly, also pass --shallow-submodules.

For example:

git clone --depth 1 --recurse-submodules --shallow-submodules https://github.com/user/repo.git

Rock, Paper, Scissors Game Java

Before we try to solve the invalid character problem, the lack of curly braces around the if and else if statements is wreaking havoc on your program's logic. Change it to this:

if (personPlay.equals(computerPlay)) {
   System.out.println("It's a tie!");
}
else if (personPlay.equals("R")) {
   if (computerPlay.equals("S")) 
      System.out.println("Rock crushes scissors. You win!!");
   else if (computerPlay.equals("P")) 
        System.out.println("Paper eats rock. You lose!!");
}
else if (personPlay.equals("P")) {
   if (computerPlay.equals("S")) 
       System.out.println("Scissor cuts paper. You lose!!"); 
   else if (computerPlay.equals("R")) 
        System.out.println("Paper eats rock. You win!!");
} 
else if (personPlay.equals("S")) {
     if (computerPlay.equals("P")) 
         System.out.println("Scissor cuts paper. You win!!"); 
     else if (computerPlay.equals("R")) 
        System.out.println("Rock breaks scissors. You lose!!");
}
else 
     System.out.println("Invalid user input.");

Much clearer! It's now actually a piece of cake to catch the bad characters. You need to move the else statement to somewhere that will catch the errors before you attempt to process anything else. So change everything to:

if( /* insert your check for bad characters here */ ) { 
     System.out.println("Invalid user input.");
}
else if (personPlay.equals(computerPlay)) {
   System.out.println("It's a tie!");
}
else if (personPlay.equals("R")) {
   if (computerPlay.equals("S")) 
      System.out.println("Rock crushes scissors. You win!!");
   else if (computerPlay.equals("P")) 
        System.out.println("Paper eats rock. You lose!!");
}
else if (personPlay.equals("P")) {
   if (computerPlay.equals("S")) 
       System.out.println("Scissor cuts paper. You lose!!"); 
   else if (computerPlay.equals("R")) 
        System.out.println("Paper eats rock. You win!!");
} 
else if (personPlay.equals("S")) {
     if (computerPlay.equals("P")) 
         System.out.println("Scissor cuts paper. You win!!"); 
     else if (computerPlay.equals("R")) 
        System.out.println("Rock breaks scissors. You lose!!");
}

How can I remove an element from a list, with lodash?

In Addition to @thefourtheye answer, using predicate instead of traditional anonymous functions:

  _.remove(obj.subTopics, (currentObject) => {
        return currentObject.subTopicId === stToDelete;
    });

OR

obj.subTopics = _.filter(obj.subTopics, (currentObject) => {
    return currentObject.subTopicId !== stToDelete;
});

.m2 , settings.xml in Ubuntu

You can find your maven files here:

cd ~/.m2

Probably you need to copy settings.xml in your .m2 folder:

cp /usr/local/bin/apache-maven-2.2.1/conf/settings.xml .m2/

If no .m2 folder exists:

mkdir -p ~/.m2

Programmatically check Play Store for app updates

Coming From a Hybrid Application POV. This is a javascript example, I have a Update Available footer on my main menu. If an update is available (ie. my version number within the config file is less than the version retrieved, display the footer) This will then direct the user to the app/play store, where the user can then click the update button.

I also get the whats new data (ie Release Notes) and display these in a modal on login if its the first time on this version.

On device Ready, set your store URL

        if (device.platform == 'iOS')
           storeURL = 'https://itunes.apple.com/lookup?bundleId=BUNDLEID';
        else
           storeURL = 'https://play.google.com/store/apps/details?id=BUNDLEID';

The Update Available method can be ran as often as you like. Mine is ran every time the user navigates to the home screen.

function isUpdateAvailable() {
    if (device.platform == 'iOS') {
        $.ajax(storeURL, {
            type: "GET",
            cache: false,
            dataType: 'json'
        }).done(function (data) {
            isUpdateAvailable_iOS(data.results[0]);
        }).fail(function (jqXHR, textStatus, errorThrown) {
            commsErrorHandler(jqXHR, textStatus, false);
        });
    } else {
        $.ajax(storeURL, {
            type: "GET",
            cache: false
        }).done(function (data) {
            isUpdateAvailable_Android(data);
        }).fail(function (jqXHR, textStatus, errorThrown) {
            commsErrorHandler(jqXHR, textStatus, false);
        });
    }
}

iOS Callback: Apple have an API, so very easy to get

function isUpdateAvailable_iOS (data) {
    var storeVersion = data.version;
    var releaseNotes = data.releaseNotes;
    // Check store Version Against My App Version ('1.14.3' -> 1143)
    var _storeV = parseInt(storeVersion.replace(/\./g, ''));
    var _appV = parseInt(appVersion.substring(1).replace(/\./g, ''));
    $('#ft-main-menu-btn').off();
    if (_storeV > _appV) {
        // Update Available
        $('#ft-main-menu-btn').text('Update Available');
        $('#ft-main-menu-btn').click(function () {
            openStore();
        });

    } else {
        $('#ft-main-menu-btn').html('&nbsp;');
        // Release Notes
        settings.updateReleaseNotes('v' + storeVersion, releaseNotes);
    }
}

Android Callback: PlayStore you have to scrape, as you can see the version is relatively easy to grab and the whats new i take the html instead of the text as this way I can use their formatting (ie new lines etc)

function isUpdateAvailable_Android(data) {
    var html = $(data);
    var storeVersion = html.find('div[itemprop=softwareVersion]').text().trim();
    var releaseNotes = html.find('.whatsnew')[0].innerHTML;
    // Check store Version Against My App Version ('1.14.3' -> 1143)
    var _storeV = parseInt(storeVersion.replace(/\./g, ''));
    var _appV = parseInt(appVersion.substring(1).replace(/\./g, ''));
    $('#ft-main-menu-btn').off();
    if (_storeV > _appV) {
        // Update Available
        $('#ft-main-menu-btn').text('Update Available');
        $('#ft-main-menu-btn').click(function () {
            openStore();
        });

    } else {
        $('#ft-main-menu-btn').html('&nbsp;');
        // Release Notes
        settings.updateReleaseNotes('v' + storeVersion, releaseNotes);
    }
}

The open store logic is straight forward, but for completeness

function openStore() {
    var url = 'https://itunes.apple.com/us/app/appname/idUniqueID';
    if (device.platform != 'iOS')
       url = 'https://play.google.com/store/apps/details?id=appid'
   window.open(url, '_system')
}

Ensure Play Store and App Store have been Whitelisted:

  <access origin="https://itunes.apple.com"/>
  <access origin="https://play.google.com"/>

How to get the size of a range in Excel

The overall dimensions of a range are in its Width and Height properties.

Dim r As Range
Set r = ActiveSheet.Range("A4:H12")

Debug.Print r.Width
Debug.Print r.Height

Powershell Get-ChildItem most recent file in directory

You could try to sort descending "sort LastWriteTime -Descending" and then "select -first 1." Not sure which one is faster

MySQL select all rows from last month until (now() - 1 month), for comparative purposes

maybe like this - all last month DATE(recDate) BETWEEN DATE_ADD(LAST_DAY(DATE_SUB(CURDATE(), INTERVAL 2 MONTH)), INTERVAL 1 DAY) AND LAST_DAY(DATE_SUB(CURDATE(), INTERVAL 1 MONTH) )

Twitter Bootstrap 3 Sticky Footer

in Haml & Sass words all that is necessary:

Haml for app/view/layouts/application.html.haml

%html
  %head
  %body
    Some  body stuff

    %footer
      footer content

Sass for app/assets/stylesheets/application.css.sass

$footer-height: 110px

html
  position: relative
  min-height: 100%

body
  margin-bottom: $footer-height

body > footer
  position: absolute
  bottom: 0
  width: 100%
  height: $footer-height

based on http://getbootstrap.com/examples/sticky-footer-navbar/

Select second last element with css

In CSS3 you have:

:nth-last-child(2)

See: https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-last-child

nth-last-child Browser Support:

  • Chrome 2
  • Firefox 3.5
  • Opera 9.5, 10
  • Safari 3.1, 4
  • Internet Explorer 9

In HTML5, can the <header> and <footer> tags appear outside of the <body> tag?

I agree with some of the others' answers. The <head> and <header> tags have two unique and very unrelated functions. The <header> tag, if I'm not mistaken, was introduced in HTML5 and was created for increased accessibility, namely for screen readers. It's generally used to indicate the heading of your document and, in order to work appropriately and effectively, should be placed inside the <body> tag. The <head> tag, since it's origin, is used for SEO in that it constructs all of the necessary meta data and such. A valid HTML structure for your page with both tags included would be like something like this:

<!DOCTYPE html/>
<html lang="es">
    <head>
        <!--crazy meta stuff here-->
    </head>
    <body>
        <header>
            <!--Optional nav tag-->
            <nav>
            </nav>
        </header>
        <!--Body content-->
    </body>
</html>

Adding Apostrophe in every field in particular column for excel

i use concantenate. works for me.

  1. fill j2-j14 with '(appostrophe)
  2. enter L2 with formula =concantenate(j2,k2)
  3. copy L2 to L3-L14

Difference between text and varchar (character varying)

UPDATING BENCHMARKS FOR 2016 (pg9.5+)

And using "pure SQL" benchmarks (without any external script)

  1. use any string_generator with UTF8

  2. main benchmarks:

    2.1. INSERT

    2.2. SELECT comparing and counting


CREATE FUNCTION string_generator(int DEFAULT 20,int DEFAULT 10) RETURNS text AS $f$
  SELECT array_to_string( array_agg(
    substring(md5(random()::text),1,$1)||chr( 9824 + (random()*10)::int )
  ), ' ' ) as s
  FROM generate_series(1, $2) i(x);
$f$ LANGUAGE SQL IMMUTABLE;

Prepare specific test (examples)

DROP TABLE IF EXISTS test;
-- CREATE TABLE test ( f varchar(500));
-- CREATE TABLE test ( f text); 
CREATE TABLE test ( f text  CHECK(char_length(f)<=500) );

Perform a basic test:

INSERT INTO test  
   SELECT string_generator(20+(random()*(i%11))::int)
   FROM generate_series(1, 99000) t(i);

And other tests,

CREATE INDEX q on test (f);

SELECT count(*) FROM (
  SELECT substring(f,1,1) || f FROM test WHERE f<'a0' ORDER BY 1 LIMIT 80000
) t;

... And use EXPLAIN ANALYZE.

UPDATED AGAIN 2018 (pg10)

little edit to add 2018's results and reinforce recommendations.


Results in 2016 and 2018

My results, after average, in many machines and many tests: all the same
(statistically less tham standard deviation).

Recommendation

  • Use text datatype,
    avoid old varchar(x) because sometimes it is not a standard, e.g. in CREATE FUNCTION clauses varchar(x)?varchar(y).

  • express limits (with same varchar performance!) by with CHECK clause in the CREATE TABLE
    e.g. CHECK(char_length(x)<=10).
    With a negligible loss of performance in INSERT/UPDATE you can also to control ranges and string structure
    e.g. CHECK(char_length(x)>5 AND char_length(x)<=20 AND x LIKE 'Hello%')

Installation of VB6 on Windows 7 / 8 / 10

I've installed and use VB6 for legacy projects many times on Windows 7.

What I have done and never came across any issues, is to install VB6, ignore the errors and then proceed to install the latest service pack, currently SP6.

Download here: http://www.microsoft.com/en-us/download/details.aspx?id=5721

Bonus: Also once you install it and realize that scrolling doesn't work, use the below: http://www.joebott.com/vb6scrollwheel.htm

How to load a jar file at runtime

I was asked to build a java system that will have the ability to load new code while running

You might want to base your system on OSGi (or at least take a lot at it), which was made for exactly this situation.

Messing with classloaders is really tricky business, mostly because of how class visibility works, and you do not want to run into hard-to-debug problems later on. For example, Class.forName(), which is widely used in many libraries does not work too well on a fragmented classloader space.

Android LinearLayout : Add border with shadow around a LinearLayout

Use this single line and hopefully you will achieve the best result;

use: android:elevation="3dp" Adjust the size as much as you need and this is the best and simplest way to achieve the shadow like buttons and other default android shadows. Let me know if it worked!

Space between Column's children in Flutter

You can use Padding widget in between those two widget or wrap those widgets with Padding widget.

Update

SizedBox widget can be use in between two widget to add space between two widget and it makes code more readable than padding widget.

Ex:

Column(
  children: <Widget>[
    Widget1(),
    SizedBox(height: 10),
    Widget2(),
  ],
),

How to delete Tkinter widgets from a window?

Today I learn some simple and good click event handling using tkinter gui library in python3, which I would like to share inside this thread.

from tkinter import *

cnt = 0


def MsgClick(event):
    children = root.winfo_children()
    for child in children:
        # print("type of widget is : " + str(type(child)))
        if str(type(child)) == "<class 'tkinter.Message'>":
            # print("Here Message widget will destroy")
            child.destroy()
            return

def MsgMotion(event):
  print("Mouse position: (%s %s)" % (event.x, event.y))
  return


def ButtonClick(event):
    global cnt, msg
    cnt += 1
    msg = Message(root, text="you just clicked the button..." + str(cnt) + "...time...")
    msg.config(bg='lightgreen', font=('times', 24, 'italic'))
    msg.bind("<Button-1>", MsgClick)
    msg.bind("<Motion>", MsgMotion)
    msg.pack()
    #print(type(msg)) tkinter.Message


def ButtonDoubleClick(event):
    import sys; sys.exit()


root = Tk()

root.title("My First GUI App in Python")
root.minsize(width=300, height=300)
root.maxsize(width=400, height=350)
button = Button(
    root, text="Click Me!", width=40, height=3
)
button.pack()
button.bind("<Button-1>", ButtonClick)
button.bind("<Double-1>", ButtonDoubleClick)

root.mainloop()

Hope it will help someone...

Xcode error: Code signing is required for product type 'Application' in SDK 'iOS 10.0'

If you need to disable the team for now, as you don't have a development account, just change the target at the top menu to iPhone instead of generic iOS device or real device.

Garbage collector in Android

It seems System.gc() do not work on Art Android 6.0.1 Nexus 5x, So I use Runtime.getRuntime().gc(); instead.

App installation failed due to application-identifier entitlement

I solved this without deleting the app

With the project open in xcode. Project -> Build Settings -> Code Signing -> Provisioning Profiles (drop down) It is probably set to automatic and is choosing the wrong profile. Open the drop down and choose the correct one, then re-run the app.

How can I remove an element from a list?

Just wanted to quickly add (because I didn't see it in any of the answers) that, for a named list, you can also do l["name"] <- NULL. For example:

l <- list(a = 1, b = 2, cc = 3)
l['b'] <- NULL

Duplicate line in Visual Studio Code

Update that may help Ubuntu users if they still want to use the ? and ? instead of another set of keys.

I just installed a fresh version of VSCode on Ubuntu 18.04 LTS and I had duplicate commands for Add Cursor Above and Add Cursor Below

Original Keybindings

I just removed the bindings that used Ctrl and added my own with the following

Copy Line Up

Ctrl + Shift + ?

Copy Line Down

Ctrl + Shift + ?

New Keybindings

How to set border on jPanel?

Swing has no idea what the preferred, minimum and maximum sizes of the GoBoard should be as you have no components inside of it for it to calculate based on, so it picks a (probably wrong) default. Since you are doing custom drawing here, you should implement these methods

Dimension getPreferredSize()
Dimension getMinumumSize()
Dimension getMaximumSize()

or conversely, call the setters for these methods.

Making an asynchronous task in Flask

You can also try using multiprocessing.Process with daemon=True; the process.start() method does not block and you can return a response/status immediately to the caller while your expensive function executes in the background.

I experienced similar problem while working with falcon framework and using daemon process helped.

You'd need to do the following:

from multiprocessing import Process

@app.route('/render/<id>', methods=['POST'])
def render_script(id=None):
    ...
    heavy_process = Process(  # Create a daemonic process with heavy "my_func"
        target=my_func,
        daemon=True
    )
    heavy_process.start()
    return Response(
        mimetype='application/json',
        status=200
    )

# Define some heavy function
def my_func():
    time.sleep(10)
    print("Process finished")

You should get a response immediately and, after 10s you should see a printed message in the console.

NOTE: Keep in mind that daemonic processes are not allowed to spawn any child processes.

html button to send email

You can use mailto, here is the HTML code:

<a href="mailto:EMAILADDRESS">

Replace EMAILADDRESS with your email.

How to add a new line of text to an existing file in Java?

Starting from Java 7:

Define a path and the String containing the line separator at the beginning:

Path p = Paths.get("C:\\Users\\first.last\\test.txt");
String s = System.lineSeparator() + "New Line!";

and then you can use one of the following approaches:

  1. Using Files.write (small files):

    try {
        Files.write(p, s.getBytes(), StandardOpenOption.APPEND);
    } catch (IOException e) {
        System.err.println(e);
    }
    
  2. Using Files.newBufferedWriter(text files):

    try (BufferedWriter writer = Files.newBufferedWriter(p, StandardOpenOption.APPEND)) {
        writer.write(s);
    } catch (IOException ioe) {
        System.err.format("IOException: %s%n", ioe);
    }
    
  3. Using Files.newOutputStream (interoperable with java.io APIs):

    try (OutputStream out = new BufferedOutputStream(Files.newOutputStream(p, StandardOpenOption.APPEND))) {
        out.write(s.getBytes());
    } catch (IOException e) {
        System.err.println(e);
    }
    
  4. Using Files.newByteChannel (random access files):

    try (SeekableByteChannel sbc = Files.newByteChannel(p, StandardOpenOption.APPEND)) {
        sbc.write(ByteBuffer.wrap(s.getBytes()));
    } catch (IOException e) {
        System.err.println(e);
    }
    
  5. Using FileChannel.open (random access files):

    try (FileChannel sbc = FileChannel.open(p, StandardOpenOption.APPEND)) {
        sbc.write(ByteBuffer.wrap(s.getBytes()));
    } catch (IOException e) {
        System.err.println(e);
    }
    

Details about these methods can be found in the Oracle's tutorial.

Is there an opposite of include? for Ruby Arrays?

if @players.exclude?(p.name)
    ...
end

ActiveSupport adds the exclude? method to Array, Hash, and String. This is not pure Ruby, but is used by a LOT of rubyists.

Source: Active Support Core Extensions (Rails Guides)

How to use JavaScript with Selenium WebDriver Java

JavaScript With Selenium WebDriver

Selenium is one of the most popular automated testing suites. Selenium is designed in a way to support and encourage automation testing of functional aspects of web based applications and a wide range of browsers and platforms.

    public static WebDriver driver;
    public static void main(String[] args) {
        driver = new FirefoxDriver(); // This opens a window    
        String url = "----";


        /*driver.findElement(By.id("username")).sendKeys("yashwanth.m");
        driver.findElement(By.name("j_password")).sendKeys("yashwanth@123");*/

        JavascriptExecutor jse = (JavascriptExecutor) driver;       
        if (jse instanceof WebDriver) {
            //Launching the browser application
            jse.executeScript("window.location = \'"+url+"\'");
jse.executeScript("document.getElementById('username').value = \"yash\";");
// Tag having name then
driver.findElement(By.xpath(".//input[@name='j_password']")).sendKeys("admin");


//Opend Site and click on some links. then you can apply go(-1)--> back  forword(-1)--> front.
//Refresheing the web-site. driver.navigate().refresh();            
jse.executeScript("window.history.go(0)");
            jse.executeScript("window.history.go(-2)");
            jse.executeScript("window.history.forward(-2)");

            String title = (String)jse.executeScript("return document.title");
            System.out.println(" Title Of site : "+title);

            String domain = (String)jse.executeScript("return document.domain");
            System.out.println("Web Site Domain-Name : "+domain);

            // To get all NodeList[1052] document.querySelectorAll('*');  or document.all
            jse.executeAsyncScript("document.getElementsByTagName('*')");

            String error=(String) jse.executeScript("return window.jsErrors");
            System.out.println("Windowerrors  :   "+error);



            System.out.println("To Find the input tag position from top"); 
            ArrayList<?> al =  (ArrayList<?>) jse.executeScript(
                    "var source = [];"+
                    "var inputs = document.getElementsByTagName('input');"+
                    "for(var i = 0; i < inputs.length; i++) { " +
                       "   source[i] = inputs[i].offsetParent.offsetTop" +      //"    inputs[i].type = 'radio';"
                    "}"+
                    "return source"                 
                    );//inputs[i].offsetParent.offsetTop     inputs[i].type

            System.out.println("next");
            System.out.println("array : "+al);

            // (CTRL + a) to access keyboard keys. org.openqa.selenium.Keys 
            Keys k = null;
            String selectAll = Keys.chord(Keys.CONTROL, "a");
            WebElement body = driver.findElement(By.tagName("body"));
            body.sendKeys(selectAll);

            // Search for text in Site. Gets all ViewSource content and checks their.
            if (driver.getPageSource().contains("login")) {
                System.out.println("Text present in Web Site");
            }

        Long clent_height = (Long) jse.executeScript("return document.body.clientHeight");
        System.out.println("Client Body Height : "+clent_height);

        // using selenium we con only execute script but not JS-functions.

    }
    driver.quit(); // to close browser
}

To Execute User-Functions, Writing JS in to a file and reading as String and executing it to easily use.

Scanner sc = new Scanner(new FileInputStream(new File("JsFile.txt")));
        String js_TxtFile = ""; 
            while (sc.hasNext()) {          
                String[] s = sc.next().split("\r\n");   
                for (int i = 0; i < s.length; i++) {
                    js_TxtFile += s[i];
                    js_TxtFile += " ";
                }           
            }
        String title =  (String) jse.executeScript(js_TxtFile);
        System.out.println("Title  : "+title);

document.title & document.getElementById() is a property/method available in Browsers.

JsFile.txt

var title = getTitle();
return title;

function getTitle() {
    return document.title;
}

Build query string for System.Net.HttpClient get

TL;DR: do not use accepted version as It's completely broken in relation to handling unicode characters, and never use internal API

I've actually found weird double encoding issue with the accepted solution:

So, If you're dealing with characters which need to be encoded, accepted solution leads to double encoding:

  • query parameters are auto encoded by using NameValueCollection indexer (and this uses UrlEncodeUnicode, not regular expected UrlEncode(!))
  • Then, when you call uriBuilder.Uri it creates new Uri using constructor which does encoding one more time (normal url encoding)
  • That cannot be avoided by doing uriBuilder.ToString() (even though this returns correct Uri which IMO is at least inconsistency, maybe a bug, but that's another question) and then using HttpClient method accepting string - client still creates Uri out of your passed string like this: new Uri(uri, UriKind.RelativeOrAbsolute)

Small, but full repro:

var builder = new UriBuilder
{
    Scheme = Uri.UriSchemeHttps,
    Port = -1,
    Host = "127.0.0.1",
    Path = "app"
};

NameValueCollection query = HttpUtility.ParseQueryString(builder.Query);

query["cyrillic"] = "????????";

builder.Query = query.ToString();
Console.WriteLine(builder.Query); //query with cyrillic stuff UrlEncodedUnicode, and that's not what you want

var uri = builder.Uri; // creates new Uri using constructor which does encode and messes cyrillic parameter even more
Console.WriteLine(uri);

// this is still wrong:
var stringUri = builder.ToString(); // returns more 'correct' (still `UrlEncodedUnicode`, but at least once, not twice)
new HttpClient().GetStringAsync(stringUri); // this creates Uri object out of 'stringUri' so we still end up sending double encoded cyrillic text to server. Ouch!

Output:

?cyrillic=%u043a%u0438%u0440%u0438%u043b%u0438%u0446%u044f

https://127.0.0.1/app?cyrillic=%25u043a%25u0438%25u0440%25u0438%25u043b%25u0438%25u0446%25u044f

As you may see, no matter if you do uribuilder.ToString() + httpClient.GetStringAsync(string) or uriBuilder.Uri + httpClient.GetStringAsync(Uri) you end up sending double encoded parameter

Fixed example could be:

var uri = new Uri(builder.ToString(), dontEscape: true);
new HttpClient().GetStringAsync(uri);

But this uses obsolete Uri constructor

P.S on my latest .NET on Windows Server, Uri constructor with bool doc comment says "obsolete, dontEscape is always false", but actually works as expected (skips escaping)

So It looks like another bug...

And even this is plain wrong - it send UrlEncodedUnicode to server, not just UrlEncoded what server expects

Update: one more thing is, NameValueCollection actually does UrlEncodeUnicode, which is not supposed to be used anymore and is incompatible with regular url.encode/decode (see NameValueCollection to URL Query?).

So the bottom line is: never use this hack with NameValueCollection query = HttpUtility.ParseQueryString(builder.Query); as it will mess your unicode query parameters. Just build query manually and assign it to UriBuilder.Query which will do necessary encoding and then get Uri using UriBuilder.Uri.

Prime example of hurting yourself by using code which is not supposed to be used like this

Passing variables, creating instances, self, The mechanics and usage of classes: need explanation

The whole point of a class is that you create an instance, and that instance encapsulates a set of data. So it's wrong to say that your variables are global within the scope of the class: say rather that an instance holds attributes, and that instance can refer to its own attributes in any of its code (via self.whatever). Similarly, any other code given an instance can use that instance to access the instance's attributes - ie instance.whatever.

How can I get the behavior of GNU's readlink -f on a Mac?

MacPorts and Homebrew provide a coreutils package containing greadlink (GNU readlink). Credit to Michael Kallweitt post in mackb.com.

brew install coreutils

greadlink -f file.txt

Set HTML element's style property in javascript

Don't set the style object itself, set the background color property of the style object that is a property of the element.

And yes, even though you said no, jquery and tablesorter with its zebra stripe plugin can do this all for you in 3 lines of code.

And just setting the class attribute would be better since then you have non-hard-coded control over the styling which is more organized

Which characters make a URL invalid?

In general URIs as defined by RFC 3986 (see Section 2: Characters) may contain any of the following 84 characters:

ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~:/?#[]@!$&'()*+,;=

Note that this list doesn't state where in the URI these characters may occur.

Any other character needs to be encoded with the percent-encoding (%hh). Each part of the URI has further restrictions about what characters need to be represented by an percent-encoded word.

Iterating through array - java

If you are using an array (and purely an array), the lookup of "contains" is O(N), because worst case, you must iterate the entire array. Now if the array is sorted you can use a binary search, which reduces the search time to log(N) with the overhead of the sort.

If this is something that is invoked repeatedly, place it in a function:

private boolean inArray(int[] array, int value)
{  
     for (int i = 0; i < array.length; i++)
     {
        if (array[i] == value) 
        {
            return true;
        }
     }
    return false;  
}  

How to join entries in a set into one string?

You have the join statement backwards try:

print ', '.join(set_3)

How do I make an attributed string using Swift?

Swift 5

    let attrStri = NSMutableAttributedString.init(string:"This is red")
    let nsRange = NSString(string: "This is red").range(of: "red", options: String.CompareOptions.caseInsensitive)
    attrStri.addAttributes([NSAttributedString.Key.foregroundColor : UIColor.red, NSAttributedString.Key.font: UIFont.init(name: "PTSans-Regular", size: 15.0) as Any], range: nsRange)
    self.label.attributedText = attrStri

enter image description here

@Cacheable key on multiple method arguments

Update: Current Spring cache implementation uses all method parameters as the cache key if not specified otherwise. If you want to use selected keys, refer to Arjan's answer which uses SpEL list {#isbn, #includeUsed} which is the simplest way to create unique keys.

From Spring Documentation

The default key generation strategy changed with the release of Spring 4.0. Earlier versions of Spring used a key generation strategy that, for multiple key parameters, only considered the hashCode() of parameters and not equals(); this could cause unexpected key collisions (see SPR-10237 for background). The new 'SimpleKeyGenerator' uses a compound key for such scenarios.

Before Spring 4.0

I suggest you to concat the values of the parameters in Spel expression with something like key="#checkWarehouse.toString() + #isbn.toString()"), I believe this should work as org.springframework.cache.interceptor.ExpressionEvaluator returns Object, which is later used as the key so you don't have to provide an int in your SPEL expression.

As for the hash code with a high collision probability - you can't use it as the key.

Someone in this thread has suggested to use T(java.util.Objects).hash(#p0,#p1, #p2) but it WILL NOT WORK and this approach is easy to break, for example I've used the data from SPR-9377 :

    System.out.println( Objects.hash("someisbn", new Integer(109), new Integer(434)));
    System.out.println( Objects.hash("someisbn", new Integer(110), new Integer(403)));

Both lines print -636517714 on my environment.

P.S. Actually in the reference documentation we have

@Cacheable(value="books", key="T(someType).hash(#isbn)") 
public Book findBook(ISBN isbn, boolean checkWarehouse, boolean includeUsed)

I think that this example is WRONG and misleading and should be removed from the documentation, as the keys should be unique.

P.P.S. also see https://jira.springsource.org/browse/SPR-9036 for some interesting ideas regarding the default key generation.

I'd like to add for the sake of correctness and as an entertaining mathematical/computer science fact that unlike built-in hash, using a secure cryptographic hash function like MD5 or SHA256, due to the properties of such function IS absolutely possible for this task, but to compute it every time may be too expensive, checkout for example Dan Boneh cryptography course to learn more.

Flask-SQLalchemy update a row's information

There is a method update on BaseQuery object in SQLAlchemy, which is returned by filter_by.

num_rows_updated = User.query.filter_by(username='admin').update(dict(email='[email protected]')))
db.session.commit()

The advantage of using update over changing the entity comes when there are many objects to be updated.

If you want to give add_user permission to all the admins,

rows_changed = User.query.filter_by(role='admin').update(dict(permission='add_user'))
db.session.commit()

Notice that filter_by takes keyword arguments (use only one =) as opposed to filter which takes an expression.

How can I make the browser wait to display the page until it's fully loaded?

Also make sure the server buffers the page and does not immediately (while building) stream it to the client browser.

Since you have not specified your technology stack:

  • PHP: look into ob_start
  • ASP.NET: make sure Response.BufferOutput = True (it is by default)

Python - 'ascii' codec can't decode byte

If you're using Python < 3, you'll need to tell the interpreter that your string literal is Unicode by prefixing it with a u:

Python 2.7.2 (default, Jan 14 2012, 23:14:09) 
[GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> "??".encode("utf8")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position 0: ordinal not in range(128)
>>> u"??".encode("utf8")
'\xe4\xbd\xa0\xe5\xa5\xbd'

Further reading: Unicode HOWTO.

Uses of content-disposition in an HTTP response header

For asp.net users, the .NET framework provides a class to create a content disposition header: System.Net.Mime.ContentDisposition

Basic usage:

var cd = new System.Net.Mime.ContentDisposition();
cd.FileName = "myFile.txt";
cd.ModificationDate = DateTime.UtcNow;
cd.Size = 100;
Response.AppendHeader("content-disposition", cd.ToString());

Python `if x is not None` or `if not x is None`?

I would prefer the more readable form x is not y than I would think how to eventually write the code handling precedence of the operators in order to produce much more readable code.

jQuery Popup Bubble/Tooltip

I'm trying to make a "bubble" that can popup when the onmouseover event is fired and will stay open as long as the mouse is over the item that threw the onmouseover event OR if the mouse is moved into the bubble. My bubble will need to have all manners of html and styling including hyperlinks, images, etc.

All those events fully managed by this plugin...

http://plugins.jquery.com/project/jqBubblePopup

How does numpy.histogram() work?

Another useful thing to do with numpy.histogram is to plot the output as the x and y coordinates on a linegraph. For example:

arr = np.random.randint(1, 51, 500)
y, x = np.histogram(arr, bins=np.arange(51))
fig, ax = plt.subplots()
ax.plot(x[:-1], y)
fig.show()

enter image description here

This can be a useful way to visualize histograms where you would like a higher level of granularity without bars everywhere. Very useful in image histograms for identifying extreme pixel values.

Angular 2 Unit Tests: Cannot find name 'describe'

Solution to this problem is connected with what @Pace has written in his answer. However, it doesn't explain everything so, if you don't mind, I'll write it by myself.

SOLUTION:

Adding this line:

///<reference path="./../../../typings/globals/jasmine/index.d.ts"/>

at the beginning of hero.spec.ts file fixes problem. Path leads to typings folder (where all typings are stored).

To install typings you need to create typings.json file in root of your project with following content:

{
  "globalDependencies": {
    "core-js": "registry:dt/core-js#0.0.0+20160602141332",
    "jasmine": "registry:dt/jasmine#2.2.0+20160621224255",
    "node": "registry:dt/node#6.0.0+20160807145350"
  }
}

And run typings install (where typings is NPM package).

How to close a Tkinter window by pressing a Button?

from tkinter import *

window = tk()
window.geometry("300x300")

def close_window (): 

    window.destroy()

button = Button ( text = "Good-bye", command = close_window)
button.pack()

window.mainloop()

How to get first and last day of week in Oracle?

SQL> var P_YEARWEEK varchar2(6)
SQL> exec :P_YEARWEEK := '201118'

PL/SQL procedure successfully completed.

SQL> with t as
  2  ( select substr(:P_YEARWEEK,1,4) year
  3         , substr(:P_YEARWEEK,5,2) week
  4      from dual
  5  )
  6  select year
  7       , week
  8       , trunc(to_date(year,'yyyy'),'yyyy')                              january_1
  9       , trunc(trunc(to_date(year,'yyyy'),'yyyy'),'iw')                  monday_week_1
 10       , trunc(trunc(to_date(year,'yyyy'),'yyyy'),'iw') + (week - 1) * 7 start_of_the_week
 11       , trunc(trunc(to_date(year,'yyyy'),'yyyy'),'iw') + week  * 7 - 1  end_of_the_week
 12    from t
 13  /

YEAR WE JANUARY_1           MONDAY_WEEK_1       START_OF_THE_WEEK   END_OF_THE_WEEK
---- -- ------------------- ------------------- ------------------- -------------------
2011 18 01-01-2011 00:00:00 27-12-2010 00:00:00 25-04-2011 00:00:00 01-05-2011 00:00:00

1 row selected.

Regards,
Rob.

Colouring plot by factor in R

data<-iris
plot(data$Sepal.Length, data$Sepal.Width, col=data$Species)
legend(7,4.3,unique(data$Species),col=1:length(data$Species),pch=1)

should do it for you. But I prefer ggplot2 and would suggest that for better graphics in R.

Concat a string to SELECT * MySql

If you want to concatenate the fields using / as a separator, you can use concat_ws:

select concat_ws('/', col1, col2, col3) from mytable

You cannot escape listing the columns in the query though. The *-syntax works only in "select * from". You can list the columns and construct the query dynamically though.

How to print bytes in hexadecimal using System.out.println?

byte test[] = new byte[3];
test[0] = 0x0A;
test[1] = 0xFF;
test[2] = 0x01;

for (byte theByte : test)
{
  System.out.println(Integer.toHexString(theByte));
}

NOTE: test[1] = 0xFF; this wont compile, you cant put 255 (FF) into a byte, java will want to use an int.

you might be able to do...

test[1] = (byte) 0xFF;

I'd test if I was near my IDE (if I was near my IDE I wouln't be on Stackoverflow)

PHP Include for HTML?

Try to get some debugging information, could be that the file path is wrong, for example.

Try these two things:- Add this line to the top of your sample page:

<?php error_reporting(E_ALL);?>

This will print all errors/warnings/notices in the page so if there is any problem you get a text message describing it instead of a blank page

Additionally you can change include() to require()

<?php require ('headings.php'); ?>
<?php require ('navbar.php'); ?>
<?php require ('image.php'); ?>

This will throw a FATAL error PHP is unable to load required pages, and should help you in getting better tracing what is going wrong..

You can post the error descriptions here, if you get any, and you are unable to figure out what it means..

Echo tab characters in bash script

From the bash man page:

Words of the form $'string' are treated specially. The word expands to string, with backslash-escaped characters replaced as specified by the ANSI C standard.

So you can do this:

echo $'hello\tworld'

How does one convert a grayscale image to RGB in OpenCV (Python)?

I am promoting my comment to an answer:

The easy way is:

You could draw in the original 'frame' itself instead of using gray image.

The hard way (method you were trying to implement):

backtorgb = cv2.cvtColor(gray,cv2.COLOR_GRAY2RGB) is the correct syntax.

PHP display image BLOB from MySQL

Since I have to store various types of content in my blob field/column, I am suppose to update my code like this:

echo "data: $mime" $result['$data']";

where: mime can be an image of any kind, text, word document, text document, PDF document, etc... content datatype is blob in database.

Producing a new line in XSLT

I've noticed from my experience that producing a new line INSIDE a <xsl:variable> clause doesn't work. I was trying to do something like:

<xsl:variable name="myVar">
  <xsl:choose>
    <xsl:when test="@myValue != ''">
      <xsl:text>My value: </xsl:text>
      <xsl:value-of select="@myValue" />
      <xsl:text></xsl:text> <!--NEW LINE-->
      <xsl:text>My other value: </xsl:text>
      <xsl:value-of select="@myOtherValue" />
    </xsl:when>
  </xsl:choose>
<xsl:variable>

<div>
  <xsl:value-of select="$myVar"/>
</div>

Anything I tried to put in that "new line" (the empty <xsl:text> node) just didn't work (including most of the simpler suggestions in this page), not to mention the fact that HTML just won't work there, so eventually I had to split it to 2 variables, call them outside the <xsl:variable> scope and put a simple <br/> between them, i.e:

<xsl:variable name="myVar1">
  <xsl:choose>
    <xsl:when test="@myValue != ''">
      <xsl:text>My value: </xsl:text>
      <xsl:value-of select="@myValue" />
    </xsl:when>
  </xsl:choose>
<xsl:variable>

<xsl:variable name="myVar2">
  <xsl:choose>
    <xsl:when test="@myValue != ''">
      <xsl:text>My other value: </xsl:text>
      <xsl:value-of select="@myOtherValue" />
    </xsl:when>
  </xsl:choose>
<xsl:variable>

<div>
  <xsl:value-of select="$myVar1"/>
  <br/>
  <xsl:value-of select="$myVar2"/>
</div>

Yeah, I know, it's not the most sophisticated solution but it works, just sharing my frustration experience with XSLs ;)

How to call a web service from jQuery

In Java, this return value fails with jQuery Ajax GET:

return Response.status(200).entity(pojoObj).build();

But this works:

ResponseBuilder rb = Response.status(200).entity(pojoObj);
return rb.header("Access-Control-Allow-Origin", "*").build();

----

Full class:

@Path("/password")
public class PasswordStorage {
    @GET
    @Produces({ MediaType.APPLICATION_JSON })
    public Response getRole() {
        Contact pojoObj= new Contact();
        pojoObj.setRole("manager");

        ResponseBuilder rb = Response.status(200).entity(pojoObj);
        return rb.header("Access-Control-Allow-Origin", "*").build();

        //Fails jQuery: return Response.status(200).entity(pojoObj).build();
    }
}

.autocomplete is not a function Error

Loading jQuery library before Angularjs library helped me.

_x000D_
_x000D_
<head>_x000D_
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>_x000D_
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>_x000D_
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>_x000D_
</head>
_x000D_
_x000D_
_x000D_

svn list of files that are modified in local copy

I'm not familiar with tortoise, but with subversion to linux i would type

svn status

Some googling tells me that tortoise also supports commandline commandos, try svn status in the folder that contains the svn repository.

Clone only one branch

--single-branch” switch is your answer, but it only works if you have git version 1.8.X onwards, first check

#git --version 

If you already have git version 1.8.X installed then simply use "-b branch and --single branch" to clone a single branch

#git clone -b branch --single-branch git://github/repository.git

By default in Ubuntu 12.04/12.10/13.10 and Debian 7 the default git installation is for version 1.7.x only, where --single-branch is an unknown switch. In that case you need to install newer git first from a non-default ppa as below.

sudo add-apt-repository ppa:pdoes/ppa
sudo apt-get update
sudo apt-get install git
git --version

Once 1.8.X is installed now simply do:

git clone -b branch --single-branch git://github/repository.git

Git will now only download a single branch from the server.

With CSS, use "..." for overflowed block of multi-lines

The link below provides a pure HTML / CSS solution to this problem.

Browser support - as stated in the article:

So far we have tested on Safari 5.0, IE 9 (must be in standards mode), Opera 12 and Firefox 15.

Older browsers will still work quite well, as the meat of the layout is in normal positioning, margin and padding properties. if your platform is older (e.g. Firefox 3.6, IE 8), you can use the method but redo the gradient as a standalone PNG image or DirectX filter.

http://www.mobify.com/dev/multiline-ellipsis-in-pure-css

the css:

p { margin: 0; padding: 0; font-family: sans-serif;}

.ellipsis {
    overflow: hidden;
    height: 200px;
    line-height: 25px;
    margin: 20px;
    border: 5px solid #AAA; }

.ellipsis:before {
    content:"";
    float: left;
    width: 5px; height: 200px; }

.ellipsis > *:first-child {
    float: right;
    width: 100%;
    margin-left: -5px; }        

.ellipsis:after {
    content: "\02026";  

    box-sizing: content-box;
    -webkit-box-sizing: content-box;
    -moz-box-sizing: content-box;

    float: right; position: relative;
    top: -25px; left: 100%; 
    width: 3em; margin-left: -3em;
    padding-right: 5px;

    text-align: right;

    background: -webkit-gradient(linear, left top, right top,
        from(rgba(255, 255, 255, 0)), to(white), color-stop(50%, white));
    background: -moz-linear-gradient(to right, rgba(255, 255, 255, 0), white 50%, white);           
    background: -o-linear-gradient(to right, rgba(255, 255, 255, 0), white 50%, white);
    background: -ms-linear-gradient(to right, rgba(255, 255, 255, 0), white 50%, white);
    background: linear-gradient(to right, rgba(255, 255, 255, 0), white 50%, white); }

the html:

<div class="ellipsis">
    <div>
        <p>Call me Ishmael.  Some years ago &ndash; never mind how long precisely &ndash; having little or no money in my purse, and nothing particular to interest me on shore, I thought I would sail about a little and see the watery part of the world.  It is a way I have of driving off the spleen, and regulating the circulation.  Whenever I find myself growing grim about the mouth; whenever it is a damp, drizzly November in my soul; whenever I find myself involuntarily pausing before coffin warehouses, and bringing up the rear of every funeral I meet; and especially whenever my hypos get such an upper hand of me, that it requires a strong moral principle to prevent me from deliberately stepping into the street, and methodically knocking people's hats off &ndash; then, I account it high time to get to sea as soon as I can.</p>  
    </div>
</div>

the fiddle

(resize browser's window for testing)

Open an html page in default browser with VBA?

You can use the Windows API function ShellExecute to do so:

Option Explicit

Private Declare Function ShellExecute _
  Lib "shell32.dll" Alias "ShellExecuteA" ( _
  ByVal hWnd As Long, _
  ByVal Operation As String, _
  ByVal Filename As String, _
  Optional ByVal Parameters As String, _
  Optional ByVal Directory As String, _
  Optional ByVal WindowStyle As Long = vbMinimizedFocus _
  ) As Long

Public Sub OpenUrl()

    Dim lSuccess As Long
    lSuccess = ShellExecute(0, "Open", "www.google.com")

End Sub

Just a short remark concerning security: If the URL comes from user input make sure to strictly validate that input as ShellExecute would execute any command with the user's permissions, also a format c: would be executed if the user is an administrator.

Git: Remove committed file after push

update: added safer method

preferred method:

  1. check out the previous (unchanged) state of your file; notice the double dash

    git checkout HEAD^ -- /path/to/file
    
  2. commit it:

    git commit -am "revert changes on this file, not finished with it yet"
    
  3. push it, no force needed:

    git push
    
  4. get back to your unfinished work, again do (3 times arrow up):

    git checkout HEAD^ -- /path/to/file
    

effectively 'uncommitting':

To modify the last commit of the repository HEAD, obfuscating your accidentally pushed work, while potentially running into a conflict with your colleague who may have pulled it already, and who will grow grey hair and lose lots of time trying to reconcile his local branch head with the central one:

To remove file change from last commit:

  1. to revert the file to the state before the last commit, do:

    git checkout HEAD^ /path/to/file
    
  2. to update the last commit with the reverted file, do:

    git commit --amend
    
  3. to push the updated commit to the repo, do:

    git push -f
    

Really, consider using the preferred method mentioned before.

Dynamically add child components in React

Firstly a warning: you should never tinker with DOM that is managed by React, which you are doing by calling ReactDOM.render(<SampleComponent ... />);

With React, you should use SampleComponent directly in the main App.

var App = require('./App.js');
var SampleComponent = require('./SampleComponent.js');
ReactDOM.render(<App/>, document.body);

The content of your Component is irrelevant, but it should be used like this:

var App = React.createClass({
    render: function() {
        return (
            <div>
                <h1>App main component! </h1>
                <SampleComponent name="SomeName"/>
            </div>
        );
    }
});

You can then extend your app component to use a list.

var App = React.createClass({
    render: function() {
        var componentList = [
            <SampleComponent name="SomeName1"/>,
            <SampleComponent name="SomeName2"/>
        ]; // Change this to get the list from props or state
        return (
            <div>
                <h1>App main component! </h1>
                {componentList}
            </div>
        );
    }
});

I would really recommend that you look at the React documentation then follow the "Get Started" instructions. The time you spend on that will pay off later.

https://facebook.github.io/react/index.html

Max parallel http connections in a browser?

Note that increasing a browser's max connections per server to an excessive number (as some sites suggest) can and does lock other users out of small sites with hosting plans that limit the total simultaneous connections on the server.

Getting unique items from a list

You can use Distinct extension method from LINQ

How to change the data type of a column without dropping the column with query?

ALTER tablename MODIFY columnName newColumnType

I'm not sure how it will handle the change from datetime to varchar though, so you may need to rename the column, add a new one with the old name and the correct data type (varchar) and then write an update query to populate the new column from the old.

http://www.1keydata.com/sql/sql-alter-table.html

argparse module How to add option without any argument?

As @Felix Kling suggested use action='store_true':

>>> from argparse import ArgumentParser
>>> p = ArgumentParser()
>>> _ = p.add_argument('-f', '--foo', action='store_true')
>>> args = p.parse_args()
>>> args.foo
False
>>> args = p.parse_args(['-f'])
>>> args.foo
True

Best way to compare dates in Android

convert the date to Calendar and make your calculations there. :)

Calendar cal = Calendar.getInstance();
cal.setTime(date);

int year = cal.get(Calendar.YEAR);
int month = cal.geT(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH); //same as cal.get(Calendar.DATE)

Or:

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date strDate = sdf.parse(valid_until);

if (strDate.after(new Date()) {
    catalog_outdated = 1;
}

How do I specify row heights in CSS Grid layout?

One of the Related posts gave me the (simple) answer.

Apparently the auto value on the grid-template-rows property does exactly what I was looking for.

.grid {
    display:grid;
    grid-template-columns: 1fr 1.5fr 1fr;
    grid-template-rows: auto auto 1fr 1fr 1fr auto auto;
    grid-gap:10px;
    height: calc(100vh - 10px);
}

What does "int 0x80" mean in assembly code?

int is nothing but an interruption i.e the processor will put its current execution to hold.

0x80 is nothing but a system call or the kernel call. i.e the system function will be executed.

To be specific 0x80 represents rt_sigtimedwait/init_module/restart_sys it varies from architecture to architecture.

For more details refer https://chromium.googlesource.com/chromiumos/docs/+/master/constants/syscalls.md

Using Bootstrap Tooltip with AngularJS

Only read this if you are assigning tooltips dynamically

i.e. <div tooltip={{ obj.somePropertyThatMayChange }} ...></div>

I had an issue with dynamic tooltips that were not always updating with the view. For example, I was doing something like this:

This didn't work consistently

<div ng-repeat="person in people">
    <span data-toggle="tooltip" data-placement="top" title="{{ person.tooltip }}">
      {{ person.name }}
    </span> 
</div> 

And activating it as so:

$timeout(function() {
  $(document).tooltip({ selector: '[data-toggle="tooltip"]'});
}, 1500)

However, as my people array would change my tooltips wouldn't always update. I tried every fix in this thread and others with no luck. The glitch seemed to only be happening around 5% of the time, and was nearly impossible to repeat.

Unfortunately, these tooltips are mission critical for my project, and showing an incorrect tooltip could be very bad.

What seemed to be the issue

Bootstrap was copying the value of the title property to a new attribute, data-original-title and removing the title property (sometimes) when I would activate the toooltips. However, when my title={{ person.tooltip }} would change the new value would not always be updated into the property data-original-title. I tried deactivating the tooltips and reactivating them, destroying them, binding to this property directly... everything. However each of these either didn't work or created new issues; such as the title and data-original-title attributes both being removed and un-bound from my object.

What did work

Perhaps the most ugly code I've ever pushed, but it solved this small but substantial problem for me. I run this code each time the tooltip is update with new data:

$timeout(function() {
    $('[data-toggle="tooltip"]').each(function(index) {
      // sometimes the title is blank for no apparent reason. don't override in these cases.
      if ($(this).attr("title").length > 0) {
        $( this ).attr("data-original-title", $(this).attr("title"));
      }
    });
    $timeout(function() {
      // finally, activate the tooltips
      $(document).tooltip({ selector: '[data-toggle="tooltip"]'});
    }, 500);
}, 1500);

What's happening here in essence is:

  • Wait some time (1500 ms) for the digest cycle to complete, and the titles to be updated.
  • If there's a title property that is not empty (i.e. it has changed), copy it to the data-original-title property so it will be picked up by Bootstrap's toolips.
  • Reactivate the tooltips

Hope this long answer helps someone who may have been struggling as I was.

TextView - setting the text size programmatically doesn't seem to work

Please see this link for more information on setting the text size in code. Basically it says:

public void setTextSize (int unit, float size)

Since: API Level 1 Set the default text size to a given unit and value. See TypedValue for the possible dimension units. Related XML Attributes

android:textSize Parameters

unit The desired dimension unit.
size The desired size in the given units.

Changing button color programmatically

Here is an example using HTML:

<input type="button" value="click me" onclick="this.style.color='#000000';
this.style.backgroundColor = '#ffffff'" />

And here is an example using JavaScript:

document.getElementById("button").bgcolor="#Insert Color Here";

Incorrect integer value: '' for column 'id' at row 1

That probably means that your id is an AUTO_INCREMENT integer and you're trying to send a string. You should specify a column list and omit it from your INSERT.

INSERT INTO workorders (column1, column2) VALUES ($column1, $column2)

Unable to load Private Key. (PEM routines:PEM_read_bio:no start line:pem_lib.c:648:Expecting: ANY PRIVATE KEY)

> I have a .key file which is PEM formatted private key file.
> ...
> Here's some asn1parse of the .key file...

That it appears OK with asn1parse leads me to believe its not PEM encoded.


Is there anything more I can try?

Because it appears to be ASN.1, try:

$ openssl rsa -in server.key -inform DER -modulus -noout

Notice the -inform DER to switch between encodings.

How to insert default values in SQL table?

Just don't include the columns that you want to use the default value for in your insert statement. For instance:

INSERT INTO table1 (field1, field3) VALUES (5, 10);

...will take the default values for field2 and field4, and assign 5 to field1 and 10 to field3.

Passing multiple parameters to pool.map() function in Python

You could use a map function that allows multiple arguments, as does the fork of multiprocessing found in pathos.

>>> from pathos.multiprocessing import ProcessingPool as Pool
>>> 
>>> def add_and_subtract(x,y):
...   return x+y, x-y
... 
>>> res = Pool().map(add_and_subtract, range(0,20,2), range(-5,5,1))
>>> res
[(-5, 5), (-2, 6), (1, 7), (4, 8), (7, 9), (10, 10), (13, 11), (16, 12), (19, 13), (22, 14)]
>>> Pool().map(add_and_subtract, *zip(*res))
[(0, -10), (4, -8), (8, -6), (12, -4), (16, -2), (20, 0), (24, 2), (28, 4), (32, 6), (36, 8)]

pathos enables you to easily nest hierarchical parallel maps with multiple inputs, so we can extend our example to demonstrate that.

>>> from pathos.multiprocessing import ThreadingPool as TPool
>>> 
>>> res = TPool().amap(add_and_subtract, *zip(*Pool().map(add_and_subtract, range(0,20,2), range(-5,5,1))))
>>> res.get()
[(0, -10), (4, -8), (8, -6), (12, -4), (16, -2), (20, 0), (24, 2), (28, 4), (32, 6), (36, 8)]

Even more fun, is to build a nested function that we can pass into the Pool. This is possible because pathos uses dill, which can serialize almost anything in python.

>>> def build_fun_things(f, g):
...   def do_fun_things(x, y):
...     return f(x,y), g(x,y)
...   return do_fun_things
... 
>>> def add(x,y):
...   return x+y
... 
>>> def sub(x,y):
...   return x-y
... 
>>> neato = build_fun_things(add, sub)
>>> 
>>> res = TPool().imap(neato, *zip(*Pool().map(neato, range(0,20,2), range(-5,5,1))))
>>> list(res)
[(0, -10), (4, -8), (8, -6), (12, -4), (16, -2), (20, 0), (24, 2), (28, 4), (32, 6), (36, 8)]

If you are not able to go outside of the standard library, however, you will have to do this another way. Your best bet in that case is to use multiprocessing.starmap as seen here: Python multiprocessing pool.map for multiple arguments (noted by @Roberto in the comments on the OP's post)

Get pathos here: https://github.com/uqfoundation

How to detect Esc Key Press in React and how to handle it

Another way to accomplish this in a functional component, is to use useEffect and useFunction, like this:

import React, { useEffect } from 'react';

const App = () => {


  useEffect(() => {
    const handleEsc = (event) => {
       if (event.keyCode === 27) {
        console.log('Close')
      }
    };
    window.addEventListener('keydown', handleEsc);

    return () => {
      window.removeEventListener('keydown', handleEsc);
    };
  }, []);

  return(<p>Press ESC to console log "Close"</p>);
}

Instead of console.log, you can use useState to trigger something.

Best practices with STDIN in Ruby?

I do something like this :

all_lines = ""
ARGV.each do |line|
  all_lines << line + "\n"
end
puts all_lines

Which SchemaType in Mongoose is Best for Timestamp?

First : npm install mongoose-timestamp

Next: let Timestamps = require('mongoose-timestamp')

Next: let MySchema = new Schema

Next: MySchema.plugin(Timestamps)

Next : const Collection = mongoose.model('Collection',MySchema)

Then you can use the Collection.createdAt or Collection.updatedAt anywhere your want.

Created on: Date Of The Week Month Date Year 00:00:00 GMT

Time is in this format.

ruby 1.9: invalid byte sequence in UTF-8

attachment = file.read

begin
   # Try it as UTF-8 directly
   cleaned = attachment.dup.force_encoding('UTF-8')
   unless cleaned.valid_encoding?
     # Some of it might be old Windows code page
     cleaned = attachment.encode( 'UTF-8', 'Windows-1252' )
   end
   attachment = cleaned
 rescue EncodingError
   # Force it to UTF-8, throwing out invalid bits
   attachment = attachment.force_encoding("ISO-8859-1").encode("utf-8", replace: nil)
 end

Does List<T> guarantee insertion order?

If you will change the order of operations, you will avoid the strange behavior: First insert the value to the right place in the list, and then delete it from his first position. Make sure you delete it by his index, because if you will delete it by reference, you might delete them both...

Algorithm to calculate the number of divisors of a given number

You might try this one. It's a bit hackish, but it's reasonably fast.

def factors(n):
    for x in xrange(2,n):
        if n%x == 0:
            return (x,) + factors(n/x)
    return (n,1)

how to make UITextView height dynamic according to text length?

Swift 4+

This is extremely easy with autolayout! I'll explain the most simple use case. Let's say there is only a UITextView in your UITableViewCell.

  • Fit the textView to the contentView with constraints.
  • Disable scrolling for the textView.
  • Update the tableView on textViewDidChange.

That's all!

protocol TextViewUpdateProtocol {
    func textViewChanged()
}

class TextViewCell: UITableViewCell {
    
    //MARK: Reuse ID
    static let identifier = debugDescription()
    
    //MARK: UI Element(s)
    /// Reference of the parent table view so that it can be updated
    var textViewUpdateDelegate: TextViewUpdateProtocol!
    
    lazy var textView: UITextView = {
        let textView = UITextView()
        textView.isScrollEnabled = false
        textView.delegate = self
        textView.layer.borderColor = UIColor.lightGray.cgColor
        textView.layer.borderWidth = 1
        textView.translatesAutoresizingMaskIntoConstraints = false
        return textView
    }()
    
    //MARK: Padding Variable(s)
    let padding: CGFloat = 50
    
    //MARK: Initializer(s)
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        addSubviews()
        addConstraints()
        
        textView.becomeFirstResponder()
    }
    
    //MARK: Helper Method(s)
    func addSubviews() {
        contentView.addSubview(textView)
    }
    
    func addConstraints() {
        textView.leadingAnchor  .constraint(equalTo: contentView.leadingAnchor, constant: padding).isActive = true
        textView.trailingAnchor .constraint(equalTo: contentView.trailingAnchor, constant: -padding).isActive = true
        textView.topAnchor      .constraint(equalTo: contentView.topAnchor, constant: padding).isActive = true
        textView.bottomAnchor   .constraint(equalTo: contentView.bottomAnchor, constant: -padding).isActive = true
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

extension TextViewCell: UITextViewDelegate {
    
    func textViewDidChange(_ textView: UITextView) {
        textViewUpdateDelegate.textViewChanged()
    }
    
}

Now you have to inherit implement the protocol in your ViewController.

extension ViewController: TextViewUpdateProtocol {
    
    func textViewChanged() {
        tableView.beginUpdates()
        tableView.endUpdates()
    }
    
}

Check out my repo for the full implementation.

Ubuntu: Using curl to download an image

If you want to keep the original name — use uppercase -O

curl -O https://www.python.org/static/apple-touch-icon-144x144-precomposed.png

If you want to save remote file with a different name — use lowercase -o

curl -o myPic.png https://www.python.org/static/apple-touch-icon-144x144-precomposed.png

Importing larger sql files into MySQL

3 things you have to do, if you are doing it locally:

in php.ini or php.cfg of your php installation

post_max_size=500M

upload_max_filesize=500M

memory_limit=900M

or set other values. Restart Apache.

OR

Use php big dump tool its best ever i have seen. its free and opensource

http://www.ozerov.de/bigdump/

Sleep Command in T-SQL?

Look at the WAITFOR command.

E.g.

-- wait for 1 minute
WAITFOR DELAY '00:01'

-- wait for 1 second
WAITFOR DELAY '00:00:01'

This command allows you a high degree of precision but is only accurate within 10ms - 16ms on a typical machine as it relies on GetTickCount. So, for example, the call WAITFOR DELAY '00:00:00:001' is likely to result in no wait at all.

Using android.support.v7.widget.CardView in my project (Eclipse)

You need to add this in your build.gradle:

dependencies {
    ...
    compile 'com.android.support:cardview-v7:+'
}

And then Sync Project with Gradle Files. Finally, you can use CardView as it's described here.

Using If else in SQL Select statement

The query will be like follows

SELECT (CASE WHEN tuLieuSo is null or tuLieuSo=''
            THEN 'Chua có dia' 
            ELSE 'Có dia' End) AS tuLieuSo,moTa
FROM [gPlan_datav3_SQHKTHN].[dbo].[gPlan_HoSo]

window.location (JS) vs header() (PHP) for redirection

The first case will fail when JS is off. It's also a little bit slower since JS must be parsed first (DOM must be loaded). However JS is safer since the destination doesn't know the referer and your redirect might be tracked (referers aren't reliable in general yet this is something).

You can also use meta refresh tag. It also requires DOM to be loaded.

Read a file line by line assigning the value to a variable

#! /bin/bash
cat filename | while read LINE; do
    echo $LINE
done

What is PHPSESSID?

PHPSESSID reveals you are using PHP. If you don't want this you can easily change the name using the session.name in your php.ini file or using the session_name() function.

How to split a string content into an array of strings in PowerShell?

Remove the spaces from the original string and split on semicolon

$address = "[email protected]; [email protected]; [email protected]"
$addresses = $address.replace(' ','').split(';')

Or all in one line:

$addresses = "[email protected]; [email protected]; [email protected]".replace(' ','').split(';')

$addresses becomes:

@('[email protected]','[email protected]','[email protected]')

Converting Integer to String with comma for thousands

Integers:

int value = 100000; 
String.format("%,d", value); // outputs 100,000

Doubles:

double value = 21403.3144d;
String.format("%,.2f", value); // outputs 21,403.31

String.format is pretty powerful.

- Edited per psuzzi feedback.

What is the difference between task and thread?

I usually use Task to interact with Winforms and simple background worker to make it not freezing the UI. here an example when I prefer using Task

private async void buttonDownload_Click(object sender, EventArgs e)
{
    buttonDownload.Enabled = false;
    await Task.Run(() => {
        using (var client = new WebClient())
        {
            client.DownloadFile("http://example.com/file.mpeg", "file.mpeg");
        }
    })
    buttonDownload.Enabled = true;
}

VS

private void buttonDownload_Click(object sender, EventArgs e)
{
    buttonDownload.Enabled = false;
    Thread t = new Thread(() =>
    {
        using (var client = new WebClient())
        {
            client.DownloadFile("http://example.com/file.mpeg", "file.mpeg");
        }
        this.Invoke((MethodInvoker)delegate()
        {
            buttonDownload.Enabled = true;
        });
    });
    t.IsBackground = true;
    t.Start();
}

the difference is you don't need to use MethodInvoker and shorter code.

How to send push notification to web browser?

this is simple way to do push notification for all browser https://pushjs.org

Push.create("Hello world!", {
body: "How's it hangin'?",
icon: '/icon.png',
timeout: 4000,
onClick: function () {
    window.focus();
    this.close();
 }
});

How to pass parameters to ThreadStart method in Thread?

The simplest is just

string filename = ...
Thread thread = new Thread(() => download(filename));
thread.Start();

The advantage(s) of this (over ParameterizedThreadStart) is that you can pass multiple parameters, and you get compile-time checking without needing to cast from object all the time.

Don't reload application when orientation changes

Just add this to your AndroidManifest.xml

<activity android:screenOrientation="landscape">

I mean, there is an activity tag, add this as another parameter. In case if you need portrait orientation, change landscape to portrait. Hope this helps.

Check for internet connection with Swift

Although it does not directly answers your question, I would like to mention Apple recentely had this talk:

https://developer.apple.com/videos/play/wwdc2018/714/

At around 09:55 he talks about doing this stuff you are asking about:

  1. Check connection
  2. If connection -> Do something
  3. If no connection -> Do something else (wait? retry?)

However, this has a few pitfalls:

  • What if in step 2 it says it has a connection, but 0.5 seconds later he hasn't?
  • What if the user is behind a proxy
  • Last but not least, what if some answers here can not determine the connectivity right? (I am sure that if you rapidly switch your connection, go to wi-fi and turn it off (just make it complicated), it almost never can correctly determine whetever I got a connection or not).
  • Quote from the video: "There is no way to guarentee whether a future operation will succeed or not"

The following points are some best practices according to Apple:

According to the talk, there shouldn't be any reason to pre-check whetever you got internet connection or not, since it may not be accurate at the time you send your request to the server.

Character Limit on Instagram Usernames

Limit - 30 symbols. Username must contains only letters, numbers, periods and underscores.

add maven repository to build.gradle

You will need to define the repository outside of buildscript. The buildscript configuration block only sets up the repositories and dependencies for the classpath of your build script but not your application.

What's the difference between OpenID and OAuth?

At finally OAuth gives you back the access token to access the resource from resource server, OpenID gives you back meta data details about resources in JWT / encrypted token

New warnings in iOS 9: "all bitcode will be dropped"

After Xcode 7, the bitcode option will be enabled by default. If your library was compiled without bitcode, but the bitcode option is enabled in your project settings, you can:

  1. Update your library with bit code,
  2. Say NO to Enable Bitcode in your target Build Settings

Enter image description here

And the Library Build Settings to remove the warnings.

For more information, go to documentation of bitcode in developer library.

And WWDC 2015 Session 102: "Platforms State of the Union"

Enter image description here

remove / reset inherited css from an element

you may use this below option.

<style>
  div:not(.no_common_style){
      background-color:red;
  }
</style>

now , if their any place where you do not want to apply default style you can use 'no_common_style' class as class. ex:

<div class="no_common_style">
  It will not display in red
</div>

CSS Classes & SubClasses

Just need to add a space:

.area2 .item
{
    ...
}

Getting a list of associative array keys

You can use: Object.keys(obj)

Example:

_x000D_
_x000D_
var dictionary = {
  "cats": [1, 2, 37, 38, 40, 32, 33, 35, 39, 36],
  "dogs": [4, 5, 6, 3, 2]
};

// Get the keys
var keys = Object.keys(dictionary);

console.log(keys);
_x000D_
_x000D_
_x000D_

See reference below for browser support. It is supported in Firefox 4.20, Chrome 5, and Internet Explorer 9. Object.keys() contains a code snippet that you can add if Object.keys() is not supported in your browser.

MySQL pivot table query with dynamic columns

I have a slightly different way of doing this than the accepted answer. This way you can avoid using GROUP_CONCAT which has a limit of 1024 characters and will not work if you have a lot of fields.

SET @sql = '';
SELECT
    @sql := CONCAT(@sql,if(@sql='','',', '),temp.output)
FROM
(
    SELECT
      DISTINCT
        CONCAT(
         'MAX(IF(pa.fieldname = ''',
          fieldname,
          ''', pa.fieldvalue, NULL)) AS ',
          fieldname
        ) as output
    FROM
        product_additional
) as temp;

SET @sql = CONCAT('SELECT p.id
                    , p.name
                    , p.description, ', @sql, ' 
                   FROM product p
                   LEFT JOIN product_additional AS pa 
                    ON p.id = pa.id
                   GROUP BY p.id');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

live output from subprocess command

Executive Summary (or "tl;dr" version): it's easy when there's at most one subprocess.PIPE, otherwise it's hard.

It may be time to explain a bit about how subprocess.Popen does its thing.

(Caveat: this is for Python 2.x, although 3.x is similar; and I'm quite fuzzy on the Windows variant. I understand the POSIX stuff much better.)

The Popen function needs to deal with zero-to-three I/O streams, somewhat simultaneously. These are denoted stdin, stdout, and stderr as usual.

You can provide:

  • None, indicating that you don't want to redirect the stream. It will inherit these as usual instead. Note that on POSIX systems, at least, this does not mean it will use Python's sys.stdout, just Python's actual stdout; see demo at end.
  • An int value. This is a "raw" file descriptor (in POSIX at least). (Side note: PIPE and STDOUT are actually ints internally, but are "impossible" descriptors, -1 and -2.)
  • A stream—really, any object with a fileno method. Popen will find the descriptor for that stream, using stream.fileno(), and then proceed as for an int value.
  • subprocess.PIPE, indicating that Python should create a pipe.
  • subprocess.STDOUT (for stderr only): tell Python to use the same descriptor as for stdout. This only makes sense if you provided a (non-None) value for stdout, and even then, it is only needed if you set stdout=subprocess.PIPE. (Otherwise you can just provide the same argument you provided for stdout, e.g., Popen(..., stdout=stream, stderr=stream).)

The easiest cases (no pipes)

If you redirect nothing (leave all three as the default None value or supply explicit None), Pipe has it quite easy. It just needs to spin off the subprocess and let it run. Or, if you redirect to a non-PIPE—an int or a stream's fileno()—it's still easy, as the OS does all the work. Python just needs to spin off the subprocess, connecting its stdin, stdout, and/or stderr to the provided file descriptors.

The still-easy case: one pipe

If you redirect only one stream, Pipe still has things pretty easy. Let's pick one stream at a time and watch.

Suppose you want to supply some stdin, but let stdout and stderr go un-redirected, or go to a file descriptor. As the parent process, your Python program simply needs to use write() to send data down the pipe. You can do this yourself, e.g.:

proc = subprocess.Popen(cmd, stdin=subprocess.PIPE)
proc.stdin.write('here, have some data\n') # etc

or you can pass the stdin data to proc.communicate(), which then does the stdin.write shown above. There is no output coming back so communicate() has only one other real job: it also closes the pipe for you. (If you don't call proc.communicate() you must call proc.stdin.close() to close the pipe, so that the subprocess knows there is no more data coming through.)

Suppose you want to capture stdout but leave stdin and stderr alone. Again, it's easy: just call proc.stdout.read() (or equivalent) until there is no more output. Since proc.stdout() is a normal Python I/O stream you can use all the normal constructs on it, like:

for line in proc.stdout:

or, again, you can use proc.communicate(), which simply does the read() for you.

If you want to capture only stderr, it works the same as with stdout.

There's one more trick before things get hard. Suppose you want to capture stdout, and also capture stderr but on the same pipe as stdout:

proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

In this case, subprocess "cheats"! Well, it has to do this, so it's not really cheating: it starts the subprocess with both its stdout and its stderr directed into the (single) pipe-descriptor that feeds back to its parent (Python) process. On the parent side, there's again only a single pipe-descriptor for reading the output. All the "stderr" output shows up in proc.stdout, and if you call proc.communicate(), the stderr result (second value in the tuple) will be None, not a string.

The hard cases: two or more pipes

The problems all come about when you want to use at least two pipes. In fact, the subprocess code itself has this bit:

def communicate(self, input=None):
    ...
    # Optimization: If we are only using one pipe, or no pipe at
    # all, using select() or threads is unnecessary.
    if [self.stdin, self.stdout, self.stderr].count(None) >= 2:

But, alas, here we've made at least two, and maybe three, different pipes, so the count(None) returns either 1 or 0. We must do things the hard way.

On Windows, this uses threading.Thread to accumulate results for self.stdout and self.stderr, and has the parent thread deliver self.stdin input data (and then close the pipe).

On POSIX, this uses poll if available, otherwise select, to accumulate output and deliver stdin input. All this runs in the (single) parent process/thread.

Threads or poll/select are needed here to avoid deadlock. Suppose, for instance, that we've redirected all three streams to three separate pipes. Suppose further that there's a small limit on how much data can be stuffed into to a pipe before the writing process is suspended, waiting for the reading process to "clean out" the pipe from the other end. Let's set that small limit to a single byte, just for illustration. (This is in fact how things work, except that the limit is much bigger than one byte.)

If the parent (Python) process tries to write several bytes—say, 'go\n'to proc.stdin, the first byte goes in and then the second causes the Python process to suspend, waiting for the subprocess to read the first byte, emptying the pipe.

Meanwhile, suppose the subprocess decides to print a friendly "Hello! Don't Panic!" greeting. The H goes into its stdout pipe, but the e causes it to suspend, waiting for its parent to read that H, emptying the stdout pipe.

Now we're stuck: the Python process is asleep, waiting to finish saying "go", and the subprocess is also asleep, waiting to finish saying "Hello! Don't Panic!".

The subprocess.Popen code avoids this problem with threading-or-select/poll. When bytes can go over the pipes, they go. When they can't, only a thread (not the whole process) has to sleep—or, in the case of select/poll, the Python process waits simultaneously for "can write" or "data available", writes to the process's stdin only when there is room, and reads its stdout and/or stderr only when data are ready. The proc.communicate() code (actually _communicate where the hairy cases are handled) returns once all stdin data (if any) have been sent and all stdout and/or stderr data have been accumulated.

If you want to read both stdout and stderr on two different pipes (regardless of any stdin redirection), you will need to avoid deadlock too. The deadlock scenario here is different—it occurs when the subprocess writes something long to stderr while you're pulling data from stdout, or vice versa—but it's still there.


The Demo

I promised to demonstrate that, un-redirected, Python subprocesses write to the underlying stdout, not sys.stdout. So, here is some code:

from cStringIO import StringIO
import os
import subprocess
import sys

def show1():
    print 'start show1'
    save = sys.stdout
    sys.stdout = StringIO()
    print 'sys.stdout being buffered'
    proc = subprocess.Popen(['echo', 'hello'])
    proc.wait()
    in_stdout = sys.stdout.getvalue()
    sys.stdout = save
    print 'in buffer:', in_stdout

def show2():
    print 'start show2'
    save = sys.stdout
    sys.stdout = open(os.devnull, 'w')
    print 'after redirect sys.stdout'
    proc = subprocess.Popen(['echo', 'hello'])
    proc.wait()
    sys.stdout = save

show1()
show2()

When run:

$ python out.py
start show1
hello
in buffer: sys.stdout being buffered

start show2
hello

Note that the first routine will fail if you add stdout=sys.stdout, as a StringIO object has no fileno. The second will omit the hello if you add stdout=sys.stdout since sys.stdout has been redirected to os.devnull.

(If you redirect Python's file-descriptor-1, the subprocess will follow that redirection. The open(os.devnull, 'w') call produces a stream whose fileno() is greater than 2.)

Why is processing a sorted array faster than processing an unsorted array?

On ARM, there is no branch needed, because every instruction has a 4-bit condition field, which tests (at zero cost) any of 16 different different conditions that may arise in the Processor Status Register, and if the condition on an instruction is false, the instruction is skipped. This eliminates the need for short branches, and there would be no branch prediction hit for this algorithm. Therefore, the sorted version of this algorithm would run slower than the unsorted version on ARM, because of the extra overhead of sorting.

The inner loop for this algorithm would look something like the following in ARM assembly language:

MOV R0, #0   // R0 = sum = 0
MOV R1, #0   // R1 = c = 0
ADR R2, data // R2 = addr of data array (put this instruction outside outer loop)
.inner_loop  // Inner loop branch label
    LDRB R3, [R2, R1]   // R3 = data[c]
    CMP R3, #128        // compare R3 to 128
    ADDGE R0, R0, R3    // if R3 >= 128, then sum += data[c] -- no branch needed!
    ADD R1, R1, #1      // c++
    CMP R1, #arraySize  // compare c to arraySize
    BLT inner_loop      // Branch to inner_loop if c < arraySize

But this is actually part of a bigger picture:

CMP opcodes always update the status bits in the Processor Status Register (PSR), because that is their purpose, but most other instructions do not touch the PSR unless you add an optional S suffix to the instruction, specifying that the PSR should be updated based on the result of the instruction. Just like the 4-bit condition suffix, being able to execute instructions without affecting the PSR is a mechanism that reduces the need for branches on ARM, and also facilitates out of order dispatch at the hardware level, because after performing some operation X that updates the status bits, subsequently (or in parallel) you can do a bunch of other work that explicitly should not affect (or be affected by) the status bits, then you can test the state of the status bits set earlier by X.

The condition testing field and the optional "set status bit" field can be combined, for example:

  • ADD R1, R2, R3 performs R1 = R2 + R3 without updating any status bits.
  • ADDGE R1, R2, R3 performs the same operation only if a previous instruction that affected the status bits resulted in a Greater than or Equal condition.
  • ADDS R1, R2, R3 performs the addition and then updates the N, Z, C and V flags in the Processor Status Register based on whether the result was Negative, Zero, Carried (for unsigned addition), or oVerflowed (for signed addition).
  • ADDSGE R1, R2, R3 performs the addition only if the GE test is true, and then subsequently updates the status bits based on the result of the addition.

Most processor architectures do not have this ability to specify whether or not the status bits should be updated for a given operation, which can necessitate writing additional code to save and later restore status bits, or may require additional branches, or may limit the processor's out of order execution efficiency: one of the side effects of most CPU instruction set architectures forcibly updating status bits after most instructions is that it is much harder to tease apart which instructions can be run in parallel without interfering with each other. Updating status bits has side effects, therefore has a linearizing effect on code. ARM's ability to mix and match branch-free condition testing on any instruction with the option to either update or not update the status bits after any instruction is extremely powerful, for both assembly language programmers and compilers, and produces very efficient code.

When you don't have to branch, you can avoid the time cost of flushing the pipeline for what would otherwise be short branches, and you can avoid the design complexity of many forms of speculative evalution. The performance impact of the initial naive imlementations of the mitigations for many recently discovered processor vulnerabilities (Spectre etc.) shows you just how much the performance of modern processors depends upon complex speculative evaluation logic. With a short pipeline and the dramatically reduced need for branching, ARM just doesn't need to rely on speculative evaluation as much as CISC processors. (Of course high-end ARM implementations do include speculative evaluation, but it's a smaller part of the performance story.)

If you have ever wondered why ARM has been so phenomenally successful, the brilliant effectiveness and interplay of these two mechanisms (combined with another mechanism that lets you "barrel shift" left or right one of the two arguments of any arithmetic operator or offset memory access operator at zero additional cost) are a big part of the story, because they are some of the greatest sources of the ARM architecture's efficiency. The brilliance of the original designers of the ARM ISA back in 1983, Steve Furber and Roger (now Sophie) Wilson, cannot be overstated.

HQL ERROR: Path expected for join

select u from UserGroup ug inner join ug.user u 
where ug.group_id = :groupId 
order by u.lastname

As a named query:

@NamedQuery(
  name = "User.findByGroupId",
  query =
    "SELECT u FROM UserGroup ug " +
    "INNER JOIN ug.user u WHERE ug.group_id = :groupId ORDER BY u.lastname"
)

Use paths in the HQL statement, from one entity to the other. See the Hibernate documentation on HQL and joins for details.

Getting a list of all subdirectories in the current directory

This below class would be able to get list of files, folder and all sub folder inside a given directory

import os
import json

class GetDirectoryList():
    def __init__(self, path):
        self.main_path = path
        self.absolute_path = []
        self.relative_path = []


    def get_files_and_folders(self, resp, path):
        all = os.listdir(path)
        resp["files"] = []
        for file_folder in all:
            if file_folder != "." and file_folder != "..":
                if os.path.isdir(path + "/" + file_folder):
                    resp[file_folder] = {}
                    self.get_files_and_folders(resp=resp[file_folder], path= path + "/" + file_folder)
                else:
                    resp["files"].append(file_folder)
                    self.absolute_path.append(path.replace(self.main_path + "/", "") + "/" + file_folder)
                    self.relative_path.append(path + "/" + file_folder)
        return resp, self.relative_path, self.absolute_path

    @property
    def get_all_files_folder(self):
        self.resp = {self.main_path: {}}
        all = self.get_files_and_folders(self.resp[self.main_path], self.main_path)
        return all

if __name__ == '__main__':
    mylib = GetDirectoryList(path="sample_folder")
    file_list = mylib.get_all_files_folder
    print (json.dumps(file_list))

Whereas Sample Directory looks like

sample_folder/
    lib_a/
        lib_c/
            lib_e/
                __init__.py
                a.txt
            __init__.py
            b.txt
            c.txt
        lib_d/
            __init__.py
        __init__.py
        d.txt
    lib_b/
        __init__.py
        e.txt
    __init__.py

Result Obtained

[
  {
    "files": [
      "__init__.py"
    ],
    "lib_b": {
      "files": [
        "__init__.py",
        "e.txt"
      ]
    },
    "lib_a": {
      "files": [
        "__init__.py",
        "d.txt"
      ],
      "lib_c": {
        "files": [
          "__init__.py",
          "c.txt",
          "b.txt"
        ],
        "lib_e": {
          "files": [
            "__init__.py",
            "a.txt"
          ]
        }
      },
      "lib_d": {
        "files": [
          "__init__.py"
        ]
      }
    }
  },
  [
    "sample_folder/lib_b/__init__.py",
    "sample_folder/lib_b/e.txt",
    "sample_folder/__init__.py",
    "sample_folder/lib_a/lib_c/lib_e/__init__.py",
    "sample_folder/lib_a/lib_c/lib_e/a.txt",
    "sample_folder/lib_a/lib_c/__init__.py",
    "sample_folder/lib_a/lib_c/c.txt",
    "sample_folder/lib_a/lib_c/b.txt",
    "sample_folder/lib_a/lib_d/__init__.py",
    "sample_folder/lib_a/__init__.py",
    "sample_folder/lib_a/d.txt"
  ],
  [
    "lib_b/__init__.py",
    "lib_b/e.txt",
    "sample_folder/__init__.py",
    "lib_a/lib_c/lib_e/__init__.py",
    "lib_a/lib_c/lib_e/a.txt",
    "lib_a/lib_c/__init__.py",
    "lib_a/lib_c/c.txt",
    "lib_a/lib_c/b.txt",
    "lib_a/lib_d/__init__.py",
    "lib_a/__init__.py",
    "lib_a/d.txt"
  ]
]

Concatenating strings in Razor

You can give like this....

<a href="@(IsProduction.IsProductionUrl)Index/LogOut">

How to convert MySQL time to UNIX timestamp using PHP?

From one of my other posts, getting a unixtimestamp:

$unixTimestamp = time();

Converting to mysql datetime format:

$mysqlTimestamp = date("Y-m-d H:i:s", $unixTimestamp);

Getting some mysql timestamp:

$mysqlTimestamp = '2013-01-10 12:13:37';

Converting it to a unixtimestamp:

$unixTimestamp = strtotime('2010-05-17 19:13:37');

...comparing it with one or a range of times, to see if the user entered a realistic time:

if($unixTimestamp > strtotime("1999-12-15") && $unixTimestamp < strtotime("2025-12-15"))
{...}

Unix timestamps are safer too. You can do the following to check if a url passed variable is valid, before checking (for example) the previous range check:

if(ctype_digit($_GET["UpdateTimestamp"]))
{...}

INSTALL_FAILED_UPDATE_INCOMPATIBLE when I try to install compiled .apk on device

It happened to me when I installed a dev build using Instant Run, and uninstalled from Google Play. For some reason the data from Instant Run is still in the device and can't install/uninstall the app again.

Only way to fix it: - disable Instant Run in android studio - install from android studio (it should work only from here) - uninstall app

now it should be clean to install from Google Play or adb.

how to rename an index in a cluster?

Just in case someone still needs it. The successful, not official, way to rename indexes are:

  1. Close indexes that need to be renamed
  2. Rename indexes' folders in all data directories of master and data nodes.
  3. Reopen old closed indexes (I use kofp plugin). Old indexes will be reopened but stay unassigned. New indexes will appear in closed state
  4. Reopen new indexes
  5. Delete old indexes

If you happen to get this error "dangled index directory name is", remove index folder in all master nodes (not data nodes), and restart one of the data nodes.

Detect when an HTML5 video finishes

You can add listener all video events nicluding ended, loadedmetadata, timeupdate where ended function gets called when video ends

_x000D_
_x000D_
$("#myVideo").on("ended", function() {_x000D_
   //TO DO: Your code goes here..._x000D_
      alert("Video Finished");_x000D_
});_x000D_
_x000D_
$("#myVideo").on("loadedmetadata", function() {_x000D_
      alert("Video loaded");_x000D_
  this.currentTime = 50;//50 seconds_x000D_
   //TO DO: Your code goes here..._x000D_
});_x000D_
_x000D_
_x000D_
$("#myVideo").on("timeupdate", function() {_x000D_
  var cTime=this.currentTime;_x000D_
  if(cTime>0 && cTime % 2 == 0)//Alerts every 2 minutes once_x000D_
      alert("Video played "+cTime+" minutes");_x000D_
   //TO DO: Your code goes here..._x000D_
  var perc=cTime * 100 / this.duration;_x000D_
  if(perc % 10 == 0)//Alerts when every 10% watched_x000D_
      alert("Video played "+ perc +"%");_x000D_
});
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
_x000D_
  <video id="myVideo" controls="controls">_x000D_
    <source src="your_video_file.mp4" type="video/mp4">_x000D_
      <source src="your_video_file.mp4" type="video/ogg">_x000D_
        Your browser does not support HTML5 video._x000D_
  </video>_x000D_
_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

How can I get the image url in a Wordpress theme?

src="<?php echo base_url()?>your_theme_dir/image_dir/img.ext"

As well

src="<?php bloginfo('template_url'); ?>/image_dir/img.ext"

What reference do I need to use Microsoft.Office.Interop.Excel in .NET?

Here is super solid solution, you just need have excell.dll in your Debug/Release folder Mine is 77,824 bytes, I downloaded it as a file, this also explain why some people have Debug compiled but Release not or vice versa.

Trento

Changing Fonts Size in Matlab Plots

To change the default property for your entire MATLAB session, see the documentation on how default properties are handled.

As an example:

set(0,'DefaultAxesFontSize',22)
x=1:200; y=sin(x);
plot(x,y)
title('hello'); xlabel('x'); ylabel('sin(x)')

NSDictionary to NSArray?

NSArray * values = [dictionary allValues];

PHP: How to generate a random, unique, alphanumeric string for use in a secret link?

When trying to generate a random password you are trying to :

  • First generate a cryptographically secure set of random bytes

  • Second is turning those random bytes into a printable string

Now, there are multiple way to generate random bytes in php like :

$length = 32;

//PHP 7+
$bytes= random_bytes($length);

//PHP < 7
$bytes= openssl_random_pseudo_bytes($length);

Then you want to turn these random bytes into a printable string :

You can use bin2hex :

$string = bin2hex($bytes);

or base64_encode :

$string = base64_encode($bytes);

However, note that you do not control the length of the string if you use base64. You can use bin2hex to do that, using 32 bytes will turn into a 64 char string. But it will only work like so in an EVEN string.

So basically you can just do :

$length = 32;

if(PHP_VERSION>=7){
    $bytes= random_bytes($length);
}else{
    $bytes= openssl_random_pseudo_bytes($length);
} 

$string = bin2hex($bytes);

what's the correct way to send a file from REST web service to client?

Change the machine address from localhost to IP address you want your client to connect with to call below mentioned service.

Client to call REST webservice:

package in.india.client.downloadfiledemo;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response.Status;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientHandlerException;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.UniformInterfaceException;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.multipart.BodyPart;
import com.sun.jersey.multipart.MultiPart;

public class DownloadFileClient {

    private static final String BASE_URI = "http://localhost:8080/DownloadFileDemo/services/downloadfile";

    public DownloadFileClient() {

        try {
            Client client = Client.create();
            WebResource objWebResource = client.resource(BASE_URI);
            ClientResponse response = objWebResource.path("/")
                    .type(MediaType.TEXT_HTML).get(ClientResponse.class);

            System.out.println("response : " + response);
            if (response.getStatus() == Status.OK.getStatusCode()
                    && response.hasEntity()) {
                MultiPart objMultiPart = response.getEntity(MultiPart.class);
                java.util.List<BodyPart> listBodyPart = objMultiPart
                        .getBodyParts();
                BodyPart filenameBodyPart = listBodyPart.get(0);
                BodyPart fileLengthBodyPart = listBodyPart.get(1);
                BodyPart fileBodyPart = listBodyPart.get(2);

                String filename = filenameBodyPart.getEntityAs(String.class);
                String fileLength = fileLengthBodyPart
                        .getEntityAs(String.class);
                File streamedFile = fileBodyPart.getEntityAs(File.class);

                BufferedInputStream objBufferedInputStream = new BufferedInputStream(
                        new FileInputStream(streamedFile));

                byte[] bytes = new byte[objBufferedInputStream.available()];

                objBufferedInputStream.read(bytes);

                String outFileName = "D:/"
                        + filename;
                System.out.println("File name is : " + filename
                        + " and length is : " + fileLength);
                FileOutputStream objFileOutputStream = new FileOutputStream(
                        outFileName);
                objFileOutputStream.write(bytes);
                objFileOutputStream.close();
                objBufferedInputStream.close();
                File receivedFile = new File(outFileName);
                System.out.print("Is the file size is same? :\t");
                System.out.println(Long.parseLong(fileLength) == receivedFile
                        .length());
            }
        } catch (UniformInterfaceException e) {
            e.printStackTrace();
        } catch (ClientHandlerException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static void main(String... args) {
        new DownloadFileClient();
    }
}

Service to response client:

package in.india.service.downloadfiledemo;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import com.sun.jersey.multipart.MultiPart;

@Path("downloadfile")
@Produces("multipart/mixed")
public class DownloadFileResource {

    @GET
    public Response getFile() {

        java.io.File objFile = new java.io.File(
                "D:/DanGilbert_2004-480p-en.mp4");
        MultiPart objMultiPart = new MultiPart();
        objMultiPart.type(new MediaType("multipart", "mixed"));
        objMultiPart
                .bodyPart(objFile.getName(), new MediaType("text", "plain"));
        objMultiPart.bodyPart("" + objFile.length(), new MediaType("text",
                "plain"));
        objMultiPart.bodyPart(objFile, new MediaType("multipart", "mixed"));

        return Response.ok(objMultiPart).build();

    }
}

JAR needed:

jersey-bundle-1.14.jar
jersey-multipart-1.14.jar
mimepull.jar

WEB.XML:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID" version="2.5">
    <display-name>DownloadFileDemo</display-name>
    <servlet>
        <display-name>JAX-RS REST Servlet</display-name>
        <servlet-name>JAX-RS REST Servlet</servlet-name>
        <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
        <init-param>
             <param-name>com.sun.jersey.config.property.packages</param-name> 
             <param-value>in.india.service.downloadfiledemo</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>JAX-RS REST Servlet</servlet-name>
        <url-pattern>/services/*</url-pattern>
    </servlet-mapping>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>

Installing Tomcat 7 as Service on Windows Server 2008

Looks like now they have the bat in the zip as well

note that you can use windows sc command to do more

e.g.

sc config tomcat7 start= auto

yes the space before auto is NEEDED

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

UPDATE user_account student, (
   SELECT teacher.education_facility_id as teacherid
   FROM user_account teacher
   WHERE teacher.user_account_id = student.teacher_id AND teacher.user_type = 'ROLE_TEACHER'
) teach SET student.student_education_facility_id= teach.teacherid WHERE student.user_type = 'ROLE_STUDENT';

How to copy data from another workbook (excel)?

I was in need of copying the data from one workbook to another using VBA. The requirement was as mentioned below 1. On pressing an Active X button open the dialogue to select the file from which the data needs to be copied. 2. On clicking OK the value should get copied from a cell / range to currently working workbook.

I did not want to use the open function because it opens the workbook which will be annoying

Below is the code that I wrote in the VBA. Any improvement or new alternative is welcome.

Code: Here I am copying the A1:C4 content from a workbook to the A1:C4 of current workbook

    Private Sub CommandButton1_Click()
        Dim BackUp As String
        Dim cellCollection As New Collection
        Dim strSourceSheetName As String
        Dim strDestinationSheetName As String
        strSourceSheetName = "Sheet1" 'Mention the Source Sheet Name of Source Workbook
        strDestinationSheetName = "Sheet2" 'Mention the Destination Sheet Name of Destination Workbook


        Set cellCollection = GetCellsFromRange("A1:C4") 'Mention the Range you want to copy data from Source Workbook

        With Application.FileDialog(msoFileDialogOpen)
            .AllowMultiSelect = False
            .Show
            '.Filters.Add "Macro Enabled Xl", "*.xlsm;", 1

            For intWorkBookCount = 1 To .SelectedItems.Count
                Dim strWorkBookName As String
                strWorkBookName = .SelectedItems(intWorkBookCount)
                For cellCount = 1 To cellCollection.Count
                    On Error GoTo ErrorHandler
                    BackUp = Sheets(strDestinationSheetName).Range(cellCollection.Item(cellCount))
                    Sheets(strDestinationSheetName).Range(cellCollection.Item(cellCount)) = GetData(strWorkBookName, strSourceSheetName, cellCollection.Item(cellCount))
                    Dim strTempValue As String
                    strTempValue = Sheets(strDestinationSheetName).Range(cellCollection.Item(cellCount)).Value
                    If (strTempValue = "0") Then
                        strTempValue = BackUp
                    End If
Sheets(strDestinationSheetName).Range(cellCollection.Item(cellCount)) = strTempValue 
ErrorHandler:
                    If (Err.Number <> 0) Then
                            Sheets(strDestinationSheetName).Range(cellCollection.Item(cellCount)) = BackUp
                        Exit For
                    End If
                Next cellCount
            Next intWorkBookCount
        End With

    End Sub

    Function GetCellsFromRange(RangeInScope As String) As Collection
        Dim startCell As String
        Dim endCell As String
        Dim intStartColumn As Integer
        Dim intEndColumn As Integer
        Dim intStartRow As Integer
        Dim intEndRow As Integer
        Dim coll As New Collection

        startCell = Left(RangeInScope, InStr(RangeInScope, ":") - 1)
        endCell = Right(RangeInScope, Len(RangeInScope) - InStr(RangeInScope, ":"))
        intStartColumn = Range(startCell).Column
        intEndColumn = Range(endCell).Column
        intStartRow = Range(startCell).Row
        intEndRow = Range(endCell).Row

        For lngColumnCount = intStartColumn To intEndColumn
            For lngRowCount = intStartRow To intEndRow
                coll.Add (Cells(lngRowCount, lngColumnCount).Address(RowAbsolute:=False, ColumnAbsolute:=False))
            Next lngRowCount
        Next lngColumnCount

        Set GetCellsFromRange = coll
    End Function

    Function GetData(FileFullPath As String, SheetName As String, CellInScope As String) As String
        Dim Path As String
        Dim FileName As String
        Dim strFinalValue As String
        Dim doesSheetExist As Boolean

        Path = FileFullPath
        Path = StrReverse(Path)
        FileName = StrReverse(Left(Path, InStr(Path, "\") - 1))
        Path = StrReverse(Right(Path, Len(Path) - InStr(Path, "\") + 1))

        strFinalValue = "='" & Path & "[" & FileName & "]" & SheetName & "'!" & CellInScope
        GetData = strFinalValue
    End Function

How to include multiple js files using jQuery $.getScript() method

I have improved @adeneo script so it will load all scripts in the specified order. It doesn't do chain loading, so it's very fast, but if you want even faster, change the 50 ms wait time.

$.getMultiScripts = function(arr, path) {

    function executeInOrder(scr, code, resolve) {
        // if its the first script that should be executed
        if (scr == arr[0]) {
            arr.shift();
            eval(code);
            resolve();
            console.log('executed', scr);
        } else {
            // waiting
            setTimeout(function(){
                executeInOrder(scr, code, resolve);
            }, 50);
        }
    }

    var _arr = $.map(arr, function(scr) {

        return new Promise((resolve) => {
            jQuery.ajax({
                type: "GET",
                url: (path || '') + scr,
                dataType: "text",
                success: function(code) {
                    console.log('loaded  ', scr);
                    executeInOrder(scr, code, resolve);
                },
                cache: true
            });
        });

    });
        
    _arr.push($.Deferred(function( deferred ){
        $( deferred.resolve );
    }));
        
    return $.when.apply($, _arr);
}

Usage is the same:

var script_arr = [
    'myscript1.js', 
    'myscript2.js', 
    'myscript3.js'
];

$.getMultiScripts(script_arr, '/mypath/').done(function() {
    // all scripts loaded
});

MongoDB distinct aggregation

Distinct and the aggregation framework are not inter-operable.

Instead you just want:

db.zips.aggregate([ 
    {$group:{_id:{city:'$city', state:'$state'}, numberOfzipcodes:{$sum:1}}}, 
    {$sort:{numberOfzipcodes:-1}},
    {$group:{_id:'$_id.state', city:{$first:'$_id.city'}, 
              numberOfzipcode:{$first:'$numberOfzipcodes'}}}
]);

How to hide reference counts in VS2013?

Another option is to use mouse, right click on "x reference". Context menu "CodeLens Options" will appear, saving all the navigation headache.

Is it possible to preview stash contents in git?

yes the best way to see what is modified is to save in file like that:

git stash show -p stash@{0} > stash.txt

Getting all selected checkboxes in an array

You could try something like this:

$('input[type="checkbox"]').change(function(){
       var checkedValue = $('input:checkbox:checked').map(function(){
                return this.value;
            }).get();         
            alert(checkedValue);   //display selected checkbox value     
 })

Here

$('input[type="checkbox"]').change(function() call when any checkbox checked or unchecked, after this
$('input:checkbox:checked').map(function()  looping on all checkbox,

Reversing an Array in Java

I like to keep the original array and return a copy. This is a generic version:

public static <T> T[] reverse(T[] array) {
    T[] copy = array.clone();
    Collections.reverse(Arrays.asList(copy));
    return copy;
}

without keeping the original array:

public static <T> void reverse(T[] array) {
    Collections.reverse(Arrays.asList(array));
}

What is the default initialization of an array in Java?

Thorbjørn Ravn Andersen answered for most of the data types. Since there was a heated discussion about array,

Quoting from the jls spec http://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.12.5 "array component is initialized with a default value when it is created"

I think irrespective of whether array is local or instance or class variable it will with default values

How to download a file via FTP with Python ftplib

If you are not limited to using ftplib you can also give wget module a try. Here, is the snippet

import wget
file_loc = 'http://www.website.com/foo.zip'
wget.download(file_loc)

Webdriver findElements By xpath

Your questions:

Q 1.) I would like to know why it returns all the texts that following the div?
It should not and I think in will not. It returns all div with 'id' attribute value equal 'containter' (and all children of this). But you are printing the results with ele.getText() Where getText will return all text content of all children of your result.

Get the visible (i.e. not hidden by CSS) innerText of this element, including sub-elements, without any leading or trailing whitespace.
Returns:
The innerText of this element.

Q 2.) how should I modify the code so it just return first or first few nodes that follow the parent note
This is not really clear what you are looking for. Example:

<p1> <div/> </p1 <p2/> 

The following to parent of the div is p2. This would be:

 //div[@id='container'][1]/parent::*/following-sibling::* 

or shorter

 //div[@id='container'][1]/../following-sibling::* 

If you are only looking for the first one extent the expression with an "predicate" (e.g [1] - for the first one. or [position() &lt; 4]for the first three)

If your are looking for the first child of the first div:

//div[@id='container'][1]/*[1]

If there is only one div with id an you are looking for the first child:

   //div[@id='container']/*[1]

and so on.

Cannot access mongodb through browser - It looks like you are trying to access MongoDB over HTTP on the native driver port

Before Mongo 3.6:

You may start mongodb with

mongod --httpinterface

And access it on

http://localhost:28017

Since version 2.6: MongoDB disables the HTTP interface by default.

Update

HTTP Interface and REST API

MongoDB 3.6 removes the deprecated HTTP interface and REST API to MongoDB.

See Mongo http interface and rest api

Access Database opens as read only

on my pc I had the same problem and it was because in properties -> security I didn't have the ownership of the file...

ASP.NET MVC Bundle not rendering script files on staging server. It works on development server

By adding following code of line in bundle to config it works for me

bundles.IgnoreList.Clear();  

Follow the link for more explanation

Yes/No message box using QMessageBox

QT can be as simple as that of Windows. The equivalent code is

if (QMessageBox::Yes == QMessageBox(QMessageBox::Information, "title", "Question", QMessageBox::Yes|QMessageBox::No).exec()) 
{

}

Convert tuple to list and back

You have a tuple of tuples.
To convert every tuple to a list:

[list(i) for i in level] # list of lists

--- OR ---

map(list, level)

And after you are done editing, just convert them back:

tuple(tuple(i) for i in edited) # tuple of tuples

--- OR --- (Thanks @jamylak)

tuple(itertools.imap(tuple, edited))

You can also use a numpy array:

>>> a = numpy.array(level1)
>>> a
array([[1, 1, 1, 1, 1, 1],
       [1, 0, 0, 0, 0, 1],
       [1, 0, 0, 0, 0, 1],
       [1, 0, 0, 0, 0, 1],
       [1, 0, 0, 0, 0, 1],
       [1, 1, 1, 1, 1, 1]])

For manipulating:

if clicked[0] == 1:
    x = (mousey + cameraY) // 60 # For readability
    y = (mousex + cameraX) // 60 # For readability
    a[x][y] = 1

How to time Java program execution speed

Be aware that there are some issues where System#nanoTime() cannot be reliably used on multi-core CPU's to record elapsed time ... each core has maintains its own TSC (Time Stamp Counter): this counter is used to obtain the nano time (really it is the number of ticks since the CPU booted).

Hence, unless the OS does some TSC time warping to keep the cores in sync, then if a thread gets scheduled on one core when the initial time reading is taken, then switched to a different core, the relative time can sporadically appear to jump backwards and forwards.

I observed this some time ago on AMD/Solaris where elapsed times between two timing points were sometimes coming back as either negative values or unexpectedly large positive numbers. There was a Solaris kernel patch and a BIOS setting required to force the AMD PowerNow! off, which appeared to solved it.

Also, there is (AFAIK) a so-far unfixed bug when using java System#nanoTime() in a VirtualBox environment; causing all sorts of bizarre intermittent threading problems for us as much of the java.util.concurrency package relies on nano time.

See also:

Is System.nanoTime() completely useless? http://vbox.innotek.de/pipermail/vbox-trac/2010-January/135631.html

What's the best way to check if a file exists in C?

Use stat like this:

#include <sys/stat.h>   // stat
#include <stdbool.h>    // bool type

bool file_exists (char *filename) {
  struct stat   buffer;   
  return (stat (filename, &buffer) == 0);
}

and call it like this:

#include <stdio.h>      // printf

int main(int ac, char **av) {
    if (ac != 2)
        return 1;

    if (file_exists(av[1]))
        printf("%s exists\n", av[1]);
    else
        printf("%s does not exist\n", av[1]);

    return 0;
}

PreparedStatement IN clause alternatives?

No simple way AFAIK. If the target is to keep statement cache ratio high (i.e to not create a statement per every parameter count), you may do the following:

  1. create a statement with a few (e.g. 10) parameters:

    ... WHERE A IN (?,?,?,?,?,?,?,?,?,?) ...

  2. Bind all actuall parameters

    setString(1,"foo"); setString(2,"bar");

  3. Bind the rest as NULL

    setNull(3,Types.VARCHAR) ... setNull(10,Types.VARCHAR)

NULL never matches anything, so it gets optimized out by the SQL plan builder.

The logic is easy to automate when you pass a List into a DAO function:

while( i < param.size() ) {
  ps.setString(i+1,param.get(i));
  i++;
}

while( i < MAX_PARAMS ) {
  ps.setNull(i+1,Types.VARCHAR);
  i++;
}

Can Mysql Split a column?

Usually substring_index does what you want:

mysql> select substring_index("[email protected]","@",-1);
+-----------------------------------------+
| substring_index("[email protected]","@",-1) |
+-----------------------------------------+
| gmail.com                               |
+-----------------------------------------+
1 row in set (0.00 sec)

Table with 100% width with equal size columns

ALL YOU HAVE TO DO:

HTML:

<table id="my-table"><tr>
<td> CELL 1 With a lot of text in it</td>
<td> CELL 2 </td>
<td> CELL 3 </td>
<td> CELL 4 With a lot of text in it </td>
<td> CELL 5 </td>
</tr></table>

CSS:

#my-table{width:100%;} /*or whatever width you want*/
#my-table td{width:2000px;} /*something big*/

if you have th you need to set it too like this:

#my-table th{width:2000px;}

Determine the number of lines within a text file

You could quickly read it in, and increment a counter, just use a loop to increment, doing nothing with the text.

Separators for Navigation

If there isn't a pressing need to use images for the separators, you could do this with pure CSS.

nav li + li:before{
    content: " | ";
    padding: 0 10px;
}

This puts a bar between each list item, just as the image in the original question described. But since we're using the adjacent selectors, it doesn't put the bar before the first element. And since we're using the :before pseudo selector, it doesn't put one at the end.

Is this the right way to clean-up Fragment back stack when leaving a deeply nested stack?

Thanks to Joachim answer, I use the code to clear all back stack entry finally.

// In your FragmentActivity use getSupprotFragmentManager() to get the FragmentManager.

// Clear all back stack.
int backStackCount = getSupportFragmentManager().getBackStackEntryCount();
for (int i = 0; i < backStackCount; i++) {

    // Get the back stack fragment id.
    int backStackId = getSupportFragmentManager().getBackStackEntryAt(i).getId();

    getSupportFragmentManager().popBackStack(backStackId, 
        FragmentManager.POP_BACK_STACK_INCLUSIVE);

} /* end of for */

Iterating a JavaScript object's properties using jQuery

Note: Most modern browsers will now allow you to navigate objects in the developer console. This answer is antiquated.

This method will walk through object properties and write them to the console with increasing indent:

function enumerate(o,s){

    //if s isn't defined, set it to an empty string
    s = typeof s !== 'undefined' ? s : "";

    //if o is null, we need to output and bail
    if(typeof o == "object" && o === null){

       console.log(s+k+": null");

    } else {    

        //iterate across o, passing keys as k and values as v
        $.each(o, function(k,v){

            //if v has nested depth
           if(typeof v == "object" && v !== null){

                //write the key to the console
                console.log(s+k+": ");

                //recursively call enumerate on the nested properties
                enumerate(v,s+"  ");

            } else {

                //log the key & value
                console.log(s+k+": "+String(v));
            }
        });
    }
}

Just pass it the object you want to iterate through:

    var response = $.ajax({
        url: myurl,
        dataType: "json"
    })
    .done(function(a){
       console.log("Returned values:");
       enumerate(a);
    })
    .fail(function(){ console.log("request failed");});

How to get `DOM Element` in Angular 2?

Use ViewChild with #localvariable as shown here,

<textarea  #someVar  id="tasknote"
                  name="tasknote"
                  [(ngModel)]="taskNote"
                  placeholder="{{ notePlaceholder }}"
                  style="background-color: pink"
                  (blur)="updateNote() ; noteEditMode = false " (click)="noteEditMode = false"> {{ todo.note }} 

</textarea>

In component,

OLDEST Way

import {ElementRef} from '@angular/core';
@ViewChild('someVar') el:ElementRef;

ngAfterViewInit()
{
   this.el.nativeElement.focus();
}


OLD Way

import {ElementRef} from '@angular/core';
@ViewChild('someVar') el:ElementRef;

constructor(private rd: Renderer) {}
ngAfterViewInit() {
    this.rd.invokeElementMethod(this.el.nativeElement,'focus');
}


Updated on 22/03(March)/2017

NEW Way

Please note from Angular v4.0.0-rc.3 (2017-03-10) few things have been changed. Since Angular team will deprecate invokeElementMethod, above code no longer can be used.

BREAKING CHANGES

since 4.0 rc.1:

rename RendererV2 to Renderer2
rename RendererTypeV2 to RendererType2
rename RendererFactoryV2 to RendererFactory2

import {ElementRef,Renderer2} from '@angular/core';
@ViewChild('someVar') el:ElementRef;

constructor(private rd: Renderer2) {}

ngAfterViewInit() {
      console.log(this.rd); 
      this.el.nativeElement.focus();      //<<<=====same as oldest way
}

console.log(this.rd) will give you following methods and you can see now invokeElementMethod is not there. Attaching img as yet it is not documented.

NOTE: You can use following methods of Rendere2 with/without ViewChild variable to do so many things.

enter image description here

How to search and replace text in a file?

Late answer, but this is what I use to find and replace inside a text file:

with open("test.txt") as r:
  text = r.read().replace("THIS", "THAT")
with open("test.txt", "w") as w:
  w.write(text)

DEMO