Programs & Examples On #Pimpl idiom

The Pimpl idiom, also known as the compilation firewall or Cheshire Cat technique, is a "private implementation" technique useful in C++ and other similar statically compiled languages.

How to add 20 minutes to a current date?

Just add 20 minutes in milliseconds to your date:

  var currentDate = new Date();

  currentDate.setTime(currentDate.getTime() + 20*60*1000);

How do I scroll to an element using JavaScript?

A method i often use to scroll a container to its contents.

/**
@param {HTMLElement} container : element scrolled.
@param {HTMLElement} target : element where to scroll.
@param {number} [offset] : scroll back by offset
*/
var scrollAt=function(container,target,offset){
    if(container.contains(target)){
        var ofs=[0,0];
        var tmp=target;
        while (tmp!==container) {
            ofs[0]+=tmp.offsetWidth;
            ofs[1]+=tmp.offsetHeight;
            tmp=tmp.parentNode;
        }
        container.scrollTop = Math.max(0,ofs[1]-(typeof(offset)==='number'?offset:0));
    }else{
        throw('scrollAt Error: target not found in container');
    }
};

if your whish to override globally, you could also do :

HTMLElement.prototype.scrollAt=function(target,offset){
    if(this.contains(target)){
        var ofs=[0,0];
        var tmp=target;
        while (tmp!==this) {
            ofs[0]+=tmp.offsetWidth;
            ofs[1]+=tmp.offsetHeight;
            tmp=tmp.parentNode;
        }
        container.scrollTop = Math.max(0,ofs[1]-(typeof(offset)==='number'?offset:0));
    }else{
        throw('scrollAt Error: target not found in container');
    }
};

Official reasons for "Software caused connection abort: socket write error"

I have seen this most often when a corporate firewall on a workstation/laptop gets in the way, it kills the connection.

eg. I have a server process and a client process on the same machine. The server is listening on all interfaces (0.0.0.0) and the client attempts a connection to the public/home interface (note not the loopback interface 127.0.0.1).

If the machine is has its network disconnected (eg wifi turned off) then the connection is formed. If the machine is connected to the corporate network (directly or vpn) then the connection is formed.

However, if the machine is connected to a public wifi (or home network) then the firewall kicks in an kills the connection. In this situation connecting the client to the loopback interface works fine, just not to the home/public interface.

Hope this helps.

When should I use File.separator and when File.pathSeparator?

You use separator when you are building a file path. So in unix the separator is /. So if you wanted to build the unix path /var/temp you would do it like this:

String path = File.separator + "var"+ File.separator + "temp"

You use the pathSeparator when you are dealing with a list of files like in a classpath. For example, if your app took a list of jars as argument the standard way to format that list on unix is: /path/to/jar1.jar:/path/to/jar2.jar:/path/to/jar3.jar

So given a list of files you would do something like this:

String listOfFiles = ...
String[] filePaths = listOfFiles.split(File.pathSeparator);

How do I tell whether my IE is 64-bit? (For that matter, Java too?)

Rob Heiser suggested checking out your java version by using 'java -version'.

That will identify the Java version that will be commonly found and used. Doing dev work, you can often have more than one version installed (I currently have 2 JREs - 6 and 7 - and may soon have 8).

http://www.coderanch.com/t/453224/java/java/java-version-work-setting-path

java -version will look for java.exe in the System32 directory in Windows. That's where a JRE will install it.

I'm assuming that IE either simply looks for java and that automatically starts checking in System32 or it'll use the path and hit whichever java.exe comes first in your path (if you tamper with the path to point to another JRE).

Also from what SLaks said, I would disagree with one thing. There is likely slightly better performance out of 64-it IE in 64-bit environments. So there is some reason for using it.

IF... OR IF... in a windows batch file

A much faster alternative I usually use is as follows, as I can "or" an arbitrary number of conditions that can fit in variable space

@(
  Echo off
  Set "_Match= 1 2 3 "
)

Set /a "var=3"

Echo:%_Match%|Find " %var% ">nul || (
  REM Code for a false condition goes here
) && (
  REM code for a true condition goes here.
)

How do I clear the std::queue efficiently?

A common idiom for clearing standard containers is swapping with an empty version of the container:

void clear( std::queue<int> &q )
{
   std::queue<int> empty;
   std::swap( q, empty );
}

It is also the only way of actually clearing the memory held inside some containers (std::vector)

Oracle PL/SQL string compare issue

I compare strings using = and not <>. I've found out that in this context = seems to work in more reasonable fashion than <>. I have specified that two empty (or NULL) strings are equal. The real implementation returns PL/SQL boolean, but here I changed that to pls_integer (0 is false and 1 is true) to be able easily demonstrate the function.

create or replace function is_equal(a in varchar2, b in varchar2)
return pls_integer as
begin
  if a is null and b is null then
    return 1;
  end if;

  if a = b then
    return 1;
  end if;

  return 0;
end;
/
show errors

begin
  /* Prints 0 */
  dbms_output.put_line(is_equal('AAA', 'BBB'));
  dbms_output.put_line(is_equal('AAA', null));
  dbms_output.put_line(is_equal(null, 'BBB'));
  dbms_output.put_line(is_equal('AAA', ''));
  dbms_output.put_line(is_equal('', 'BBB'));

  /* Prints 1 */
  dbms_output.put_line(is_equal(null, null));
  dbms_output.put_line(is_equal(null, ''));
  dbms_output.put_line(is_equal('', ''));
  dbms_output.put_line(is_equal('AAA', 'AAA'));
end;
/

using jquery $.ajax to call a PHP function

I would stick with normal approach to call the file directly, but if you really want to call a function, have a look at JSON-RPC (JSON Remote Procedure Call).

You basically send a JSON string in a specific format to the server, e.g.

{ "method": "echo", "params": ["Hello JSON-RPC"], "id": 1}

which includes the function to call and the parameters of that function.

Of course the server has to know how to handle such requests.
Here is jQuery plugin for JSON-RPC and e.g. the Zend JSON Server as server implementation in PHP.


This might be overkill for a small project or less functions. Easiest way would be karim's answer. On the other hand, JSON-RPC is a standard.

Adding a new value to an existing ENUM Type

Simplest: get rid of enums. They are not easily modifiable, and thus should very rarely be used.

What is an MDF file?

SQL Server databases use two files - an MDF file, known as the primary database file, which contains the schema and data, and a LDF file, which contains the logs. See wikipedia. A database may also use secondary database file, which normally uses a .ndf extension.

As John S. indicates, these file extensions are purely convention - you can use whatever you want, although I can't think of a good reason to do that.

More info on MSDN here and in Beginning SQL Server 2005 Administation (Google Books) here.

how to overwrite css style

Increase your CSS Specificity

Example:

.parent-class .flex-control-thumbs li {
  width: auto;
  float: none;
}

Demo:

_x000D_
_x000D_
.sample-class {
  height: 50px;
  width: 50px;
  background: red;
}

.inner-page .sample-class {
  background: green;
}
_x000D_
<div>
  <div class="sample-class"></div>
</div>

<div class="inner-page">
  <div class="sample-class"></div>
</div>
_x000D_
_x000D_
_x000D_

Align DIV's to bottom or baseline

_x000D_
_x000D_
td {_x000D_
  height: 150px;_x000D_
  width: 150px;_x000D_
  text-align: center;_x000D_
}_x000D_
_x000D_
b {_x000D_
  border: 1px solid black;_x000D_
}_x000D_
_x000D_
.child-2 {_x000D_
  vertical-align: bottom;_x000D_
}_x000D_
_x000D_
.child-3 {_x000D_
  vertical-align: top;_x000D_
}
_x000D_
<table border=1>_x000D_
  <tr>_x000D_
    <td class="child-1">_x000D_
      <b>child 1</b>_x000D_
    </td>_x000D_
    <td class="child-2">_x000D_
     <b>child 2</b>_x000D_
    </td>_x000D_
    <td class="child-3">_x000D_
      <b>child 3</b>_x000D_
    </td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

This is my solution

How can I consume a WSDL (SOAP) web service in Python?

SOAPpy is now obsolete, AFAIK, replaced by ZSL. It's a moot point, because I can't get either one to work, much less compile, on either Python 2.5 or Python 2.6

Linux command for extracting war file?

A war file is just a zip file with a specific directory structure. So you can use unzip or the jar tool for unzipping.

But you probably don't want to do that. If you add the war file into the webapps directory of Tomcat the Tomcat will take care of extracting/installing the war file.

Cross-Origin Request Headers(CORS) with PHP headers

add this code in .htaccess

add custom authentication key's in header like app_key,auth_key..etc

Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Headers: "customKey1,customKey2, headers, Origin, X-Requested-With, Content-Type, Accept, Authorization"

The Response content must be a string or object implementing __toString(), "boolean" given after move to psql

It is being pointed out not directly in the file which is caused the error. But it is actually triggered in a controller file. It happens when a return value from a method defined inside in a controller file is set on a boolean value. It must not be set on a boolean type but on the other hand, it must be set or given a value of a string type. It can be shown as follows :

public function saveFormSummary(Request $request) {
      ... 
      $status = true;
      return $status;
}

Given the return value of a boolean type above in a method, to be able to solve the problem to handle the error specified. Just change the type of the return value into a string type

as follows :

public function saveFormSummary(Request $request) {
      ... 
      $status = "true";
      return $status;
}

Eclipse error ... cannot be resolved to a type

Easy Solution:
Go to

Project property -> java builder path -> maven -> find c3p0-0.9.5.2.jar

and see the location where the file is stored in the local repository and go to this location and delete the repository manually.

G

ssh script returns 255 error

As @wes-floyd and @zpon wrote, add these parameters to SSH to bypass "Are you sure you want to continue connecting (yes/no)?"

-o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no

How to set background image of a view?

self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"imageName.png"]];

more info with example project

How to import component into another root component in Angular 2

For Angular RC5 and RC6 you have to declare component in the module metadata decorator's declarations key, so add CoursesComponent in your main module declarations as below and remove directives from AppComponent metadata.

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppComponent } from './app.component';
import { CoursesComponent } from './courses.component';

@NgModule({
  imports:      [ BrowserModule ],
  declarations: [ AppComponent, CoursesComponent ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

How to set background color of HTML element using css properties in JavaScript

You might find your code is more maintainable if you keep all your styles, etc. in CSS and just set / unset class names in JavaScript.

Your CSS would obviously be something like:

.highlight {
    background:#ff00aa;
}

Then in JavaScript:

element.className = element.className === 'highlight' ? '' : 'highlight';

How do I get a file extension in PHP?

Here is an example. Suppose $filename is "example.txt",

$ext = substr($filename, strrpos($filename, '.', -1), strlen($filename));

So $ext will be ".txt".

jQuery/JavaScript to replace broken images

By using Prestaul's answer, I added some checks and I prefer to use the jQuery way.

<img src="image1.png" onerror="imgError(this,1);"/>
<img src="image2.png" onerror="imgError(this,2);"/>

function imgError(image, type) {
    if (typeof jQuery !== 'undefined') {
       var imgWidth=$(image).attr("width");
       var imgHeight=$(image).attr("height");

        // Type 1 puts a placeholder image
        // Type 2 hides img tag
        if (type == 1) {
            if (typeof imgWidth !== 'undefined' && typeof imgHeight !== 'undefined') {
                $(image).attr("src", "http://lorempixel.com/" + imgWidth + "/" + imgHeight + "/");
            } else {
               $(image).attr("src", "http://lorempixel.com/200/200/");
            }
        } else if (type == 2) {
            $(image).hide();
        }
    }
    return true;
}

How to compare two NSDates: Which is more recent?

Late to the party, but another easy way of comparing NSDate objects is to convert them into primitive types which allows for easy use of '>' '<' '==' etc

eg.

if ([dateA timeIntervalSinceReferenceDate] > [dateB timeIntervalSinceReferenceDate]) {
    //do stuff
}

timeIntervalSinceReferenceDate converts the date into seconds since the reference date (1 January 2001, GMT). As timeIntervalSinceReferenceDate returns a NSTimeInterval (which is a double typedef), we can use primitive comparators.

Django: ImproperlyConfigured: The SECRET_KEY setting must not be empty

I had the same problem with Celery. My setting.py before:

SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY')

after:

SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY', <YOUR developing key>)

If the environment variables are not defined then: SECRET_KEY = YOUR developing key

Saving timestamp in mysql table using php

Use FROM_UNIXTIME().

Note: 1299762201428 looks more like a millisecond-timestamp (like Date()*1 in JavaScript), and you probably have to divide that by 1000.

TortoiseSVN Error: "OPTIONS of 'https://...' could not connect to server (...)"

Late reaction, but I've struggled with this for a while so maybe I can save somebody some time by showing my solution.

My problem showed a bit different, but the cause might be the same.

In my situation, TortoiseSVN kept on trying to connect via a proxy server. I could access SVN via chrome, firefox and IE fine.

Turns out that there is a configuration file that has a different configuration than the GUI in TortoiseSVN shows.

Mine was located here: C:\Documents and Settings\[username]\Application Data\Subversion\, but you can also open the file via the TortoiseSVN gui.

TortoiseSVN

In my file, http-proxy-exceptions was empty. After I specified it, everything worked fine.

[global]
http-proxy-exceptions = 10.1.1.11
http-proxy-host = 197.132.0.223
http-proxy-port = 8080
http-proxy-username = defaultusername
http-proxy-password = defaultpassword
http-compression = no

Batch: Remove file extension

Using cygwin bash to do the chopping

  :: e.g. FILE=basename.mp4 => FILE_NO_EXT=basename
  set FILE=%1
  for /f "delims=" %%a in ('bash -c "FILE=%FILE%; echo ${FILE/.*/}" ') do set FILE_NO_EXT=%%a

Checking if a SQL Server login already exists

You can use the built-in function:

SUSER_ID ( [ 'myUsername' ] )

via

IF [value] IS NULL [statement]

like:

IF SUSER_ID (N'myUsername') IS NULL
CREATE LOGIN [myUsername] WITH PASSWORD=N'myPassword', 
DEFAULT_LANGUAGE=[us_english], 
CHECK_EXPIRATION=OFF, 
CHECK_POLICY=OFF 
GO

https://technet.microsoft.com/en-us/library/ms176042(v=sql.110).aspx

How to get IP address of the device from code?

In all honesty I am only a little familiar with code safety, so this may be hack-ish. But for me this is the most versatile way to do it:

package com.my_objects.ip;

import java.net.InetAddress;
import java.net.UnknownHostException;

public class MyIpByHost 
{
  public static void main(String a[])
  {
   try 
    {
      InetAddress host = InetAddress.getByName("nameOfDevice or webAddress");
      System.out.println(host.getHostAddress());
    } 
   catch (UnknownHostException e) 
    {
      e.printStackTrace();
    }
} }

How can I pretty-print JSON in a shell script?

Use Ruby in one line:

echo '{"test":1,"test2":2}' | ruby -e "require 'json'; puts JSON.pretty_generate(JSON.parse(STDIN.read))"

And you can set an alias for this:

alias to_j="ruby -e \"require 'json';puts JSON.pretty_generate(JSON.parse(STDIN.read))\""

Then you can use it more conveniently

echo '{"test":1,"test2":2}' | to_j

{
  "test": 1,
  "test2": 2
}

And if you want display JSON with color, your can install awesome_print,

gem install awesome_print

then

alias to_j="ruby -e \"require 'json';require 'awesome_print';ap JSON.parse(STDIN.read)\""

Try it!

echo '{"test":1,"test2":2, "arr":["aa","bb","cc"] }' | to_j

Enter image description here

I do not understand how execlp() works in Linux

this prototype:

  int execlp(const char *file, const char *arg, ...);

Says that execlp ìs a variable argument function. It takes 2 const char *. The rest of the arguments, if any, are the additional arguments to hand over to program we want to run - also char * - all these are C strings (and the last argument must be a NULL pointer)

So, the file argument is the path name of an executable file to be executed. arg is the string we want to appear as argv[0] in the executable. By convention, argv[0] is just the file name of the executable, normally it's set to the same as file.

The ... are now the additional arguments to give to the executable.

Say you run this from a commandline/shell:

$ ls

That'd be execlp("ls", "ls", (char *)NULL); Or if you run

$ ls -l /

That'd be execlp("ls", "ls", "-l", "/", (char *)NULL);

So on to execlp("/bin/sh", ..., "ls -l /bin/??", ...);

Here you are going to the shell, /bin/sh , and you're giving the shell a command to execute. That command is "ls -l /bin/??". You can run that manually from a commandline/shell:

 $ ls -l /bin/??

Now, how do you run a shell and tell it to execute a command ? You open up the documentation/man page for your shell and read it.

What you want to run is:

$ /bin/sh -c "ls -l /bin/??"

This becomes

  execlp("/bin/sh","/bin/sh", "-c", "ls -l /bin/??", (char *)NULL);

Side note: The /bin/?? is doing pattern matching, this pattern matching is done by the shell, and it expands to all files under /bin/ with 2 characters. If you simply did

  execlp("ls","ls", "-l", "/bin/??", (char *)NULL);

Probably nothing would happen (unless there's a file actually named /bin/??) as there's no shell that interprets and expands /bin/??

Getting data posted in between two dates

if you want to force using BETWEEN keyword on Codeigniter query helper. You can use where without escape false like this code. Works well on CI version 3.1.5. Hope its help someone.

if(!empty($tglmin) && !empty($tglmax)){
        $this->db->group_start();
        $this->db->where('DATE(create_date) BETWEEN "'.$tglmin.'" AND "'.$tglmax.'"', '',false);
        $this->db->group_end();
    }

Why do Python's math.ceil() and math.floor() operations return floats instead of integers?

As pointed out by other answers, in python they return floats probably because of historical reasons to prevent overflow problems. However, they return integers in python 3.

>>> import math
>>> type(math.floor(3.1))
<class 'int'>
>>> type(math.ceil(3.1))
<class 'int'>

You can find more information in PEP 3141.

Deleting rows with MySQL LEFT JOIN

You simply need to specify on which tables to apply the DELETE.

Delete only the deadline rows:

DELETE `deadline` FROM `deadline` LEFT JOIN `job` ....

Delete the deadline and job rows:

DELETE `deadline`, `job` FROM `deadline` LEFT JOIN `job` ....

Delete only the job rows:

DELETE `job` FROM `deadline` LEFT JOIN `job` ....

Selenium IDE - Command to wait for 5 seconds

In Chrome, For "Selenium IDE", I was also struggling that it doesn't pause. It will pause, if you give as below:

  • Command: pause
  • Target: blank
  • Value: 10000

This will pause for 10 seconds.

Git Bash won't run my python files?

Adapting the PATH should work. Just tried on my Git bash:

$ python --version
sh.exe": python: command not found

$ PATH=$PATH:/c/Python27/

$ python --version
Python 2.7.6

In particular, only provide the directory; don't specify the .exe on the PATH ; and use slashes.

How can I split a string with a string delimiter?

Read C# Split String Examples - Dot Net Pearls and the solution can be something like:

var results = yourString.Split(new string[] { "is Marco and" }, StringSplitOptions.None);

Print text in Oracle SQL Developer SQL Worksheet window

For me, I could only get it to work with

set serveroutput on format word_wrapped;

The wraped and WRAPPED just threw errors: SQLPLUS command failed - not enough arguments

jQuery: find element by text

In jQuery documentation it says:

The matching text can appear directly within the selected element, in any of that element's descendants, or a combination

Therefore it is not enough that you use :contains() selector, you also need to check if the text you search for is the direct content of the element you are targeting for, something like that:

function findElementByText(text) {
    var jSpot = $("b:contains(" + text + ")")
                .filter(function() { return $(this).children().length === 0;})
                .parent();  // because you asked the parent of that element

    return jSpot;
}

How to config routeProvider and locationProvider in angularJS?

you could try:

<a href="#/controllerone">Controller One</a>||
<a href="#/controllerTwo">Controller Two</a>||
<a href="#/controllerThree">Controller Three</a>

<div>
    <div ng-view=""></div>
</div>

Docker Repository Does Not Have a Release File on Running apt-get update on Ubuntu

I still have the same issue. None of the answers above seem to solve it. I have ubuntu 16.04, and I follow the steps described in https://docs.docker.com/install/linux/docker-ce/ubuntu/

I suspect it is related to an apt-get bug regarding https. The information being printed by apt-get is kind of misleading.

I think that Failed to fetch.. can also be translated as: problem accessing resource from within an https connection

How did I come to this conclusion:

First of all I am behind a corporate proxy so I have set the following configuration:

/etc/apt/apt.conf

Acquire::http::proxy "http://squidproxy:8080/";
Acquire::https::proxy "http://squidproxy:8080/";
Acquire::ftp::proxy "ftp://squidproxy:8080/";

Acquire::https::CaInfo     "/etc/ssl/certs/ca-certificates.pem";

/etc/apt/apt.conf.d/99proxy

Acquire::http::Proxy {
    localhost DIRECT;
    localhost:9020 DIRECT;
    localhost:9021 DIRECT;
};

I performed the following tests with differrent entries in sources.list

test entry 1:

deb [arch=amd64] https://download.docker.com/linux/ubuntu xenial stable

sudo apt-get update

W: The repository 'https://download.docker.com/linux/ubuntu xenial Release' does not have a Release file.
N: Data from such a repository can't be authenticated and is therefore potentially dangerous to use.
N: See apt-secure(8) manpage for repository creation and user configuration     details.
E: Failed to fetch     https://download.docker.com/linux/ubuntu/dists/xenial/stable/binary-amd64/Packages  
E: Some index files failed to download. They have been ignored, or old ones used instead.

Failure

test entry 2:

deb [arch=amd64] http://localhost:9020/linux/ubuntu xenial stable

/etc/apache2/sites-enabled/apt-proxy.conf

# http to https reverse proxy configuration.
Listen 9020
<VirtualHost *:9020>
SSLProxyEngine On
# pass from squid proxy
ProxyRemote https://download.docker.com/ http://squidproxy:8080
ProxyPass / https://download.docker.com/
ProxyPassReverse / https://download.docker.com/
ErrorLog ${APACHE_LOG_DIR}/apt-proxy-error.log
CustomLog ${APACHE_LOG_DIR}/apt-proxy-access.log combined
</VirtualHost>

sudo apt-get update

Hit:1 ..
Hit:2 ..
  ...                                                              
Hit:7 http://localhost:9020/linux/ubuntu xenial InRelease                
Get:8 ...
Fetched 323 kB in 0s (419 kB/s)
Reading package lists... Done

Success

test entry 3:

deb [arch=amd64] https://localhost:9021/linux/ubuntu xenial stable

/etc/apache2/sites-enabled/apt-proxy.conf

# https to https revere proxy
Listen 9021
<VirtualHost *:9021>
# serve on https
SSLEngine on
SSLCertificateFile      /etc/ssl/certs/ssl-cert-snakeoil.pem
SSLCertificateKeyFile /etc/ssl/private/ssl-cert-snakeoil.key
SSLProxyEngine On
# pass from squid proxy
ProxyRemote https://download.docker.com/ http://squidproxy:8080
ProxyPass / https://download.docker.com/
ProxyPassReverse / https://download.docker.com/
ErrorLog ${APACHE_LOG_DIR}/apt-proxy-error.log
CustomLog ${APACHE_LOG_DIR}/apt-proxy-access.log combined
</VirtualHost>

sudo apt-get update

W: The repository 'https://localhost:9021/linux/ubuntu xenial Release' does not have a Release file.
N: Data from such a repository can't be authenticated and is therefore potentially dangerous to use.
N: See apt-secure(8) manpage for repository creation and user configuration details.
E: Failed to fetch https://localhost:9021/linux/ubuntu/dists/xenial/stable/binary-amd64/Packages  
E: Some index files failed to download. They have been ignored, or old ones used instead.

Failure


In the above cases the url which apt-get Failed to fetch and also the Release file, were actually accessible from browser / wget / curl using the same proxy configuration.
The fact that apt-get worked only with http reverse proxy url, implies that there is some issue accessing resources from within an https connection.
I do not know what this issue is but apt-get should show a more informative message ( apt is even less verbose ).

Note: wiresharking case 1 showed that proxy CONNECT was successful, and no RST was sent, but of course the files could not be read.

Size of character ('a') in C/C++

As Paul stated, it's because 'a' is an int in C but a char in C++.

I cover that specific difference between C and C++ in something I wrote a few years ago, at: http://david.tribble.com/text/cdiffs.htm

Is there an easy way to return a string repeated X number of times?

Surprised nobody went old-school. I am not making any claims about this code, but just for fun:

public static string Repeat(this string @this, int count)
{
    var dest = new char[@this.Length * count];
    for (int i = 0; i < dest.Length; i += 1)
    {
        dest[i] = @this[i % @this.Length];
    }
    return new string(dest);
}

C++ "Access violation reading location" Error

You haven't posted the findvertex method, but Access Reading Violation with an offset like 0x00000048 means that the Vertex* f; in your getCost function is receiving null, and when trying to access the member adj in the null Vertex pointer (that is, in f), it is offsetting to adj (in this case, 72 bytes ( 0x48 bytes in decimal )), it's reading near the 0 or null memory address.

Doing a read like this violates Operating-System protected memory, and more importantly means whatever you're pointing at isn't a valid pointer. Make sure findvertex isn't returning null, or do a comparisong for null on f before using it to keep yourself sane (or use an assert):

assert( f != null ); // A good sanity check

EDIT:

If you have a map for doing something like a find, you can just use the map's find method to make sure the vertex exists:

Vertex* Graph::findvertex(string s)
{
    vmap::iterator itr = map1.find( s );
    if ( itr == map1.end() )
    {
        return NULL;
    }
    return itr->second;
}

Just make sure you're still careful to handle the error case where it does return NULL. Otherwise, you'll keep getting this access violation.

Writing an Excel file in EPPlus

If you have a collection of objects that you load using stored procedure you can also use LoadFromCollection.

using (ExcelPackage package = new ExcelPackage(file))
{
    ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("test");

    worksheet.Cells["A1"].LoadFromCollection(myColl, true, OfficeOpenXml.Table.TableStyles.Medium1);

    package.Save();
}

How to have an auto incrementing version number (Visual Studio)?

  • Star in version (like "2.10.3.*") - it is simple, but the numbers are too large

  • AutoBuildVersion - looks great but its dont work on my VS2010.

  • @DrewChapin's script works, but I can not in my studio set different modes for Debug pre-build event and Release pre-build event.

so I changed the script a bit... commamd:

"%CommonProgramFiles(x86)%\microsoft shared\TextTemplating\10.0\TextTransform.exe" -a !!$(ConfigurationName)!1 "$(ProjectDir)Properties\AssemblyInfo.tt"

and script (this works to the "Debug" and "Release" configurations):

<#@ template debug="true" hostspecific="true" language="C#" #>
<#@ output extension=".cs" #>
<#@ assembly name="System.Windows.Forms" #>
<#@ import namespace="System.IO" #>
<#@ import namespace="System.Text.RegularExpressions" #>
<#
    int incRevision = 1;
    int incBuild = 1;

    try { incRevision = Convert.ToInt32(this.Host.ResolveParameterValue("","","Debug"));} catch( Exception ) { incBuild=0; }
    try { incBuild = Convert.ToInt32(this.Host.ResolveParameterValue("","","Release")); } catch( Exception ) { incRevision=0; }
    try {
        string currentDirectory = Path.GetDirectoryName(Host.TemplateFile);
        string assemblyInfo = File.ReadAllText(Path.Combine(currentDirectory,"AssemblyInfo.cs"));
        Regex pattern = new Regex("AssemblyVersion\\(\"\\d+\\.\\d+\\.(?<revision>\\d+)\\.(?<build>\\d+)\"\\)");
        MatchCollection matches = pattern.Matches(assemblyInfo);
        revision = Convert.ToInt32(matches[0].Groups["revision"].Value) + incRevision;
        build = Convert.ToInt32(matches[0].Groups["build"].Value) + incBuild;
    }
    catch( Exception ) { }
#>
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Game engine. Keys: F2 (Debug trace), F4 (Fullscreen), Shift+Arrows (Move view). ")]
[assembly: AssemblyProduct("Game engine")]
[assembly: AssemblyDescription("My engine for game")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyCopyright("Copyright © Name 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components.  If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type. Only Windows
// assemblies support COM.
[assembly: ComVisible(false)]

// On Windows, the following GUID is for the ID of the typelib if this
// project is exposed to COM. On other platforms, it unique identifies the
// title storage container when deploying this assembly to the device.
[assembly: Guid("00000000-0000-0000-0000-000000000000")]

// Version information for an assembly consists of the following four values:
//
//      Major Version
//      Minor Version
//      Build Number
//      Revision
//
[assembly: AssemblyVersion("0.1.<#= this.revision #>.<#= this.build #>")]
[assembly: AssemblyFileVersion("0.1.<#= this.revision #>.<#= this.build #>")]

<#+
    int revision = 0;
    int build = 0;
#>

How to lookup JNDI resources on WebLogic?

I had a similar problem to this one. It got solved by deleting the java:comp/env/ prefix and using jdbc/myDataSource in the context lookup. Just as someone pointed out in the comments.

LINQ query to find if items in a list are contained in another list

List<string> test1 = new List<string> { "@bob.com", "@tom.com" };
List<string> test2 = new List<string> { "[email protected]", "[email protected]", "[email protected]" };

var result = (from t2 in test2
              where test1.Any(t => t2.Contains(t)) == false
              select t2);

If query form is what you want to use, this is legible and more or less as "performant" as this could be.

What i mean is that what you are trying to do is an O(N*M) algorithm, that is, you have to traverse N items and compare them against M values. What you want is to traverse the first list only once, and compare against the other list just as many times as needed (worst case is when the email is valid since it has to compare against every black listed domain).

from t2 in test we loop the email list once.

test1.Any(t => t2.Contains(t)) == false we compare with the blacklist and when we found one match return (hence not comparing against the whole list if is not needed)

select t2 keep the ones that are clean.

So this is what I would use.

How to set calculation mode to manual when opening an excel file?

The best way around this would be to create an Excel called 'launcher.xlsm' in the same folder as the file you wish to open. In the 'launcher' file put the following code in the 'Workbook' object, but set the constant TargetWBName to be the name of the file you wish to open.

Private Const TargetWBName As String = "myworkbook.xlsx"

'// First, a function to tell us if the workbook is already open...
Function WorkbookOpen(WorkBookName As String) As Boolean
' returns TRUE if the workbook is open
    WorkbookOpen = False
    On Error GoTo WorkBookNotOpen
    If Len(Application.Workbooks(WorkBookName).Name) > 0 Then
        WorkbookOpen = True
        Exit Function
    End If
WorkBookNotOpen:
End Function

Private Sub Workbook_Open()
    'Check if our target workbook is open
    If WorkbookOpen(TargetWBName) = False Then
        'set calculation to manual
        Application.Calculation = xlCalculationManual
        Workbooks.Open ThisWorkbook.Path & "\" & TargetWBName
        DoEvents
        Me.Close False
    End If
End Sub

Set the constant 'TargetWBName' to be the name of the workbook that you wish to open. This code will simply switch calculation to manual, then open the file. The launcher file will then automatically close itself. *NOTE: If you do not wish to be prompted to 'Enable Content' every time you open this file (depending on your security settings) you should temporarily remove the 'me.close' to prevent it from closing itself, save the file and set it to be trusted, and then re-enable the 'me.close' call before saving again. Alternatively, you could just set the False to True after Me.Close

Why XML-Serializable class need a parameterless constructor

This is a limitation of XmlSerializer. Note that BinaryFormatter and DataContractSerializer do not require this - they can create an uninitialized object out of the ether and initialize it during deserialization.

Since you are using xml, you might consider using DataContractSerializer and marking your class with [DataContract]/[DataMember], but note that this changes the schema (for example, there is no equivalent of [XmlAttribute] - everything becomes elements).

Update: if you really want to know, BinaryFormatter et al use FormatterServices.GetUninitializedObject() to create the object without invoking the constructor. Probably dangerous; I don't recommend using it too often ;-p See also the remarks on MSDN:

Because the new instance of the object is initialized to zero and no constructors are run, the object might not represent a state that is regarded as valid by that object. The current method should only be used for deserialization when the user intends to immediately populate all fields. It does not create an uninitialized string, since creating an empty instance of an immutable type serves no purpose.

I have my own serialization engine, but I don't intend making it use FormatterServices; I quite like knowing that a constructor (any constructor) has actually executed.

In PHP how can you clear a WSDL cache?

You can safely delete the WSDL cache files. If you wish to prevent future caching, use:

ini_set("soap.wsdl_cache_enabled", 0);

or dynamically:

$client = new SoapClient('http://somewhere.com/?wsdl', array('cache_wsdl' => WSDL_CACHE_NONE) );

Limit the output of the TOP command to a specific process name

I came here looking for the answer to this on OSX. I ended up getting what I wanted with bash and awk:

topfiltered() {
  [[ -z "$1" ]] && return
  dump="/tmp/top_dump"
  rm -f "$dump"
  while :; do
    clear
    [[ -s "$dump" ]] && head -n $(( $LINES - 1 )) "$dump"
    top -l 1 -o cpu -ncols $(( $COLUMNS / 8 )) | awk -v p="$(pgrep -d ' ' $@)" '
        BEGIN { split(p, arr); for (k in arr) pids[arr[k]]=1 }
        NR<=12 || ($1 in pids)
    ' >"$dump"
  done
}

I loop top in logging mode and filter it with awk, building an associative array from the output of pgrep. Awk prints the first 12 lines, where line 12 is the column headers, and then every line which has a pid that's a key in the array. The dump file is used for a more watchable loop.

How to wait for a process to terminate to execute another process in batch file

This works and is even simpler. If you remove ECHO-s, it will be even smaller:

REM
REM DEMO - how to launch several processes in parallel, and wait until all of them finish.
REM

@ECHO OFF
start "!The Title!" Echo Close me manually!
start "!The Title!" Echo Close me manually!
:waittofinish
echo At least one process is still running...
timeout /T 2 /nobreak >nul
tasklist.exe /fi "WINDOWTITLE eq !The Title!" | find ":" >nul
if errorlevel 1 goto waittofinish
echo Finished!
PAUSE

How to compare arrays in JavaScript?

This compares 2 unsorted arrays:

function areEqual(a, b) {
  if ( a.length != b.length) {
    return false;
  }
  return a.filter(function(i) {
    return !b.includes(i);
  }).length === 0;  
}

Finding rows that don't contain numeric data in Oracle

You can use this one check:

create or replace function to_n(c varchar2) return number is
begin return to_number(c);
exception when others then return -123456;
end;

select id, n from t where to_n(n) = -123456;

How to pass ArrayList of Objects from one to another activity using Intent in android?

Your intent creation seems correct if your Question implements Parcelable.

In the next activity you can retrieve your list of questions like this:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if(getIntent() != null && getIntent().hasExtra("QuestionsExtra")) {
        List<Question> mQuestionsList = getIntent().getParcelableArrayListExtra("QuestionsExtra");
    }
}

Sometimes adding a WCF Service Reference generates an empty reference.cs

When this happens, look in the Errors window and the Output window to see if there are any error messages. If that doesn't help, try running svcutil.exe manually, and see if there are any error messages.

AndroidStudio gradle proxy

The following works for me . File -> Settings -> Appearance & Behavior -> System Settings -> HTTP Proxy Put in your proxy setting in Manual proxy configuration

Restart android studio, a prompt pops up and asks you to add the proxy setting to gradle, click yes.

Error:java: invalid source release: 8 in Intellij. What does it mean?

I was recently facing the same problem. This Error was showing on my screen after running my project main file. Error:java: invalid source release: 11 Follow the steps to resolve this error

  1. File->Project Structure -> Project
  2. Click New button under Project SDK: Add the latest SDK and Click OK.

enter image description here

After running You will see error is resolved..

enter image description here

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

Just use

Dim Cell As Range
Columns("B:B").Select
Set cell = Selection.Find(What:="celda", After:=ActiveCell, LookIn:=xlFormulas, _
        LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
        MatchCase:=False, SearchFormat:=False)

If cell Is Nothing Then
    'do it something

Else
    'do it another thing
End If

How to replace deprecated android.support.v4.app.ActionBarDrawerToggle

There's no need for you to use super-call of the ActionBarDrawerToggle which requires the Toolbar. This means instead of using the following constructor:

ActionBarDrawerToggle(Activity activity, DrawerLayout drawerLayout, Toolbar toolbar, int openDrawerContentDescRes, int closeDrawerContentDescRes)

You should use this one:

ActionBarDrawerToggle(Activity activity, DrawerLayout drawerLayout, int openDrawerContentDescRes, int closeDrawerContentDescRes)

So basically the only thing you have to do is to remove your custom drawable:

super(mActivity, mDrawerLayout, R.string.ns_menu_open, R.string.ns_menu_close);

More about the "new" ActionBarDrawerToggle in the Docs (click).

Why is using "for...in" for array iteration a bad idea?

You should use the for(var x in y) only on property lists, not on objects (as explained above).

How do I do logging in C# without using 3rd party libraries?

If you want your own custom Error Logging you can easily write your own code. I'll give you a snippet from one of my projects.

public void SaveLogFile(object method, Exception exception)
{
    string location = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + @"\FolderName\";
    try
    {
        //Opens a new file stream which allows asynchronous reading and writing
        using (StreamWriter sw = new StreamWriter(new FileStream(location + @"log.txt", FileMode.Append, FileAccess.Write, FileShare.ReadWrite)))
        {
            //Writes the method name with the exception and writes the exception underneath
            sw.WriteLine(String.Format("{0} ({1}) - Method: {2}", DateTime.Now.ToShortDateString(), DateTime.Now.ToShortTimeString(), method.ToString()));
            sw.WriteLine(exception.ToString()); sw.WriteLine("");
        }
    }
    catch (IOException)
    {
        if (!File.Exists(location + @"log.txt"))
        {
            File.Create(location + @"log.txt");
        }
    }
}

Then to actually write to the error log just write (q being the caught exception)

SaveLogFile(MethodBase.GetCurrentMethod(), `q`);

How to convert string to string[]?

To convert a string with comma separated values to a string array use Split:

string strOne = "One,Two,Three,Four";
string[] strArrayOne = new string[] {""};
//somewhere in your code
strArrayOne = strOne.Split(',');

Result will be a string array with four strings:

{"One","Two","Three","Four"}

CSS Change List Item Background Color with Class

Live Demo


If you want this to be highlighted depending upon the page your user is on then do this:

To auto-highlight your current navigation, first label your body tags with an ID or class that matches the section of the site (usually a directory) that the page is in.

<body class="ab">

We label all files in the "/about/" directory with the "ab" class. Note that we use a class here to label the body tags. We found that using an ID in the body did not work consistently in some older browsers. Next we label our menu items so we can target them individually thus:

<div id="n"> <a class="b" id="hm"
href="/">Home</a> ... <a class="b"
id="ab" href="/about/">About</a> ...
</div>

Note that we use the "b"utton class to label menu items as buttons and an ID ("ab") to label each unique menu item (in this case about). Now all we need is a CSS selector that matches up the body label with the appropriate menu label like this:

body.ab #n #ab, body.ab #n #ab
a{color:#333;background:#dcdcdc;text-decoration:none;}

This code effectively highlights the "About" menu item and makes it appear dark gray. When you label the rest of the site and menu items, you'll end up with a grouped selector that looks something like this:

body.hm #n #hm, body.hm #n #hm a,
body.sm #n #sm, body.sm #n #sm a,
body.is #n #is, body.is #n #is a,
body.ab #n #ab, body.ab #n #ab a, 
body.ct #n #ct, body.ct #n #ct
a{color:#333;background:#dcdcdc;text-decoration:none;}

For example when the user navigates to the sitemap section the .sm classed body tag matches the #sm menu option and triggers the CSS highlight of the "Sitemap" in the navigation bar.

Source

Run cmd commands through Java

One way to run a process from a different directory to the working directory of your Java program is to change directory and then run the process in the same command line. You can do this by getting cmd.exe to run a command line such as cd some_directory && some_program.

The following example changes to a different directory and runs dir from there. Admittedly, I could just dir that directory without needing to cd to it, but this is only an example:

import java.io.*;

public class CmdTest {
    public static void main(String[] args) throws Exception {
        ProcessBuilder builder = new ProcessBuilder(
            "cmd.exe", "/c", "cd \"C:\\Program Files\\Microsoft SQL Server\" && dir");
        builder.redirectErrorStream(true);
        Process p = builder.start();
        BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String line;
        while (true) {
            line = r.readLine();
            if (line == null) { break; }
            System.out.println(line);
        }
    }
}

Note also that I'm using a ProcessBuilder to run the command. Amongst other things, this allows me to redirect the process's standard error into its standard output, by calling redirectErrorStream(true). Doing so gives me only one stream to read from.

This gives me the following output on my machine:

C:\Users\Luke\StackOverflow>java CmdTest
 Volume in drive C is Windows7
 Volume Serial Number is D8F0-C934

 Directory of C:\Program Files\Microsoft SQL Server

29/07/2011  11:03    <DIR>          .
29/07/2011  11:03    <DIR>          ..
21/01/2011  20:37    <DIR>          100
21/01/2011  20:35    <DIR>          80
21/01/2011  20:35    <DIR>          90
21/01/2011  20:39    <DIR>          MSSQL10_50.SQLEXPRESS
               0 File(s)              0 bytes
               6 Dir(s)  209,496,424,448 bytes free

How to remove item from a JavaScript object

_x000D_
_x000D_
var test = {'red':'#FF0000', 'blue':'#0000FF'};_x000D_
delete test.blue; // or use => delete test['blue'];_x000D_
console.log(test);
_x000D_
_x000D_
_x000D_

this deletes test.blue

Better way to revert to a previous SVN revision of a file?

svn merge will merge revisions, not revert them. i.e. if you have some addition in your HEAD version then merge that with a previous revision, then the change will persist.

I use svn cat then redirect it into the file:

svn cat -r 851 l3toks.dtx > l3toks.dtx

Then you have the 851 content in that file and can check it back in.

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

This is a feature, not a bug.

See http://docs.python.org/howto/unicode.html, specifically the 'unicode type' section.

Vue.js redirection to another page

According to the docs, router.push seems like the preferred method:

To navigate to a different URL, use router.push. This method pushes a new entry into the history stack, so when the user clicks the browser back button they will be taken to the previous URL.

source: https://router.vuejs.org/en/essentials/navigation.html

FYI : Webpack & component setup, single page app (where you import the router through Main.js), I had to call the router functions by saying:

this.$router

Example: if you wanted to redirect to a route called "Home" after a condition is met:

this.$router.push('Home') 

How to get value by key from JObject?

Try this:

private string GetJArrayValue(JObject yourJArray, string key)
{
    foreach (KeyValuePair<string, JToken> keyValuePair in yourJArray)
    {
        if (key == keyValuePair.Key)
        {
            return keyValuePair.Value.ToString();
        }
    }
}

Keeping session alive with Curl and PHP

You have correctly used "CURLOPT_COOKIEJAR" (writing) but you also need to set "CURLOPT_COOKIEFILE" (reading)

curl_setopt ($ch, CURLOPT_COOKIEJAR, COOKIE_FILE); 
curl_setopt ($ch, CURLOPT_COOKIEFILE, COOKIE_FILE); 

Concatenate multiple node values in xpath

If you need to join xpath-selected text nodes but can not use string-join (when you are stuck with XSL 1.0) this might help:

<xsl:variable name="x">
    <xsl:apply-templates select="..." mode="string-join-mode"/>
</xsl:variable>
joined and normalized: <xsl:value-of select="normalize-space($x)"/>

<xsl:template match="*" mode="string-join-mode">
    <xsl:apply-templates mode="string-join-mode"/>
</xsl:template>    

<xsl:template match="text()" mode="string-join-mode">
    <xsl:value-of select="."/>
</xsl:template>    

R barplot Y-axis scale too short

barplot(data)

enter image description here

barplot(data, yaxp=c(0, max(data), 5))

enter image description here

yaxp=c(minY-axis, maxY-axis, Interval)

Confusion: @NotNull vs. @Column(nullable = false) with JPA and Hibernate

The JPA @Column Annotation

The nullable attribute of the @Column annotation has two purposes:

  • it's used by the schema generation tool
  • it's used by Hibernate during flushing the Persistence Context

Schema Generation Tool

The HBM2DDL schema generation tool translates the @Column(nullable = false) entity attribute to a NOT NULL constraint for the associated table column when generating the CREATE TABLE statement.

As I explained in the Hibernate User Guide, it's better to use a tool like Flyway instead of relying on the HBM2DDL mechanism for generating the database schema.

Persistence Context Flush

When flushing the Persistence Context, Hibernate ORM also uses the @Column(nullable = false) entity attribute:

new Nullability( session ).checkNullability( values, persister, true );

If the validation fails, Hibernate will throw a PropertyValueException, and prevents the INSERT or UPDATE statement to be executed needesly:

if ( !nullability[i] && value == null ) {
    //check basic level one nullablilty
    throw new PropertyValueException(
            "not-null property references a null or transient value",
            persister.getEntityName(),
            persister.getPropertyNames()[i]
        );    
}

The Bean Validation @NotNull Annotation

The @NotNull annotation is defined by Bean Validation and, just like Hibernate ORM is the most popular JPA implementation, the most popular Bean Validation implementation is the Hibernate Validator framework.

When using Hibernate Validator along with Hibernate ORM, Hibernate Validator will throw a ConstraintViolation when validating the entity.

How do I migrate an SVN repository with history to a new Git repository?

See the official git-svn manpage. In particular, look under "Basic Examples":

Tracking and contributing to an entire Subversion-managed project (complete with a trunk, tags and branches):

# Clone a repo (like git clone):
    git svn clone http://svn.foo.org/project -T trunk -b branches -t tags

comparing two strings in SQL Server

There is no direct string compare function in SQL Server

CASE
  WHEN str1 = str2 THEN 0
  WHEN str1 < str2 THEN -1
  WHEN str1 > str2 THEN 1
  ELSE NULL --one of the strings is NULL so won't compare (added on edit)
END

Notes

  • you can wraps this via a UDF using CREATE FUNCTION etc
  • you may need NULL handling (in my code above, any NULL will report 1)
  • str1 and str2 will be column names or @variables

How do I overload the square-bracket operator in C#?

For CLI C++ (compiled with /clr) see this MSDN link.

In short, a property can be given the name "default":

ref class Class
{
 public:
  property System::String^ default[int i]
  {
    System::String^ get(int i) { return "hello world"; }
  }
};

How to pass an ArrayList to a varargs method parameter?

You can do:

getMap(locations.toArray(new WorldLocation[locations.size()]));

or

getMap(locations.toArray(new WorldLocation[0]));

or

getMap(new WorldLocation[locations.size()]);

@SuppressWarnings("unchecked") is needed to remove the ide warning.

Auto refresh page every 30 seconds

Use setInterval instead of setTimeout. Though in this case either will be fine but setTimeout inherently triggers only once setInterval continues indefinitely.

<script language="javascript">
setInterval(function(){
   window.location.reload(1);
}, 30000);
</script>

Update a column value, replacing part of a string

First, have to check

SELECT * FROM university WHERE course_name LIKE '%&amp%'

Next, have to update

UPDATE university SET course_name = REPLACE(course_name, '&amp', '&') WHERE id = 1

Results: Engineering &amp Technology => Engineering & Technology

How to read XML using XPath in Java

You can try this.

XML Document

Save as employees.xml.

<?xml version="1.0" encoding="UTF-8"?>
<Employees>
    <Employee id="1">
        <age>29</age>
        <name>Pankaj</name>
        <gender>Male</gender>
        <role>Java Developer</role>
    </Employee>
    <Employee id="2">
        <age>35</age>
        <name>Lisa</name>
        <gender>Female</gender>
        <role>CEO</role>
    </Employee>
    <Employee id="3">
        <age>40</age>
        <name>Tom</name>
        <gender>Male</gender>
        <role>Manager</role>
    </Employee>
    <Employee id="4">
        <age>25</age>
        <name>Meghan</name>
        <gender>Female</gender>
        <role>Manager</role>
    </Employee>
</Employees>

Parser class

The class have following methods

  • List item
  • A Method that will return the Employee Name for input ID.
  • A Method that will return list of Employees Name with age greater than the input age.
  • A Method that will return list of Female Employees Name.

Source Code

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;


public class Parser {

    public static void main(String[] args) {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        DocumentBuilder builder;
        Document doc = null;
        try {
            builder = factory.newDocumentBuilder();
            doc = builder.parse("employees.xml");

            // Create XPathFactory object
            XPathFactory xpathFactory = XPathFactory.newInstance();

            // Create XPath object
            XPath xpath = xpathFactory.newXPath();

            String name = getEmployeeNameById(doc, xpath, 4);
            System.out.println("Employee Name with ID 4: " + name);

            List<String> names = getEmployeeNameWithAge(doc, xpath, 30);
            System.out.println("Employees with 'age>30' are:" + Arrays.toString(names.toArray()));

            List<String> femaleEmps = getFemaleEmployeesName(doc, xpath);
            System.out.println("Female Employees names are:" +
                    Arrays.toString(femaleEmps.toArray()));

        } catch (ParserConfigurationException | SAXException | IOException e) {
            e.printStackTrace();
        }

    }


    private static List<String> getFemaleEmployeesName(Document doc, XPath xpath) {
        List<String> list = new ArrayList<>();
        try {
            //create XPathExpression object
            XPathExpression expr =
                xpath.compile("/Employees/Employee[gender='Female']/name/text()");
            //evaluate expression result on XML document
            NodeList nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
            for (int i = 0; i < nodes.getLength(); i++)
                list.add(nodes.item(i).getNodeValue());
        } catch (XPathExpressionException e) {
            e.printStackTrace();
        }
        return list;
    }


    private static List<String> getEmployeeNameWithAge(Document doc, XPath xpath, int age) {
        List<String> list = new ArrayList<>();
        try {
            XPathExpression expr =
                xpath.compile("/Employees/Employee[age>" + age + "]/name/text()");
            NodeList nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
            for (int i = 0; i < nodes.getLength(); i++)
                list.add(nodes.item(i).getNodeValue());
        } catch (XPathExpressionException e) {
            e.printStackTrace();
        }
        return list;
    }


    private static String getEmployeeNameById(Document doc, XPath xpath, int id) {
        String name = null;
        try {
            XPathExpression expr =
                xpath.compile("/Employees/Employee[@id='" + id + "']/name/text()");
            name = (String) expr.evaluate(doc, XPathConstants.STRING);
        } catch (XPathExpressionException e) {
            e.printStackTrace();
        }

        return name;
    }

}

How to remove error about glyphicons-halflings-regular.woff2 not found

This problem happens because IIS does not find the actual location of woff2 file mime types. Set URL of font-face properly, also keep font-family as glyphicons-halflings-regular in your CSS file as shown below.

@font-face {
font-family: 'glyphicons-halflings-regular'; 
src: url('../../../fonts/glyphicons-halflings-regular.woff2') format('woff2');}

Why is there no xrange function in Python3?

Some performance measurements, using timeit instead of trying to do it manually with time.

First, Apple 2.7.2 64-bit:

In [37]: %timeit collections.deque((x for x in xrange(10000000) if x%4 == 0), maxlen=0)
1 loops, best of 3: 1.05 s per loop

Now, python.org 3.3.0 64-bit:

In [83]: %timeit collections.deque((x for x in range(10000000) if x%4 == 0), maxlen=0)
1 loops, best of 3: 1.32 s per loop

In [84]: %timeit collections.deque((x for x in xrange(10000000) if x%4 == 0), maxlen=0)
1 loops, best of 3: 1.31 s per loop

In [85]: %timeit collections.deque((x for x in iter(range(10000000)) if x%4 == 0), maxlen=0) 
1 loops, best of 3: 1.33 s per loop

Apparently, 3.x range really is a bit slower than 2.x xrange. And the OP's xrange function has nothing to do with it. (Not surprising, as a one-time call to the __iter__ slot isn't likely to be visible among 10000000 calls to whatever happens in the loop, but someone brought it up as a possibility.)

But it's only 30% slower. How did the OP get 2x as slow? Well, if I repeat the same tests with 32-bit Python, I get 1.58 vs. 3.12. So my guess is that this is yet another of those cases where 3.x has been optimized for 64-bit performance in ways that hurt 32-bit.

But does it really matter? Check this out, with 3.3.0 64-bit again:

In [86]: %timeit [x for x in range(10000000) if x%4 == 0]
1 loops, best of 3: 3.65 s per loop

So, building the list takes more than twice as long than the entire iteration.

And as for "consumes much more resources than Python 2.6+", from my tests, it looks like a 3.x range is exactly the same size as a 2.x xrange—and, even if it were 10x as big, building the unnecessary list is still about 10000000x more of a problem than anything the range iteration could possibly do.

And what about an explicit for loop instead of the C loop inside deque?

In [87]: def consume(x):
   ....:     for i in x:
   ....:         pass
In [88]: %timeit consume(x for x in range(10000000) if x%4 == 0)
1 loops, best of 3: 1.85 s per loop

So, almost as much time wasted in the for statement as in the actual work of iterating the range.

If you're worried about optimizing the iteration of a range object, you're probably looking in the wrong place.


Meanwhile, you keep asking why xrange was removed, no matter how many times people tell you the same thing, but I'll repeat it again: It was not removed: it was renamed to range, and the 2.x range is what was removed.

Here's some proof that the 3.3 range object is a direct descendant of the 2.x xrange object (and not of the 2.x range function): the source to 3.3 range and 2.7 xrange. You can even see the change history (linked to, I believe, the change that replaced the last instance of the string "xrange" anywhere in the file).

So, why is it slower?

Well, for one, they've added a lot of new features. For another, they've done all kinds of changes all over the place (especially inside iteration) that have minor side effects. And there'd been a lot of work to dramatically optimize various important cases, even if it sometimes slightly pessimizes less important cases. Add this all up, and I'm not surprised that iterating a range as fast as possible is now a bit slower. It's one of those less-important cases that nobody would ever care enough to focus on. No one is likely to ever have a real-life use case where this performance difference is the hotspot in their code.

Java SSL: how to disable hostname verification

In case you're using apache's http-client 4:

SSLConnectionSocketFactory sslConnectionSocketFactory = 
    new SSLConnectionSocketFactory(sslContext,
             new String[] { "TLSv1.2" }, null, new HostnameVerifier() {
                    public boolean verify(String arg0, SSLSession arg1) {
                            return true;
            }
      });

How do I read from parameters.yml in a controller in symfony2?

In Symfony 4, you can use the ParameterBagInterface:

use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;

class MessageGenerator
{
    private $params;

    public function __construct(ParameterBagInterface $params)
    {
        $this->params = $params;
    }

    public function someMethod()
    {
        $parameterValue = $this->params->get('parameter_name');
        // ...
    }
}

and in app/config/services.yaml:

parameters:
    locale: 'en'
    dir: '%kernel.project_dir%'

It works for me in both controller and form classes. More details can be found in the Symfony blog.

Iterating over each line of ls -l output

So, why didn't anybody suggest just using options that eliminate the parts he doesn't want to process.

On modern Debian you just get your file with:

ls --format=single-column 

Further more, you don't have to pay attention to what directory you are running it in if you use the full directory:

ls --format=single-column /root/dir/starting/point/to/target/dir/

This last command I am using the above and I get the following output:

bot@dev:~/downloaded/Daily# ls --format=single-column /home/bot/downloaded/Daily/*.gz
/home/bot/downloaded/Daily/Liq_DailyManifest_V3_US_20141119_IENT1.txt.gz
/home/bot/downloaded/Daily/Liq_DailyManifest_V3_US_20141120_IENT1.txt.gz
/home/bot/downloaded/Daily/Liq_DailyManifest_V3_US_20141121_IENT1.txt.gz

char initial value in Java

you can initialize it to ' ' instead. Also, the reason that you received an error -1 being too many characters is because it is treating '-' and 1 as separate.

ImageView in android XML layout with layout_height="wrap_content" has padding top & bottom

I had a simular issue and resolved it using android:adjustViewBounds="true" on the ImageView.

<ImageView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:adjustViewBounds="true"
    android:contentDescription="@string/banner_alt"
    android:src="@drawable/banner_portrait" />

Boto3 to download all files from a S3 Bucket

import os
import boto3

#initiate s3 resource
s3 = boto3.resource('s3')

# select bucket
my_bucket = s3.Bucket('my_bucket_name')

# download file into current directory
for s3_object in my_bucket.objects.all():
    # Need to split s3_object.key into path and file name, else it will give error file not found.
    path, filename = os.path.split(s3_object.key)
    my_bucket.download_file(s3_object.key, filename)

momentJS date string add 5 days

moment(moment('2015/04/09 16:00:00').add(7, 'd').format('YYYY/MM/DD HH:mm:mm'))

has to format and then convert to moment again.

Extracting first n columns of a numpy matrix

If a is your array:

In [11]: a[:,:2]
Out[11]: 
array([[-0.57098887, -0.4274751 ],
       [-0.22279713, -0.51723555],
       [ 0.67492385, -0.69294472],
       [ 0.41086611,  0.26374238]])

React.createElement: type is invalid -- expected a string

Circular dependency is also one of the reasons for this. [in general]

How do I capture the output into a variable from an external process in PowerShell?

Another real-life example:

$result = & "$env:cust_tls_store\Tools\WDK\x64\devcon.exe" enable $strHwid 2>&1 | Out-String

Notice that this example includes a path (which begins with an environment variable). Notice that the quotes must surround the path and the EXE file, but not the parameters!

Note: Don't forget the & character in front of the command, but outside of the quotes.

The error output is also collected.

It took me a while to get this combination working, so I thought that I would share it.

Call ASP.NET function from JavaScript?

I try this and so I could run an Asp.Net method while using jQuery.

  1. Do a page redirect in your jQuery code

    window.location = "Page.aspx?key=1";
    
  2. Then use a Query String in Page Load

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.QueryString["key"] != null)
        {
            string key= Request.QueryString["key"];
            if (key=="1")
            {
                // Some code
            }
        }
    }
    

So no need to run an extra code

How to extract base URL from a string in JavaScript?

var tilllastbackslashregex = new RegExp(/^.*\//);
baseUrl = tilllastbackslashregex.exec(window.location.href);

window.location.href gives the current url address from browser address bar

it can be any thing like https://stackoverflow.com/abc/xyz or https://www.google.com/search?q=abc tilllastbackslashregex.exec() run regex and retun the matched string till last backslash ie https://stackoverflow.com/abc/ or https://www.google.com/ respectively

Faster alternative in Oracle to SELECT COUNT(*) FROM sometable

Option 1: Have an index on a non-null column present that can be used for the scan. Or create a function-based index as:

create index idx on t(0);

this can then be scanned to give the count.

Option 2: If you have monitoring turned on then check the monitoring view USER_TAB_MODIFICATIONS and add/subtract the relevant values to the table statistics.

Option 3: For a quick estimate on large tables invoke the SAMPLE clause ... for example ...

SELECT 1000*COUNT(*) FROM sometable SAMPLE(0.1); 

Option 4: Use a materialized view to maintain the count(*). Powerful medicine though.

um ...

What's the easiest way to install a missing Perl module?

2 ways that I know of :

USING PPM :

With Windows (ActivePerl) I've used ppm

from the command line type ppm. At the ppm prompt ...

ppm> install foo

or

ppm> search foo

to get a list of foo modules available. Type help for all the commands

USING CPAN :

you can also use CPAN like this (*nix systems) :

perl -MCPAN -e 'shell'

gets you a prompt

cpan>

at the prompt ...

cpan> install foo  (again to install the foo module)

type h to get a list of commands for cpan

Dark theme in Netbeans 7 or 8

On Mac

Netbeans 8.0.2 Tools -> Plugins -> type in search: Dark Look and Feel. Then install plugin.

NOTE: There is no "Option" Or "Appearance" in the "Tools" section in Netbeans 8.0.2.

enter image description here

Write Base64-encoded image to file

Assuming the image data is already in the format you want, you don't need image ImageIO at all - you just need to write the data to the file:

// Note preferred way of declaring an array variable
byte[] data = Base64.decodeBase64(crntImage);
try (OutputStream stream = new FileOutputStream("c:/decode/abc.bmp")) {
    stream.write(data);
}

(I'm assuming you're using Java 7 here - if not, you'll need to write a manual try/finally statement to close the stream.)

If the image data isn't in the format you want, you'll need to give more details.

C# binary literals

Basically, I think the answer is NO, there is no easy way. Use decimal or hexadecimal constants - they are simple and clear. @RoyTinkers answer is also good - use a comment.

int someHexFlag = 0x010; // 000000010000
int someDecFlag = 8;     // 000000001000

The others answers here present several useful work-a rounds, but I think they aren't better then the simple answer. C# language designers probably considered a '0b' prefix unnecessary. HEX is easy to convert to binary, and most programmers are going to have to know the DEC equivalents of 0-8 anyways.

Also, when examining values in the debugger, they will be displayed has HEX or DEC.

How to convert integer into date object python?

I would suggest the following simple approach for conversion:

from datetime import datetime, timedelta
s = "20120213"
# you could also import date instead of datetime and use that.
date = datetime(year=int(s[0:4]), month=int(s[4:6]), day=int(s[6:8]))

For adding/subtracting an arbitary amount of days (seconds work too btw.), you could do the following:

date += timedelta(days=10)
date -= timedelta(days=5)

And convert back using:

s = date.strftime("%Y%m%d")

To convert the integer to a string safely, use:

s = "{0:-08d}".format(i)

This ensures that your string is eight charecters long and left-padded with zeroes, even if the year is smaller than 1000 (negative years could become funny though).

Further reference: datetime objects, timedelta objects

equivalent of rm and mv in windows .cmd

move and del ARE certainly the equivalents, but from a functionality standpoint they are woefully NOT equivalent. For example, you can't move both files AND folders (in a wildcard scenario) with the move command. And the same thing applies with del.

The preferred solution in my view is to use Win32 ports of the Linux tools, the best collection of which I have found being here.

mv and rm are in the CoreUtils package and they work wonderfully!

Python sockets error TypeError: a bytes-like object is required, not 'str' with send function

The reason for this error is that in Python 3, strings are Unicode, but when transmitting on the network, the data needs to be bytes instead. So... a couple of suggestions:

  1. Suggest using c.sendall() instead of c.send() to prevent possible issues where you may not have sent the entire msg with one call (see docs).
  2. For literals, add a 'b' for bytes string: c.sendall(b'Thank you for connecting')
  3. For variables, you need to encode Unicode strings to byte strings (see below)

Best solution (should work w/both 2.x & 3.x):

output = 'Thank you for connecting'
c.sendall(output.encode('utf-8'))

Epilogue/background: this isn't an issue in Python 2 because strings are bytes strings already -- your OP code would work perfectly in that environment. Unicode strings were added to Python in releases 1.6 & 2.0 but took a back seat until 3.0 when they became the default string type. Also see this similar question as well as this one.

Requested bean is currently in creation: Is there an unresolvable circular reference?

@Resource annotation on field level also could be used to declare look up at runtime

How to declare 2D array in bash

For simulating a 2-dimensional array, I first load the first n-elements (the elements of the first column)

local pano_array=()  

i=0

for line in $(grep  "filename" "$file")
do 
  url=$(extract_url_from_xml $line)
  pano_array[i]="$url"
  i=$((i+1))
done

To add the second column, I define the size of the first column and calculate the values in an offset variable

array_len="${#pano_array[@]}"

i=0

while [[ $i -lt $array_len ]]
do
  url="${pano_array[$i]}"
  offset=$(($array_len+i)) 
  found_file=$(get_file $url)
  pano_array[$offset]=$found_file

  i=$((i+1))
done

Restart pods when configmap updates in Kubernetes?

The current best solution to this problem (referenced deep in https://github.com/kubernetes/kubernetes/issues/22368 linked in the sibling answer) is to use Deployments, and consider your ConfigMaps to be immutable.

When you want to change your config, create a new ConfigMap with the changes you want to make, and point your deployment at the new ConfigMap. If the new config is broken, the Deployment will refuse to scale down your working ReplicaSet. If the new config works, then your old ReplicaSet will be scaled to 0 replicas and deleted, and new pods will be started with the new config.

Not quite as quick as just editing the ConfigMap in place, but much safer.

How can I control Chromedriver open window size?

C# version of @yonatan-kiron's answer, and Selenium's using statement from their example code.

ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.AddArgument("--window-size=1300,1000");

using (IWebDriver driver = new ChromeDriver(chromeOptions))
{
    ...
}

Why is Ant giving me a Unsupported major.minor version error

If you're getting this error because you're purposefully trying to build to Java 6, but you have Java 7 elsewhere in Eclipse, then it may be because you are referencing a Java 7 tools.jar in a Java 6 environment.

You'll need to install the JDK 6 (not JRE) and add the JRE 6 tools.jar as a User Entry in the Classpath of the build configuration, listed above the JRE 7 tools.jar.

[Vue warn]: Property or method is not defined on the instance but referenced during render

If you're experiencing this problem, check to make sure you don't have

methods: {
...
}

or

computed: {
...
}

declared twice

Index was outside the bounds of the Array. (Microsoft.SqlServer.smo)

The Reason behind the error message is that SQL couldn't show new features in your old SQL server version.

Please upgrade your client SQL version to same as your server Sql version

Is there a command to restart computer into safe mode?

My first answer!

This will set the safemode switch:

bcdedit /set {current} safeboot minimal 

with networking:

bcdedit /set {current} safeboot network

then reboot the machine with

shutdown /r

to put back in normal mode via dos:

bcdedit /deletevalue {current} safeboot

Turn off deprecated errors in PHP 5.3

All the previous answers are correct. Since no one have hinted out how to turn off all errors in PHP, I would like to mention it here:

error_reporting(0); // Turn off warning, deprecated,
                    // notice everything except error

Somebody might find it useful...

dereferencing pointer to incomplete type

Outside of possible scenarios involving whole-program optimization, the code code generated for something like:

struct foo *bar;
struct foo *test(struct foo *whatever, int blah)
{
  return blah ? whatever: bar;
}

will be totally unaffected by what members struct foo might contain. Because make utilities will generally recompile any compilation unit in which the complete definition of a structure appears, even when such changes couldn't actually affect the code generated for them, it's common to omit complete structure definitions from compilation units that don't actually need them, and such omission is generally not worthy of a warning.

A compiler needs to have a complete structure or union definition to know how to handle declarations objects of the type with automatic or static duration, declarations of aggregates containing members of the type, or code which accesses members of the structure or union. If the compiler doesn't have the information needed to perform one of the above operations, it will have no choice but to squawk about it.

Incidentally, there's one more situation where the Standard would allow a compiler to require a complete union definition to be visible but would not require a diagnostic: if two structures start with a Common Initial Sequence, and a union type containing both is visible when the compiler is processing code that uses a pointer of one of the structure types to inspects a member of that Common Initial Sequence, the compiler is required to recognize that such code might be accessing the corresponding member of a structure of the other type. I don't know what compilers if any comply with the Standard when the complete union type is visible but not when it isn't [gcc is prone to generate non-conforming code in either case unless the -fno-strict-aliasing flag is used, in which case it will generate conforming code in both cases] but if one wants to write code that uses the CIS rule in such a fashion as to guarantee correct behavior on conforming compilers, one may need to ensure that complete union type definition is visible; failure to do so may result in a compiler silently generating bogus code.

C++ compile time error: expected identifier before numeric constant

Since your compiler probably doesn't support all of C++11 yet, which supports similar syntax, you're getting these errors because you have to initialize your class members in constructors:

Attribute() : name(5),val(5,0) {}

Java and HTTPS url connection without downloading certificate

But why don't I have to install a certificate locally for the site?

Well the code that you are using is explicitly designed to accept the certificate without doing any checks whatsoever. This is not good practice ... but if that is what you want to do, then (obviously) there is no need to install a certificate that your code is explicitly ignoring.

Shouldn't I have to install a certificate locally and load it for this program or is it downloaded behind the covers?

No, and no. See above.

Is the traffic between the client to the remote site still encrypted in transmission?

Yes it is. However, the problem is that since you have told it to trust the server's certificate without doing any checks, you don't know if you are talking to the real server, or to some other site that is pretending to be the real server. Whether this is a problem depends on the circumstances.


If we used the browser as an example, typically a browser doesn't ask the user to explicitly install a certificate for each ssl site visited.

The browser has a set of trusted root certificates pre-installed. Most times, when you visit an "https" site, the browser can verify that the site's certificate is (ultimately, via the certificate chain) secured by one of those trusted certs. If the browser doesn't recognize the cert at the start of the chain as being a trusted cert (or if the certificates are out of date or otherwise invalid / inappropriate), then it will display a warning.

Java works the same way. The JVM's keystore has a set of trusted certificates, and the same process is used to check the certificate is secured by a trusted certificate.

Does the java https client api support some type of mechanism to download certificate information automatically?

No. Allowing applications to download certificates from random places, and install them (as trusted) in the system keystore would be a security hole.

How to hide columns in an ASP.NET GridView with auto-generated columns?

I found Steve Hibbert's response to be very helpful. The problem the OP seemed to be describing is that of an AutoGeneratedColumns on a GridView.

In this instance you can set which columns will be "visible" and which will be hidden when you bind a data table in the code behind.

For example: A Gridview is on the page as follows.

<asp:GridView ID="gv" runat="server" AutoGenerateColumns="False" >
</asp:GridView>

And then in the code behind a PopulateGridView routine is called during the page load event.

protected void PopulateGridView()
{
    DataTable dt = GetDataSource();
    gv.DataSource = dt;
    foreach (DataColumn col in dt.Columns)
    {
        BoundField field = new BoundField();
        field.DataField = col.ColumnName;
        field.HeaderText = col.ColumnName;
        if (col.ColumnName.EndsWith("ID"))
        {
            field.Visible = false;
        }
        gv.Columns.Add(field);
    }
    gv.DataBind();
}

In the above the GridView AutoGenerateColumns is set to False and the codebehind is used to create the bound fields. One is obtaining the datasource as a datatable through one's own process which here I labeled GetDataSource(). Then one loops through the columns collection of the datatable. If the column name meets a given criteria, you can set the bound field visible property accordingly. Then you bind the data to the gridview. This is very similar to AutoGenerateColumns="True" but you get to have criteria for the columns. This approach is most useful when the criteria for hiding and un-hiding is based upon the column name.

Find the files existing in one directory but not in the other

A simplified way to compare 2 directories using the DIFF command

diff filename.1 filename.2 > filename.dat >>Enter

open filename.dat after the run is complete

and you will see: Only in filename.1: filename.2 Only in: directory_name: name_of_file1 Only in: directory_Name: name_of_file2

Java rounding up to an int using Math.ceil

Use double to cast like

Math.ceil((double)value) or like

Math.ceil((double)value1/(double)value2);

How to insert a SQLite record with a datetime set to 'now' in Android application?

There are a couple options you can use:

  1. You could try using the string "(DATETIME('now'))" instead.
  2. Insert the datetime yourself, ie with System.currentTimeMillis()
  3. When creating the SQLite table, specify a default value for the created_date column as the current date time.
  4. Use SQLiteDatabase.execSQL to insert directly.

How to push elements in JSON from javascript array

I think you want to make objects from array and combine it with an old object (BODY.recipients.values), if it's then you may do it using $.extent (because you are using jQuery/tagged) method after prepare the object from array

var BODY = {
    "recipients": {
        "values": []
    },
    "subject": 'TitleOfSubject',
    "body": 'This is the message body.'
}

var values = [],
names = ['sheikh', 'muhammed', 'Answer', 'Uddin', 'Heera']; // for testing
for (var ln = 0; ln < names.length; ln++) {
    var item1 = {
        "person": { "_path": "/people/"+names[ln] }
    };
    values.push(item1);
}

// Now merge with BODY
$.extend(BODY.recipients.values, values);

DEMO.

What are the differences between delegates and events?

Here is another good link to refer to. http://csharpindepth.com/Articles/Chapter2/Events.aspx

Briefly, the take away from the article - Events are encapsulation over delegates.

Quote from article:

Suppose events didn't exist as a concept in C#/.NET. How would another class subscribe to an event? Three options:

  1. A public delegate variable

  2. A delegate variable backed by a property

  3. A delegate variable with AddXXXHandler and RemoveXXXHandler methods

Option 1 is clearly horrible, for all the normal reasons we abhor public variables.

Option 2 is slightly better, but allows subscribers to effectively override each other - it would be all too easy to write someInstance.MyEvent = eventHandler; which would replace any existing event handlers rather than adding a new one. In addition, you still need to write the properties.

Option 3 is basically what events give you, but with a guaranteed convention (generated by the compiler and backed by extra flags in the IL) and a "free" implementation if you're happy with the semantics that field-like events give you. Subscribing to and unsubscribing from events is encapsulated without allowing arbitrary access to the list of event handlers, and languages can make things simpler by providing syntax for both declaration and subscription.

Android: keep Service running when app is killed

In your service, add the following code.

@Override
public void onTaskRemoved(Intent rootIntent){
    Intent restartServiceIntent = new Intent(getApplicationContext(), this.getClass());
    restartServiceIntent.setPackage(getPackageName());

    PendingIntent restartServicePendingIntent = PendingIntent.getService(getApplicationContext(), 1, restartServiceIntent, PendingIntent.FLAG_ONE_SHOT);
    AlarmManager alarmService = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
    alarmService.set(
    AlarmManager.ELAPSED_REALTIME,
    SystemClock.elapsedRealtime() + 1000,
    restartServicePendingIntent);

    super.onTaskRemoved(rootIntent);
 }

How to change the color of the axis, ticks and labels for a plot in matplotlib

If you have several figures or subplots that you want to modify, it can be helpful to use the matplotlib context manager to change the color, instead of changing each one individually. The context manager allows you to temporarily change the rc parameters only for the immediately following indented code, but does not affect the global rc parameters.

This snippet yields two figures, the first one with modified colors for the axis, ticks and ticklabels, and the second one with the default rc parameters.

import matplotlib.pyplot as plt
with plt.rc_context({'axes.edgecolor':'orange', 'xtick.color':'red', 'ytick.color':'green', 'figure.facecolor':'white'}):
    # Temporary rc parameters in effect
    fig, (ax1, ax2) = plt.subplots(1,2)
    ax1.plot(range(10))
    ax2.plot(range(10))
# Back to default rc parameters
fig, ax = plt.subplots()
ax.plot(range(10))

enter image description here

enter image description here

You can type plt.rcParams to view all available rc parameters, and use list comprehension to search for keywords:

# Search for all parameters containing the word 'color'
[(param, value) for param, value in plt.rcParams.items() if 'color' in param]

jQuery show/hide options from one select drop down, when option on other select dropdown is slected

// find the first select and bind a click handler
$('#column_select').bind('click', function(){
    // retrieve the selected value
    var value = $(this).val(),
        // build a regular expression that does a head-match
        expression = new RegExp('^' + value),
        // find the second select
        $select = $('#layout_select);

    // hide all children (<option>s) of the second select,
    // check each element's value agains the regular expression built from the first select's value
    // show elements that match the expression
    $select.children().hide().filter(function(){
      return !!$(this).val().match(expression);
    }).show();
});

(this is far from perfect, but should get you there…)

Bootstrap 3 panel header with buttons wrong position

You should apply a "clearfix" to clear the parent element. Next thing, the h4 for the header title, extend all the way across the header, so after you apply clearfix, it will push down the child element causing the header div to have a larger height.

Here is a fix, just replace it with your code.

  <div class="panel-heading clearfix">
     <b>Panel header</b>
       <div class="btn-group pull-right">
        <a href="#" class="btn btn-default btn-sm">## Lock</a>
        <a href="#" class="btn btn-default btn-sm">## Delete</a>
        <a href="#" class="btn btn-default btn-sm">## Move</a>
      </div>
   </div>

Editted on 12/22/2015 - added .clearfix to heading div

Using FileUtils in eclipse

I have come accross the above issue. I have solved it as below. Its working fine for me.

  1. Download the 'org.apache.commons.io.jar' file on navigating to [org.apache.commons.io.FileUtils] [ http://www.java2s.com/Code/Jar/o/Downloadorgapachecommonsiojar.htm ]

  2. Extract the downloaded zip file to a specified folder.

  3. Update the project properties by using below navigation Right click on project>Select Properties>Select Java Build Path> Click Libraries tab>Click Add External Class Folder button>Select the folder where zip file is extracted for org.apache.commons.io.FileUtils.zip file.

  4. Now access the File Utils.

How to fire an event when v-model changes?

Just to add to the correct answer above, in Vue.JS v1.0 you can write

<a v-on:click="doSomething">

So in this example it would be

 v-on:change="foo"

See: http://v1.vuejs.org/guide/syntax.html#Arguments

Handling NULL values in Hive

I use below sql to exclude the null string and empty string lines.

select * from table where length(nvl(column1,0))>0

Because, the length of empty string is 0.

select length('');
+-----------+--+
| length()  |
+-----------+--+
| 0         |
+-----------+--+

PHP form - on submit stay on same page

There are two ways of doing it:

  1. Submit the form to the same page: Handle the submitted form using PHP script. (This can be done by setting the form action to the current page URL.)

    if(isset($_POST['submit'])) {
        // Enter the code you want to execute after the form has been submitted
        // Display Success or Failure message (if any)
      } else {
        // Display the Form and the Submit Button
    }
    
  2. Using AJAX Form Submission which is a little more difficult for a beginner than method #1.

Python - Check If Word Is In A String

As you are asking for a word and not for a string, I would like to present a solution which is not sensitive to prefixes / suffixes and ignores case:

#!/usr/bin/env python

import re


def is_word_in_text(word, text):
    """
    Check if a word is in a text.

    Parameters
    ----------
    word : str
    text : str

    Returns
    -------
    bool : True if word is in text, otherwise False.

    Examples
    --------
    >>> is_word_in_text("Python", "python is awesome.")
    True

    >>> is_word_in_text("Python", "camelCase is pythonic.")
    False

    >>> is_word_in_text("Python", "At the end is Python")
    True
    """
    pattern = r'(^|[^\w]){}([^\w]|$)'.format(word)
    pattern = re.compile(pattern, re.IGNORECASE)
    matches = re.search(pattern, text)
    return bool(matches)


if __name__ == '__main__':
    import doctest
    doctest.testmod()

If your words might contain regex special chars (such as +), then you need re.escape(word)

How do you push just a single Git branch (and no other branches)?

By default git push updates all the remote branches. But you can configure git to update only the current branch to it's upstream.

git config push.default upstream

It means git will update only the current (checked out) branch when you do git push.

Other valid options are:

  • nothing : Do not push anything (error out) unless a refspec is explicitly given. This is primarily meant for people who want to avoid mistakes by always being explicit.
  • matching : Push all branches having the same name on both ends. (default option prior to Ver 1.7.11)
  • upstream: Push the current branch to its upstream branch. This mode only makes sense if you are pushing to the same repository you would normally pull from (i.e. central workflow). No need to have the same name for local and remote branch.
  • tracking : Deprecated, use upstream instead.
  • current : Push the current branch to the remote branch of the same name on the receiving end. Works in both central and non-central workflows.
  • simple : [available since Ver 1.7.11] in centralized workflow, work like upstream with an added safety to refuse to push if the upstream branch’s name is different from the local one. When pushing to a remote that is different from the remote you normally pull from, work as current. This is the safest option and is suited for beginners. This mode has become the default in Git 2.0.

How to inject a Map using the @Value Spring Annotation?

Following worked for me:

SpingBoot 2.1.7.RELEASE

YAML Property (Notice value sourrounded by single quotes)

property:
   name: '{"key1": false, "key2": false, "key3": true}'

In Java/Kotlin annotate field with (Notice use of #) (For java no need to escape '$' with '\')

@Value("#{\${property.name}}")

Javascript document.getElementById("id").value returning null instead of empty string when the element is an empty text box

try this...    
<script type="text/javascript">
    function test(){
    var av=document.getElementById("mytext").value;
    alert(av);
    }
    </script>

    <input type="text" value="" id="mytext">
    <input type="button" onclick="test()" value="go" />

Uninitialized Constant MessagesController

Your model is @Messages, change it to @message.

To change it like you should use migration:

def change   rename_table :old_table_name, :new_table_name end 

Of course do not create that file by hand but use rails generator:

rails g migration ChangeMessagesToMessage 

That will generate new file with proper timestamp in name in 'db dir. Then run:

rake db:migrate 

And your app should be fine since then.

How can javascript upload a blob?

2019 Update

This updates the answers with the latest Fetch API and doesn't need jQuery.

Disclaimer: doesn't work on IE, Opera Mini and older browsers. See caniuse.

Basic Fetch

It could be as simple as:

  fetch(`https://example.com/upload.php`, {method:"POST", body:blobData})
                .then(response => console.log(response.text()))

Fetch with Error Handling

After adding error handling, it could look like:

fetch(`https://example.com/upload.php`, {method:"POST", body:blobData})
            .then(response => {
                if (response.ok) return response;
                else throw Error(`Server returned ${response.status}: ${response.statusText}`)
            })
            .then(response => console.log(response.text()))
            .catch(err => {
                alert(err);
            });

PHP Code

This is the server-side code in upload.php.

<?php    
    // gets entire POST body
    $data = file_get_contents('php://input');
    // write the data out to the file
    $fp = fopen("path/to/file", "wb");

    fwrite($fp, $data);
    fclose($fp);
?>

How do I get the current location of an iframe?

I use this.

var iframe = parent.document.getElementById("theiframe");
var innerDoc = iframe.contentDocument || iframe.contentWindow.document;

var currentFrame = innerDoc.location.href;

SQL (MySQL) vs NoSQL (CouchDB)

One of the best options is to go for MongoDB(NOSql dB) that supports scalability.Stores large amounts of data nothing but bigdata in the form of documents unlike rows and tables in sql.This is fasters that follows sharding of the data.Uses replicasets to ensure data guarantee that maintains multiple servers having primary db server as the base. Language independent. Flexible to use

How to upgrade OpenSSL in CentOS 6.5 / Linux / Unix from source?

My approach was:

openssl version
OpenSSL 1.0.1e 11 Feb 2013

wget https://www.openssl.org/source/openssl-1.0.2a.tar.gz
wget http://www.linuxfromscratch.org/patches/blfs/svn/openssl-1.0.2a-fix_parallel_build-1.patch
tar xzf openssl-1.0.2a.tar.gz
cd openssl-1.0.2a
patch -Np1 -i ../openssl-1.0.2a-fix_parallel_build-1.patch
./config --prefix=/usr --openssldir=/etc/ssl --libdir=lib shared zlib-dynamic
make
make install

openssl version
OpenSSL 1.0.2a 19 Mar 2015 

PowerShell to remove text from a string

This should do what you want:

C:\PS> if ('=keep this,' -match '=([^,]*)') { $matches[1] }
keep this

Cloudfront custom-origin distribution returns 502 "ERROR The request could not be satisfied." for some URLs

In my case, I use nginx as reverse-proxy for an API Gateway URL. I got same error.

I resolved the issue when I added the following two lines to the Nginx config:

proxy_set_header Host "XXXXXX.execute-api.REGION.amazonaws.com";
proxy_ssl_server_name on;

Source is here: Setting up proxy_pass on nginx to make API calls to API Gateway

Why do I have ORA-00904 even when the column is present?

Have you compared the table definitions in Prod and Dev?

And when you are running it in SQL Developer, are you running the query in Prod (same database as the application) and with the same user?

If there are some additional columns that you are adding (using an alter command) and these changes are not yet promoted to prod, this issue is possible.

Can you post the definition of the table and your actual Query?

Using Pandas to pd.read_excel() for multiple worksheets of the same workbook

You could also specify the sheet name as a parameter:

data_file = pd.read_excel('path_to_file.xls', sheet_name="sheet_name")

will upload only the sheet "sheet_name".

How do I create the small icon next to the website tab for my site?

It is called favicon.ico and you can generate it from this site.

http://www.favicon.cc/

How to get a Char from an ASCII Character Code in c#

It is important to notice that in C# the char type is stored as Unicode UTF-16.

From ASCII equivalent integer to char

char c = (char)88;

or

char c = Convert.ToChar(88)

From char to ASCII equivalent integer

int asciiCode = (int)'A';

The literal must be ASCII equivalent. For example:

string str = "X?????????";
Console.WriteLine((int)str[0]);
Console.WriteLine((int)str[1]);

will print

X
3626

Extended ASCII ranges from 0 to 255.

From default UTF-16 literal to char

Using the Symbol

char c = 'X';

Using the Unicode code

char c = '\u0058';

Using the Hexadecimal

char c = '\x0058';

Is there a way to access the "previous row" value in a SELECT statement?

Use the lag function:

SELECT value - lag(value) OVER (ORDER BY Id) FROM table

Sequences used for Ids can skip values, so Id-1 does not always work.

MySQL: How to allow remote connection to mysql

All process for remote login. Remote login is off by default.You need to open it manually for all ip..to give access all ip

GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY 'password';

Specific Ip

GRANT ALL PRIVILEGES ON *.* TO 'root'@'your_desire_ip' IDENTIFIED BY 'password';

then

flush privileges;

You can check your User Host & Password

SELECT host,user,authentication_string FROM mysql.user;

Now your duty is to change this

bind-address = 127.0.0.1

You can find this on

sudo nano /etc/mysql/mysql.conf.d/mysqld.cnf

if you not find this on there then try this

sudo nano /etc/mysql/my.cnf

comment in this

#bind-address = 127.0.0.1

Then restart Mysql

sudo service mysql restart

Now enjoy remote login

How to NodeJS require inside TypeScript file?

The best solution is to get a copy of Node's type definitions. This will solve all kinds of dependency issues, not only require(). This was previously done using packages like typings, but as Mike Chamberlain mentioned, Typings are deprecated. The modern way is doing it like this:

npm install --save-dev @types/node

Not only will it fix the compiler error, it will also add the definitions of the Node API to your IDE.

C++ class forward declaration

The problem is that tick() needs to know the definition of tile_tree_apple, but all it has is a forward declaration of it. You should separate the declarations and definitions like so:

tile_tree.h

#ifndef TILE_TREE_H
#define TILE_TREE_H
#include "tile.h"

class tile_tree : public tile
{
public:
    tile onDestroy();
    tile tick();
    void onCreate();
};

#endif

tile_tree.cpp:

tile tile_tree::onDestroy() {
    return *new tile_grass;
}

tile tile_tree::tick() {
     if (rand() % 20 == 0)
         return *new tile_tree_apple;
}

void tile_tree::onCreate() {
    health = rand() % 5 + 4;
    type = TILET_TREE;
}

Except you have a major problem: you’re allocating memory (with new), then copying the allocated object and returning the copy. This is called a memory leak, because there’s no way for your program to free the memory it uses. Not only that, but you’re copying a tile_tree into a tile, which discards the information that makes a tile_tree different from a tile; this is called slicing.

What you want is to return a pointer to a new tile, and make sure you call delete at some point to free the memory:

tile* tile_tree::tick() {
     if (rand() % 20 == 0)
         return new tile_tree_apple;
}

Even better would be to return a smart pointer that will handle the memory management for you:

#include <memory>

std::shared_ptr<tile> tile_tree::tick() {
     if (rand() % 20 == 0)
         return std::make_shared<tile_tree_apple>();
}

Numpy isnan() fails on an array of floats (from pandas dataframe apply)

np.isnan can be applied to NumPy arrays of native dtype (such as np.float64):

In [99]: np.isnan(np.array([np.nan, 0], dtype=np.float64))
Out[99]: array([ True, False], dtype=bool)

but raises TypeError when applied to object arrays:

In [96]: np.isnan(np.array([np.nan, 0], dtype=object))
TypeError: ufunc 'isnan' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

Since you have Pandas, you could use pd.isnull instead -- it can accept NumPy arrays of object or native dtypes:

In [97]: pd.isnull(np.array([np.nan, 0], dtype=float))
Out[97]: array([ True, False], dtype=bool)

In [98]: pd.isnull(np.array([np.nan, 0], dtype=object))
Out[98]: array([ True, False], dtype=bool)

Note that None is also considered a null value in object arrays.

"Cannot send session cache limiter - headers already sent"

"Headers already sent" means that your PHP script already sent the HTTP headers, and as such it can't make modifications to them now.

Check that you don't send ANY content before calling session_start. Better yet, just make session_start the first thing you do in your PHP file (so put it at the absolute beginning, before all HTML etc).

Angularjs prevent form submission when input validation fails

I know it's late and was answered, but I'd like to share the neat stuff I made. I created an ng-validate directive that hooks the onsubmit of the form, then it issues prevent-default if the $eval is false:

app.directive('ngValidate', function() {
  return function(scope, element, attrs) {
    if (!element.is('form'))
        throw new Error("ng-validate must be set on a form elment!");

    element.bind("submit", function(event) {
        if (!scope.$eval(attrs.ngValidate, {'$event': event}))
            event.preventDefault();
        if (!scope.$$phase)
            scope.$digest();            
    });
  };
});

In your html:

<form name="offering" method="post" action="offer" ng-validate="<boolean expression">

Can someone explain mappedBy in JPA and Hibernate?

By specifying the @JoinColumn on both models you don't have a two way relationship. You have two one way relationships, and a very confusing mapping of it at that. You're telling both models that they "own" the IDAIRLINE column. Really only one of them actually should! The 'normal' thing is to take the @JoinColumn off of the @OneToMany side entirely, and instead add mappedBy to the @OneToMany.

@OneToMany(cascade = CascadeType.ALL, mappedBy="airline")
public Set<AirlineFlight> getAirlineFlights() {
    return airlineFlights;
}

That tells Hibernate "Go look over on the bean property named 'airline' on the thing I have a collection of to find the configuration."

Removing double quotes from variables in batch file creates problems with CMD environment

This sounds like a simple bug where you are using %~ somewhere where you shouldn't be. The use if %~ doesn't fundamentally change the way batch files work, it just removes quotes from the string in that single situation.

Passing struct to function

You need to specify a type on person:

void addStudent(struct student person) {
...
}

Also, you can typedef your struct to avoid having to type struct every time you use it:

typedef struct student{
...
} student_t;

void addStudent(student_t person) {
...
}

Replace non ASCII character from string

The ASCII table contains 128 codes, with a total of 95 printable characters, of which only 52 characters are letters:

  • [0-127] ASCII codes
    • [32-126] printable characters
      • [48-57] digits [0-9]
      • [65-90] uppercase letters [A-Z]
      • [97-122] lowercase letters [a-z]

You can use String.codePoints method to get a stream over int values of characters of this string and filter out non-ASCII characters:

String str1 = "A função, Ãugent";

String str2 = str1.codePoints()
        .filter(ch -> ch < 128)
        .mapToObj(Character::toString)
        .collect(Collectors.joining());

System.out.println(str2); // A funo, ugent

Or you can explicitly specify character ranges. For example filter out everything except letters:

String str3 = str1.codePoints()
        .filter(ch -> ch >= 'A' && ch <= 'Z'
                || ch >= 'a' && ch <= 'z')
        .mapToObj(Character::toString)
        .collect(Collectors.joining());

System.out.println(str3); // Afunougent

See also: How do I not take Special Characters in my Password Validation (without Regex)?

How to uninstall an older PHP version from centOS7

yum -y remove php* to remove all php packages then you can install the 5.6 ones.

Merge two Excel tables Based on matching data in Columns

Put the table in the second image on Sheet2, columns D to F.

In Sheet1, cell D2 use the formula

=iferror(vlookup($A2,Sheet2!$D$1:$F$100,column(A1),false),"")

copy across and down.

Edit: here is a picture. The data is in two sheets. On Sheet1, enter the formula into cell D2. Then copy the formula across to F2 and then down as many rows as you need.

enter image description here

How can I split a text file using PowerShell?

Simple one-liner to split based on number of lines (100 in this case):

$i=0; Get-Content .....log -ReadCount 100 | %{$i++; $_ | Out-File out_$i.txt}

Python convert object to float

  • You can use pandas.Series.astype
  • You can do something like this :

    weather["Temp"] = weather.Temp.astype(float)
    
  • You can also use pd.to_numeric that will convert the column from object to float

  • For details on how to use it checkout this link :http://pandas.pydata.org/pandas-docs/version/0.20/generated/pandas.to_numeric.html
  • Example :

    s = pd.Series(['apple', '1.0', '2', -3])
    print(pd.to_numeric(s, errors='ignore'))
    print("=========================")
    print(pd.to_numeric(s, errors='coerce'))
    
  • Output:

    0    apple
    1      1.0
    2        2
    3       -3
    =========================
    dtype: object
    0    NaN
    1    1.0
    2    2.0
    3   -3.0
    dtype: float64
    
  • In your case you can do something like this:

    weather["Temp"] = pd.to_numeric(weather.Temp, errors='coerce')
    
  • Other option is to use convert_objects
  • Example is as follows

    >> pd.Series([1,2,3,4,'.']).convert_objects(convert_numeric=True)
    
    0     1
    1     2
    2     3
    3     4
    4   NaN
    dtype: float64
    
  • You can use this as follows:

    weather["Temp"] = weather.Temp.convert_objects(convert_numeric=True)
    
  • I have showed you examples because if any of your column won't have a number then it will be converted to NaN... so be careful while using it.

Highcharts - redraw() vs. new Highcharts.chart

you have to call set and add functions on chart object before calling redraw.

chart.xAxis[0].setCategories([2,4,5,6,7], false);

chart.addSeries({
    name: "acx",
    data: [4,5,6,7,8]
}, false);

chart.redraw();

jQuery detect if string contains something

use Contains of jquery Contains like this

if ($('.type:contains("> <")').length > 0)
{
 //do stuffs to change 
}

Using XPATH to search text containing &nbsp;

I cannot get a match using Xpather, but the following worked for me with plain XML and XSL files in Microsoft's XML Notepad:

<xsl:value-of select="count(//td[text()='&nbsp;'])" />

The value returned is 1, which is the correct value in my test case.

However, I did have to declare nbsp as an entity within my XML and XSL using the following:

<!DOCTYPE xsl:stylesheet [ <!ENTITY nbsp "&#160;"> ]>

I'm not sure if that helps you, but I was able to actually find nbsp using an XPath expression.

Edit: My code sample actually contains the characters '&nbsp;' but the JavaScript syntax highlight converts it to the space character. Don't be mislead!

Excel formula to get week number in month (having Monday)

If week 1 always starts on the first Monday of the month try this formula for week number

=INT((6+DAY(A1+1-WEEKDAY(A1-1)))/7)

That gets the week number from the date in A1 with no intermediate calculations - if you want to use your "Monday's date" in B1 you can use this version

=INT((DAY(B1)+6)/7)

Where do I find the current C or C++ standard documents?

C99 is available online. Quoted from www.open-std.org:

The lastest publically available version of the standard is the combined C99 + TC1 + TC2 + TC3, WG14 N1256, dated 2007-09-07. This is a WG14 working paper, but it reflects the consolidated standard at the time of issue.

How can I convert a PFX certificate file for use with Apache on a linux server?

Took some tooling around but this is what I ended up with.

Generated and installed a certificate on IIS7. Exported as PFX from IIS

Convert to pkcs12

openssl pkcs12 -in certificate.pfx -out certificate.cer -nodes

NOTE: While converting PFX to PEM format, openssl will put all the Certificates and Private Key into a single file. You will need to open the file in Text editor and copy each Certificate & Private key(including the BEGIN/END statements) to its own individual text file and save them as certificate.cer, CAcert.cer, privateKey.key respectively.

-----BEGIN PRIVATE KEY-----
Saved as certificate.key
-----END PRIVATE KEY-----

-----BEGIN CERTIFICATE-----
Saved as certificate.crt
-----END CERTIFICATE-----

Added to apache vhost w/ Webmin.

Using NSPredicate to filter an NSArray based on NSDictionary keys

It should work - as long as the data variable is actually an array containing a dictionary with the key SPORT

NSArray *data = [NSArray arrayWithObject:[NSMutableDictionary dictionaryWithObject:@"foo" forKey:@"BAR"]];    
NSArray *filtered = [data filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"(BAR == %@)", @"foo"]];

Filtered in this case contains the dictionary.

(the %@ does not have to be quoted, this is done when NSPredicate creates the object.)

What is the default maximum heap size for Sun's JVM from Java SE 6?

As of JDK6U18 following are configurations for the Heap Size.

In the Client JVM, the default Java heap configuration has been modified to improve the performance of today's rich client applications. Initial and maximum heap sizes are larger and settings related to generational garbage collection are better tuned.

The default maximum heap size is half of the physical memory up to a physical memory size of 192 megabytes and otherwise one fourth of the physical memory up to a physical memory size of 1 gigabyte. For example, if your machine has 128 megabytes of physical memory, then the maximum heap size is 64 megabytes, and greater than or equal to 1 gigabyte of physical memory results in a maximum heap size of 256 megabytes. The maximum heap size is not actually used by the JVM unless your program creates enough objects to require it. A much smaller amount, termed the initial heap size, is allocated during JVM initialization. This amount is at least 8 megabytes and otherwise 1/64 of physical memory up to a physical memory size of 1 gigabyte.

Source : http://www.oracle.com/technetwork/java/javase/6u18-142093.html

How to develop or migrate apps for iPhone 5 screen resolution?

First show this image. In that image you show warning for Retina 4 support so click on this warning and click on add so your Retina 4 splash screen automatically add in your project.

Show image here

and after you use this code :

if([[UIScreen mainScreen] bounds].size.height == 568)
    {
        // For iphone 5
    }
    else
    {
        // For iphone 4 or less
    }

Making macOS Installer Packages which are Developer ID ready

A +1 to accepted answer:

Destination Selection in Installer

If domain (a.k.a destination) selection is desired between user domain and system domain then rather than trying <domains enable_anywhere="true"> use following:

<domains enable_currentUserHome="true" enable_localSystem="true"/>

enable_currentUserHome installs application app under ~/Applications/ and enable_localSystem allows the application to be installed under /Application

I've tried this in El Capitan 10.11.6 (15G1217) and it seems to be working perfectly fine in 1 dev machine and 2 different VMs I tried.

Different class for the last element in ng-repeat

To elaborate on Paul's answer, this is the controller logic that coincides with the template code.

// HTML
<div class="row" ng-repeat="thing in things">
  <div class="well" ng-class="isLast($last)">
      <p>Data-driven {{thing.name}}</p>
  </div>
</div>

// CSS
.last { /* Desired Styles */}

// Controller
$scope.isLast = function(check) {
    var cssClass = check ? 'last' : null;
    return cssClass;
};

Its also worth noting that you really should avoid this solution if possible. By nature CSS can handle this, making a JS-based solution is unnecessary and non-performant. Unfortunately if you need to support IE8> this solution won't work for you (see MDN support docs).

CSS-Only Solution

// Using the above example syntax
.row:last-of-type { /* Desired Style */ }

'printf' with leading zeros in C

Your format specifier is incorrect. From the printf() man page on my machine:

0 A zero '0' character indicating that zero-padding should be used rather than blank-padding. A '-' overrides a '0' if both are used;

Field Width: An optional digit string specifying a field width; if the output string has fewer characters than the field width it will be blank-padded on the left (or right, if the left-adjustment indicator has been given) to make up the field width (note that a leading zero is a flag, but an embedded zero is part of a field width);

Precision: An optional period, '.', followed by an optional digit string giving a precision which specifies the number of digits to appear after the decimal point, for e and f formats, or the maximum number of characters to be printed from a string; if the digit string is missing, the precision is treated as zero;

For your case, your format would be %09.3f:

#include <stdio.h>

int main(int argc, char **argv)
{
  printf("%09.3f\n", 4917.24);
  return 0;
}

Output:

$ make testapp
cc     testapp.c   -o testapp
$ ./testapp 
04917.240

Note that this answer is conditional on your embedded system having a printf() implementation that is standard-compliant for these details - many embedded environments do not have such an implementation.

How do I make background-size work in IE?

I created jquery.backgroundSize.js: a 1.5K jquery plugin that can be used as a IE8 fallback for "cover" and "contain" values. Have a look at the demo.

How can I suppress all output from a command using Bash?

An alternative that may fit in some situations is to assign the result of a command to a variable:

$ DUMMY=$( grep root /etc/passwd 2>&1 )
$ echo $?
0
$ DUMMY=$( grep r00t /etc/passwd 2>&1 )
$ echo $?
1

Since Bash and other POSIX commandline interpreters does not consider variable assignments as a command, the present command's return code is respected.

Note: assignement with the typeset or declare keyword is considered as a command, so the evaluated return code in case is the assignement itself and not the command executed in the sub-shell:

$ declare DUMMY=$( grep r00t /etc/passwd 2>&1 )
$ echo $?
0

UIGestureRecognizer on UIImageView

You can also drag a tap gesture recogniser to the image view in Storyboard. Then create an action by ctrl + drag to the code.

Fast way to get the min/max values among properties of object

Here's a solution that allows you to return the key as well and only does one loop. It sorts the Object's entries (by val) and then returns the first and last one.

Additionally, it returns the sorted Object which can replace the existing Object so that future sorts will be faster because it will already be semi-sorted = better than O(n). It's important to note that Objects retain their order in ES6.

_x000D_
_x000D_
const maxMinVal = (obj) => {_x000D_
  const sortedEntriesByVal = Object.entries(obj).sort(([, v1], [, v2]) => v1 - v2);_x000D_
_x000D_
  return {_x000D_
    min: sortedEntriesByVal[0],_x000D_
    max: sortedEntriesByVal[sortedEntriesByVal.length - 1],_x000D_
    sortedObjByVal: sortedEntriesByVal.reduce((r, [k, v]) => ({ ...r, [k]: v }), {}),_x000D_
  };_x000D_
};_x000D_
_x000D_
const obj = {_x000D_
  a: 4, b: 0.5, c: 0.35, d: 5_x000D_
};_x000D_
_x000D_
console.log(maxMinVal(obj));
_x000D_
_x000D_
_x000D_

Using Pairs or 2-tuples in Java

Android Tuple Utils

This object provides a sensible implementation of equals(), returning true if equals() is true on each of the contained objects.

What is difference between Lightsail and EC2?

Testing¹ reveals that Lightsail instances in fact are EC2 instances, from the t2 class of burstable instances.

EC2, of course, has many more instance families and classes other than the t2, almost all of which are more "powerful" (or better equipped for certain tasks) than these, but also much more expensive. But for meaningful comparisons, the 512 MiB Lightsail instance appears to be completely equivalent in specifications to the similarly-priced t2.nano, the 1GiB is a t2.micro, the 2 GiB is a t2.small, etc.

Lightsail is a lightweight, simplified product offering -- hard disks are fixed size EBS SSD volumes, instances are still billable when stopped, security group rules are much less flexible, and only a very limited subset of EC2 features and options are accessible.

It also has a dramatically simplified console, and even though the machines run in EC2, you can't see them in the EC2 section of the AWS console. The instances run in a special VPC, but this aspect is also provisioned automatically, and invisible in the console. Lightsail supports optionally peering this hidden VPC with your default VPC in the same AWS region, allowing Lightsail instances to access services like EC2 and RDS in the default VPC within the same AWS account.²

Bandwidth is unlimited, but of course free bandwidth is not -- however, Lightsail instances do include a significant monthly bandwidth allowance before any bandwidth-related charges apply.³ Lightsail also has a simplified interface to Route 53 with limited functionality.

But if those sound like drawbacks, they aren't. The point of Lightsail seems to be simplicity. The flexibility of EC2 (and much of AWS) leads inevitably to complexity. The target market for Lightsail appears to be those who "just want a simple VPS" without having to navigate the myriad options available in AWS services like EC2, EBS, VPC, and Route 53. There is virtually no learning curve, here. You don't even technically need to know how to use SSH with a private key -- the Lightsail console even has a built-in SSH client -- but there is no requirement that you use it. You can access these instances normally, with a standard SSH client.


¹Lightsail instances, just like "regular" EC2 (VPC and Classic) instances, have access to the instance metadata service, which allows an instance to discover things about itself, such as its instance type and availability zone. Lightsail instances are identified in the instance metadata as t2 machines.

²The Lightsail docs are not explicit about the fact that peering only works with your Default VPC, but this appears to be the case. If your AWS account was created in 2013 or before, then you may not actually have a VPC with the "Default VPC" designation. This can be resolved by submitting a support request, as I explained in Can't establish VPC peering connection from Amazon Lightsail (at Server Fault).

³The bandwidth allowance applies to both inbound and outbound traffic; after this total amount of traffic is exceeded, inbound traffic continues to be free, but outbound traffic becomes billable. See "What does data transfer cost?" in the Lightsail FAQ.

PHP FPM - check if running

PHP-FPM is a service that spawns new PHP processes when needed, usually through a fast-cgi module like nginx. You can tell (with a margin of error) by just checking the init.d script e.g. "sudo /etc/init.d/php-fpm status"

What port or unix file socket is being used is up to the configuration, but often is just TCP port 9000. i.e. 127.0.0.1:9000

The best way to tell if it is running correctly is to have nginx running, and setup a virtual host that will fast-cgi pass to PHP-FPM, and just check it with wget or a browser.

JavaScript Number Split into individual digits

A fun introduction to recursion. This answer takes a Number and returns an array of Number digits. It does not convert the number to a string as an intermediate step.

Given n = 1234,

  • n % 10 will return first (right-moist) digit, 4
  • n / 10 will return 123 with some remainder
  • Using Math.floor we can chop the remainder off
  • Repeating these steps, we can form the entire result

Now we just have to build the recursion condition,

  • If the number is already a single digit (n < 10), return an array singleton of the digit
  • otherwise (inductive) the number is 10 or greater; recur and prepend to the first digit

_x000D_
_x000D_
const digits = (n = 0) =>_x000D_
  n < 10_x000D_
    ? [ n ]_x000D_
    : [ ... digits (Math.floor (n / 10)), n % 10 ]_x000D_
_x000D_
console.log (digits ())        // [ 0 ]_x000D_
console.log (digits (1))       // [ 1 ]_x000D_
console.log (digits (12))      // [ 1, 2 ]_x000D_
console.log (digits (123))     // [ 1, 2, 3 ]_x000D_
console.log (digits (11234))   // [ 1, 2, 3, 4 ]_x000D_
_x000D_
console.log (digits (123456789012))_x000D_
// [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2 ]
_x000D_
_x000D_
_x000D_

How to load a jar file at runtime

Reloading existing classes with existing data is likely to break things.

You can load new code into new class loaders relatively easily:

ClassLoader loader = URLClassLoader.newInstance(
    new URL[] { yourURL },
    getClass().getClassLoader()
);
Class<?> clazz = Class.forName("mypackage.MyClass", true, loader);
Class<? extends Runnable> runClass = clazz.asSubclass(Runnable.class);
// Avoid Class.newInstance, for it is evil.
Constructor<? extends Runnable> ctor = runClass.getConstructor();
Runnable doRun = ctor.newInstance();
doRun.run();

Class loaders no longer used can be garbage collected (unless there is a memory leak, as is often the case with using ThreadLocal, JDBC drivers, java.beans, etc).

If you want to keep the object data, then I suggest a persistence mechanism such as Serialisation, or whatever you are used to.

Of course debugging systems can do fancier things, but are more hacky and less reliable.

It is possible to add new classes into a class loader. For instance, using URLClassLoader.addURL. However, if a class fails to load (because, say, you haven't added it), then it will never load in that class loader instance.

Removing X-Powered-By

If you use FastCGI try:

fastcgi_hide_header X-Powered-By;

Best way to store a key=>value array in JavaScript?

Objects inside an array:

var cars = [
        { "id": 1, brand: "Ferrari" }
        , { "id": 2, brand: "Lotus" }
        , { "id": 3, brand: "Lamborghini" }
    ];

Get cookie by name

I have done it this way. so that i get an object to access to separate the values.With this u can pass the cookie to the parent and then you can access your values by the keys like

var cookies=getCookieVal(mycookie);
alert(cookies.mykey);
function getCookieVal(parent) {
            var cookievalue = $.cookie(parent).split('&');
            var obj = {};
            $.each(cookievalue, function (i, v) {
                var key = v.substr(0, v.indexOf("="));
                var val = v.substr(v.indexOf("=") + 1, v.length);

                obj[key] = val;

            });
            return obj;
        }  

passing object by reference in C++

Passing by reference in the above case is just an alias for the actual object.

You'll be referring to the actual object just with a different name.

There are many advantages which references offer compared to pointer references.

How to set default text for a Tkinter Entry widget

Use Entry.insert. For example:

try:
    from tkinter import *  # Python 3.x
except Import Error:
    from Tkinter import *  # Python 2.x

root = Tk()
e = Entry(root)
e.insert(END, 'default text')
e.pack()
root.mainloop()

Or use textvariable option:

try:
    from tkinter import *  # Python 3.x
except Import Error:
    from Tkinter import *  # Python 2.x

root = Tk()
v = StringVar(root, value='default text')
e = Entry(root, textvariable=v)
e.pack()
root.mainloop()

How to print an unsigned char in C?

Declare your ch as

unsigned char ch = 212 ;

And your printf will work.

Which Ruby version am I really running?

Run this command:

rvm get stable --auto-dotfiles

and make sure to read all the output. RVM will tell you if something is wrong, which in your case might be because GEM_HOME is set to something different then PATH.

How to replace special characters in a string?

For spaces use "[^a-z A-Z 0-9]" this pattern

Pretty print in MongoDB shell as default

Oh so i guess .pretty() is equal to:

db.collection.find().forEach(printjson);

How to upgrade Git on Windows to the latest version?

If you have already installed git , you can update the git with the command git update-git-for-windows

to know the current version use git --version

you can run this commands in cmd prompt

What is the difference between const int*, const int * const, and int const *?

There are many other subtle points surrounding const correctness in C++. I suppose the question here has simply been about C, but I'll give some related examples since the tag is C++ :

  • You often pass large arguments like strings as TYPE const & which prevents the object from being either modified or copied. Example :

    TYPE& TYPE::operator=(const TYPE &rhs) { ... return *this; }

    But TYPE & const is meaningless because references are always const.

  • You should always label class methods that do not modify the class as const, otherwise you cannot call the method from a TYPE const & reference. Example :

    bool TYPE::operator==(const TYPE &rhs) const { ... }

  • There are common situations where both the return value and the method should be const. Example :

    const TYPE TYPE::operator+(const TYPE &rhs) const { ... }

    In fact, const methods must not return internal class data as a reference-to-non-const.

  • As a result, one must often create both a const and a non-const method using const overloading. For example, if you define T const& operator[] (unsigned i) const;, then you'll probably also want the non-const version given by :

    inline T& operator[] (unsigned i) { return const_cast<char&>( static_cast<const TYPE&>(*this)[](i) ); }

Afaik, there are no const functions in C, non-member functions cannot themselves be const in C++, const methods might have side effects, and the compiler cannot use const functions to avoid duplicate function calls. In fact, even a simple int const & reference might witness the value to which it refers be changed elsewhere.

Google Maps API V3 : How show the direction from a point A to point B (Blue line)?

  // First Initiate your map. Tie it to some ID in the HTML eg. 'MyMapID'
  var map = new google.maps.Map(
    document.getElementById('MyMapID'),
    {
      center: {
        lat: Some.latitude,
        lng: Some.longitude
      }
    }
  );
  // Create a new directionsService object.
  var directionsService = new google.maps.DirectionsService;
    directionsService.route({
      origin: origin.latitude +','+ origin.longitude,
      destination: destination.latitude +','+ destination.longitude,
      travelMode: 'DRIVING',
    }, function(response, status) {
      if (status === google.maps.DirectionsStatus.OK) {
        var directionsDisplay = new google.maps.DirectionsRenderer({
          suppressMarkers: true,
          map: map,
          directions: response,
          draggable: false,
          suppressPolylines: true, 
          // IF YOU SET `suppressPolylines` TO FALSE, THE LINE WILL BE
          // AUTOMATICALLY DRAWN FOR YOU.
        });

        // IF YOU WISH TO APPLY USER ACTIONS TO YOUR LINE YOU NEED TO CREATE A 
        // `polyLine` OBJECT BY LOOPING THROUGH THE RESPONSE ROUTES AND CREATING A 
        // LIST
        pathPoints = response.routes[0].overview_path.map(function (location) {
          return {lat: location.lat(), lng: location.lng()};
        });

        var assumedPath = new google.maps.Polyline({
         path: pathPoints, //APPLY LIST TO PATH
         geodesic: true,
         strokeColor: '#708090',
         strokeOpacity: 0.7,
         strokeWeight: 2.5
       });

       assumedPath.setMap(map); // Set the path object to the map

Seeing the console's output in Visual Studio 2010?

You can use the System.Diagnostics.Debug.Write or System.Runtime.InteropServices method to write messages to the Output Window.