Programs & Examples On #Mosix

Method List in Visual Studio Code

UPDATE: The extension features are now built-in and the extension itself is now deprecated

I have found this extention: Code Outline. This is how it looks like:

This is how it looks like

I believe that is what you have been looking for.

Generate random numbers uniformly over an entire range

Check what RAND_MAX is on your system -- I'm guessing it is only 16 bits, and your range is too big for it.

Beyond that see this discussion on: Generating Random Integers within a Desired Range and the notes on using (or not) the C rand() function.

SELECT list is not in GROUP BY clause and contains nonaggregated column

As @Brian Riley already said you should either remove 1 column in your select

select countrylanguage.language ,sum(country.population*countrylanguage.percentage/100)
from countrylanguage
join country on countrylanguage.countrycode = country.code
group by countrylanguage.language
order by sum(country.population*countrylanguage.percentage) desc ;

or add it to your grouping

select countrylanguage.language, country.code, sum(country.population*countrylanguage.percentage/100)
from countrylanguage
join country on countrylanguage.countrycode = country.code
group by countrylanguage.language, country.code
order by sum(country.population*countrylanguage.percentage) desc ;

Eclipse will not start and I haven't changed anything

Definitely a network/proxy thing. I connect via wifi and a corporate gateway. Deleted workspace, reinstalled GGTS - still hangs. Turn off the network - launches fine.

How to create border in UIButton?

You can set the border properties on the CALayer by accessing the layer property of the button.

First, add Quartz

#import <QuartzCore/QuartzCore.h>

Set properties:

myButton.layer.borderWidth = 2.0f;
myButton.layer.borderColor = [UIColor greenColor].CGColor;


The CALayer in the link above allows you to set other properties like corner radius, maskToBounds etc...

Also, a good article on button fun:

JAVA_HOME directory in Linux

I know this is late, but this command searches the /usr/ directory to find java for you

sudo find /usr/ -name *jdk

Results to


FYI, if you are on a Mac, currently JAVA_HOME is located at


Getting "conflicting types for function" in C, why?

A C Function-Declaration Backgrounder

In C, function declarations don't work like they do in other languages: The C compiler itself doesn't search backward and forward in the file to find the function's declaration from the place you call it, and it doesn't scan the file multiple times to figure out the relationships either: The compiler only scans forward in the file exactly once, from top to bottom. Connecting function calls to function declarations is part of the linker's job, and is only done after the file is compiled down to raw assembly instructions.

This means that as the compiler scans forward through the file, the very first time the compiler encounters the name of a function, one of two things have to be the case: It either is seeing the function declaration itself, in which case the compiler knows exactly what the function is and what types it takes as arguments and what types it returns — or it's a call to the function, and the compiler has to guess how the function will eventually be declared.

(There's a third option, where the name is used in a function prototype, but we'll ignore that for now, since if you're seeing this problem in the first place, you're probably not using prototypes.)

History Lesson

In the earliest days of C, the fact that the compiler had to guess types wasn't really an issue: All of the types were more-or-less the same — pretty much everything was either an int or a pointer, and they were the same size. (In fact, in B, the language that preceded C, there were no types at all; everything was just an int or pointer and its type was determined solely by how you used it!) So the compiler could safely guess the behavior of any function just based on the number of parameters that were passed: If you passed two parameters, the compiler would push two things onto the call stack, and presumably the callee would have two arguments declared, and that would all line up. If you passed only one parameter but the function expected two, it would still sort-of work, and the second argument would just be ignored/garbage. If you passed three parameters and the function expected two, it would also still sort-of work, and the third parameter would be ignored and stomped on by the function's local variables. (Some old C code still expects these mismatched-argument rules will work, too.)

But having the compiler let you pass anything to anything isn't really a good way to design a programming language. It worked well in the early days because the early C programmers were mostly wizards, and they knew not to pass the wrong type to functions, and even if they did get the types wrong, there were always tools like lint that could do deeper double-checking of your C code and warn you about such things.

Fast-forward to today, and we're not quite in the same boat. C has grown up, and a lot of people are programming in it who aren't wizards, and to accommodate them (and to accommodate everyone else who regularly used lint anyway), the compilers have taken on many of the abilities that were previously part of lint — especially the part where they check your code to ensure it's type-safe. Early C compilers would let you write int foo = "hello"; and it would just blithely assign the pointer to the integer, and it was up to you to make sure you weren't doing anything stupid. Modern C compilers complain loudly when you get your types wrong, and that's a good thing.

Type Conflicts

So what's all this got to do with the mysterious conflicting-type error on the line of the function declaration? As I said above, C compilers still have to either know or guess what a name means the first time they see that name as they scan forward through the file: They can know what it means it if it's an actual function declaration itself (or a function "prototype," more on that shortly), but if it's just a call to the function, they have to guess. And, sadly, the guess is often wrong.

When the compiler saw your call to do_something(), it looked at how it was invoked, and it concluded that do_something() would eventually be declared like this:

int do_something(char arg1[], char arg2[])

Why did it conclude that? Because that's how you called it! (Some C compilers may conclude that it was int do_something(int arg1, int arg2), or simply int do_something(...), both of which are even farther from what you want, but the important point is that regardless of how the compiler guesses the types, it guesses them differently from what your actual function uses.)

Later on, as the compiler scans forward in the file, it sees your actual declaration of char *do_something(char *, char *). That function declaration isn't even close to the declaration that the compiler guessed, which means that the line where the compiler compiled the call was compiled wrong, and the program is just not going to work. So it rightly prints an error telling you that your code isn't going to work as written.

You might be wondering, "Why does it assume I'm returning an int?" Well, it assumes that type because there's no information to the contrary: printf() can take in any type in its variable arguments, so without a better answer, int is as good a guess as any. (Many early C compilers always assumed int for every unspecified type, and assumed you meant ... for the arguments for every function declared f() — not void — which is why many modern code standards recommend always putting void in for the arguments if there really aren't supposed to be any.)

The Fix

There are two common fixes for the function-declaration error.

The first solution, which is recommended by many other answers here, is to put a prototype in the source code above the place where the function is first called. A prototype looks just like the function's declaration, but it has a semicolon where the body should be:

char *do_something(char *dest, const char *src);

By putting the prototype first, the compiler then knows what the function will eventually look like, so it doesn't have to guess. By convention, programmers often put prototypes at the top of the file, just under the #include statements, to ensure that they'll always be defined before any potential usages of them.

The other solution, which also shows up in some real-world code, is to simply reorder your functions so that the function declarations are always before anything that calls them! You could move the entire char *do_something(char *dest, const char *src) { ... } function above the first call to it, and the compiler then would know exactly what the function looks like and wouldn't have to guess.

In practice, most people use function prototypes, because you can also take function prototypes and move them into header (.h) files so that code in other .c files can call those functions. But either solution works, and many codebases use both.

C99 and C11

It is useful to note that the rules are slightly different in the newer versions of the C standard. In the earlier versions (C89 and K&R), the compiler really would guess the types at function-call time (and K&R-era compilers often wouldn't even warn you if they were wrong). C99 and C11 both require that the function declaration/prototype must precede the first call, and it's an error if it doesn't. But many modern C compilers — mainly for backward compatibility with earlier code — will only warn about a missing prototype and not consider it an error.

How to update cursor limit for ORA-01000: maximum open cursors exceed

Assuming that you are using a spfile to start the database

alter system set open_cursors = 1000 scope=both;

If you are using a pfile instead, you can change the setting for the running instance

alter system set open_cursors = 1000 

You would also then need to edit the parameter file to specify the new open_cursors setting. It would generally be a good idea to restart the database shortly thereafter to make sure that the parameter file change works as expected (it's highly annoying to discover months later the next time that you reboot the database that some parameter file change than no one remembers wasn't done correctly).

I'm also hoping that you are certain that you actually need more than 300 open cursors per session. A large fraction of the time, people that are adjusting this setting actually have a cursor leak and they are simply trying to paper over the bug rather than addressing the root cause.

libpng warning: iCCP: known incorrect sRGB profile

some background info on this:

Some changes in libpng version 1.6+ cause it to issue a warning or even not work correctly with the original HP/MS sRGB profile, leading to the following stderr: libpng warning: iCCP: known incorrect sRGB profile The old profile uses a D50 whitepoint, where D65 is standard. This profile is not uncommon, being used by Adobe Photoshop, although it was not embedded into images by default.


Error detection in some chunks has improved; in particular the iCCP chunk reader now does pretty complete validation of the basic format. Some bad profiles that were previously accepted are now rejected, in particular the very old broken Microsoft/HP sRGB profile. The PNG spec requirement that only grayscale profiles may appear in images with color type 0 or 4 and that even if the image only contains gray pixels, only RGB profiles may appear in images with color type 2, 3, or 6, is now enforced. The sRGB chunk is allowed to appear in images with any color type.


Show and hide a View with a slide up/down animation


Based on Suragch's answer, here is an elegant way using View extension:

fun View.slideUp(duration: Int = 500) {
    visibility = View.VISIBLE
    val animate = TranslateAnimation(0f, 0f, this.height.toFloat(), 0f)
    animate.duration = duration.toLong()
    animate.fillAfter = true

fun View.slideDown(duration: Int = 500) {
    visibility = View.VISIBLE
    val animate = TranslateAnimation(0f, 0f, 0f, this.height.toFloat())
    animate.duration = duration.toLong()
    animate.fillAfter = true

And then wherever you want to use it, you just need myView.slideUp() or myView.slideDown()

Setting Short Value Java

Generally you can just cast the variable to become a short.

You can also get problems like this that can be confusing. This is because the + operator promotes them to an int

enter image description here

Casting the elements won't help:

enter image description here

You need to cast the expression:

enter image description here

How do I reset the scale/zoom of a web app on an orientation change on the iPhone?

Here's another way to do it, which seems to work well.

  1. Set the meta tag to restrict the viewport to scale=1, which prevents zooming:

    < meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1">

  2. With javascript, change the meta tag 1/2 second later to allow zooming:

    setTimeout(function(){ document.querySelector("meta[name=viewport]").setAttribute('content','width=device-width, initial-scale=1');}, 500);

  3. Again with javascript, on orientation change, reload the page:

    window.onorientationchange = function(){window.location.reload();};

Every time you reorient the device, the page reloads, initially without zoom. But 1/2 second later, ability to zoom is restored.

Change <select>'s option and trigger events with JavaScript

It is as simple as this:

var sel = document.getElementById('sel');
var button = document.getElementById('button');

button.addEventListener('click', function (e) {
    sel.options[1].selected = true;

But this way has a problem. You can't call events just like you would, with normal functions, because there may be more than one function listening for an event, and they can get set in several different ways.

Unfortunately, the 'right way' to fire an event is not so easy because you have to do it differently in Internet Explorer (using document.createEventObject) and Firefox (using document.createEvent("HTMLEvents"))

var sel = document.getElementById('sel');
var button = document.getElementById('button');

button.addEventListener('click', function (e) {
    sel.options[1].selected = true;


function fireEvent(element,event){
    if (document.createEventObject){
    // dispatch for IE
    var evt = document.createEventObject();
    return element.fireEvent('on'+event,evt)
    // dispatch for firefox + others
    var evt = document.createEvent("HTMLEvents");
    evt.initEvent(event, true, true ); // event type,bubbling,cancelable
    return !element.dispatchEvent(evt);

Change HTML email body font type and size in VBA

Set texts with different sizes and styles, and size and style for texts from cells ( with Range)

Sub EmailManuellAbsenden()

Dim ghApp As Object
Dim ghOldBody As String
Dim ghNewBody As String

Set ghApp = CreateObject("Outlook.Application")
With ghApp.CreateItem(0)
.To = Range("B2")
.CC = Range("B3")
.Subject = Range("B4")
 ghOldBody = .htmlBody

 ghNewBody = "<font style=""font-family: Calibri; font-size: 11pt;""/font>" & _
 "<font style=""font-family: Arial; font-size: 14pt;"">Arial Text 14</font>" & _
 Range("B5") & "<br>" & _
 Range("B6") & "<br>" & _
 "<font style=""font-family: Chiller; font-size: 21pt;"">Ciller 21</font>" &
 .htmlBody = ghNewBody & ghOldBody

 End With

End Sub
'Fill B2 to B6 with some letters for testing
'"<font style=""font-family: Calibri; font-size: 15pt;""/font>" = works for all Range Objekts

Why is the console window closing immediately once displayed my output?

According to my concern, if we want to stable the OUTPUT OF CONSOLE APPLICATION, till the close of output display USE, the label: after the MainMethod, and goto label; before end of the program

In the Program.


static void Main(string[] args)

    // Snippet of code

    goto label;

Ruby on Rails: Clear a cached page

This line in development.rb ensures that caching is not happening.

config.action_controller.perform_caching             = false

You can clear the Rails cache with


That said - I am not convinced this is a caching issue. Are you making changes to the page and not seeing them reflected? You aren't perhaps looking at the live version of that page? I have done that once (blush).


You can call that command from in the console. Are you sure you are running the application in development?

The only alternative is that the page that you are trying to render isn't the page that is being rendered.

If you watch the server output you should be able to see the render command when the page is rendered similar to this:

Rendered shared_partials/_latest_featured_video (31.9ms)
Rendered shared_partials/_s_invite_friends (2.9ms)
Rendered layouts/_sidebar (2002.1ms)
Rendered layouts/_footer (2.8ms)
Rendered layouts/_busy_indicator (0.6ms)

MVC which submit button has been pressed

this is a better answer, so we can have both text and value for a button:

<button name="button" value="register">Register</button>
<button name="button" value="cancel">Cancel</button>

and the controller:

public ActionResult Register(string button, string userName, string email, string password, string confirmPassword)
if (button == "cancel")
    return RedirectToAction("Index", "Home");

in short its a SUBMIT button but you choose the name using the name attribute, its even more powerful because your not obligated to the name submit or button in the controller method parameters, you can call it as you like...

How do I convert a single character into it's hex ascii value in python

This might help

import binascii

x = b'test'
x = binascii.hexlify(x)
y = str(x,'ascii')

print(x) # Outputs b'74657374' (hex encoding of "test")
print(y) # Outputs 74657374

x_unhexed = binascii.unhexlify(x)
print(x_unhexed) # Outputs b'test'

x_ascii = str(x_unhexed,'ascii')
print(x_ascii) # Outputs test

This code contains examples for converting ASCII characters to and from hexadecimal. In your situation, the line you'd want to use is str(binascii.hexlify(c),'ascii').

How to select between brackets (or quotes or ...) in Vim?

To select between the single quotes I usually do a vi' ("select inner single quotes").

Inside a parenthesis block, I use vib ("select inner block")

Inside a curly braces block you can use viB ("capital B")

To make the selections "inclusive" (select also the quotes, parenthesis or braces) you can use a instead of i.

You can read more about the Text object selections on the manual, or :help text-objects within vim.

copy from one database to another using oracle sql developer - connection failed

The copy command is a SQL*Plus command (not a SQL Developer command). If you have your tnsname entries setup for SID1 and SID2 (e.g. try a tnsping), you should be able to execute your command.

Another assumption is that table1 has the same columns as the message_table (and the columns have only the following data types: CHAR, DATE, LONG, NUMBER or VARCHAR2). Also, with an insert command, you would need to be concerned about primary keys (e.g. that you are not inserting duplicate records).

I tried a variation of your command as follows in SQL*Plus (with no errors):

copy from scott/tiger@db1 to scott/tiger@db2 create new_emp using select * from emp;

After I executed the above statement, I also truncate the new_emp table and executed this command:

copy from scott/tiger@db1 to scott/tiger@db2 insert new_emp using select * from emp;

With SQL Developer, you could do the following to perform a similar approach to copying objects:

  1. On the tool bar, select Tools>Database copy.

  2. Identify source and destination connections with the copy options you would like. enter image description here

  3. For object type, select table(s). enter image description here

  4. Specify the specific table(s) (e.g. table1). enter image description here

The copy command approach is old and its features are not being updated with the release of new data types. There are a number of more current approaches to this like Oracle's data pump (even for tables).

Export specific rows from a PostgreSQL table as INSERT SQL script

You can make view of the table with specifit records and then dump sql file

SELECT id,name,city FROM nyummy.cimory WHERE city = 'tokyo'

How to see the values of a table variable at debug time in T-SQL?


Insert the above statement at the point where you want to view the table's contents. The table's contents will be rendered as XML in the locals window, or you can add @v to the watches window.

enter image description here

Import Libraries in Eclipse?

No, don't do it that way.

From your Eclipse workspace, right click your project on the left pane -> Properties -> Java Build Path -> Add Jars -> add your jars here.

Tadaa!! :)

How to fix "The ConnectionString property has not been initialized"

Use [] instead of () as below example.

SqlDataAdapter adapter = new SqlDataAdapter(sql, ConfigurationManager.ConnectionStrings["FADB_ConnectionString"].ConnectionString);
            DataTable data = new DataTable();
            DataSet ds = new DataSet();

What is an API key?

An API key is a unique value that is assigned to a user of this service when he's accepted as a user of the service.

The service maintains all the issued keys and checks them at each request.

By looking at the supplied key at the request, a service checks whether it is a valid key to decide on whether to grant access to a user or not.

how to overwrite css style

Just add

.flex-control-thumbs li {
width: auto; 

Java 8 Distinct by property

The easiest way to implement this is to jump on the sort feature as it already provides an optional Comparator which can be created using an element’s property. Then you have to filter duplicates out which can be done using a statefull Predicate which uses the fact that for a sorted stream all equal elements are adjacent:

Comparator<Person> c=Comparator.comparing(Person::getName);
stream.sorted(c).filter(new Predicate<Person>() {
    Person previous;
    public boolean test(Person p) {
      if(previous!=null &&, p)==0)
        return false;
      return true;
})./* more stream operations here */;

Of course, a statefull Predicate is not thread-safe, however if that’s your need you can move this logic into a Collector and let the stream take care of the thread-safety when using your Collector. This depends on what you want to do with the stream of distinct elements which you didn’t tell us in your question.

How to export datagridview to excel using

Regarding your need to 'print directly from datagridview', check out this article on CodeProject:

The DataGridViewPrinter Class

There are a number of similar articles but I've had luck with the one I linked.

how to change text box value with jQuery?

Use like this on dropdown change

What does this square bracket and parenthesis bracket notation mean [first1,last1)?

A bracket - [ or ] - means that end of the range is inclusive -- it includes the element listed. A parenthesis - ( or ) - means that end is exclusive and doesn't contain the listed element. So for [first1, last1), the range starts with first1 (and includes it), but ends just before last1.

Assuming integers:

  • (0, 5) = 1, 2, 3, 4
  • (0, 5] = 1, 2, 3, 4, 5
  • [0, 5) = 0, 1, 2, 3, 4
  • [0, 5] = 0, 1, 2, 3, 4, 5

.htaccess redirect http to https

Forcing HTTPS with the .htaccess File

==> Redirect All Web Traffic :-

To force all web traffic to use HTTPS, insert the following lines of code in the .htaccess file in your website’s root folder.

RewriteEngine On 
RewriteCond %{HTTPS} !on
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

==> Redirect Only Specified Domain :-

To force a specific domain to use HTTPS, use the following lines of code in the .htaccess file in your website’s root folder:

RewriteCond %{REQUEST_URI} !^/[0-9]+\..+\.cpaneldcv$
RewriteCond %{REQUEST_URI} !^/\.well-known/pki-validation/[A-F0-9]{32}\.txt(?:\ Comodo\ DCV)?$
RewriteEngine On 
RewriteCond %{HTTP_HOST} ^example\.com [NC]
RewriteCond %{SERVER_PORT} 80 
RewriteRule ^(.*)$$1 [R=301,L]

If this doesn’t work, try removing the first two lines.

RewriteEngine On
RewriteCond %{HTTP_HOST} ^example\.com [NC]
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$$1 [R=301,L]

Make sure to replace with the domain name you’re trying force to https. Additionally, you need to replace with your actual domain name.

==> Redirect Specified Folder :-

If you want to force SSL on a specific folder, insert the code below into a .htaccess file placed in that specific folder:

RewriteCond %{REQUEST_URI} !^/[0-9]+\..+\.cpaneldcv$
RewriteCond %{REQUEST_URI} !^/\.well-known/pki-validation/[A-F0-9]{32}\.txt(?:\ Comodo\ DCV)?$
RewriteEngine On 
RewriteCond %{SERVER_PORT} 80 
RewriteCond %{REQUEST_URI} folder
RewriteRule ^(.*)$$1 [R=301,L]

Make sure you change the folder reference to the actual folder name. Then be sure to replace with your actual domain name and folder you want to force the SSL on.

python: iterate a specific range in a list

You want to use slicing.

for item in listOfStuff[1:3]:
    print item

Change default icon

Go to form's properties, ICON ... Choose an icon you want.

EDIT: try this

  1. Edit App.Ico to make it look like you want.
  2. In the property pane for your form, set the Icon property to your project's App.Ico file.
  3. Rebuild solution.

And read this one icons

Accessing the web page's HTTP Headers in JavaScript

For those looking for a way to parse all HTTP headers into an object that can be accessed as a dictionary headers["content-type"], I've created a function parseHttpHeaders:

function parseHttpHeaders(httpHeaders) {
    return httpHeaders.split("\n")
     .map(x=>x.split(/: */,2))
     .reduce((ac, x)=>{ac[x[0]] = x[1];return ac;}, {});

var req = new XMLHttpRequest();'GET', document.location, false);
var headers = parseHttpHeaders(req.getAllResponseHeaders());
// Now we can do:  headers["content-type"]

creating a new list with subset of list using index in python


a = ['a', 'b', 'c', 3, 4, 'd', 6, 7, 8]

and the list of indexes is stored in

b= [0, 1, 2, 4, 6, 7, 8]

then a simple one-line solution will be

c = [a[i] for i in b]

Floating Div Over An Image

You've got the right idea. Looks to me like you just need to change .tag's position:relative to position:absolute, and add position:relative to .container.

Replace last occurrence of character in string

var someString = "(/n{})+++(/n{})---(/n{})$$$";_x000D_
var toRemove = "(/n{})"; // should find & remove last occurrence _x000D_
function removeLast(s, r){_x000D_
  s = s.split(r)_x000D_
  return s.slice(0,-1).join(r) + s.pop()_x000D_
  removeLast(someString, toRemove)_x000D_


s = s.split(toRemove)         // ["", "+++", "---", "$$$"]
s.slice(0,-1)                 //  ["", "+++", "---"]   
s.slice(0,-1).join(toRemove)  // "})()+++})()---"
s.pop()                       //  "$$$"   

Disable Input fields in reactive form

The best solution is here:

Outline of solution (in case of broken link):

(1) Create a directive

import { NgControl } from '@angular/forms';

@Directive({selector: '[disableControl]'})
export class DisableControlDirective {

  @Input() set disableControl( condition : boolean ) {
    const action = condition ? 'disable' : 'enable';

  constructor( private ngControl : NgControl ) {}

(2) Use it like so

<input [formControl]="formControl" [disableControl]="condition">

(3) Since disabled inputs do not show in form.value on submit you may need to use the following instead (if required):

onSubmit(form) {
  const formValue = form.getRawValue() // gets form.value including disabled controls

Jenkins: Cannot define variable in pipeline stage

Agree with @Pom12, @abayer. To complete the answer you need to add script block

Try something like this:

pipeline {
    agent any
    environment {
        ENV_NAME = "${env.BRANCH_NAME}"

    // ----------------

    stages {
        stage('Build Container') {
            steps {
                echo 'Building Container..'

                script {
                    if (ENVIRONMENT_NAME == 'development') {
                        ENV_NAME = 'Development'
                    } else if (ENVIRONMENT_NAME == 'release') {
                        ENV_NAME = 'Production'
                echo 'Building Branch: ' + env.BRANCH_NAME
                echo 'Build Number: ' + env.BUILD_NUMBER
                echo 'Building Environment: ' + ENV_NAME

                echo "Running your service with environemnt ${ENV_NAME} now"

How to change a field name in JSON using Jackson

Have you tried using @JsonProperty?

public class City {
   Long id;
   String name;

   public String getName() { return name; }

   public void setName(String name){ = name; }

   public Long getId() { return id; }

   public void setId(Long id){ = id; }

How to display (print) vector in Matlab?

You can use

x = [1, 2, 3]
disp(sprintf('Answer: (%d, %d, %d)', x))

This results in

Answer: (1, 2, 3)

For vectors of arbitrary size, you can use

disp(strrep(['Answer: (' sprintf(' %d,', x) ')'], ',)', ')'))

An alternative way would be

disp(strrep(['Answer: (' num2str(x, ' %d,') ')'], ',)', ')'))

Including external HTML file to another HTML file

The iframe element.

<iframe src="name.html"></iframe>

But content that you way to have appear on multiple pages is better handled using templates.

ERROR: SQLSTATE[HY000] [2002] No connection could be made because the target machine actively refused it

Delete the following files from the directory:


This solved my problem.

Genymotion Android emulator - adb access?

We need to connect with IP address to the emulator, so look for the IP address of the running emulator (it's shown in the emulator title bar) and use something like:

adb connect

Afterward adb works normally. You may also find out the IP address of a running emulator by starting "Genymotion Shell" and typing 'devices list'

I also find out that occasionally I have to do the above when the emulator is running for a longer time and somehow ADB disconnects from it.


What is a Windows Handle?

A HANDLE is a context-specific unique identifier. By context-specific, I mean that a handle obtained from one context cannot necessarily be used in any other aribtrary context that also works on HANDLEs.

For example, GetModuleHandle returns a unique identifier to a currently loaded module. The returned handle can be used in other functions that accept module handles. It cannot be given to functions that require other types of handles. For example, you couldn't give a handle returned from GetModuleHandle to HeapDestroy and expect it to do something sensible.

The HANDLE itself is just an integral type. Usually, but not necessarily, it is a pointer to some underlying type or memory location. For example, the HANDLE returned by GetModuleHandle is actually a pointer to the base virtual memory address of the module. But there is no rule stating that handles must be pointers. A handle could also just be a simple integer (which could possibly be used by some Win32 API as an index into an array).

HANDLEs are intentionally opaque representations that provide encapsulation and abstraction from internal Win32 resources. This way, the Win32 APIs could potentially change the underlying type behind a HANDLE, without it impacting user code in any way (at least that's the idea).

Consider these three different internal implementations of a Win32 API that I just made up, and assume that Widget is a struct.

Widget * GetWidget (std::string name)
    Widget *w;

    w = findWidget(name);

    return w;
void * GetWidget (std::string name)
    Widget *w;

    w = findWidget(name);

    return reinterpret_cast<void *>(w);
typedef void * HANDLE;

HANDLE GetWidget (std::string name)
    Widget *w;

    w = findWidget(name);

    return reinterpret_cast<HANDLE>(w);

The first example exposes the internal details about the API: it allows the user code to know that GetWidget returns a pointer to a struct Widget. This has a couple of consequences:

  • the user code must have access to the header file that defines the Widget struct
  • the user code could potentially modify internal parts of the returned Widget struct

Both of these consequences may be undesirable.

The second example hides this internal detail from the user code, by returning just void *. The user code doesn't need access to the header that defines the Widget struct.

The third example is exactly the same as the second, but we just call the void * a HANDLE instead. Perhaps this discourages user code from trying to figure out exactly what the void * points to.

Why go through this trouble? Consider this fourth example of a newer version of this same API:

typedef void * HANDLE;

HANDLE GetWidget (std::string name)
    NewImprovedWidget *w;

    w = findImprovedWidget(name);

    return reinterpret_cast<HANDLE>(w);

Notice that the function's interface is identical to the third example above. This means that user code can continue to use this new version of the API, without any changes, even though the "behind the scenes" implementation has changed to use the NewImprovedWidget struct instead.

The handles in these example are really just a new, presumably friendlier, name for void *, which is exactly what a HANDLE is in the Win32 API (look it up at MSDN). It provides an opaque wall between the user code and the Win32 library's internal representations that increases portability, between versions of Windows, of code that uses the Win32 API.

How to change the color of an svg element?

You can't change the color of an image that way. If you load SVG as an image, you can't change how it is displayed using CSS or Javascript in the browser.

If you want to change your SVG image, you have to load it using <object>, <iframe> or using <svg> inline.

If you want to use the techniques in the page, you need the Modernizr library, where you can check for SVG support and conditionally display or not a fallback image. You can then inline your SVG and apply the styles you need.

See :

#time-3-icon {_x000D_
   fill: green;_x000D_
.my-svg-alternate {_x000D_
  display: none;_x000D_
.no-svg .my-svg-alternate {_x000D_
  display: block;_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
  background-image: url(image.png);_x000D_
<svg width="96px" height="96px" viewBox="0 0 512 512" enable-background="new 0 0 512 512" xml:space="preserve">_x000D_
<path id="time-3-icon" d="M256,50C142.229,50,50,142.229,50,256c0,113.77,92.229,206,206,206c113.77,0,206-92.23,206-206_x000D_
 C462,142.229,369.77,50,256,50z M256,417c-88.977,0-161-72.008-161-161c0-88.979,72.008-161,161-161c88.977,0,161,72.007,161,161_x000D_
 C417,344.977,344.992,417,256,417z M382.816,265.785c1.711,0.297,2.961,1.781,2.961,3.518v0.093c0,1.72-1.223,3.188-2.914,3.505_x000D_
<image class="my-svg-alternate" width="96" height="96" src="ppngfallback.png" />

You can inline your SVG, tag your fallback image with a class name (my-svg-alternate):

<svg width="96px" height="96px" viewBox="0 0 512 512" enable-background="new 0 0 512 512" xml:space="preserve">
<path id="time-3-icon" .../>

<image class="my-svg-alternate" width="96" height="96" src="ppngfallback.png" />

And in CSS use the no-svg class from Modernizr (CDN: ) to check for SVG support. If there is no SVG support the SVG block will be ignored and the image will be displayed, otherwise the image will be removed from the DOM tree (display: none):

.my-svg-alternate {
  display: none;
.no-svg .my-svg-alternate {
  display: block;
  width: 100px;
  height: 100px;
  background-image: url(image.png);

Then you can change the color of your inlined element:

#time-3-icon {
   fill: green;

Where and why do I have to put the "template" and "typename" keywords?

I am placing JLBorges's excellent response to a similar question verbatim from, as it is the most succinct explanation I've read on the subject.

In a template that we write, there are two kinds of names that could be used - dependant names and non- dependant names. A dependant name is a name that depends on a template parameter; a non-dependant name has the same meaning irrespective of what the template parameters are.

For example:

template< typename T > void foo( T& x, std::string str, int count )
    // these names are looked up during the second phase
    // when foo is instantiated and the type T is known
    x.size(); // dependant name (non-type)
    T::instance_count ; // dependant name (non-type)
    typename T::iterator i ; // dependant name (type)
    // during the first phase, 
    // T::instance_count is treated as a non-type (this is the default)
    // the typename keyword specifies that T::iterator is to be treated as a type.

    // these names are looked up during the first phase
    std::string::size_type s ; // non-dependant name (type)
    std::string::npos ; // non-dependant name (non-type)
    str.empty() ; // non-dependant name (non-type)
    count ; // non-dependant name (non-type)

What a dependant name refers to could be something different for each different instantiation of the template. As a consequence, C++ templates are subject to "two-phase name lookup". When a template is initially parsed (before any instantiation takes place) the compiler looks up the non-dependent names. When a particular instantiation of the template takes place, the template parameters are known by then, and the compiler looks up dependent names.

During the first phase, the parser needs to know if a dependant name is the name of a type or the name of a non-type. By default, a dependant name is assumed to be the name of a non-type. The typename keyword before a dependant name specifies that it is the name of a type.


Use the keyword typename only in template declarations and definitions provided you have a qualified name that refers to a type and depends on a template parameter.

What's the difference between "2*2" and "2**2" in Python?

The ** operator in Python is really "power;" that is, 2**3 = 8.

What tools do you use to test your public REST API?

I use

Ha. Sorry, I mis-read your post. I've used cucumber to test it before. It worked out nicely.

PG::ConnectionBad - could not connect to server: Connection refused

You probably restarted your computer and forgot to launch the Postgres app.

How to refactor Node.js code that uses fs.readFileSync() into using fs.readFile()?

var fs = require("fs");
var filename = "./index.html";

function start(resp) {
    resp.writeHead(200, {
        "Content-Type": "text/html"
    fs.readFile(filename, "utf8", function(err, data) {
        if (err) throw err;

How can I create directory tree in C++/Linux?

So I need mkdirp() today, and found the solutions on this page overly complicated. Hence I wrote a fairly short snippet, that easily be copied in for others who stumble upon this thread an wonder why we need so many lines of code.


#ifndef MKDIRP_H
#define MKDIRP_H

#include <sys/stat.h>


/** Utility function to create directory tree */
bool mkdirp(const char* path, mode_t mode = DEFAULT_MODE);

#endif // MKDIRP_H


#include <errno.h>

bool mkdirp(const char* path, mode_t mode) {
  // const cast for hack
  char* p = const_cast<char*>(path);

  // Do mkdir for each slash until end of string or error
  while (*p != '\0') {
    // Skip first character

    // Find first slash or end
    while(*p != '\0' && *p != '/') p++;

    // Remember value from p
    char v = *p;

    // Write end of string at p
    *p = '\0';

    // Create folder from path to '\0' inserted at p
    if(mkdir(path, mode) == -1 && errno != EEXIST) {
      *p = v;
      return false;

    // Restore path to it's former glory
    *p = v;

  return true;

If you don't like const casting and temporarily modifying the string, just do a strdup() and free() it afterwards.

how to make a jquery "$.post" request synchronous

jQuery < 1.8

May I suggest that you use $.ajax() instead of $.post() as it's much more customizable.

If you are calling $.post(), e.g., like this:

$.post( url, data, success, dataType );

You could turn it into its $.ajax() equivalent:

  type: 'POST',
  url: url,
  data: data,
  success: success,
  dataType: dataType,

Please note the async:false at the end of the $.ajax() parameter object.

Here you have a full detail of the $.ajax() parameters: jQuery.ajax() – jQuery API Documentation.

jQuery >=1.8 "async:false" deprecation notice

jQuery >=1.8 won't block the UI during the http request, so we have to use a workaround to stop user interaction as long as the request is processed. For example:

  • use a plugin e.g. BlockUI;
  • manually add an overlay before calling $.ajax(), and then remove it when the AJAX .done() callback is called.

Please have a look at this answer for an example.

Is it possible to have a HTML SELECT/OPTION value as NULL using PHP?

All you need is a check on the post side of things.

if(empty($_REQUEST['type_id']) && $_REQUEST['type_id'] != 0)
    $_REQUEST['type_id'] = null;

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

As mentioned the size should reflect the current architecture. You could take a peak around in limits.h if you want to see how your current compiler is handling things.

How to get last inserted row ID from WordPress database?

Straight after the $wpdb->insert() that does the insert, do this:

$lastid = $wpdb->insert_id;

More information about how to do things the WordPress way can be found in the WordPress codex. The details above were found here on the wpdb class page

C# find biggest number

I needed to find a way to do this too, using numbers from different places and not in a collection. I was sure there was a method to do this in c#...though by the looks of it I'm muddling my languages...

Anyway, I ended up writing a couple of generic methods to do it...

    static T Max<T>(params T[] numberItems)
        return numberItems.Max();

    static T Min<T>(params T[] numberItems)
        return numberItems.Min();
    } them this way...

    int intTest = Max(1, 2, 3, 4);
    float floatTest = Min(0f, 255.3f, 12f, -1.2f);

How do I view the SSIS packages in SQL Server Management Studio?

If you have SQL Server installed there is also a menu option for finding local SSIS packages.

In the Start menu > All Programs > 'Microsoft Sql Server' there should be a menu option for 'Integration Services' > 'Execute Package Utility' (this is available if SSIS was included in your SQLserver installation).

When you open the Execute Package Utility, type your local sql server name in the 'Server Name' textbox and click on the Package button, you will see your saved package in the popup window. From here you can run your previously saved package

How to copy java.util.list Collection

Use the ArrayList copy constructor, then sort that.

List oldList;
List newList = new ArrayList(oldList);

After making the copy, any changes to newList do not affect oldList.

Note however that only the references are copied, so the two lists share the same objects, so changes made to elements of one list affect the elements of the other.

Missing artifact in pom.xml

You might have problem on Windows while adding jar to maven because of syntax.

Try encapsulating -D parameters with double quotas like this;

mvn install:install-file "-Dfile=ojdbc6.jar" "" "-DartifactId=ojdbc6" "-Dversion=11.2.0" "-Dpackaging=jar" 

Be aware of you should use same version/atifactId/groupId inside your pom.xml. You can't use version after command above. You have to put his in you pom.xml;


If you want to use another version, like, you should run above command with that version or other info

How to get public directory?

I know this is a little late, but if someone else comes across this looking, you can now use public_path(); in Laravel 4, it has been added to the helper.php file in the support folder see here.

Why is <deny users="?" /> included in the following example?

ASP.NET grants access from the configuration file as a matter of precedence. In case of a potential conflict, the first occurring grant takes precedence. So,

deny user="?" 

denies access to the anonymous user. Then

allow users="dan,matthew" 

grants access to that user. Finally, it denies access to everyone. This shakes out as everyone except dan,matthew is denied access.

Edited to add: and as @Deviant points out, denying access to unauthenticated is pointless, since the last entry includes unauthenticated as well. A good blog entry discussing this topic can be found at: Guru Sarkar's Blog

Removing Spaces from a String in C?

Easiest and most efficient don't usually go together...

Here's a possible solution:

void remove_spaces(char* s) {
    const char* d = s;
    do {
        while (*d == ' ') {
    } while (*s++ = *d++);

Open Cygwin at a specific folder

In the answer that uses the registry, I found that on Windows 2008 R2 SP1, you need to drop the Background out of the path. Further, since the chere and xhere are not part of cygwin64, here is a solution that works for both, combining the registry and the Send To solutions. Replace 'E:\cygwin64' with your install location:

Windows Registry Editor Version 5.00

@="Open Cygwin Here"

@="E:\\cygwin64\\bin\\mintty.exe -i /Cygwin-Terminal.ico --exec /bin/bash.exe --login -c \"cd '%1' ; exec bash -rcfile ~/.bashrc\""

Failed to create provisioning profile

For me this happened when I was making a tvOS app and didn't have a appleTV registered.

In general, you need to plug in the device or have logged into it (connected to it)..then it shows up here:

You can also add devices need to click reset to be able to add a new device. the reset button should be labeled modify because it doesn't reset anything.

for example, if you need to make a tvOS app then you need to have an apple TV in the device list. Once you add that then you're good to go. kisses.

AngularJS UI Router - change url without reloading state

This setup solved following issues for me:

  • The training controller is not called twice when updating the url from .../ to .../123
  • The training controller is not getting invoked again when navigating to another state

State configuration

state('training', {
    abstract: true,
    url: '/training',
    templateUrl: 'partials/training.html',
    controller: 'TrainingController'
state('training.edit', {
    url: '/:trainingId'
state('', {
    url: '/{trainingId}',
    // Optional Parameter
    params: {
        trainingId: null

Invoking the states (from any other controller)

$scope.editTraining = function (training) {
    $state.go('training.edit', { trainingId: });

$scope.newTraining = function () {
    $state.go('', { });

Training Controller

var newTraining;

if (!!!$state.params.trainingId) {

    // new      

    newTraining = // create new training ...

    // Update the URL without reloading the controller
            trainingId :
            location: 'replace', //  update url and replace
            inherit: false,
            notify: false

} else {

    // edit

    // load existing training ...

Javascript loading CSV file into an array

You can't use AJAX to fetch files from the user machine. This is absolutely the wrong way to go about it.

Use the FileReader API:

<input type="file" id="file input">


console.log(document.getElementById("file input").files); // list of File objects

var file = document.getElementById("file input").files[0];
var reader = new FileReader();
content = reader.readAsText(file);

Then parse content as CSV. Keep in mind that your parser currently does not deal with escaped values in CSV like: value1,value2,"value 3","value ""4"""

How to get the employees with their managers

This is a classic self-join, try the following:

SELECT e.ename, e.empno, m.ename as manager, e.mgr
    emp e, emp m
WHERE e.mgr = m.empno

And if you want to include the president which has no manager then instead of an inner join use an outer join in Oracle syntax:

SELECT e.ename, e.empno, m.ename as manager, e.mgr
    emp e, emp m
WHERE e.mgr = m.empno(+)

Or in ANSI SQL syntax:

SELECT e.ename, e.empno, m.ename as manager, e.mgr
    emp e
        ON e.mgr = m.empno

Android: crashes with getApplicationContext

Had a similar problem with (compatibility) Fragments in which using a getActivity() within crashes it. I'd agree that it is because of timing.

A possible fix:

mContext = getApplicationContext();

if (mContext != null) {
    mProgressDialog =, "", getString(R.string.loading), true);

instead of using

mProgressDialog =, "", getString(R.string.loading), true);

Place the mContext as early as possible to give it more time to grab the context. There's still no guarantee that this will work, it just reduces the likelihood of a crash. If it still doesn't work, you'd have to resort to the timer hack (which can cause other timing problems like dismissing the dialog later).

Of course, if you can use this or ActivityName.this, it's more stable because this already points to something. But in some cases, like with certain Fragment architectures, it's not an option.

npm install error - MSB3428: Could not load the Visual C++ component "VCBuild.exe"

npm install --global windows-build-tools

just run this command via powershell (right click and run as administrator!)

worked for me..

How can I tell jackson to ignore a property for which I don't have control over the source code?

I had a similar issue, but it was related to Hibernate's bi-directional relationships. I wanted to show one side of the relationship and programmatically ignore the other, depending on what view I was dealing with. If you can't do that, you end up with nasty StackOverflowExceptions. For instance, if I had these objects

public class A{
  Long id;
  String name;
  List<B> children;

public class B{
  Long id;
  A parent;

I would want to programmatically ignore the parent field in B if I were looking at A, and ignore the children field in A if I were looking at B.

I started off using mixins to do this, but that very quickly becomes horrible; you have so many useless classes laying around that exist solely to format data. I ended up writing my own serializer to handle this in a cleaner way:

It allows you programmatically specify what fields to ignore:

ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addSerializer(JsonView.class, new JsonViewSerializer());

List<A> list = getListOfA();
String json = mapper.writeValueAsString(JsonView.with(list)
    .onClass(B.class, match()

It also lets you easily specify very simplified views through wildcard matchers:

String json = mapper.writeValueAsString(JsonView.with(list)
    .onClass(A.class, match()
         .include("id", "name")));

In my original case, the need for simple views like this was to show the bare minimum about the parent/child, but it also became useful for our role-based security. Less privileged views of objects needed to return less information about the object.

All of this comes from the serializer, but I was using Spring MVC in my app. To get it to properly handle these cases, I wrote an integration that you can drop in to existing Spring controller classes:

public class JsonController {
  private JsonResult json = JsonResult.instance();
  private TestObjectService service;

  @RequestMapping(method = RequestMethod.GET, value = "/bean")
  public List<TestObject> getTestObject() {
    List<TestObject> list = service.list();

    return json.use(JsonView.with(list)
        .onClass(TestObject.class, Match.match()

Both are available on Maven Central. I hope it helps someone else out there, this is a particularly ugly problem with Jackson that didn't have a good solution for my case.

How to create file object from URL object (image)

You can make use of ImageIO in order to load the image from an URL and then write it to a file. Something like this:

URL url = new URL("");
BufferedImage img =;
File file = new File("downloaded.jpg");
ImageIO.write(img, "jpg", file);

This also allows you to convert the image to some other format if needed.

PHP - Move a file into a different folder on the server

Some solution is first to copy() the file (as mentioned above) and when the destination file exists - unlink() file from previous localization. Additionally you can validate the MD5 checksum before unlinking to be sure

Converting JSONarray to ArrayList

public static List<JSONObject> getJSONObjectListFromJSONArray(JSONArray array) 
        throws JSONException {
  ArrayList<JSONObject> jsonObjects = new ArrayList<>();
  for (int i = 0; 
           i < (array != null ? array.length() : 0);           
  return jsonObjects;

Escaping Strings in JavaScript

A variation of the function provided by Paolo Bergantino that works directly on String:

String.prototype.addSlashes = function() 
   //no need to do (str+'') anymore because 'this' can only be a string
   return this.replace(/[\\"']/g, '\\$&').replace(/\u0000/g, '\\0');

By adding the code above in your library you will be able to do:

var test = "hello single ' double \" and slash \\ yippie";


Following suggestions in the comments, whoever is concerned about conflicts amongst JavaScript libraries can add the following code:

   String.prototype.addSlashes = function()... 
   alert("Warning: String.addSlashes has already been declared elsewhere.");

Pandas DataFrame concat vs append

So what are you doing is with append and concat is almost equivalent. The difference is the empty DataFrame. For some reason this causes a big slowdown, not sure exactly why, will have to look at some point. Below is a recreation of basically what you did.

I almost always use concat (though in this case they are equivalent, except for the empty frame); if you don't use the empty frame they will be the same speed.

In [17]: df1 = pd.DataFrame(dict(A = range(10000)),index=pd.date_range('20130101',periods=10000,freq='s'))

In [18]: df1
<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 10000 entries, 2013-01-01 00:00:00 to 2013-01-01 02:46:39
Freq: S
Data columns (total 1 columns):
A    10000  non-null values
dtypes: int64(1)

In [19]: df4 = pd.DataFrame()

The concat

In [20]: %timeit pd.concat([df1,df2,df3])
1000 loops, best of 3: 270 us per loop

This is equavalent of your append

In [21]: %timeit pd.concat([df4,df1,df2,df3])
10 loops, best of 

 3: 56.8 ms per loop

Node package ( Grunt ) installed but not available

Sometimes you have to npm install package_name -g for it to work.

What does question mark and dot operator ?. mean in C# 6.0?

It can be very useful when flattening a hierarchy and/or mapping objects. Instead of:

if (Model.Model2 == null
  || Model.Model2.Model3 == null
  || Model.Model2.Model3.Model4 == null
  || Model.Model2.Model3.Model4.Name == null)
  mapped.Name = "N/A"
  mapped.Name = Model.Model2.Model3.Model4.Name;

It can be written like (same logic as above)

mapped.Name = Model.Model2?.Model3?.Model4?.Name ?? "N/A";

DotNetFiddle.Net Working Example.

(the ?? or null-coalescing operator is different than the ? or null conditional operator).

It can also be used out side of assignment operators with Action. Instead of

Action<TValue> myAction = null;

if (myAction != null)

It can be simplified to:


DotNetFiddle Example:

using System;

public class Program
  public static void Main()
    Action<string> consoleWrite = null;

    consoleWrite?.Invoke("Test 1");

    consoleWrite = (s) => Console.WriteLine(s);

    consoleWrite?.Invoke("Test 2");


Test 2

Python - How to convert JSON File to Dataframe

There are 2 inputs you might have and you can also convert between them.

  1. input: listOfDictionaries --> use @VikashSingh solution

example: [{"":{"...

The pd.DataFrame() needs a listOfDictionaries as input.

  1. input: jsonStr --> use @JustinMalinchak solution

example: '{"":{"...

If you have jsonStr, you need an extra step to listOfDictionaries first. This is obvious as it is generated like:

jsonStr = json.dumps(listOfDictionaries)

Thus, switch back from jsonStr to listOfDictionaries first:

listOfDictionaries = json.loads(jsonStr)

Is there a way to 'uniq' by column?

To consider multiple column.

Sort and give unique list based on column 1 and column 3:

sort -u -t : -k 1,1 -k 3,3 test.txt
  • -t : colon is separator
  • -k 1,1 -k 3,3 based on column 1 and column 3

What is Bit Masking?

A mask defines which bits you want to keep, and which bits you want to clear.

Masking is the act of applying a mask to a value. This is accomplished by doing:

  • Bitwise ANDing in order to extract a subset of the bits in the value
  • Bitwise ORing in order to set a subset of the bits in the value
  • Bitwise XORing in order to toggle a subset of the bits in the value

Below is an example of extracting a subset of the bits in the value:

Mask:   00001111b
Value:  01010101b

Applying the mask to the value means that we want to clear the first (higher) 4 bits, and keep the last (lower) 4 bits. Thus we have extracted the lower 4 bits. The result is:

Mask:   00001111b
Value:  01010101b
Result: 00000101b

Masking is implemented using AND, so in C we get:

uint8_t stuff(...) {
  uint8_t mask = 0x0f;   // 00001111b
  uint8_t value = 0x55;  // 01010101b
  return mask & value;

Here is a fairly common use-case: Extracting individual bytes from a larger word. We define the high-order bits in the word as the first byte. We use two operators for this, &, and >> (shift right). This is how we can extract the four bytes from a 32-bit integer:

void more_stuff(uint32_t value) {             // Example value: 0x01020304
    uint32_t byte1 = (value >> 24);           // 0x01020304 >> 24 is 0x01 so
                                              // no masking is necessary
    uint32_t byte2 = (value >> 16) & 0xff;    // 0x01020304 >> 16 is 0x0102 so
                                              // we must mask to get 0x02
    uint32_t byte3 = (value >> 8)  & 0xff;    // 0x01020304 >> 8 is 0x010203 so
                                              // we must mask to get 0x03
    uint32_t byte4 = value & 0xff;            // here we only mask, no shifting
                                              // is necessary

Notice that you could switch the order of the operators above, you could first do the mask, then the shift. The results are the same, but now you would have to use a different mask:

uint32_t byte3 = (value & 0xff00) >> 8;

Getting Checkbox Value in ASP.NET MVC 4

Since you are using Model.Name to set the value. I assume you are passing an empty view model to the View.

So the value for Remember is false, and sets the value on the checkbox element to false. This means that when you then select the checkbox, you are posting the value "false" with the form. When you don't select it, it doesn't get posted, so the model defaults to false. Which is why you are seeing a false value in both cases.

The value is only passed when you check the select box. To do a checkbox in Mvc use

@Html.CheckBoxFor(x => x.Remember)

or if you don't want to bind the model to the view.


Mvc does some magic with a hidden field to persist values when they are not selected.

Edit, if you really have an aversion to doing that and want to generate the element yourself, you could do.

<input id="Remember" name="Remember" type="checkbox" value="true" @(Model.Remember ? "checked=\"checked\"" : "") />

Can someone explain __all__ in Python?

__all__ affects how from foo import * works.

Code that is inside a module body (but not in the body of a function or class) may use an asterisk (*) in a from statement:

from foo import *

The * requests that all attributes of module foo (except those beginning with underscores) be bound as global variables in the importing module. When foo has an attribute __all__, the attribute's value is the list of the names that are bound by this type of from statement.

If foo is a package and its defines a list named __all__, it is taken to be the list of submodule names that should be imported when from foo import * is encountered. If __all__ is not defined, the statement from foo import * imports whatever names are defined in the package. This includes any names defined (and submodules explicitly loaded) by

Note that __all__ doesn't have to be a list. As per the documentation on the import statement, if defined, __all__ must be a sequence of strings which are names defined or imported by the module. So you may as well use a tuple to save some memory and CPU cycles. Just don't forget a comma in case the module defines a single public name:

__all__ = ('some_name',)

See also Why is “import *” bad?

What does the 'u' symbol mean in front of string values?

This is a feature, not a bug.

See, specifically the 'unicode type' section.

How do I add the Java API documentation to Eclipse?

Choose one class you want to view its documentation and press Ctrl+click over it, the Javadoc page will inform you that there is no Javadoc file attached and bellow will see a button named "Attach File". Press that button and browse to the directory where JDK is installed, normally for Win is C:\Program files\Java\jdk_xxx and inside this folder there is a file - sleect it and press OK and all is done - you already have Javadoc attached.

Python error: TypeError: 'module' object is not callable for HeadFirst Python code

You module and class AthleteList have the same name. Change:

import AthleteList


from AthleteList import AthleteList

This now means that you are importing the module object and will not be able to access any module methods you have in AthleteList

Line Break in XML?

just use &lt;br&gt; at the end of your lines.

Trouble setting up git with my GitHub Account error: could not lock config file

just do Run as need to run the program in the run as administrator mode in windows

Insert a string at a specific index

my_string          = "hello world";
my_insert          = " dear";
my_insert_location = 5;

my_string = my_string.split('');  
my_string.splice( my_insert_location , 0, my_insert );
my_string = my_string.join('');

Get data from file input in JQuery

input element, of type file

<input id="fileInput" type="file" />

On your input change use the FileReader object and read your input file property:

$('#fileInput').on('change', function () {
    var fileReader = new FileReader();
    fileReader.onload = function () {
      var data = fileReader.result;  // data <-- in this var you have the file data in Base64 format

FileReader will load your file and in fileReader.result you have the file data in Base64 format (also the file content-type (MIME), text/plain, image/jpg, etc)

Spring Data JPA - "No Property Found for Type" Exception

this error happens if you try access un-exists property

my guess is that sorting is done by spring by property name and not by real column name. and the error indicates that, in "UserBoard" there is no property named "boardId".



How to assign an action for UIImageView object in Swift

You could actually just set the image of the UIButton to what you would normally put in a UIImageView. For example, where you would do:

myImageView.image = myUIImage

You could instead use:

myButton.setImage(myUIImage, forState: UIControlState.Normal)

So, here's what your code could look like:

override func viewDidLoad(){

  var myUIImage: UIImage //set the UIImage here
  myButton.setImage(myUIImage, forState: UIControlState.Normal)

@IBOutlet var myButton: UIButton!
@IBAction func buttonTap(sender: UIButton!){
  //handle the image tap

The great thing about using this method is that if you have to load the image from a database, you could set the title of the button before you set the image:

myButton.setTitle("Loading Image...", forState: UIControlState.Normal)

To tell your users that you are loading the image

What is the best way to extract the first word from a string in Java?

You can use String.split with a limit of 2.

    String s = "Hello World, I'm the rest.";
    String[] result = s.split(" ", 2);
    String first = result[0];
    String rest = result[1];
    System.out.println("First: " + first);
    System.out.println("Rest: " + rest);

    // prints =>
    // First: Hello
    // Rest: World, I'm the rest.

The page cannot be displayed because an internal server error has occurred on server

For those of you who hit this stackoverflow entry because it ranks high for the phrase:

The page cannot be displayed because an internal server error has occurred.

In my personal situation with this exact error message, I had turned on python 2.7 thinking I could use some python with my .NET API. I then had that exact error message when I attempted to deploy a vanilla version of the API or MVC from visual studio pro 2013. I was deploying to an azure cloud webapp.

Hope this helps anyone with my same experience. I didn't even think to turn off python until I found this suggestion.

Why binary_crossentropy and categorical_crossentropy give different performances for the same problem?

You are passing a target array of shape (x-dim, y-dim) while using as loss categorical_crossentropy. categorical_crossentropy expects targets to be binary matrices (1s and 0s) of shape (samples, classes). If your targets are integer classes, you can convert them to the expected format via:

from keras.utils import to_categorical
y_binary = to_categorical(y_int)

Alternatively, you can use the loss function sparse_categorical_crossentropy instead, which does expect integer targets.

model.compile(loss='sparse_categorical_crossentropy', optimizer='adam', metrics=['accuracy'])

Type datetime for input parameter in procedure

In this part of your SP:

IF @DateFirst <> '' and @DateLast <> ''
   set @FinalSQL  = @FinalSQL
       + '  or convert (Date,DateLog) >=     ''' + @DateFirst
       + ' and convert (Date,DateLog) <=''' + @DateLast  

you are trying to concatenate strings and datetimes.

As the datetime type has higher priority than varchar/nvarchar, the + operator, when it happens between a string and a datetime, is interpreted as addition, not as concatenation, and the engine then tries to convert your string parts (' or convert (Date,DateLog) >= ''' and others) to datetime or numeric values. And fails.

That doesn't happen if you omit the last two parameters when invoking the procedure, because the condition evaluates to false and the offending statement isn't executed.

To amend the situation, you need to add explicit casting of your datetime variables to strings:

set @FinalSQL  = @FinalSQL
    + '  or convert (Date,DateLog) >=     ''' + convert(date, @DateFirst)
    + ' and convert (Date,DateLog) <=''' + convert(date, @DateLast)

You'll also need to add closing single quotes:

set @FinalSQL  = @FinalSQL
    + '  or convert (Date,DateLog) >=     ''' + convert(date, @DateFirst) + ''''
    + ' and convert (Date,DateLog) <=''' + convert(date, @DateLast) + ''''

Fastest Way to Find Distance Between Two Lat/Long Points

Using mysql

SET @orig_lon = 1.027125;
SET @dest_lon = 1.027125;

SET @orig_lat = 2.398441;
SET @dest_lat = 2.398441;

SET @kmormiles = 6371;-- for distance in miles set to : 3956

SELECT @kmormiles * ACOS(LEAST(COS(RADIANS(@orig_lat)) * 
 COS(RADIANS(@dest_lat)) * COS(RADIANS(@orig_lon - @dest_lon)) + 
 SIN(RADIANS(@orig_lat)) * SIN(RADIANS(@dest_lat)),1.0)) as distance;




NOTE: LEAST is used to avoid null values as a comment suggested on

java.lang.IllegalArgumentException: View not attached to window manager

What worked for me most of the time is to verify whether the Activity is not finishing.

if (!mActivity.isFinishing()) {

Is there a reason for C#'s reuse of the variable in a foreach?

The compiler declares the variable in a way that makes it highly prone to an error that is often difficult to find and debug, while producing no perceivable benefits.

Your criticism is entirely justified.

I discuss this problem in detail here:

Closing over the loop variable considered harmful

Is there something you can do with foreach loops this way that you couldn't if they were compiled with an inner-scoped variable? or is this just an arbitrary choice that was made before anonymous methods and lambda expressions were available or common, and which hasn't been revised since then?

The latter. The C# 1.0 specification actually did not say whether the loop variable was inside or outside the loop body, as it made no observable difference. When closure semantics were introduced in C# 2.0, the choice was made to put the loop variable outside the loop, consistent with the "for" loop.

I think it is fair to say that all regret that decision. This is one of the worst "gotchas" in C#, and we are going to take the breaking change to fix it. In C# 5 the foreach loop variable will be logically inside the body of the loop, and therefore closures will get a fresh copy every time.

The for loop will not be changed, and the change will not be "back ported" to previous versions of C#. You should therefore continue to be careful when using this idiom.

Where can I find php.ini?

For SAPI: php-fpm

There is no need to create a file (it is not a good policy to leave it for the world to read anyway). On the command line:

php-fpm -i | more

Somewhere in its output, it will show this line:

Configuration File (php.ini) Path => /etc

Here is a more complete explanation:

Eclipse+Maven src/main/java not visible in src folder in Package Explorer

After creating the project go to properties --> build path --> configure build path --> order and export tab and check jre and maven dependencies. You will then have the folder.

AngularJS multiple filter with custom filter function

Try this:

<tr ng-repeat="player in players | filter:{id: player_id, name:player_name} | filter:ageFilter">

$scope.ageFilter = function (player) {
    return (player.age > $scope.min_age && player.age < $scope.max_age);

How get all values in a column using PHP?

How to put MySQL functions back into PHP 7
Step 1

First get the mysql extension source which was removed in March:

Step 2

Then edit your php.ini

Somewhere either in the “Extensions” section or “MySQL” section, simply add this line:

extension = /usr/local/lib/php/extensions/no-debug-non-zts-20141001/

Step 3

Restart PHP and mysql_* functions should now be working again.

Step 4

Turn off all deprecated warnings including them from mysql_*:

error_reporting(E_ALL ^ E_DEPRECATED);

Now Below Code Help You :

$result = mysql_query("SELECT names FROM Customers");
$Data= Array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) 
        $Data[] =  $row['names'];  

You can also get all values in column using mysql_fetch_assoc

$result = mysql_query("SELECT names FROM Customers");
    $Data= Array();
    while ($row = mysql_fetch_assoc($result)) 
            $Data[] =  $row['names'];  

This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used.




// Check connection
if (mysqli_connect_errno())
  echo "Failed to connect to MySQL: " . mysqli_connect_error();

$sql="SELECT Lastname,Age FROM Persons ORDER BY Lastname";

// Numeric array
printf ("%s (%s)\n",$row[0],$row[1]);

// Associative array
printf ("%s (%s)\n",$row["Lastname"],$row["Age"]);

// Free result set


Reading file from Workspace in Jenkins with Groovy script

As mentioned in a different post Read .txt file from workspace groovy script in Jenkins I was struggling to make it work for the pom modules for a file in the workspace, in the Extended Choice Parameter. Here is my solution with the printlns:

import groovy.util.XmlSlurper
import java.util.Map
import jenkins.*
import jenkins.model.*
import hudson.*
import hudson.model.*    

//get Jenkins instance
    def jenkins = Jenkins.instance
//get job Item
    def item = jenkins.getItemByFullName("The_JOB_NAME")
    println item
// get workspacePath for the job Item
    def workspacePath = jenkins.getWorkspaceFor (item)
    println workspacePath

    def file = new File(workspacePath.toString()+"\\pom.xml")
    def pomFile = new XmlSlurper().parse(file)
    def pomModules = pomFile.modules.children().join(",")
    return pomModules
} catch (Exception ex){
    println ex.message

How do you get the current time of day?

I think this code will solve your problem


How to count items in JSON data

You're close. A really simple solution is just to get the length from the 'run' objects returned. No need to bother with 'load' or 'loads':


Different between parseInt() and valueOf() in java?

Well, the API for Integer.valueOf(String) does indeed say that the String is interpreted exactly as if it were given to Integer.parseInt(String). However, valueOf(String) returns a new Integer() object whereas parseInt(String) returns a primitive int.

If you want to enjoy the potential caching benefits of Integer.valueOf(int), you could also use this eyesore:

Integer k = Integer.valueOf(Integer.parseInt("123"))

Now, if what you want is the object and not the primitive, then using valueOf(String) may be more attractive than making a new object out of parseInt(String) because the former is consistently present across Integer, Long, Double, etc.

How do you keep parents of floated elements from collapsing?

Although the code isn't perfectly semantic, I think it's more straightforward to have what I call a "clearing div" at the bottom of every container with floats in it. In fact, I've included the following style rule in my reset block for every project:

   clear: both;

If you're styling for IE6 (god help you), you might want to give this rule a 0px line-height and height as well.

IOPub data rate exceeded in Jupyter notebook (when viewing image)

Removing print statements can also fix the problem.

Apart from loading images, this error also happens when your code is printing continuously at a high rate, which is causing the error "IOPub data rate exceeded". E.g. if you have a print statement in a for loop somewhere that is being called over 1000 times.

Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled

I added @Component annotation from import org.springframework.stereotype.Component and the problem was solved.

How can I capture packets in Android?

It's probably worth mentioning that for http/https some people proxy their browser traffic through Burp/ZAP or another intercepting "attack proxy". A thread that covers options for this on Android devices can be found here:

Avoid line break between html elements

This is the real solution:

  <span class="inline-flag">
    <i class="flag-bfh-ES"></i> 
    <span>+34 666 66 66 66</span>


.inline-flag {
   position: relative;
   display: inline;
   line-height: 14px; /* play with this */

.inline-flag > i {
   position: absolute;
   display: block;
   top: -1px; /* play with this */

.inline-flag > span {
   margin-left: 18px; /* play with this */

Example, images which always before text:

enter image description here

How to redirect docker container logs to a single file?

docker logs -f <yourContainer> &> your.log &


  • -f (i.e.--follow): writes all existing logs and continues (follows) logging everything that comes next.
  • &> redirects both the standard output and standard error.
  • Likely you want to run that method in the background, thus the &.
  • You can separate output and stderr by: > output.log 2> error.log (instead of using &>).


I have checked the <%= csrf_meta_tags %> are present and clearing cookies in browser worked for me.

java.lang.NoSuchMethodError: org.apache.commons.codec.binary.Base64.encodeBase64String() in Java EE application

Simply create an object of Base64 and use it to encode or decode, when using org.apache.commons.codec.binary.Base64 library

To Encode

Base64 ed=new Base64();

String encoded=new String(ed.encode("Hello".getBytes()));

Replace "Hello" with the text to be encoded in String Format.

To Decode

Base64 ed=new Base64();

String decoded=new String(ed.decode(encoded.getBytes()));

Here encoded is the String variable to be decoded

How to iterate through a list of objects in C++

You're close.

std::list<Student>::iterator it;
for (it = data.begin(); it != data.end(); ++it){
    std::cout << it->name;

Note that you can define it inside the for loop:

for (std::list<Student>::iterator it = data.begin(); it != data.end(); ++it){
    std::cout << it->name;

And if you are using C++11 then you can use a range-based for loop instead:

for (auto const& i : data) {
    std::cout <<;

Here auto automatically deduces the correct type. You could have written Student const& i instead.

How to search JSON data in MySQL?

I think...

Search partial value:

SELECT id FROM table_name WHERE field_name REGEXP '"key_name":"([^"])*key_word([^"])*"';

Search exact word:

SELECT id FROM table_name WHERE field_name RLIKE '"key_name":"[[:<:]]key_word[[:>:]]"';

How to specify the actual x axis values to plot as x axis ticks in R

Hope this coding will helps you :)

plot(x,y,xaxt = 'n')





Counting how many times a certain char appears in a string before any other char appears

You could use the Count method

var count = mystring.Count(x => x == '$')

Use underscore inside Angular controllers

If you don't mind using lodash try out it wraps lodash completely so it is the only dependency and you don't need to load any other script files such as lodash.

Lodash is completely off of the window scope and no "hoping" that it's been loaded prior to your module.

How to fetch FetchType.LAZY associations with JPA and Hibernate in a Spring Controller

it can only be lazily loaded whilst within a transaction. So you could access the collection in your repository, which has a transaction - or what I normally do is a get with association, or set fetchmode to eager.

How do I get PHP errors to display?

If you have Xdebug installed you can override every setting by setting:

xdebug.force_display_errors = 1;
xdebug.force_error_reporting = -1;


Type: int, Default value: 0, Introduced in Xdebug >= 2.3 If this setting is set to 1 then errors will always be displayed, no matter what the setting of PHP's display_errors is.


Type: int, Default value: 0, Introduced in Xdebug >= 2.3 This setting is a bitmask, like error_reporting. This bitmask will be logically ORed with the bitmask represented by error_reporting to dermine which errors should be displayed. This setting can only be made in php.ini and allows you to force certain errors from being shown no matter what an application does with ini_set().

How to monitor Java memory usage?

I would say that the consultant is right in the theory, and you are right in practice. As the saying goes:

In theory, theory and practice are the same. In practice, they are not.

The Java spec says that System.gc suggests to call garbage collection. In practice, it just spawns a thread and runs right away on the Sun JVM.

Although in theory you could be messing up some finely tuned JVM implementation of garbage collection, unless you are writing generic code intended to be deployed on any JVM out there, don't worry about it. If it works for you, do it.

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

You can generate NPM dependency trees without the need of installing a dependency by using the command

npm list

This will generate a dependency tree for the project at the current directory and print it to the console.

You can get the dependency tree of a specific dependency like so:

npm list [dependency]

You can also set the maximum depth level by doing

npm list --depth=[depth]

Note that you can only view the dependency tree of a dependency that you have installed either globally, or locally to the NPM project.

How to call a JavaScript function, declared in <head>, in the body when I want to call it

You can call it like that:

<!DOCTYPE html>
<html lang="en">
        <script type="text/javascript">
            var person = { name: 'Joe Blow' };
            function myfunction() {
        <script type="text/javascript">

The result should be page with the only content: Joe Blow

Look here:

Best regards!

Unable to copy a file from obj\Debug to bin\Debug

for me it was the antivirus. Just add visual studio project or entire parent folder to Antivirus exclusion list or you can also add file extension as exclusion and this method worked for me in visual studio 2010/2012

MSOnline can't be imported on PowerShell (Connect-MsolService error)

Connects to both Office 365 and Exchange Online in one easy to use script.

REMINDER: You must have the following installed in order to manage Office 365 via PowerShell.

Microsoft Online Services Sign-in Assistant:

Azure AD Module for Windows PowerShell 32 bit - 64 bit -


Randomize numbers with jQuery?

Others have answered the question, but just for the fun of it, here is a visual dice throwing example, using the Math.random javascript method, a background image and some recursive timeouts.

How do I compile the asm generated by GCC?

If you have main.s file. you can generate object file by GCC and also as

# gcc -c main.s
# as main.s -o main.o

check this link, it will help you learn some binutils of GCC

curl : (1) Protocol https not supported or disabled in libcurl

I also faced this issue and after debugging the culprit was found. In my case it was the "space" character right before the https

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

Here's a utility method (ES5 compatible) which only maps non null values (hides the call to reduce):

function mapNonNull(arr, cb) {_x000D_
    return arr.reduce(function (accumulator, value, index, arr) {_x000D_
        var result =, value, index, arr);_x000D_
        if (result != null) {_x000D_
        return accumulator;_x000D_
    }, []);_x000D_
var result = mapNonNull(["a", "b", "c"], function (value) {_x000D_
    return value === "b" ? null : value; // exclude "b"_x000D_
console.log(result); // ["a", "c"]

Could not load type 'XXX.Global'

When you try to access the Microsoft Dynamics NAV Web client, you get the following error. Could not load type 'System.ServiceModel.Activation.HttpModule' from assembly 'System.ServiceModel, Version=, Culture=neutral, PublicKeyToken=b77a5c561934e089 This error can occur when there are multiple versions of the .NET Framework on the computer that is running IIS, and IIS was installed after .NET Framework 4.0 or before the Service Model in Windows Communication Foundation was registered.

For Windows 7 and Windows Server 2008, use the ASP.NET IIS Registration Tool (aspnet_regiis.exe,) to register the correct version of ASP.NET. For more information about the aspnet_regiis.exe, see ASP.NET IIS Registration Tool at Microsoft web site.

try this solution

"fatal: Not a git repository (or any of the parent directories)" from git status

If Existing Project Solution is planned to move on TSF in VS Code:

open Terminal and run following commands:

  1. Initialize git in that folder (root Directory)

    git init

  2. Add Git

    git add .

  3. Link your TSf/Git to that Project - {url} replace with your git address

    git remote add origin {url}

  4. Commit those Changes:

    git commit -m "initial commit"

  5. Push - I pushed code as version1 you can use any name for your branch

    git push origin HEAD:Version1

SQL Server 2008 R2 Express permissions -- cannot create database or modify users

Coming late to the party, but I found this fantastic step-by-step guide on getting control of your SQLExpress instance if you don't have your sa password. I used this process to not only reset my sa password, but I also added my domain account to all the available server roles. I can now create databases, alter logins, do bulk operations, backups/restores, etc using my normal login.

To summarize, you use SQL Server Configuration Manager to put your instance into single-user mode. This elevates you to sysadmin when you connect, allowing you the ability to set everything up.

Edit: I've copied the steps below - kudos to the original author of the link above.

  1. Log on to the computer as an Administrator (or Any user with administrator privileges)
  2. Open "SQL Server Configuration Manager"
  3. Click "SQL Server Services" on the left pane
  4. Stop "SQL Server" and "SQL Server Agent" instance on the right pane if it is running
  5. Run the SQL Express in single-user mode by right clicking on "SQL Server" instance -> Properties (on the right pane of SQL Server Configuration Manager).
  6. Click Advanced Tab, and look for "Startup Parameters". Change the "Startup Parameters" so that the new value will be -m; (without the <>) example: from: -dc:\Program Files\Microsoft SQL.............(til end of string) to: -m;-dc:\Program Files\Microsoft SQL.............(til end of string)
  7. Start the SQL Server
  8. Open your MS SQL Server Management Studio and log on to the SQL server with "Windows Authentication" as the authentication mode. Since we have the SQL Server running on single user mode, and you are logged on to the computer with Administrator privileges, you will have a "sysadmin" access to the database.
  9. Expand the "Security" node on MS SQL Server Management Studio on the left pane
  10. Expand the "Logins" node
  11. Double-click the 'sa' login
  12. Change the password by entering a complex password if "Enforce password policy" is ticked, otherwise, just enter any password.
  13. Make sure that "sa" Account is "enabled" by clicking on Status on the left pane. Set the radio box under "Login" to "Enabled"
  14. Click "OK"
  15. Back on the main window of MS SQL Server Management Studio, verify if SQL Server Authentication is used by right clicking on the top most node in the left pane (usually ".\SQLEXPRESS (SQL Server )") and choosing properties.
  16. Click "Security" in the left pane and ensure that "SQL Server and Windows Authentication mode" is the one selected under "Server authentication"
  17. Click "OK"
  18. Disconnect from MS SQL Server Management Studio
  19. Open "Sql Server Configuration Manager" again and stop the SQL Server instance.
  20. Right-click on SQL Server instance and click on "Advanced" tab. Again look for "Startup Parameters" and remove the "-m;" that you added earlier.
  21. Click "OK" and start the SQL Server Instance again
  22. You should now be able to log on as "sa" using the new password that you have set in step 12.

Is there any standard for JSON API response format?

Best Response for web apis that can easily understand by mobile developers.

This is for "Success" Response

   "ReturnMsg":"Successfull Transaction",

This is for "Error" Response

    "ReturnCode": "4",
    "ReturnMsg": "Invalid Username and Password",
    "ReturnValue": "",
    "Data": {}

Pipe to/from the clipboard in Bash script

From this thread, there is an option which does not require installing any gclip/xclip/xsel third-party software.

A perl script (since perl is usually always installed)

use Win32::Clipboard;
print Win32::Clipboard::GetText();

How do I expand the output display to see more columns of a pandas DataFrame?

Only using these 3 lines worked for me:

pd.set_option('display.max_columns', None)  
pd.set_option('display.expand_frame_repr', False)
pd.set_option('max_colwidth', -1)

Anaconda / Python 3.6.5 / pandas: 0.23.0 / Visual Studio Code 1.26

What is the difference between HTTP and REST?

Not quite...

REST was initially described in the context of HTTP, but is not limited to that protocol. RESTful architectures can be based on other Application Layer protocols if they already provide a rich and uniform vocabulary for applications based on the transfer of meaningful representational state. RESTful applications maximise the use of the pre-existing, well-defined interface and other built-in capabilities provided by the chosen network protocol, and minimise the addition of new application-specific features on top of it.

(Simple Object Access Protocol) The standard for web services messages. Based on XML, SOAP defines an envelope format and various rules for describing its contents. Seen (with WSDL and UDDI) as one of the three foundation standards of web services, it is the preferred protocol for exchanging web services, but by no means the only one; proponents of REST say that it adds unnecessary complexity.

Bootstrap button drop-down inside responsive table not visible because of scroll

This solution worked great for me :

@media (max-width: 767px) {
    .table-responsive .dropdown-menu {
        position: static !important;
@media (min-width: 768px) {
    .table-responsive {
        overflow: visible;

More detail:

How to get featured image of a product in woocommerce

In WC 3.0+ versions the image can get by below code.

$image_url = wp_get_attachment_image_src( get_post_thumbnail_id( $item->get_product_id() ), 'single-post-thumbnail' );
echo $image_url[0]

Java NIO: What does IOException: Broken pipe mean?

You should assume the socket was closed on the other end. Wrap your code with a try catch block for IOException.

You can use isConnected() to determine if the SocketChannel is connected or not, but that might change before your write() invocation finishes. Try calling it in your catch block to see if in fact this is why you are getting the IOException.

How to get all of the immediate subdirectories in Python

I have to mention the library, which I use very often.

Fetching the immediate subdirectories become as simple as that:


The full working example is:

from path import Path

my_directory = Path("path/to/my/directory")

subdirs = my_directory.dirs()

NB: my_directory still can be manipulated as a string, since Path is a subclass of string, but providing a bunch of useful methods for manipulating paths

Could not create SSL/TLS secure channel, despite setting ServerCertificateValidationCallback

In my case TLS1_2 was enabled both on client and server but the server was using MD5 while client disabled it. So, test both client and server on or test using openssl/s_client to see what's happening. Also, check the selected cipher using Wireshark.

I want to get the type of a variable at runtime

i have tested that and it worked

val x = 9
def printType[T](x:T) :Unit = {println(x.getClass.toString())}

How to sort an array of objects in Java?

Arrays.sort(yourList,new Comparator<YourObject>() {

    public int compare(YourObjecto1, YourObjecto2) {
        return compare(o1.getYourColumn(), o2.getYourColumn());

curl: (35) error:1408F10B:SSL routines:ssl3_get_record:wrong version number

* Uses proxy env variable http_proxy == ''   

The https:// is wrong, it should be http://. The proxy itself should be accessed by HTTP and not HTTPS even though the target URL is HTTPS. The proxy will nevertheless properly handle HTTPS connection and keep the end-to-end encryption. See HTTP CONNECT method for details how this is done.

Setting table row height

I found the best answer for my purposes was to use:

.topics tr { 
    overflow: hidden;
    height: 14px;
    white-space: nowrap;

The white-space: nowrap is important as it prevents your row's cells from breaking across multiple lines.

I personally like to add text-overflow: ellipsis to my th and td elements to make the overflowing text look nicer by adding the trailing fullstops, for example Too long gets dots...

What's the difference between getRequestURI and getPathInfo methods in HttpServletRequest?

I will put a small comparison table here (just to have it somewhere):

Servlet is mapped as /test%3F/* and the application is deployed under /app.


Method              URL-Decoded Result           
getContextPath()        no      /app
getLocalName()                  30thh.loc
getLocalPort()                  8480
getMethod()                     GET
getPathInfo()           yes     /a?+b
getProtocol()                   HTTP/1.1
getQueryString()        no      p+1=c+d&p+2=e+f
getRequestedSessionId() no      S%3F+ID
getRequestURI()         no      /app/test%3F/a%3F+b;jsessionid=S+ID
getRequestURL()         no      http://30thh.loc:8480/app/test%3F/a%3F+b;jsessionid=S+ID
getScheme()                     http
getServerName()                 30thh.loc
getServerPort()                 8480
getServletPath()        yes     /test?
getParameterNames()     yes     [p 2, p 1]
getParameter("p 1")     yes     c d

In the example above the server is running on the localhost:8480 and the name 30thh.loc was put into OS hosts file.


  • "+" is handled as space only in the query string

  • Anchor "#a" is not transferred to the server. Only the browser can work with it.

  • If the url-pattern in the servlet mapping does not end with * (for example /test or *.jsp), getPathInfo() returns null.

If Spring MVC is used

  • Method getPathInfo() returns null.

  • Method getServletPath() returns the part between the context path and the session ID. In the example above the value would be /test?/a?+b

  • Be careful with URL encoded parts of @RequestMapping and @RequestParam in Spring. It is buggy (current version 3.2.4) and is usually not working as expected.

How to upgrade scikit-learn package in anaconda

I would suggest using conda. Conda is an anconda specific package manager. If you want to know more about conda, read the conda docs.

Using conda in the command line, the command below would install scipy 0.17.

conda install scipy=0.17.0

How to set session timeout in web.config

If you are using MVC, you put this in the web.config file in the Root directory of the web application, not the web.config in the Views directory. It also needs to be IN the system.web node, not under like George2 stated in his question: "I wrote under system.web section in the web.config"

The timeout parameter value represents minutes.

There are other attributes that can be set in the sessionState element. You can find information here: sessionState

      <sessionState timeout="20"></sessionState>

You can then catch the begining of a new session in the Global.asax file by adding the following method:

void Session_Start(object sender, EventArgs e)
    if (Session.IsNewSession)
        //do things that need to happen
        //when a new session starts.

How to get the first non-null value in Java?

With Guava you can do:


which doesn't throw NPE if both a and b are null.

EDIT: I was wrong, it does throw NPE. The correct way as commented by Michal Cizmazia is:


How to make a JFrame button open another JFrame class in Netbeans?

new SecondForm().setVisible(true);

You can either use setVisible(false) or dispose() method to disappear current form.

Have nginx access_log and error_log log to STDOUT and STDERR of master process

Edit: it seems nginx now supports error_log stderr; as mentioned in Anon's answer.

You can send the logs to /dev/stdout. In nginx.conf:

daemon off;
error_log /dev/stdout info;

http {
  access_log /dev/stdout;

edit: May need to run ln -sf /proc/self/fd /dev/ if using running certain docker containers, then use /dev/fd/1 or /dev/fd/2

Print an integer in binary format in Java

check out this logic can convert a number to any base

public static void toBase(int number, int base) {
    String binary = "";
    int temp = number/2+1;
    for (int j = 0; j < temp ; j++) {
        try {
            binary += "" + number % base;

            number /= base;
        } catch (Exception e) {
    for (int j = binary.length() - 1; j >= 0; j--) {


StringBuilder binary = new StringBuilder();
int n=15;
while (n>0) {

How to copy selected lines to clipboard in vim

If you're on Linux and are using a VIm version 7.3.74 or higher (the version that gets installed in Ubuntu 11.10 onwards satisfies this), you can do

set clipboard=unnamedplus

which will place yanked text into the global clipboard, and allow you to paste from the global clipboard, without having to use any special registers. Unlike ldigas's solution, this will also work on non-gui versions of VIm.

Calling a javascript function recursively

Here's one very simple example:

var counter = 0;

function getSlug(tokens) {
    var slug = '';

    if (!!tokens.length) {
        slug = tokens.shift();
        slug = slug.toLowerCase();
        slug += getSlug(tokens);

        counter += 1;
        console.log('THE SLUG ELEMENT IS: %s, counter is: %s', slug, counter);

    return slug;

var mySlug = getSlug(['This', 'Is', 'My', 'Slug']);
console.log('THE SLUG IS: %s', mySlug);

Notice that the counter counts "backwards" in regards to what slug's value is. This is because of the position at which we are logging these values, as the function recurs before logging -- so, we essentially keep nesting deeper and deeper into the call-stack before logging takes place.

Once the recursion meets the final call-stack item, it trampolines "out" of the function calls, whereas, the first increment of counter occurs inside of the last nested call.

I know this is not a "fix" on the Questioner's code, but given the title I thought I'd generically exemplify Recursion for a better understanding of recursion, outright.

How do I write a Windows batch script to copy the newest file from a directory?

The accepted answer gives an example of using the newest file in a command and then exiting. If you need to do this in a bat file with other complex operations you can use the following to store the file name of the newest file in a variable:

FOR /F "delims=|" %%I IN ('DIR "*.*" /B /O:D') DO SET NewestFile=%%I

Now you can reference %NewestFile% throughout the rest of your bat file.

For example here is what we use to get the latest version of a database .bak file from a directory, copy it to a server, and then restore the db:

SET DatabaseBackupPath=\\virtualserver1\Database Backups

echo Restore WebServer Database
FOR /F "delims=|" %%I IN ('DIR "%DatabaseBackupPath%\WebServer\*.bak" /B /O:D') DO SET NewestFile=%%I
copy "%DatabaseBackupPath%\WebServer\%NewestFile%" "D:\"

sqlcmd -U <username> -P <password> -d master -Q ^
"RESTORE DATABASE [ExampleDatabaseName] ^
FROM  DISK = N'D:\%NewestFile%' ^
WITH  FILE = 1,  ^
MOVE N'Example_CS' TO N'C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Example.mdf',  ^
MOVE N'Example_CS_log' TO N'C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Example_1.LDF',  ^

What does `return` keyword mean inside `forEach` function?

The return exits the current function, but the iterations keeps on, so you get the "next" item that skips the if and alerts the 4...

If you need to stop the looping, you should just use a plain for loop like so:

$('button').click(function () {
   var arr = [1, 2, 3, 4, 5];
   for(var i = 0; i < arr.length; i++) {
     var n = arr[i]; 
     if (n == 3) {

You can read more about js break & continue here:

Why are C++ inline functions in the header?

The definition of an inline function doesn't have to be in a header file but, because of the one definition rule (ODR) for inline functions, an identical definition for the function must exist in every translation unit that uses it.

The easiest way to achieve this is by putting the definition in a header file.

If you want to put the definition of a function in a single source file then you shouldn't declare it inline. A function not declared inline does not mean that the compiler cannot inline the function.

Whether you should declare a function inline or not is usually a choice that you should make based on which version of the one definition rules it makes most sense for you to follow; adding inline and then being restricted by the subsequent constraints makes little sense.

bash shell nested for loop

The question does not contain a nested loop, just a single loop. But THIS nested version works, too:

# for i in c d; do for j in a b; do echo $i $j; done; done
c a
c b
d a
d b

Checking if a variable is an integer in PHP

When i start reading it i did notice that you guys forgot about abvious think like type of to check if we have int, string, null or Boolean. So i think gettype() should be as 1st answer. Explain: So if we have $test = [1,w2,3.45,sasd]; we start test it

foreach ($test as $value) {
        $check = gettype($value);
        if($check == 'integer'){
            echo "This var is int\r\n";
        if($check != 'integer'){
            echo "This var is {$check}\r\n";

And output:

> This var is int 
> This var is string 
> This var is double 
> This var is string

I think this is easiest way to check if our var is int, string, double or Boolean.

How can I change all input values to uppercase using Jquery?

use css :

input.upper { text-transform: uppercase; }

probably best to use the style, and convert serverside. There's also a jQuery plugin to force uppercase:

Overlay normal curve to histogram in R

This is an implementation of aforementioned StanLe's anwer, also fixing the case where his answer would produce no curve when using densities.

This replaces the existing but hidden hist.default() function, to only add the normalcurve parameter (which defaults to TRUE).

The first three lines are to support roxygen2 for package building.

#' @noRd
#' @exportMethod hist.default
#' @export
hist.default <- function(x,
                         breaks = "Sturges",
                         freq = NULL,
                         include.lowest = TRUE,
                         normalcurve = TRUE,
                         right = TRUE,
                         density = NULL,
                         angle = 45,
                         col = NULL,
                         border = NULL,
                         main = paste("Histogram of", xname),
                         ylim = NULL,
                         xlab = xname,
                         ylab = NULL,
                         axes = TRUE,
                         plot = TRUE,
                         labels = FALSE,
                         warn.unused = TRUE,
                         ...)  {

  xname <- paste(deparse(substitute(x), 500), collapse = "\n")

    h <- graphics::hist.default(
      x = x,
      breaks = breaks,
      freq = freq,
      include.lowest = include.lowest,
      right = right,
      density = density,
      angle = angle,
      col = col,
      border = border,
      main = main,
      ylim = ylim,
      xlab = xlab,
      ylab = ylab,
      axes = axes,
      plot = plot,
      labels = labels,
      warn.unused = warn.unused,

  if (normalcurve == TRUE & plot == TRUE) {
    x <- x[!]
    xfit <- seq(min(x), max(x), length = 40)
    yfit <- dnorm(xfit, mean = mean(x), sd = sd(x))
    if (isTRUE(freq) | (is.null(freq) & is.null(density))) {
      yfit <- yfit * diff(h$mids[1:2]) * length(x)
    lines(xfit, yfit, col = "black", lwd = 2)

  if (plot == TRUE) {
  } else {

Quick example:


enter image description here

For dates it's bit different. For reference:

#' @noRd
#' @exportMethod hist.Date
#' @export
hist.Date <- function(x,
                      breaks = "months",
                      format = "%b",
                      normalcurve = TRUE,
                      xlab = xname,
                      plot = TRUE,
                      freq = NULL,
                      density = NULL,
                      start.on.monday = TRUE,
                      right = TRUE,
                      ...)  {

  xname <- paste(deparse(substitute(x), 500), collapse = "\n")

    h <- graphics:::hist.Date(
      x = x,
      breaks = breaks,
      format = format,
      freq = freq,
      density = density,
      start.on.monday = start.on.monday,
      right = right,
      xlab = xlab,
      plot = plot,

  if (normalcurve == TRUE & plot == TRUE) {
    x <- x[!]
    xfit <- seq(min(x), max(x), length = 40)
    yfit <- dnorm(xfit, mean = mean(x), sd = sd(x))
    if (isTRUE(freq) | (is.null(freq) & is.null(density))) {
      yfit <- as.double(yfit) * diff(h$mids[1:2]) * length(x)
    lines(xfit, yfit, col = "black", lwd = 2)

  if (plot == TRUE) {
  } else {

Exponentiation in Python - should I prefer ** operator instead of math.pow and math.sqrt?

math.sqrt is the C implementation of square root and is therefore different from using the ** operator which implements Python's built-in pow function. Thus, using math.sqrt actually gives a different answer than using the ** operator and there is indeed a computational reason to prefer numpy or math module implementation over the built-in. Specifically the sqrt functions are probably implemented in the most efficient way possible whereas ** operates over a large number of bases and exponents and is probably unoptimized for the specific case of square root. On the other hand, the built-in pow function handles a few extra cases like "complex numbers, unbounded integer powers, and modular exponentiation".

See this Stack Overflow question for more information on the difference between ** and math.sqrt.

In terms of which is more "Pythonic", I think we need to discuss the very definition of that word. From the official Python glossary, it states that a piece of code or idea is Pythonic if it "closely follows the most common idioms of the Python language, rather than implementing code using concepts common to other languages." In every single other language I can think of, there is some math module with basic square root functions. However there are languages that lack a power operator like ** e.g. C++. So ** is probably more Pythonic, but whether or not it's objectively better depends on the use case.

How to check if a value exists in an object using JavaScript

You can try this:

function checkIfExistingValue(obj, key, value) {
    return obj.hasOwnProperty(key) && obj[key] === value;
var test = [{name : "jack", sex: F}, {name: "joe", sex: M}]
console.log(test.some(function(person) { return checkIfExistingValue(person, "name", "jack"); }));

How to escape JSON string?

I have used following code to escape the string value for json. You need to add your '"' to the output of the following code:

public static string EscapeStringValue(string value)
    const char BACK_SLASH = '\\';
    const char SLASH = '/';
    const char DBL_QUOTE = '"';

    var output = new StringBuilder(value.Length);
    foreach (char c in value)
        switch (c)
            case SLASH:
                output.AppendFormat("{0}{1}", BACK_SLASH, SLASH);

            case BACK_SLASH:
                output.AppendFormat("{0}{0}", BACK_SLASH);

            case DBL_QUOTE:


    return output.ToString();

How do I reformat HTML code using Sublime Text 2?

I recommend this plugin: HTML/CSS/JS Prettify, It really works.

After the installation, just select the code and press Ctrl+Shift+H.


How to convert string to date to string in Swift iOS?

First, you need to convert your string to NSDate with its format. Then, you change the dateFormatter to your simple format and convert it back to a String.

Swift 3

let dateString = "Thu, 22 Oct 2015 07:45:17 +0000"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EEE, dd MMM yyyy hh:mm:ss +zzzz"
dateFormatter.locale = Locale.init(identifier: "en_GB")

let dateObj = dateString)

dateFormatter.dateFormat = "MM-dd-yyyy"
print("Dateobj: \(dateFormatter.string(from: dateObj!))")

The printed result is: Dateobj: 10-22-2015

ERROR 1452: Cannot add or update a child row: a foreign key constraint fails

I know this thread is long already but when I ran a laravel seeding for category tables it created some strange ids which were 1, 11, 21, 31 which caused me error as I tried to reference it in another another table using ids like 1, 2, 3 ... the whole day until I checked the database up manually,

So sometimes go look up the database table to ensure the foreign data actually exist properly.


top -c command in linux to filter processes listed based on processname

You can add filters to top while it is running, just press the o key and then type in a filter expression. For example, to monitor all java processes use the filter expression COMMAND=java. You can add multiple filters by pressing the key again, you can filter by user with the u key, and you can clear all filters with the = key.

What is the cause for "angular is not defined"

You have not placed the script tags for angular js

you can do so by using cdn or downloading the angularjs for your project and then referencing it

after this you have to add your own java script in your case main.js

that should do

How to convert Double to int directly?

int average_in_int = ( (Double) Math.ceil( sum/count ) ).intValue();

Maven Jacoco Configuration - Exclude classes/packages from report not working

Your XML is slightly wrong, you need to add any class exclusions within an excludes parent field, so your above configuration should look like the following as per the Jacoco docs


The values of the exclude fields should be class paths (not package names) of the compiled classes relative to the directory target/classes/ using the standard wildcard syntax

*   Match zero or more characters
**  Match zero or more directories
?   Match a single character

You may also exclude a package and all of its children/subpackages this way:


This will exclude every class in some.package, as well as any children. For example, some.package.child wouldn't be included in the reports either.

I have tested and my report goal reports on a reduced number of classes using the above.

If you are then pushing this report into Sonar, you will then need to tell Sonar to exclude these classes in the display which can be done in the Sonar settings

Settings > General Settings > Exclusions > Code Coverage

Sonar Docs explains it a bit more

Running your command above

mvn clean verify

Will show the classes have been excluded

No exclusions

[INFO] --- jacoco-maven-plugin: (post-test) @ ** ---
[INFO] Analyzed bundle '**' with 37 classes

With exclusions

[INFO] --- jacoco-maven-plugin: (post-test) @ ** ---
[INFO] Analyzed bundle '**' with 34 classes

Hope this helps

How to send password securely over HTTP?

Using HTTP with SSL will make your life much easier and you can rest at ease very smart people (smarter than me at least!) have scrutinized this method of confidential communication for years.

How to save the output of a console.log(object) to a file?

In case you have an object logged:

  • Right click on the object in console and click Store as a global variable
  • the output will be something like temp1
  • type in console copy(temp1)
  • paste to your favorite text editor

Mockito matcher and array of primitives

I would try any(byte[].class)

MS Access DB Engine (32-bit) with Office 64-bit

Even tried all suggestions, in my case (Office x64 - Visual Studio 2017), the only way to have both access engines on a Office 64x installation so you can use it on Visual Studio and using a 2016+ version of Office, is to install the 2010 version of the Engine.

First install the x64 from this page

and then the x86 version from this one

as from this blog:

PermissionError: [Errno 13] in python

When doing;

a_file = open('E:\Python Win7-64-AMD 3.3\Test', encoding='utf-8')'re trying to open a directory as a file, which may (and on most non UNIX file systems will) fail.

Your other example though;

a_file = open('E:\Python Win7-64-AMD 3.3\Test\a.txt', encoding='utf-8')

should work well if you just have the permission on a.txt. You may want to use a raw (r-prefixed) string though, to make sure your path does not contain any escape characters like \n that will be translated to special characters.

a_file = open(r'E:\Python Win7-64-AMD 3.3\Test\a.txt', encoding='utf-8')

How can I edit a view using phpMyAdmin 3.2.4?

To expand one what CheeseConQueso is saying, here are the entire steps to update a view using PHPMyAdmin:

  1. Run the following query: SHOW CREATE VIEW your_view_name
  2. Expand the options and choose Full Texts
  3. Press Go
  4. Copy entire contents of the Create View column.
  5. Make changes to the query in the editor of your choice
  6. Run the query directly (without the CREATE VIEW... syntax) to make sure it runs as you expect it to.
  7. Once you're satisfied, click on your view in the list on the left to browse its data and then scroll all the way to the bottom where you'll see a CREATE VIEW link. Click that.
  8. Place a check in the OR REPLACE field.
  9. In the VIEW name put the name of the view you are going to update.
  10. In the AS field put the contents of the query that you ran while testing (without the CREATE VIEW... syntax).
  11. Press Go

I hope that helps somebody. Special thanks to CheesConQueso for his/her insightful answer.

JavaScript error (Uncaught SyntaxError: Unexpected end of input) is helpful to indent your minified JS code.

Also, with Google Chrome you can use "pretty print". See the example screenshot below showing jquery.min.js from Stack Overflow nicely indented right from my browser :)

enter image description here

Ignore mapping one property with Automapper

Could use IgnoreAttribute on the property which needs to be ignored

Set a form's action attribute when submitting?

You can also set onSubmit attribute's value in form tag. You can set its value using Javascript.

Something like this:

<form id="whatever" name="whatever" onSubmit="return xyz();">
    Here is your entire form
    <input type="submit">

<script type=text/javascript>
function xyz() {
  document.getElementById('whatever').action = 'whatever you want'

Remember that onSubmit has higher priority than action attribute. So whenever you specify onSubmit value, that operation will be performed first and then the form will move to action.

Expand/collapse section in UITableView in iOS

You have to make your own custom header row and put that as the first row of each section. Subclassing the UITableView or the headers that are already there will be a pain. Based on the way they work now, I am not sure you can easily get actions out of them. You could set up a cell to LOOK like a header, and setup the tableView:didSelectRowAtIndexPath to manually expand or collapse the section it is in.

I'd store an array of booleans corresponding the the "expended" value of each of your sections. Then you could have the tableView:didSelectRowAtIndexPath on each of your custom header rows toggle this value and then reload that specific section.

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        ///it's the first row of any section so it would be your custom section header

        ///put in your code to toggle your boolean value here
        mybooleans[indexPath.section] = !mybooleans[indexPath.section];

        ///reload this section
        [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationFade];

Then set numberOfRowsInSection to check the mybooleans value and return 1 if the section isn't expanded, or 1+ the number of items in the section if it is expanded.

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    if (mybooleans[section]) {
        ///we want the number of people plus the header cell
        return [self numberOfPeopleInGroup:section] + 1;
    } else {
        ///we just want the header cell
        return 1;

Also, you will need to update cellForRowAtIndexPath to return a custom header cell for the first row in any section.

How to format a date using ng-model?

Since you have used datepicker as a class I'm assuming you are using a Jquery datepicker or something similar.

There is a way to do what you are intending without using moment.js at all, purely using just datepicker and angularjs directives.

I've given a example here in this Fiddle

Excerpts from the fiddle here:

  1. Datepicker has a different format and angularjs format is different, need to find the appropriate match so that date is preselected in the control and is also populated in the input field while the ng-model is bound. The below format is equivalent to 'mediumDate' format of AngularJS.

                 dateFormat: 'M d, yy'
  2. The date input directive needs to have an interim string variable to represent the human readable form of date.

  3. Refreshing across different sections of page should happen via events, like $broadcast and $on.

  4. Using filter to represent date in human readable form is possible in ng-model as well but with a temporary model variable.

    $scope.dateValString = $filter('date')($scope.dateVal, 'mediumDate');

Javascript - validation, numbers only

No need for the long code for number input restriction just try this code.

It also accepts valid int & float both values.

Javascript Approach

onload =function(){ _x000D_
  var ele = document.querySelectorAll('.number-only')[0];_x000D_
  ele.onkeypress = function(e) {_x000D_
        return false;_x000D_
  ele.onpaste = function(e){_x000D_
<p> Input box that accepts only valid int and float values.</p>_x000D_
<input class="number-only" type=text />

jQuery Approach

  $('.number-only').keypress(function(e) {_x000D_
 if(isNaN(this.value+""+String.fromCharCode(e.charCode))) return false;_x000D_
  .on("cut copy paste",function(e){_x000D_
<script src=""></script>_x000D_
<p> Input box that accepts only valid int and float values.</p>_x000D_
<input class="number-only" type=text />

The above answers are for most common use case - validating input as a number.

But to allow few special cases like negative numbers & showing the invalid keystrokes to user before removing it, so below is the code snippet for such special use cases.

  $('.number-only').keyup(function(e) {_x000D_
            this.value = this.value.split('').reverse().join('').replace(/[\D]/i,'')_x000D_
    .on("cut copy paste",function(e){_x000D_
<script src=""></script>_x000D_
<p> Input box that accepts only valid int and float values.</p>_x000D_
<input class="number-only" type=text />

What are type hints in Python 3.5?

The newly released PyCharm 5 supports type hinting. In their blog post about it (see Python 3.5 type hinting in PyCharm 5) they offer a great explanation of what type hints are and aren't along with several examples and illustrations for how to use them in your code.

Additionally, it is supported in Python 2.7, as explained in this comment:

PyCharm supports the typing module from PyPI for Python 2.7, Python 3.2-3.4. For 2.7 you have to put type hints in *.pyi stub files since function annotations were added in Python 3.0.

How to compile makefile using MinGW?

First check if mingw32-make is installed on your system. Use mingw32-make.exe command in windows terminal or cmd to check, else install the package mingw32-make-bin.

then go to bin directory default ( C:\MinGW\bin) create new file make.bat

@echo off
"%~dp0mingw32-make.exe" %*

add the above content and save it

set the env variable in powershell


then compile the file

make hello

where hello.c is the name of source code

PHP json_encode encoding numbers as strings

For sake of completeness (as I can't add comments yet), let me also add this detail as another answer:

(Edit: To be read after realizing that the source data (i.e. in the OP's case, database result set) could be the problem (by returning numeric columns as strings), and json_encode() in fact was not the source of the problem)

Manual pages of both "mysql_fetch_array":

Returns an array of strings that corresponds to the fetched row,

... and "mysql_ fetch_ row":

Returns an numerical array of strings that corresponds to the fetched row

clearly states that; the entries in the returned array will be strings.

(I was using the DB class in phpBB2 (yes I know, it's obsolete!), and "sql_fetchrow()" method of that class uses "mysql_fetch_array()")

Not realizing that, I also ended up finding this question, and understanding the problem! :)

As Pascal Martin stated above in his follow-up comments, I believe a solution that takes care of the "incorrect type" problem at the source (i.e. by using the "mysql_field_type()" function and doing the casting right after fetch, (or other fetch methods like "object"?)) would be the better in general.

How to get my project path?

Your program has no knowledge of where your VS project is, so see get path for my .exe and go ../.. to get your project's path.

What is a "callable"?

A callable is an object allows you to use round parenthesis ( ) and eventually pass some parameters, just like functions.

Every time you define a function python creates a callable object. In example, you could define the function func in these ways (it's the same):

class a(object):
    def __call__(self, *args):
        print 'Hello'

func = a()

# or ... 
def func(*args):
    print 'Hello'

You could use this method instead of methods like doit or run, I think it's just more clear to see obj() than obj.doit()

How do I run a program with commandline arguments using GDB within a Bash script?

gdb -ex=r --args myprogram arg1 arg2

-ex=r is short for -ex=run and tells gdb to run your program immediately, rather than wait for you to type "run" at the prompt. Then --args says that everything that follows is the command and arguments, just as you'd normally type them at the commandline prompt.

Failed to resolve:

enter image description hereI was facing the same issue but I switched 26.0.0-beta1 dependencies to 26.1.0 and it's working now.

What are the differences between git remote prune, git prune, git fetch --prune, etc

In the event that anyone would be interested. Here's a quick shell script that will remove all local branches that aren't tracked remotely. A word of caution: This will get rid of any branch that isn't tracked remotely regardless of whether it was merged or not.

If you guys see any issues with this please let me know and I'll fix it (etc. etc.)

Save it in a file called git-rm-ntb (call it whatever) on PATH and run:

git-rm-ntb <remote1:optional> <remote2:optional> ...

  if [ -z "$REMOTES" ]; then
    REMOTES=$(git remote);
  REMOTES=$(echo "$REMOTES" | xargs -n1 echo)
  while read REMOTE; do
    CURRBRANCHES=($(git ls-remote $REMOTE | awk '{print $2}' | grep 'refs/heads/' | sed 's:refs/heads/::'))
  done < <(echo "$REMOTES" )
  [[ $RBRANCHES ]] || exit
  LBRANCHES=($(git branch | sed 's:\*::' | awk '{print $1}'))
  for i in "${LBRANCHES[@]}"; do
    for j in "${RBRANCHES[@]}"; do
      [[ $i == $j ]] && { skip=1; echo -e "\033[32m Keeping $i \033[0m"; break; }
    [[ -n $skip ]] || { echo -e "\033[31m $(git branch -D $i) \033[0m"; }

clean $@

SQL to Entity Framework Count Group-By

A useful extension is to collect the results in a Dictionary for fast lookup (e.g. in a loop):

var resultDict = _dbContext.Projects
    .Where(p => p.Status == ProjectStatus.Active)
    .GroupBy(f => f.Country)
    .Select(g => new { country = g.Key, count = g.Count() })
    .ToDictionary(k =>, i => i.count);

Originally found here: