Programs & Examples On #Delphi xe2

Delphi XE2 is a specific version of Delphi. Delphi XE2 was released on September 1, 2011 and is available as a standalone product or as part of RAD Studio XE2.

Why does CreateProcess give error 193 (%1 is not a valid Win32 app)

Let me add an example here:

I'm trying to build Alluxio on windows platform and got the same issue, it's because the pom.xml contains below step:

      <plugin>
        <artifactId>exec-maven-plugin</artifactId>
        <groupId>org.codehaus.mojo</groupId>
        <inherited>false</inherited>
        <executions>
          <execution>
            <id>Check that there are no Windows line endings</id>
            <phase>compile</phase>
            <goals>
              <goal>exec</goal>
            </goals>
            <configuration>
              <executable>${build.path}/style/check_no_windows_line_endings.sh</executable>
            </configuration>
          </execution>
        </executions>
      </plugin>

The .sh file is not executable on windows so the error throws.

Comment it out if you do want build Alluxio on windows.

What is the meaning of "operator bool() const"

It's an implicit conversion to bool. I.e. wherever implicit conversions are allowed, your class can be converted to bool by calling that method.

How do I iterate through each element in an n-dimensional matrix in MATLAB?

The idea of a linear index for arrays in matlab is an important one. An array in MATLAB is really just a vector of elements, strung out in memory. MATLAB allows you to use either a row and column index, or a single linear index. For example,

A = magic(3)
A =
     8     1     6
     3     5     7
     4     9     2

A(2,3)
ans =
     7

A(8)
ans =
     7

We can see the order the elements are stored in memory by unrolling the array into a vector.

A(:)
ans =
     8
     3
     4
     1
     5
     9
     6
     7
     2

As you can see, the 8th element is the number 7. In fact, the function find returns its results as a linear index.

find(A>6)
ans =
     1
     6
     8

The result is, we can access each element in turn of a general n-d array using a single loop. For example, if we wanted to square the elements of A (yes, I know there are better ways to do this), one might do this:

B = zeros(size(A));
for i = 1:numel(A)
  B(i) = A(i).^2;
end

B
B =
    64     1    36
     9    25    49
    16    81     4

There are many circumstances where the linear index is more useful. Conversion between the linear index and two (or higher) dimensional subscripts is accomplished with the sub2ind and ind2sub functions.

The linear index applies in general to any array in matlab. So you can use it on structures, cell arrays, etc. The only problem with the linear index is when they get too large. MATLAB uses a 32 bit integer to store these indexes. So if your array has more then a total of 2^32 elements in it, the linear index will fail. It is really only an issue if you use sparse matrices often, when occasionally this will cause a problem. (Though I don't use a 64 bit MATLAB release, I believe that problem has been resolved for those lucky individuals who do.)

concatenate char array in C

in rare cases when you can't use strncat, strcat or strcpy. And you don't have access to <string.h> so you can't use strlen. Also you maybe don't even know the size of the char arrays and you still want to concatenate because you got only pointers. Well, you can do old school malloc and count characters yourself like..

char *combineStrings(char* inputA, char* inputB) {
    size_t len = 0, lenB = 0;
    while(inputA[len] != '\0') len++;
    while(inputB[lenB] != '\0') lenB++;
    char* output = malloc(len+lenB);
    sprintf((char*)output,"%s%s",inputA,inputB);
    return output;
}

It just needs #include <stdio.h> which you will have most likely included already

Failed to connect to mysql at 127.0.0.1:3306 with user root access denied for user 'root'@'localhost'(using password:YES)

I know this is old but I have come across this issue as well but found a fix for this that worked for me:

  1. go to "Services"
  2. under "Name" find your username
  3. right click and select "Start"

Go to your MySQL workbench and select "Startup / Shutdown" under "INSTANCE" and you should be good to go. Hope this helps anyone that comes across this.

How to get page content using cURL?

For a realistic approach that emulates the most human behavior, you may want to add a referer in your curl options. You may also want to add a follow_location to your curl options. Trust me, whoever said that cURLING Google results is impossible, is a complete dolt and should throw his/her computer against the wall in hopes of never returning to the internetz again. Everything that you can do "IRL" with your own browser can all be emulated using PHP cURL or libCURL in Python. You just need to do more cURLS to get buff. Then you will see what I mean. :)

  $url = "http://www.google.com/search?q=".$strSearch."&hl=en&start=0&sa=N";
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_REFERER, 'http://www.example.com/1');
  curl_setopt($ch, CURLOPT_HEADER, 0);
  curl_setopt($ch, CURLOPT_VERBOSE, 0);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible;)");
  curl_setopt($ch, CURLOPT_URL, urlencode($url));
  $response = curl_exec($ch);
  curl_close($ch);

How can I delete one element from an array by value

Another option:

a = [2,4,6,3,8]

a -= [3]

which results in

=> [2, 4, 6, 8] 

Getting time and date from timestamp with php

$timestamp='2014-11-21 16:38:00';

list($date,$time)=explode(' ',$timestamp);

// just time

preg_match("/ (\d\d:\d\d):\d\d$/",$timestamp,$match);
echo "\n<br>".$match[1];

How do I handle a click anywhere in the page, even when a certain element stops the propagation?

You could use jQuery to add an event listener on the document DOM.

_x000D_
_x000D_
    $(document).on("click", function () {_x000D_
        console.log('clicked');_x000D_
    });
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

Unix ls command: show full path when using options

You can combine the find command and the ls command. Use the path (.) and selector (*) to narrow down the files you're after. Surround the find command in back quotes. The argument to -name is doublequote star doublequote in case you can't read it.

ls -lart `find . -type f -name "*" `

Javascript onHover event

How about something like this?

<html>
<head>
<script type="text/javascript">

var HoverListener = {
  addElem: function( elem, callback, delay )
  {
    if ( delay === undefined )
    {
      delay = 1000;
    }

    var hoverTimer;

    addEvent( elem, 'mouseover', function()
    {
      hoverTimer = setTimeout( callback, delay );
    } );

    addEvent( elem, 'mouseout', function()
    {
      clearTimeout( hoverTimer );
    } );
  }
}

function tester()
{
  alert( 'hi' );
}

//  Generic event abstractor
function addEvent( obj, evt, fn )
{
  if ( 'undefined' != typeof obj.addEventListener )
  {
    obj.addEventListener( evt, fn, false );
  }
  else if ( 'undefined' != typeof obj.attachEvent )
  {
    obj.attachEvent( "on" + evt, fn );
  }
}

addEvent( window, 'load', function()
{
  HoverListener.addElem(
      document.getElementById( 'test' )
    , tester 
  );
  HoverListener.addElem(
      document.getElementById( 'test2' )
    , function()
      {
        alert( 'Hello World!' );
      }
    , 2300
  );
} );

</script>
</head>
<body>
<div id="test">Will alert "hi" on hover after one second</div>
<div id="test2">Will alert "Hello World!" on hover 2.3 seconds</div>
</body>
</html>

Disable Input fields in reactive form

Providing disabled property as true inside FormControl surely disables the input field.

this.form=this.fb.group({
  FirstName:[{value:'first name', disabled:true}],
  LastValue:['last name,[Validators.required]]
})

The above example will disable the FirstName input field.

But real problem arises when you try to access disabled field value through form like this console.log(this.form.value.FirstName); and it shows as undefined instead of printing field's actual value. So, to access disabled field's value, one must use getRawValue() method provided by Reactive Forms. i.e. console.log(this.form.getRawValue().FirstName); would print the actual value of form field and not undefined.

Get individual query parameters from Uri

Have a look at HttpUtility.ParseQueryString() It'll give you a NameValueCollection instead of a dictionary, but should still do what you need.

The other option is to use string.Split().

    string url = @"http://example.com/file?a=1&b=2&c=string%20param";
    string[] parts = url.Split(new char[] {'?','&'});
    ///parts[0] now contains http://example.com/file
    ///parts[1] = "a=1"
    ///parts[2] = "b=2"
    ///parts[3] = "c=string%20param"

Is < faster than <=?

At the very least, if this were true a compiler could trivially optimise a <= b to !(a > b), and so even if the comparison itself were actually slower, with all but the most naive compiler you would not notice a difference.

<img>: Unsafe value used in a resource URL context

Pipe

// Angular
import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer, SafeHtml, SafeStyle, SafeScript, SafeUrl, SafeResourceUrl } from '@angular/platform-browser';

/**
 * Sanitize HTML
 */
@Pipe({
  name: 'safe'
})
export class SafePipe implements PipeTransform {
  /**
   * Pipe Constructor
   *
   * @param _sanitizer: DomSanitezer
   */
  // tslint:disable-next-line
  constructor(protected _sanitizer: DomSanitizer) {
  }

  /**
   * Transform
   *
   * @param value: string
   * @param type: string
   */
  transform(value: string, type: string): SafeHtml | SafeStyle | SafeScript | SafeUrl | SafeResourceUrl {
    switch (type) {
      case 'html':
        return this._sanitizer.bypassSecurityTrustHtml(value);
      case 'style':
        return this._sanitizer.bypassSecurityTrustStyle(value);
      case 'script':
        return this._sanitizer.bypassSecurityTrustScript(value);
      case 'url':
        return this._sanitizer.bypassSecurityTrustUrl(value);
      case 'resourceUrl':
        return this._sanitizer.bypassSecurityTrustResourceUrl(value);
      default:
        return this._sanitizer.bypassSecurityTrustHtml(value);
    }
  }
}

Template

{{ data.url | safe:'url' }}

That's it!

Note: You shouldn't need it but here is the component use of the pipe
  // Public properties
  itsSafe: SafeHtml;

  // Private properties
  private safePipe: SafePipe = new SafePipe(this.domSanitizer);

  /**
   * Component constructor
   *
   * @param safePipe: SafeHtml
   * @param domSanitizer: DomSanitizer
   */
  constructor(private safePipe: SafePipe, private domSanitizer: DomSanitizer) {
  }

  /**
   * On init
   */
  ngOnInit(): void {
    this.itsSafe = this.safePipe.transform('<h1>Hi</h1>', 'html');
  }

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

The JSON Ruby Gem is bundled with a shell script to prettify JSON:

sudo gem install json
echo '{ "foo": "bar" }' | prettify_json.rb

Script download: gist.github.com/3738968

Make button width fit to the text

Keeping the element's size relative to its content can also be done with display: inline-flex and display: table

The centering can be done with..

  • text-align: center; on the parent (or above, it's inherited)

  • display: flex; and justify-content: center; on the parent

  • position: absolute; left: 50%; transform: translateX(-50%); on the element with position: relative; (at least) on the parent.

Here's a flexbox guide from CSS Tricks

Here's an article on centering from CSS Tricks.

Keeping an element only as wide as its content..

  • Can use display: table;

  • Or inline-anything including inline-flex as used in my snippet example below.

Keep in mind that when centering with flexbox's justify-content: center; when the text wraps the text will align left. So you will still need text-align: center; if your site is responsive and you expect lines to wrap.

_x000D_
_x000D_
body {_x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
  height: 100vh;_x000D_
  padding: 20px;_x000D_
}_x000D_
.container {_x000D_
  display: flex;_x000D_
  justify-content: center; /* center horizontally */_x000D_
  align-items: center; /* center vertically */_x000D_
  height: 50%;_x000D_
}_x000D_
.container.c1 {_x000D_
  text-align: center; /* needed if the text wraps */_x000D_
  /* text-align is inherited, it can be put on the parent or the target element */_x000D_
}_x000D_
.container.c2 {_x000D_
 /* without text-align: center; */_x000D_
}_x000D_
.button {_x000D_
  padding: 5px 10px;_x000D_
  font-size: 30px;_x000D_
  text-decoration: none;_x000D_
  color: hsla(0, 0%, 90%, 1);_x000D_
  background: linear-gradient(hsla(21, 85%, 51%, 1), hsla(21, 85%, 61%, 1));_x000D_
  border-radius: 10px;_x000D_
  box-shadow: 2px 2px 15px -5px hsla(0, 0%, 0%, 1);_x000D_
}_x000D_
.button:hover {_x000D_
  background: linear-gradient(hsl(207.5, 84.8%, 51%), hsla(207, 84%, 62%, 1));_x000D_
  transition: all 0.2s linear;_x000D_
}_x000D_
.button.b1 {_x000D_
    display: inline-flex; /* element only as wide as content */_x000D_
}_x000D_
.button.b2 {_x000D_
    display: table; /* element only as wide as content */_x000D_
}
_x000D_
<div class="container c1">_x000D_
  <a class="button b1" href="https://stackoverflow.com/questions/27722872/">This Text Is Centered Before And After Wrap</a>_x000D_
</div>_x000D_
<div class="container c2">_x000D_
  <a class="button b2" href="https://stackoverflow.com/questions/27722872/">This Text Is Centered Only Before Wrap</a>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Fiddle

https://jsfiddle.net/Hastig/02fbs3pv/

How to make the first option of <select> selected with jQuery

On the back of James Lee Baker's reply, I prefer this solution as it removes the reliance on browser support for :first :selected ...

$('#target').children().prop('selected', false);
$($('#target').children()[0]).prop('selected', 'selected');

How to select all records from one table that do not exist in another table?

Watch out for pitfalls. If the field Name in Table1 contain Nulls you are in for surprises. Better is:

SELECT name
FROM table2
WHERE name NOT IN
    (SELECT ISNULL(name ,'')
     FROM table1)

MySQL: Large VARCHAR vs. TEXT?

Disclaimer: I'm not a MySQL expert ... but this is my understanding of the issues.

I think TEXT is stored outside the mysql row, while I think VARCHAR is stored as part of the row. There is a maximum row length for mysql rows .. so you can limit how much other data you can store in a row by using the VARCHAR.

Also due to VARCHAR forming part of the row, I suspect that queries looking at that field will be slightly faster than those using a TEXT chunk.

Sending email with gmail smtp with codeigniter email library

$config = Array(
    'protocol' => 'smtp',
    'smtp_host' => 'ssl://smtp.googlemail.com',
    'smtp_port' => 465,
    'smtp_user' => 'xxx',
    'smtp_pass' => 'xxx',
    'mailtype'  => 'html', 
    'charset'   => 'iso-8859-1'
);
$this->load->library('email', $config);
$this->email->set_newline("\r\n");

// Set to, from, message, etc.

$result = $this->email->send();

From the CodeIgniter Forums

"Cannot start compilation: the output path is not specified for module..."

Open .iml file. Look for keyword 'NewModuleRootManager'. Check if attribute 'inherit-compiler-output' is set to true or not. If not set to true.

Like this :

component name="NewModuleRootManager" inherit-compiler-output="true">
    <content url="file://$MODULE_DIR$">
      <sourceFolder url="file://$MODULE_DIR$/test" isTestSource="true" />
      <sourceFolder url="file://$MODULE_DIR$/spec" isTestSource="true" />
      <sourceFolder url="file://$MODULE_DIR$/app" isTestSource="false" />

What is monkey patching?

What is a monkey patch?

Simply put, monkey patching is making changes to a module or class while the program is running.

Example in usage

There's an example of monkey-patching in the Pandas documentation:

import pandas as pd
def just_foo_cols(self):
    """Get a list of column names containing the string 'foo'

    """
    return [x for x in self.columns if 'foo' in x]

pd.DataFrame.just_foo_cols = just_foo_cols # monkey-patch the DataFrame class
df = pd.DataFrame([list(range(4))], columns=["A","foo","foozball","bar"])
df.just_foo_cols()
del pd.DataFrame.just_foo_cols # you can also remove the new method

To break this down, first we import our module:

import pandas as pd

Next we create a method definition, which exists unbound and free outside the scope of any class definitions (since the distinction is fairly meaningless between a function and an unbound method, Python 3 does away with the unbound method):

def just_foo_cols(self):
    """Get a list of column names containing the string 'foo'

    """
    return [x for x in self.columns if 'foo' in x]

Next we simply attach that method to the class we want to use it on:

pd.DataFrame.just_foo_cols = just_foo_cols # monkey-patch the DataFrame class

And then we can use the method on an instance of the class, and delete the method when we're done:

df = pd.DataFrame([list(range(4))], columns=["A","foo","foozball","bar"])
df.just_foo_cols()
del pd.DataFrame.just_foo_cols # you can also remove the new method

Caveat for name-mangling

If you're using name-mangling (prefixing attributes with a double-underscore, which alters the name, and which I don't recommend) you'll have to name-mangle manually if you do this. Since I don't recommend name-mangling, I will not demonstrate it here.

Testing Example

How can we use this knowledge, for example, in testing?

Say we need to simulate a data retrieval call to an outside data source that results in an error, because we want to ensure correct behavior in such a case. We can monkey patch the data structure to ensure this behavior. (So using a similar method name as suggested by Daniel Roseman:)

import datasource

def get_data(self):
    '''monkey patch datasource.Structure with this to simulate error'''
    raise datasource.DataRetrievalError

datasource.Structure.get_data = get_data

And when we test it for behavior that relies on this method raising an error, if correctly implemented, we'll get that behavior in the test results.

Just doing the above will alter the Structure object for the life of the process, so you'll want to use setups and teardowns in your unittests to avoid doing that, e.g.:

def setUp(self):
    # retain a pointer to the actual real method:
    self.real_get_data = datasource.Structure.get_data
    # monkey patch it:
    datasource.Structure.get_data = get_data

def tearDown(self):
    # give the real method back to the Structure object:
    datasource.Structure.get_data = self.real_get_data

(While the above is fine, it would probably be a better idea to use the mock library to patch the code. mock's patch decorator would be less error prone than doing the above, which would require more lines of code and thus more opportunities to introduce errors. I have yet to review the code in mock but I imagine it uses monkey-patching in a similar way.)

How to set Highcharts chart maximum yAxis value

Taking help from above answer link mentioned in the above answer sets the max value with option

yAxis: { max: 100 },

On similar line min value can be set.So if you want to set min-max value then

yAxis: {
   min: 0,     
   max: 100
},

If you are using HighRoller php library for integration if Highchart graphs then you just need to set the option

$series->yAxis->min=0;
$series->yAxis->max=100;

How to set an button align-right with Bootstrap?

function Continue({show, onContinue}) {
  return(<div className="row continue">
  { show ? <div className="col-11">
    <button class="btn btn-primary btn-lg float-right" onClick= {onContinue}>Continue</button>
    </div>
    : null }
  </div>);
}

Resize a picture to fit a JLabel

You can try it:

ImageIcon imageIcon = new ImageIcon(new ImageIcon("icon.png").getImage().getScaledInstance(20, 20, Image.SCALE_DEFAULT));
label.setIcon(imageIcon);

Or in one line:

label.setIcon(new ImageIcon(new ImageIcon("icon.png").getImage().getScaledInstance(20, 20, Image.SCALE_DEFAULT)));

The execution time is much more faster than File and ImageIO.

I recommend you to compare the two solutions in a loop.

How do I strip all spaces out of a string in PHP?

If you want to remove all whitespace:

$str = preg_replace('/\s+/', '', $str);

See the 5th example on the preg_replace documentation. (Note I originally copied that here.)

Edit: commenters pointed out, and are correct, that str_replace is better than preg_replace if you really just want to remove the space character. The reason to use preg_replace would be to remove all whitespace (including tabs, etc.).

Rendering raw html with reactjs

dangerouslySetInnerHTML should not be used unless absolutely necessary. According to the docs, "This is mainly for cooperating with DOM string manipulation libraries". When you use it, you're giving up the benefit of React's DOM management.

In your case, it is pretty straightforward to convert to valid JSX syntax; just change class attributes to className. Or, as mentioned in the comments above, you can use the ReactBootstrap library which encapsulates Bootstrap elements into React components.

How to escape a single quote inside awk

This maybe what you're looking for:

awk 'BEGIN {FS=" ";} {printf "'\''%s'\'' ", $1}'

That is, with '\'' you close the opening ', then print a literal ' by escaping it and finally open the ' again.

Removing first x characters from string?

Example to show last 3 digits of account number.

x = '1234567890'   
x.replace(x[:7], '')

o/p: '890'

Reset identity seed after deleting records in SQL Server

The DBCC CHECKIDENT management command is used to reset identity counter. The command syntax is:

DBCC CHECKIDENT (table_name [, { NORESEED | { RESEED [, new_reseed_value ]}}])
[ WITH NO_INFOMSGS ]

Example:

DBCC CHECKIDENT ('[TestTable]', RESEED, 0);
GO

It was not supported in previous versions of the Azure SQL Database but is supported now.


Thanks to Solomon Rutzky the docs for the command are now fixed.

Django auto_now and auto_now_add

You can use timezone.now() for created and auto_now for modified:

from django.utils import timezone
class User(models.Model):
    created = models.DateTimeField(default=timezone.now())
    modified = models.DateTimeField(auto_now=True)

If you are using a custom primary key instead of the default auto- increment int, auto_now_add will lead to a bug.

Here is the code of Django's default DateTimeField.pre_save withauto_now and auto_now_add:

def pre_save(self, model_instance, add):
    if self.auto_now or (self.auto_now_add and add):
        value = timezone.now()
        setattr(model_instance, self.attname, value)
        return value
    else:
        return super(DateTimeField, self).pre_save(model_instance, add)

I am not sure what the parameter add is. I hope it will some thing like:

add = True if getattr(model_instance, 'id') else False

The new record will not have attr id, so getattr(model_instance, 'id') will return False will lead to not setting any value in the field.

ipad safari: disable scrolling, and bounce effect?

You can use js for prevent scroll:

let body = document.body;

let hideScroll = function(e) {
  e.preventDefault();
};

function toggleScroll (bool) {

  if (bool === true) {
    body.addEventListener("touchmove", hideScroll);
  } else {
    body.removeEventListener("touchmove", hideScroll);
  }
}

And than just run/stop toggleScroll func when you opnen/close modal.

Like this toggleScroll(true) / toggleScroll(false)

(This is only for iOS, on Android not working)

No resource identifier found for attribute '...' in package 'com.app....'

this helps for me:

on your build.gradle:

implementation 'com.android.support:design:28.0.0'

Calling a function on bootstrap modal open

you can use show instead of shown for making the function to load just before modal open, instead of after modal open.

$('#code').on('show.bs.modal', function (e) {
  // do something...
})

Eclipse Java Missing required source folder: 'src'

Edit your .classpath file. (Or via the project build path).

How to reload .bashrc settings without logging out and back in again?

I used easyengine to set up my vultr cloud based server.
I found my bash file at /etc/bash.bashrc.

So source /etc/bash.bashrc did the trick for me!

update

When setting up a bare server (ubuntu 16.04), you can use the above info, when you have not yet set up a username, and are logging in via root.

It's best to create a user (with sudo privledges), and login as this username instead.
This will create a directory for your settings, including .profile and .bashrc files.
https://linuxize.com/post/how-to-create-a-sudo-user-on-ubuntu/

Now, you will edit and (and "source") the ~/.bashrc file.

On my server, this was located at /home/your_username/.bashrc
(where your_username is actually the new username you created above, and now login with)

How to get request URI without context path?

A way to do this is to rest the servelet context path from request URI.

String p = request.getRequestURI();
String cp = getServletContext().getContextPath();

if (p.startsWith(cp)) {
  String.err.println(p.substring(cp.length());
}

Read here .

CSS3 :unchecked pseudo-class

:unchecked is not defined in the Selectors or CSS UI level 3 specs, nor has it appeared in level 4 of Selectors.

In fact, the quote from W3C is taken from the Selectors 4 spec. Since Selectors 4 recommends using :not(:checked), it's safe to assume that there is no corresponding :unchecked pseudo. Browser support for :not() and :checked is identical, so that shouldn't be a problem.

This may seem inconsistent with the :enabled and :disabled states, especially since an element can be neither enabled nor disabled (i.e. the semantics completely do not apply), however there does not appear to be any explanation for this inconsistency.

(:indeterminate does not count, because an element can similarly be neither unchecked, checked nor indeterminate because the semantics don't apply.)

How can I read a whole file into a string variable

If you just want the content as string, then the simple solution is to use the ReadFile function from the io/ioutil package. This function returns a slice of bytes which you can easily convert to a string.

package main

import (
    "fmt"
    "io/ioutil"
)

func main() {
    b, err := ioutil.ReadFile("file.txt") // just pass the file name
    if err != nil {
        fmt.Print(err)
    }

    fmt.Println(b) // print the content as 'bytes'

    str := string(b) // convert content to a 'string'

    fmt.Println(str) // print the content as a 'string'
}

How do I get whole and fractional parts from double in JSP/Java?

http://www.java2s.com/Code/Java/Data-Type/Obtainingtheintegerandfractionalparts.htm

double num;
long iPart;
double fPart;

// Get user input
num = 2.3d;
iPart = (long) num;
fPart = num - iPart;
System.out.println("Integer part = " + iPart);
System.out.println("Fractional part = " + fPart);

Outputs:

Integer part = 2
Fractional part = 0.2999999999999998

Best way to detect when a user leaves a web page?

I know this question has been answered, but in case you only want something to trigger when the actual BROWSER is closed, and not just when a pageload occurs, you can use this code:

window.onbeforeunload = function (e) {
        if ((window.event.clientY < 0)) {
            //window.localStorage.clear();
            //alert("Y coords: " + window.event.clientY)
        }
};

In my example, I am clearing local storage and alerting the user with the mouses y coords, only when the browser is closed, this will be ignored on all page loads from within the program.

Testing if a list of integer is odd or even

You could try using Linq to project the list:

var output = lst.Select(x => x % 2 == 0).ToList();

This will return a new list of bools such that {1, 2, 3, 4, 5} will map to {false, true, false, true, false}.

Can you "compile" PHP code and upload a binary-ish file, which will just be run by the byte code interpreter?

There is also

which aims

  • To encode entire script in a proprietary PHP application
  • To encode some classes and/or functions in a proprietary PHP application
  • To enable the production of php-gtk applications that could be used on client desktops, without the need for a php.exe.
  • To do the feasibility study for a PHP to C converter

The extension is available from PECL.

Replace all particular values in a data frame

Like this:

> df[df==""]<-NA
> df
     A    B
1 <NA>   12
2  xyz <NA>
3  jkl  100

Difference between a user and a schema in Oracle?

A user account is like relatives who holds a key to your home, but does not own anything i.e. a user account does not own any database object...no data dictionary...

Whereas a schema is an encapsulation of database objects. It's like the owner of the house who owns everything in your house and a user account will be able to access the goods at the home only when the owner i.e. schema gives needed grants to it.

Going to a specific line number using Less in Unix

To open at a specific line straight from the command line, use:

less +320123 filename

If you want to see the line numbers too:

less +320123 -N filename

You can also choose to display a specific line of the file at a specific line of the terminal, for when you need a few lines of context. For example, this will open the file with line 320123 on the 10th line of the terminal:

less +320123 -j 10 filename

Pick images of root folder from sub-folder

Your index.html can just do src="images/logo.png" and from sub.html you would do src="../images/logo.png"

ConvergenceWarning: Liblinear failed to converge, increase the number of iterations

I reached the point that I set, up to max_iter=1200000 on my LinearSVC classifier, but still the "ConvergenceWarning" was still present. I fix the issue by just setting dual=False and leaving max_iter to its default.

With LogisticRegression(solver='lbfgs') classifier, you should increase max_iter. Mine have reached max_iter=7600 before the "ConvergenceWarning" disappears when training with large dataset's features.

Pointers, smart pointers or shared pointers?

Sydius outlined the types fairly well:

  • Normal pointers are just that - they point to some thing in memory somewhere. Who owns it? Only the comments will let you know. Who frees it? Hopefully the owner at some point.
  • Smart pointers are a blanket term that cover many types; I'll assume you meant scoped pointer which uses the RAII pattern. It is a stack-allocated object that wraps a pointer; when it goes out of scope, it calls delete on the pointer it wraps. It "owns" the contained pointer in that it is in charge of deleteing it at some point. They allow you to get a raw reference to the pointer they wrap for passing to other methods, as well as releasing the pointer, allowing someone else to own it. Copying them does not make sense.
  • Shared pointers is a stack-allocated object that wraps a pointer so that you don't have to know who owns it. When the last shared pointer for an object in memory is destructed, the wrapped pointer will also be deleted.

How about when you should use them? You will either make heavy use of scoped pointers or shared pointers. How many threads are running in your application? If the answer is "potentially a lot", shared pointers can turn out to be a performance bottleneck if used everywhere. The reason being that creating/copying/destructing a shared pointer needs to be an atomic operation, and this can hinder performance if you have many threads running. However, it won't always be the case - only testing will tell you for sure.

There is an argument (that I like) against shared pointers - by using them, you are allowing programmers to ignore who owns a pointer. This can lead to tricky situations with circular references (Java will detect these, but shared pointers cannot) or general programmer laziness in a large code base.

There are two reasons to use scoped pointers. The first is for simple exception safety and cleanup operations - if you want to guarantee that an object is cleaned up no matter what in the face of exceptions, and you don't want to stack allocate that object, put it in a scoped pointer. If the operation is a success, you can feel free to transfer it over to a shared pointer, but in the meantime save the overhead with a scoped pointer.

The other case is when you want clear object ownership. Some teams prefer this, some do not. For instance, a data structure may return pointers to internal objects. Under a scoped pointer, it would return a raw pointer or reference that should be treated as a weak reference - it is an error to access that pointer after the data structure that owns it is destructed, and it is an error to delete it. Under a shared pointer, the owning object can't destruct the internal data it returned if someone still holds a handle on it - this could leave resources open for much longer than necessary, or much worse depending on the code.

How to read data from java properties file using Spring Boot

I have created following class

ConfigUtility.java

@Configuration
public class ConfigUtility {

    @Autowired
    private Environment env;

    public String getProperty(String pPropertyKey) {
        return env.getProperty(pPropertyKey);
    }
} 

and called as follow to get application.properties value

myclass.java

@Autowired
private ConfigUtility configUtil;

public AppResponse getDetails() {

  AppResponse response = new AppResponse();
    String email = configUtil.getProperty("emailid");
    return response;        
}

application.properties

[email protected]

unit tested, working as expected...

Windows batch: sleep

I just wrote my own sleep which called the Win32 Sleep API function.

jQuery Change event on an <input> element - any way to retain previous value?

I found a dirty trick but it works, you could use the hover function to get the value before change!

Android JSONObject - How can I loop through a flat JSON object to get each key and value

Take a look at the JSONObject reference:

http://www.json.org/javadoc/org/json/JSONObject.html

Without actually using the object, it looks like using either getNames() or keys() which returns an Iterator is the way to go.

Calling Member Functions within Main C++

You need to create an object since printInformation() is non-static. Try:

int main() {

MyClass o;
o.printInformation();

fgetc( stdin );
return(0);

}

How to upgrade safely php version in wamp server

WAMP server generally provide addond for different php/mysql versions. However you mentioned you have downloaded latest wamp server. As of now, latest Wamp server v2.5 provide PHP version 5.5.12

So you need to upgrade it manually as follow:

  1. Download binaries on php.net
  2. Extract all files in a new folder : C:/wamp/bin/php/php5.5.27/
  3. Copy the wampserver.conf from another php folder (like php/php5.5.12/) to the new folder
  4. Rename php.ini-development file to phpForApache.ini
  5. Done ! Restart WampServer (>Right Mouseclick on trayicon >Exit)

Although not asked, I'd recommend to vagrant/puppet or docker for local development. Check puphpet.com for details. It has slight learning curve but it will give you much better control of different versions of every tool.

How do I navigate to a parent route from a child route?

You can navigate to your parent root like this

this.router.navigate(['.'], { relativeTo: this.activeRoute.parent });

You will need to inject the current active Route in the constructor

constructor(
    private router: Router,
    private activeRoute: ActivatedRoute) {

  }

If statement in aspx page

Just use simple code

<%
if(condition)
{%>

html code

<% } 
else 
{
%>
html code
<% } %>

System.Net.WebException: The remote name could not be resolved:

Open the hosts file located at : **C:\windows\system32\drivers\etc**.

Hosts file is for what?

Add the following at end of this file :

YourServerIP YourDNS

Example:

198.168.1.1 maps.google.com

MSVCP140.dll missing

Either make your friends download the runtime DLL (@Kay's answer), or compile the app with static linking.

In visual studio, go to Project tab -> properties - > configuration properties -> C/C++ -> Code Generation on runtime library choose /MTd for debug mode and /MT for release mode.

This will cause the compiler to embed the runtime into the app. The executable will be significantly bigger, but it will run without any need of runtime dlls.

What does the explicit keyword mean?

In C++, a constructor with only one required parameter is considered an implicit conversion function. It converts the parameter type to the class type. Whether this is a good thing or not depends on the semantics of the constructor.

For example, if you have a string class with constructor String(const char* s), that's probably exactly what you want. You can pass a const char* to a function expecting a String, and the compiler will automatically construct a temporary String object for you.

On the other hand, if you have a buffer class whose constructor Buffer(int size) takes the size of the buffer in bytes, you probably don't want the compiler to quietly turn ints into Buffers. To prevent that, you declare the constructor with the explicit keyword:

class Buffer { explicit Buffer(int size); ... }

That way,

void useBuffer(Buffer& buf);
useBuffer(4);

becomes a compile-time error. If you want to pass a temporary Buffer object, you have to do so explicitly:

useBuffer(Buffer(4));

In summary, if your single-parameter constructor converts the parameter into an object of your class, you probably don't want to use the explicit keyword. But if you have a constructor that simply happens to take a single parameter, you should declare it as explicit to prevent the compiler from surprising you with unexpected conversions.

Event detect when css property changed using Jquery

You can't. CSS does not support "events". Dare I ask what you need it for? Check out this post here on SO. I can't think of a reason why you would want to hook up an event to a style change. I'm assuming here that the style change is triggered somwhere else by a piece of javascript. Why not add extra logic there?

MATLAB error: Undefined function or method X for input arguments of type 'double'

As others have pointed out, this is very probably a problem with the path of the function file not being in Matlab's 'path'.

One easy way to verify this is to open your function in the Editor and press the F5 key. This would make the Editor try to run the file, and in case the file is not in path, it will prompt you with a message box. Choose Add to Path in that, and you must be fine to go.

One side note: at the end of the above process, Matlab command window will give an error saying arguments missing: obviously, we didn't provide any arguments when we tried to run from the editor. But from now on you can use the function from the command line giving the correct arguments.

What are good ways to prevent SQL injection?

By using the SqlCommand and its child collection of parameters all the pain of checking for sql injection is taken away from you and will be handled by these classes.

Here is an example, taken from one of the articles above:

private static void UpdateDemographics(Int32 customerID,
    string demoXml, string connectionString)
{
    // Update the demographics for a store, which is stored  
    // in an xml column.  
    string commandText = "UPDATE Sales.Store SET Demographics = @demographics "
        + "WHERE CustomerID = @ID;";

    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        SqlCommand command = new SqlCommand(commandText, connection);
        command.Parameters.Add("@ID", SqlDbType.Int);
        command.Parameters["@ID"].Value = customerID;

        // Use AddWithValue to assign Demographics. 
        // SQL Server will implicitly convert strings into XML.
        command.Parameters.AddWithValue("@demographics", demoXml);

        try
        {
            connection.Open();
            Int32 rowsAffected = command.ExecuteNonQuery();
            Console.WriteLine("RowsAffected: {0}", rowsAffected);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
}

Calculate difference in keys contained in two Python dictionaries

In case you want the difference recursively, I have written a package for python: https://github.com/seperman/deepdiff

Installation

Install from PyPi:

pip install deepdiff

Example usage

Importing

>>> from deepdiff import DeepDiff
>>> from pprint import pprint
>>> from __future__ import print_function # In case running on Python 2

Same object returns empty

>>> t1 = {1:1, 2:2, 3:3}
>>> t2 = t1
>>> print(DeepDiff(t1, t2))
{}

Type of an item has changed

>>> t1 = {1:1, 2:2, 3:3}
>>> t2 = {1:1, 2:"2", 3:3}
>>> pprint(DeepDiff(t1, t2), indent=2)
{ 'type_changes': { 'root[2]': { 'newtype': <class 'str'>,
                                 'newvalue': '2',
                                 'oldtype': <class 'int'>,
                                 'oldvalue': 2}}}

Value of an item has changed

>>> t1 = {1:1, 2:2, 3:3}
>>> t2 = {1:1, 2:4, 3:3}
>>> pprint(DeepDiff(t1, t2), indent=2)
{'values_changed': {'root[2]': {'newvalue': 4, 'oldvalue': 2}}}

Item added and/or removed

>>> t1 = {1:1, 2:2, 3:3, 4:4}
>>> t2 = {1:1, 2:4, 3:3, 5:5, 6:6}
>>> ddiff = DeepDiff(t1, t2)
>>> pprint (ddiff)
{'dic_item_added': ['root[5]', 'root[6]'],
 'dic_item_removed': ['root[4]'],
 'values_changed': {'root[2]': {'newvalue': 4, 'oldvalue': 2}}}

String difference

>>> t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":"world"}}
>>> t2 = {1:1, 2:4, 3:3, 4:{"a":"hello", "b":"world!"}}
>>> ddiff = DeepDiff(t1, t2)
>>> pprint (ddiff, indent = 2)
{ 'values_changed': { 'root[2]': {'newvalue': 4, 'oldvalue': 2},
                      "root[4]['b']": { 'newvalue': 'world!',
                                        'oldvalue': 'world'}}}

String difference 2

>>> t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":"world!\nGoodbye!\n1\n2\nEnd"}}
>>> t2 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":"world\n1\n2\nEnd"}}
>>> ddiff = DeepDiff(t1, t2)
>>> pprint (ddiff, indent = 2)
{ 'values_changed': { "root[4]['b']": { 'diff': '--- \n'
                                                '+++ \n'
                                                '@@ -1,5 +1,4 @@\n'
                                                '-world!\n'
                                                '-Goodbye!\n'
                                                '+world\n'
                                                ' 1\n'
                                                ' 2\n'
                                                ' End',
                                        'newvalue': 'world\n1\n2\nEnd',
                                        'oldvalue': 'world!\n'
                                                    'Goodbye!\n'
                                                    '1\n'
                                                    '2\n'
                                                    'End'}}}

>>> 
>>> print (ddiff['values_changed']["root[4]['b']"]["diff"])
--- 
+++ 
@@ -1,5 +1,4 @@
-world!
-Goodbye!
+world
 1
 2
 End

Type change

>>> t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2, 3]}}
>>> t2 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":"world\n\n\nEnd"}}
>>> ddiff = DeepDiff(t1, t2)
>>> pprint (ddiff, indent = 2)
{ 'type_changes': { "root[4]['b']": { 'newtype': <class 'str'>,
                                      'newvalue': 'world\n\n\nEnd',
                                      'oldtype': <class 'list'>,
                                      'oldvalue': [1, 2, 3]}}}

List difference

>>> t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2, 3, 4]}}
>>> t2 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2]}}
>>> ddiff = DeepDiff(t1, t2)
>>> pprint (ddiff, indent = 2)
{'iterable_item_removed': {"root[4]['b'][2]": 3, "root[4]['b'][3]": 4}}

List difference 2:

>>> t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2, 3]}}
>>> t2 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 3, 2, 3]}}
>>> ddiff = DeepDiff(t1, t2)
>>> pprint (ddiff, indent = 2)
{ 'iterable_item_added': {"root[4]['b'][3]": 3},
  'values_changed': { "root[4]['b'][1]": {'newvalue': 3, 'oldvalue': 2},
                      "root[4]['b'][2]": {'newvalue': 2, 'oldvalue': 3}}}

List difference ignoring order or duplicates: (with the same dictionaries as above)

>>> t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2, 3]}}
>>> t2 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 3, 2, 3]}}
>>> ddiff = DeepDiff(t1, t2, ignore_order=True)
>>> print (ddiff)
{}

List that contains dictionary:

>>> t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2, {1:1, 2:2}]}}
>>> t2 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2, {1:3}]}}
>>> ddiff = DeepDiff(t1, t2)
>>> pprint (ddiff, indent = 2)
{ 'dic_item_removed': ["root[4]['b'][2][2]"],
  'values_changed': {"root[4]['b'][2][1]": {'newvalue': 3, 'oldvalue': 1}}}

Sets:

>>> t1 = {1, 2, 8}
>>> t2 = {1, 2, 3, 5}
>>> ddiff = DeepDiff(t1, t2)
>>> pprint (DeepDiff(t1, t2))
{'set_item_added': ['root[3]', 'root[5]'], 'set_item_removed': ['root[8]']}

Named Tuples:

>>> from collections import namedtuple
>>> Point = namedtuple('Point', ['x', 'y'])
>>> t1 = Point(x=11, y=22)
>>> t2 = Point(x=11, y=23)
>>> pprint (DeepDiff(t1, t2))
{'values_changed': {'root.y': {'newvalue': 23, 'oldvalue': 22}}}

Custom objects:

>>> class ClassA(object):
...     a = 1
...     def __init__(self, b):
...         self.b = b
... 
>>> t1 = ClassA(1)
>>> t2 = ClassA(2)
>>> 
>>> pprint(DeepDiff(t1, t2))
{'values_changed': {'root.b': {'newvalue': 2, 'oldvalue': 1}}}

Object attribute added:

>>> t2.c = "new attribute"
>>> pprint(DeepDiff(t1, t2))
{'attribute_added': ['root.c'],
 'values_changed': {'root.b': {'newvalue': 2, 'oldvalue': 1}}}

jquery: change the URL address without redirecting?

No, because that would open up the floodgates for phishing. The only part of the URI you can change is the fragment (everything after the #). You can do so by setting window.location.hash.

PHP function to generate v4 UUID

From tom, on http://www.php.net/manual/en/function.uniqid.php

$r = unpack('v*', fread(fopen('/dev/random', 'r'),16));
$uuid = sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
    $r[1], $r[2], $r[3], $r[4] & 0x0fff | 0x4000,
    $r[5] & 0x3fff | 0x8000, $r[6], $r[7], $r[8])

Installing PDO driver on MySQL Linux server

  1. PDO stands for PHP Data Object.
  2. PDO_MYSQL is the driver that will implement the interface between the dataobject(database) and the user input (a layer under the user interface called "code behind") accessing your data object, the MySQL database.

The purpose of using this is to implement an additional layer of security between the user interface and the database. By using this layer, data can be normalized before being inserted into your data structure. (Capitals are Capitals, no leading or trailing spaces, all dates at properly formed.)

But there are a few nuances to this which you might not be aware of.

First of all, up until now, you've probably written all your queries in something similar to the URL, and you pass the parameters using the URL itself. Using the PDO, all of this is done under the user interface level. User interface hands off the ball to the PDO which carries it down field and plants it into the database for a 7-point TOUCHDOWN.. he gets seven points, because he got it there and did so much more securely than passing information through the URL.

You can also harden your site to SQL injection by using a data-layer. By using this intermediary layer that is the ONLY 'player' who talks to the database itself, I'm sure you can see how this could be much more secure. Interface to datalayer to database, datalayer to database to datalayer to interface.

And:

By implementing best practices while writing your code you will be much happier with the outcome.

Additional sources:

Re: MySQL Functions in the url php dot net/manual/en/ref dot pdo-mysql dot php

Re: three-tier architecture - adding security to your applications https://blog.42.nl/articles/introducing-a-security-layer-in-your-application-architecture/

Re: Object Oriented Design using UML If you really want to learn more about this, this is the best book on the market, Grady Booch was the father of UML http://dl.acm.org/citation.cfm?id=291167&CFID=241218549&CFTOKEN=82813028

Or check with bitmonkey. There's a group there I'm sure you could learn a lot with.

>

If we knew what the terminology really meant we wouldn't need to learn anything.

>

Mean per group in a data.frame

Here are a variety of ways to do this in base R including an alternative aggregate approach. The examples below return means per month, which I think is what you requested. Although, the same approach could be used to return means per person:

Using ave:

my.data <- read.table(text = '
     Name     Month  Rate1     Rate2
     Aira       1      12        23
     Aira       2      18        73
     Aira       3      19        45
     Ben        1      53        19
     Ben        2      22        87
     Ben        3      19        45
     Cat        1      22        87
     Cat        2      67        43
     Cat        3      45        32
', header = TRUE, stringsAsFactors = FALSE, na.strings = 'NA')

Rate1.mean <- with(my.data, ave(Rate1, Month, FUN = function(x) mean(x, na.rm = TRUE)))
Rate2.mean <- with(my.data, ave(Rate2, Month, FUN = function(x) mean(x, na.rm = TRUE)))

my.data <- data.frame(my.data, Rate1.mean, Rate2.mean)
my.data

Using by:

my.data <- read.table(text = '
     Name     Month  Rate1     Rate2
     Aira       1      12        23
     Aira       2      18        73
     Aira       3      19        45
     Ben        1      53        19
     Ben        2      22        87
     Ben        3      19        45
     Cat        1      22        87
     Cat        2      67        43
     Cat        3      45        32
', header = TRUE, stringsAsFactors = FALSE, na.strings = 'NA')

by.month <- as.data.frame(do.call("rbind", by(my.data, my.data$Month, FUN = function(x) colMeans(x[,3:4]))))
colnames(by.month) <- c('Rate1.mean', 'Rate2.mean')
by.month <- cbind(Month = rownames(by.month), by.month)

my.data <- merge(my.data, by.month, by = 'Month')
my.data

Using lapply and split:

my.data <- read.table(text = '
     Name     Month  Rate1     Rate2
     Aira       1      12        23
     Aira       2      18        73
     Aira       3      19        45
     Ben        1      53        19
     Ben        2      22        87
     Ben        3      19        45
     Cat        1      22        87
     Cat        2      67        43
     Cat        3      45        32
', header = TRUE, stringsAsFactors = FALSE, na.strings = 'NA')

ly.mean <- lapply(split(my.data, my.data$Month), function(x) c(Mean = colMeans(x[,3:4])))
ly.mean <- as.data.frame(do.call("rbind", ly.mean))
ly.mean <- cbind(Month = rownames(ly.mean), ly.mean)

my.data <- merge(my.data, ly.mean, by = 'Month')
my.data

Using sapply and split:

my.data <- read.table(text = '
     Name     Month  Rate1     Rate2
     Aira       1      12        23
     Aira       2      18        73
     Aira       3      19        45
     Ben        1      53        19
     Ben        2      22        87
     Ben        3      19        45
     Cat        1      22        87
     Cat        2      67        43
     Cat        3      45        32
', header = TRUE, stringsAsFactors = FALSE, na.strings = 'NA')
my.data

sy.mean <- t(sapply(split(my.data, my.data$Month), function(x) colMeans(x[,3:4])))
colnames(sy.mean) <- c('Rate1.mean', 'Rate2.mean')
sy.mean <- data.frame(Month = rownames(sy.mean), sy.mean, stringsAsFactors = FALSE)
my.data <- merge(my.data, sy.mean, by = 'Month')
my.data

Using aggregate:

my.data <- read.table(text = '
     Name     Month  Rate1     Rate2
     Aira       1      12        23
     Aira       2      18        73
     Aira       3      19        45
     Ben        1      53        19
     Ben        2      22        87
     Ben        3      19        45
     Cat        1      22        87
     Cat        2      67        43
     Cat        3      45        32
', header = TRUE, stringsAsFactors = FALSE, na.strings = 'NA')

my.summary <- with(my.data, aggregate(list(Rate1, Rate2), by = list(Month), 
                   FUN = function(x) { mon.mean = mean(x, na.rm = TRUE) } ))

my.summary <- do.call(data.frame, my.summary)
colnames(my.summary) <- c('Month', 'Rate1.mean', 'Rate2.mean')
my.summary

my.data <- merge(my.data, my.summary, by = 'Month')
my.data

EDIT: June 28, 2020

Here I use aggregate to obtain the column means of an entire matrix by group where group is defined in an external vector:

my.group <- c(1,2,1,2,2,3,1,2,3,3)

my.data <- matrix(c(   1,    2,    3,    4,    5,
                      10,   20,   30,   40,   50,
                       2,    4,    6,    8,   10,
                      20,   30,   40,   50,   60,
                      20,   18,   16,   14,   12,
                    1000, 1100, 1200, 1300, 1400,
                       2,    3,    4,    3,    2,
                      50,   40,   30,   20,   10,
                    1001, 2001, 3001, 4001, 5001,
                    1000, 2000, 3000, 4000, 5000), nrow = 10, ncol = 5, byrow = TRUE)
my.data

my.summary <- aggregate(list(my.data), by = list(my.group), FUN = function(x) { my.mean = mean(x, na.rm = TRUE) } )
my.summary
#  Group.1          X1       X2          X3       X4          X5
#1       1    1.666667    3.000    4.333333    5.000    5.666667
#2       2   25.000000   27.000   29.000000   31.000   33.000000
#3       3 1000.333333 1700.333 2400.333333 3100.333 3800.333333

How to get access to raw resources that I put in res folder?

InputStream raw = context.getAssets().open("filename.ext");

Reader is = new BufferedReader(new InputStreamReader(raw, "UTF8"));

Python Set Comprehension

primes = {x for x in range(2, 101) if all(x%y for y in range(2, min(x, 11)))}

I simplified the test a bit - if all(x%y instead of if not any(not x%y

I also limited y's range; there is no point in testing for divisors > sqrt(x). So max(x) == 100 implies max(y) == 10. For x <= 10, y must also be < x.

pairs = {(x, x+2) for x in primes if x+2 in primes}

Instead of generating pairs of primes and testing them, get one and see if the corresponding higher prime exists.

How to use filter, map, and reduce in Python 3

One of the advantages of map, filter and reduce is how legible they become when you "chain" them together to do something complex. However, the built-in syntax isn't legible and is all "backwards". So, I suggest using the PyFunctional package (https://pypi.org/project/PyFunctional/). Here's a comparison of the two:

flight_destinations_dict = {'NY': {'London', 'Rome'}, 'Berlin': {'NY'}}

PyFunctional version

Very legible syntax. You can say:

"I have a sequence of flight destinations. Out of which I want to get the dict key if city is in the dict values. Finally, filter out the empty lists I created in the process."

from functional import seq  # PyFunctional package to allow easier syntax

def find_return_flights_PYFUNCTIONAL_SYNTAX(city, flight_destinations_dict):
    return seq(flight_destinations_dict.items()) \
        .map(lambda x: x[0] if city in x[1] else []) \
        .filter(lambda x: x != []) \

Default Python version

It's all backwards. You need to say:

"OK, so, there's a list. I want to filter empty lists out of it. Why? Because I first got the dict key if the city was in the dict values. Oh, the list I'm doing this to is flight_destinations_dict."

def find_return_flights_DEFAULT_SYNTAX(city, flight_destinations_dict):
    return list(
        filter(lambda x: x != [],
               map(lambda x: x[0] if city in x[1] else [], flight_destinations_dict.items())
               )
    )

How to get the seconds since epoch from the time + date output of gmtime()?

t = datetime.strptime('Jul 9, 2009 @ 20:02:58 UTC',"%b %d, %Y @ %H:%M:%S %Z")

How to print to stderr in Python?

The same applies to stdout:

print 'spam'
sys.stdout.write('spam\n')

As stated in the other answers, print offers a pretty interface that is often more convenient (e.g. for printing debug information), while write is faster and can also be more convenient when you have to format the output exactly in certain way. I would consider maintainability as well:

  1. You may later decide to switch between stdout/stderr and a regular file.

  2. print() syntax has changed in Python 3, so if you need to support both versions, write() might be better.

Is there a kind of Firebug or JavaScript console debug for Android?

We are following the below steps in our project for debugging a website on mobile.

  1. Install mobogenie software on mobile and desktop (both have the same version).
  2. Open your site in mobile Google Chrome browser.
  3. Open Google Chrome on desktop. Go to Option --> More Options --> Inspect Device.
  4. Here you find a list of sites which are open on mobile and click on inspect and you get the JavaScript console which you want.

How to get a right click mouse event? Changing EventArgs to MouseEventArgs causes an error in Form1Designer?

You should introduce a cast inside the click event handler

MouseEventArgs me = (MouseEventArgs) e;

How to get day of the month?

tl;dr

LocalDate           // Represent a date-only, without time-of-day and without time zone.
.now()              // Better to pass a `ZoneId` optional argument to `now` as shown below than rely implicitly on the JVM’s current default time zone.
.getDayOfMonth()    // Interrogate for the day of the month (1-31). 

java.time

The modern approach is the LocalDate class to represent a date-only value.

A time zone is crucial in determine the current date. For any given moment, the date varies around the globe by zone.

ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate ld = LocalDate.now( z ) ;
int dayOfMonth = ld.getDayOfMonth();

You can also get the day-of-week.

DayOfWeek dow = ld.getDayOfWeek();

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Using a JDBC driver compliant with JDBC 4.2 or later, you may exchange java.time objects directly with your database. No need for strings nor java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.


Joda-Time

UPDATE: The Joda-Time project is now in maintenance mode, and advises migration to the java.time classes. This section left intact for history.

Using the Joda-Time 2.5 library rather than the notoriously troublesome java.util.Date and .Calendar classes.

Time zone is crucial to determining a date. Better to specify the zone rather than rely implicitly on the JVM’s current default time zone being assigned.

DateTimeZone zone = DateTimeZone.forID( "America/Montreal" );
DateTime now = DateTime.now( zone ).withTimeAtStartOfDay();
int dayOfMonth = now.getDayOfMonth();

Or use similar code with the LocalDate class that has no time-of-day portion.

List of swagger UI alternatives

Yes, there are a few of them.

Hosted solutions that support swagger:

Check the following articles for more details:

Java Serializable Object to Byte Array

I also recommend to use SerializationUtils tool. I want to make a ajust on a wrong comment by @Abilash. The SerializationUtils.serialize() method is not restricted to 1024 bytes, contrary to another answer here.

public static byte[] serialize(Object object) {
    if (object == null) {
        return null;
    }
    ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
    try {
        ObjectOutputStream oos = new ObjectOutputStream(baos);
        oos.writeObject(object);
        oos.flush();
    }
    catch (IOException ex) {
        throw new IllegalArgumentException("Failed to serialize object of type: " + object.getClass(), ex);
    }
    return baos.toByteArray();
}

At first sight, you may think that new ByteArrayOutputStream(1024) will only allow a fixed size. But if you take a close look at the ByteArrayOutputStream, you will figure out the the stream will grow if necessary:

This class implements an output stream in which the data is written into a byte array. The buffer automatically grows as data is written to it. The data can be retrieved using toByteArray() and toString().

How to use group by with union in t-sql

You need to alias the subquery. Thus, your statement should be:

Select Z.id
From    (
        Select id, time
        From dbo.tablea
        Union All
        Select id, time
        From dbo.tableb
        ) As Z
Group By Z.id

installation app blocked by play protect

I am adding this answer for others who are still seeking a solution to this problem if you don't want to upload your app on playstore then temporarily there is a workaround for this problem.

Google is providing safety device verification api which you need to call only once in your application and after that your application will not be blocked by play protect:

Here are there the links:

https://developer.android.com/training/safetynet/attestation#verify-attestation-response

Link for sample code project:

https://github.com/googlesamples/android-play-safetynet

python JSON only get keys in first level

Just do a simple .keys()

>>> dct = {
...     "1": "a", 
...     "3": "b", 
...     "8": {
...         "12": "c", 
...         "25": "d"
...     }
... }
>>> 
>>> dct.keys()
['1', '8', '3']
>>> for key in dct.keys(): print key
...
1
8
3
>>>

If you need a sorted list:

keylist = dct.keys()
keylist.sort()

R for loop skip to next iteration ifelse

for(n in 1:5) {
  if(n==3) next # skip 3rd iteration and go to next iteration
  cat(n)
}

Can't Find Theme.AppCompat.Light for New Android ActionBar Support

In my case the problem occurred since I wanted to use a SDK that doesnt include the required library. When I increased the min. SDK level the problem dissappeared. Of course directly including the library's itself, should remove the error as well.

Postfix is installed but how do I test it?

(I just got this working, with my main issue being that I don't have a real internet hostname, so answering this question in case it helps someone)

You need to specify a hostname with HELO. Even so, you should get an error, so Postfix is probably not running.

Also, the => is not a command. The '.' on a single line without any text around it is what tells Postfix that the entry is complete. Here are the entries I used:

telnet localhost 25
(says connected)
EHLO howdy.com
(returns a bunch of 250 codes)
MAIL FROM: [email protected]
RCPT TO: (use a real email address you want to send to)
DATA (type whatever you want on muliple lines)
. (this on a single line tells Postfix that the DATA is complete)

You should get a response like:

250 2.0.0 Ok: queued as 6E414C4643A

The email will probably end up in a junk folder. If it is not showing up, then you probably need to setup the 'Postfix on hosts without a real Internet hostname'. Here is the breakdown on how I completed that step on my Ubuntu box:

sudo vim /etc/postfix/main.cf
smtp_generic_maps = hash:/etc/postfix/generic (add this line somewhere)
(edit or create the file 'generic' if it doesn't exist)
sudo vim /etc/postfix/generic
(add these lines, I don't think it matters what names you use, at least to test)
[email protected]             [email protected]
[email protected]             [email protected]
@localdomain.local                [email protected]
then run:
postmap /etc/postfix/generic (this needs to be run whenever you change the 
generic file)

Happy Trails

Autoreload of modules in IPython

If you add file ipython_config.py into the ~/.ipython/profile_default directory with lines like below, then the autoreload functionality will be loaded on IPython startup (tested on 2.0.0):

print "--------->>>>>>>> ENABLE AUTORELOAD <<<<<<<<<------------"

c = get_config()
c.InteractiveShellApp.exec_lines = []
c.InteractiveShellApp.exec_lines.append('%load_ext autoreload')
c.InteractiveShellApp.exec_lines.append('%autoreload 2')

Shuffling a list of objects

In some cases when using numpy arrays, using random.shuffle created duplicate data in the array.

An alternative is to use numpy.random.shuffle. If you're working with numpy already, this is the preferred method over the generic random.shuffle.

numpy.random.shuffle

Example

>>> import numpy as np
>>> import random

Using random.shuffle:

>>> foo = np.array([[1,2,3],[4,5,6],[7,8,9]])
>>> foo

array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])


>>> random.shuffle(foo)
>>> foo

array([[1, 2, 3],
       [1, 2, 3],
       [4, 5, 6]])

Using numpy.random.shuffle:

>>> foo = np.array([[1,2,3],[4,5,6],[7,8,9]])
>>> foo

array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])


>>> np.random.shuffle(foo)
>>> foo

array([[1, 2, 3],
       [7, 8, 9],
       [4, 5, 6]])

How can I enable auto complete support in Notepad++?

Open Notepad++ and Settings -> Preferences -> Auto-Completion -> Check the Auto-insert options you want. this link will help alot: http://docs.notepad-plus-plus.org/index.php/Auto_Completion

Java Can't connect to X11 window server using 'localhost:10.0' as the value of the DISPLAY variable

I run into the same error with you when i run the jconsole command at remote. I want to modify a parameter at jconsole that run on a remote Linux host, i can login the host use the secureCRT, the terminal throw this error information. Fortunately, when use the Putty, it's ok. Weird....

What are differences between AssemblyVersion, AssemblyFileVersion and AssemblyInformationalVersion?

AssemblyInformationalVersion and AssemblyFileVersion are displayed when you view the "Version" information on a file through Windows Explorer by viewing the file properties. These attributes actually get compiled in to a VERSION_INFO resource that is created by the compiler.

AssemblyInformationalVersion is the "Product version" value. AssemblyFileVersion is the "File version" value.

The AssemblyVersion is specific to .NET assemblies and is used by the .NET assembly loader to know which version of an assembly to load/bind at runtime.

Out of these, the only one that is absolutely required by .NET is the AssemblyVersion attribute. Unfortunately it can also cause the most problems when it changes indiscriminately, especially if you are strong naming your assemblies.

Angular ng-class if else

Just make a rule for each case:

<div id="homePage" ng-class="{ 'center': page.isSelected(1) , 'left': !page.isSelected(1)  }">

Or use the ternary operator:

<div id="homePage" ng-class="page.isSelected(1) ? 'center' : 'left'">

How to change legend size with matplotlib.pyplot

On my install, FontProperties only changes the text size, but it's still too large and spaced out. I found a parameter in pyplot.rcParams: legend.labelspacing, which I'm guessing is set to a fraction of the font size. I've changed it with

pyplot.rcParams.update({'legend.labelspacing':0.25})

I'm not sure how to specify it to the pyplot.legend function - passing

prop={'labelspacing':0.25}

or

prop={'legend.labelspacing':0.25}

comes back with an error.

Mismatched anonymous define() module

Be aware that some browser extensions can add code to the pages. In my case I had an "Emmet in all textareas" plugin that messed up with my requireJs. Make sure that no extra code is beign added to your document by inspecting it in the browser.

Duplicating a MySQL table, indices, and data

To duplicate a table and its structure without data from a different a database use this. On the new database sql type

CREATE TABLE currentdatabase.tablename LIKE olddatabase.tablename

npm install gives error "can't find a package.json file"

solve using this code:

npm install npm@latest -g

PHP DOMDocument loadHTML not encoding UTF-8 correctly

The only thing that worked for me was the accepted answer of

$profile = '<p>???????????????????????9</p>';
$dom = new DOMDocument();
$dom->loadHTML('<?xml encoding="utf-8" ?>' . $profile);
echo $dom->saveHTML();

HOWEVER

This brought about new issues, of having <?xml encoding="utf-8" ?> in the output of the document.

The solution for me was then to do

foreach ($doc->childNodes as $xx) {
    if ($xx instanceof \DOMProcessingInstruction) {
        $xx->parentNode->removeChild($xx);
    }
}

Some solutions told me that to remove the xml header, that I had to perform

$dom->saveXML($dom->documentElement);

This didn't work for me as for a partial document (e.g. a doc with two <p> tags), only one of the <p> tags where being returned.

How do I check my gcc C++ compiler version for my Eclipse?

The answer is:

gcc --version

Rather than searching on forums, for any possible option you can always type:

gcc --help

haha! :)

FileProvider - IllegalArgumentException: Failed to find configured root

none of the above worked for me, after a few hours debugging I found out that the problem is in createImageFile(), specifically absolute path vs relative path

I assume that you guys are using the official Android guide for taking photo. https://developer.android.com/training/camera/photobasics

    private static File createImageFile(Context context) throws IOException {
        // Create an image file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        File image = File.createTempFile(
                imageFileName,  /* prefix */
                ".jpg",         /* suffix */
                storageDir      /* directory */
        );

        // Save a file: path for use with ACTION_VIEW intents
        mCurrentPhotoPath = image.getAbsolutePath();
        return image;
    }

Take note of the storageDir, this is the location where the file will be created. So in order to get the absolute path of this file, I simply use image.getAbsolutePath(), this path will be used in onActivityResult if you need the Bitmap image after taking photo

below is the file_path.xml, simply use . so that it uses the absolute path

<paths>
    <external-path
        name="my_images"
        path="." />
</paths>

and if you need the bitmap after taking photo

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Bitmap bmp = null;
        try {
            bmp = BitmapFactory.decodeFile(mCurrentPhotoPath);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

How do I call Objective-C code from Swift?

Making any Swift class subclass of NSObject makes sense also I prefer for using any Swift class to be seen in Objective-C classes like:

@objc(MySwiftClass)
@objcMembers class MySwiftClass {...}

String contains another string

You can use .indexOf():

if(str.indexOf(substr) > -1) {

}

Missing XML comment for publicly visible type or member

Insert an XML comment. ;-)

/// <summary>
/// Describe your member here.
/// </summary>
public string Something
{
    get;
    set;
}

This may appear like a joke at the first glance, but it may actually be useful. For me it turned out to be helpful to think about what methods do even for private methods (unless really trivial, of course).

Setting the default page for ASP.NET (Visual Studio) server configuration

The built-in webserver is hardwired to use Default.aspx as the default page.

The project must have atleast an empty Default.aspx file to overcome the Directory Listing problem for Global.asax.

:)

Once you add that empty file all requests can be handled in one location.

public class Global : System.Web.HttpApplication
{
    protected void Application_BeginRequest(object sender, EventArgs e)
    {
        this.Response.Write("hi@ " + this.Request.Path + "?" + this.Request.QueryString);
        this.Response.StatusCode = 200;
        this.Response.ContentType = "text/plain";

        this.Response.End();
    }
}

What does the percentage sign mean in Python

While this is slightly off-topic, since people will find this by searching for "percentage sign in Python" (as I did), I wanted to note that the % sign is also used to prefix a "magic" function in iPython: https://ipython.org/ipython-doc/3/interactive/tutorial.html#magic-functions

global variable for all controller and views

In file - \vendor\autoload.php, define your gobals variable as follows, should be in the topmost line.

$global_variable = "Some value";//the global variable

Access that global variable anywhere as :-

$GLOBALS['global_variable'];

Enjoy :)

How to disable mouse scroll wheel scaling with Google Maps API

You just need to add in map options:

scrollwheel: false

cannot open shared object file: No such file or directory

When working on a supercomputer, I received this error when I ran:

module load python/3.4.0
screen
python

To resolve the error, I simply needed to reload the module in the screen terminal:

module load python/3.4.0
python

Why doesn't Git ignore my specified file?

I tried most commands above on VS Code terminal and I got errors like:

fatal: pathspec '[dir]/[file]' did not match any files

I opened the project on GitHub Desktop and ignored from there and it worked.

Adding :default => true to boolean in existing Rails column

change_column :things, :price_1, :integer, default: 123, null: false

Seems to be best way to add a default to an existing column that doesn't have null: false already.

Otherwise:

change_column :things, :price_1, :integer, default: 123

Some research I did on this:

https://gist.github.com/Dorian/417b9a0e1a4e09a558c39345d50c8c3b

How to represent a fix number of repeats in regular expression?

In Java create the pattern with Pattern p = Pattern.compile("^\\w{14}$"); for further information see the javadoc

Python Requests - No connection adapters

One more reason, maybe your url include some hiden characters, such as '\n'.

If you define your url like below, this exception will raise:

url = '''
http://google.com
'''

because there are '\n' hide in the string. The url in fact become:

\nhttp://google.com\n

How to fix C++ error: expected unqualified-id

As a side note, consider passing strings in setWord() as const references to avoid excess copying. Also, in displayWord, consider making this a const function to follow const-correctness.

void setWord(const std::string& word) {
  theWord = word;
}

Using helpers in model: how do I include helper dependencies?

Just change the first line as follows :

include ActionView::Helpers

that will make it works.

UPDATE: For Rails 3 use:

ActionController::Base.helpers.sanitize(str)

Credit goes to lornc's answer

Removing whitespace from strings in Java

In java we can do following operation:

String pattern="[\\s]";
String replace="";
part="name=john age=13 year=2001";
Pattern p=Pattern.compile(pattern);
Matcher m=p.matcher(part);
part=m.replaceAll(replace);
System.out.println(part);

for this you need to import following packages to your program:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

i hope it will help you.

How to randomize (or permute) a dataframe rowwise and columnwise?

Random Samples and Permutations ina dataframe If it is in matrix form convert into data.frame use the sample function from the base package indexes = sample(1:nrow(df1), size=1*nrow(df1)) Random Samples and Permutations

Replace HTML page with contents retrieved via AJAX

Here's how to do it in Prototype: $(id).update(data)

And jQuery: $('#id').replaceWith(data)

But document.getElementById(id).innerHTML=data should work too.

EDIT: Prototype and jQuery automatically evaluate scripts for you.

Cannot use a CONTAINS or FREETEXT predicate on table or indexed view because it is not full-text indexed

There is one more solution to set column Full text to true.

These solution for example didn't work for me

ALTER TABLE news ADD FULLTEXT(headline, story);

My solution.

  1. Right click on table
  2. Design
  3. Right Click on column which you want to edit
  4. Full text index
  5. Add
  6. Close
  7. Refresh

NEXT STEPS

  1. Right click on table
  2. Design
  3. Click on column which you want to edit
  4. On bottom of mssql you there will be tab "Column properties"
  5. Full-text Specification -> (Is Full-text Indexed) set to true.

Refresh

Version of mssql 2014

Received fatal alert: handshake_failure through SSLHandshakeException

This issue is occurring because of the java version. I was using 1.8.0.231 JDK and getting this error. I have degraded my java version from 1.8.0.231 to 1.8.0.171, Now It is working fine.

How to pass model attributes from one Spring MVC controller to another controller?

I use spring 3.2.3 and here is how I solved similar problem.
1) Added RedirectAttributes redirectAttributes to the method parameter list in controller 1.

public String controlMapping1(
        @ModelAttribute("mapping1Form") final Object mapping1FormObject,
        final BindingResult mapping1BindingResult,
        final Model model, 
        final RedirectAttributes redirectAttributes)

2) Inside the method added code to add flash attribute to redirectAttributes redirectAttributes.addFlashAttribute("mapping1Form", mapping1FormObject);

3) Then, in the second contoller use method parameter annotated with @ModelAttribute to access redirect Attributes

@ModelAttribute("mapping1Form") final Object mapping1FormObject

Here is the sample code from Controller 1:

@RequestMapping(value = { "/mapping1" }, method = RequestMethod.POST)
public String controlMapping1(
        @ModelAttribute("mapping1Form") final Object mapping1FormObject,
        final BindingResult mapping1BindingResult,
        final Model model, 
        final RedirectAttributes redirectAttributes) {

    redirectAttributes.addFlashAttribute("mapping1Form", mapping1FormObject);

    return "redirect:mapping2";
}   

From Contoller 2:

@RequestMapping(value = "/mapping2", method = RequestMethod.GET)
public String controlMapping2(
        @ModelAttribute("mapping1Form") final Object mapping1FormObject,
        final BindingResult mapping1BindingResult,
        final Model model) {

    model.addAttribute("transformationForm", mapping1FormObject);

    return "new/view";  
}

Laravel 4: how to run a raw SQL?

Laravel raw sql – Insert query:

lets create a get link to insert data which is accessible through url . so our link name is ‘insertintodb’ and inside that function we use db class . db class helps us to interact with database . we us db class static function insert . Inside insert function we will write our PDO query to insert data in database . in below query we will insert ‘ my title ‘ and ‘my content’ as data in posts table .

put below code in your web.php file inside routes directory :

Route::get('/insertintodb',function(){
DB::insert('insert into posts(title,content) values (?,?)',['my title','my content']);
});

Now fire above insert query from browser link below :

localhost/yourprojectname/insertintodb

You can see output of above insert query by going into your database table .you will find a record with id 1 .

Laravel raw sql – Read query :

Now , lets create a get link to read data , which is accessible through url . so our link name is ‘readfromdb’. we us db class static function read . Inside read function we will write our PDO query to read data from database . in below query we will read data of id ‘1’ from posts table .

put below code in your web.php file inside routes directory :

Route::get('/readfromdb',function() {
    $result =  DB::select('select * from posts where id = ?', [1]);
    var_dump($result);
});

now fire above read query from browser link below :

localhost/yourprojectname/readfromdb

How to return rows from left table not found in right table?

If you are asking for T-SQL then lets look at fundamentals first. There are three types of joins here each with its own set of logical processing phases as:

  1. A cross join is simplest of all. It implements only one logical query processing phase, a Cartesian Product. This phase operates on the two tables provided as inputs to the join and produces a Cartesian product of the two. That is, each row from one input is matched with all rows from the other. So if you have m rows in one table and n rows in the other, you get m×n rows in the result.
  2. Then are Inner joins : They apply two logical query processing phases: A Cartesian product between the two input tables as in a cross join, and then it filters rows based on a predicate that you specify in ON clause (also known as Join condition).
  3. Next comes the third type of joins, Outer Joins:

    In an outer join, you mark a table as a preserved table by using the keywords LEFT OUTER JOIN, RIGHT OUTER JOIN, or FULL OUTER JOIN between the table names. The OUTER keyword is optional. The LEFT keyword means that the rows of the left table are preserved; the RIGHT keyword means that the rows in the right table are preserved; and the FULL keyword means that the rows in both the left and right tables are preserved.

    The third logical query processing phase of an outer join identifies the rows from the preserved table that did not find matches in the other table based on the ON predicate. This phase adds those rows to the result table produced by the first two phases of the join, and uses NULL marks as placeholders for the attributes from the nonpreserved side of the join in those outer rows.

Now if we look at the question: To return records from the left table which are not found in the right table use Left outer join and filter out the rows with NULL values for the attributes from the right side of the join.

What's the best way to parse command line arguments?

The new hip way is argparse for these reasons. argparse > optparse > getopt

update: As of py2.7 argparse is part of the standard library and optparse is deprecated.

When is TCP option SO_LINGER (0) required?

When linger is on but the timeout is zero the TCP stack doesn't wait for pending data to be sent before closing the connection. Data could be lost due to this but by setting linger this way you're accepting this and asking that the connection be reset straight away rather than closed gracefully. This causes an RST to be sent rather than the usual FIN.

Thanks to EJP for his comment, see here for details.

How to get object length

One more answer:

_x000D_
_x000D_
var j = '[{"uid":"1","name":"Bingo Boy", "profile_img":"funtimes.jpg"},{"uid":"2","name":"Johnny Apples", "profile_img":"badtime.jpg"}]';_x000D_
_x000D_
obj = Object.keys(j).length;_x000D_
console.log(obj)
_x000D_
_x000D_
_x000D_

jquery toggle slide from left to right and back

Use this...

$('#cat_icon').click(function () {
    $('#categories').toggle("slow");
    //$('#cat_icon').hide();
});
$('.panel_title').click(function () {
    $('#categories').toggle("slow");
    //$('#cat_icon').show();
});

See this Example

Greetings.

How do I sort an observable collection?

I needed to be able to sort by multiple things not just one. This answer is based on some of the other answers but it allows for more complex sorting.

static class Extensions
{
    public static void Sort<T, TKey>(this ObservableCollection<T> collection, Func<ObservableCollection<T>, TKey> sort)
    {
        var sorted = (sort.Invoke(collection) as IOrderedEnumerable<T>).ToArray();
        for (int i = 0; i < sorted.Count(); i++)
            collection.Move(collection.IndexOf(sorted[i]), i);
    }
}

When you use it, pass in a series of OrderBy/ThenBy calls. Like this:

Children.Sort(col => col.OrderByDescending(xx => xx.ItemType == "drive")
                    .ThenByDescending(xx => xx.ItemType == "folder")
                    .ThenBy(xx => xx.Path));

How to drop all user tables?

The easiest way would be to drop the tablespace then build the tablespace back up. But I'd rather not have to do that. This is similar to Henry's except that I just do a copy/paste on the resultset in my gui.

SELECT
  'DROP'
  ,object_type
  ,object_name
  ,CASE(object_type)
     WHEN 'TABLE' THEN 'CASCADE CONSTRAINTS;'
     ELSE ';'
   END
 FROM user_objects
 WHERE
   object_type IN ('TABLE','VIEW','PACKAGE','PROCEDURE','FUNCTION','SEQUENCE')

Generating a random password in php

Try This with Capital Letters, Small Letters, Numeric(s) and Special Characters

function generatePassword($_len) {

    $_alphaSmall = 'abcdefghijklmnopqrstuvwxyz';            // small letters
    $_alphaCaps  = strtoupper($_alphaSmall);                // CAPITAL LETTERS
    $_numerics   = '1234567890';                            // numerics
    $_specialChars = '`~!@#$%^&*()-_=+]}[{;:,<.>/?\'"\|';   // Special Characters

    $_container = $_alphaSmall.$_alphaCaps.$_numerics.$_specialChars;   // Contains all characters
    $password = '';         // will contain the desired pass

    for($i = 0; $i < $_len; $i++) {                                 // Loop till the length mentioned
        $_rand = rand(0, strlen($_container) - 1);                  // Get Randomized Length
        $password .= substr($_container, $_rand, 1);                // returns part of the string [ high tensile strength ;) ] 
    }

    return $password;       // Returns the generated Pass
}

Let's Say we need 10 Digit Pass

echo generatePassword(10);  

Example Output(s) :

,IZCQ_IV\7

@wlqsfhT(d

1!8+1\4@uD

Show Error on the tip of the Edit Text Android

private void showError() {
   mEditText.setError("Password and username didn't match");
}

Which will result in errors shown like this:

enter image description here

And if you want to remove it:

 textView.setError(null);

Exposing a port on a live Docker container

I wrote a blog post that explains how to access an unpublished port of a container In different ways depending on the needs:

  • by committing a new image and running a new container,
  • by using socat to avoid restarting the container.

The post also goes through a brief introduction of both how port mapping works, the difference between exposing and publishing a port, and what is socat.

Here’s the link: https://lmcaraig.com/accessing-an-unpublished-port-of-a-running-docker-container

Difference between Dictionary and Hashtable

ILookup Interface is used in .net 3.5 with linq.

The HashTable is the base class that is weakly type; the DictionaryBase abstract class is stronly typed and uses internally a HashTable.

I found a a strange thing about Dictionary, when we add the multiple entries in Dictionary, the order in which the entries are added is maintained. Thus if I apply a foreach on the Dictionary, I will get the records in the same order I have inserted them.

Whereas, this is not true with normal HashTable, as when I add same records in Hashtable the order is not maintained. As far as my knowledge goes, Dictionary is based on Hashtable, if this is true, why my Dictionary maintains the order but HashTable does not?

As to why they behave differently, it's because Generic Dictionary implements a hashtable, but is not based on System.Collections.Hashtable. The Generic Dictionary implementation is based on allocating key-value-pairs from a list. These are then indexed with the hashtable buckets for random access, but when it returns an enumerator, it just walks the list in sequential order - which will be the order of insertion as long as entries are not re-used.

shiv govind Birlasoft.:)

Open Form2 from Form1, close Form1 from Form2

Your question is vague but you could use ShowDialog to display form 2. Then when you close form 2, pass a DialogResult object back to let the user know how the form was closed - if the user clicked the button, then close form 1 as well.

Selenium -- How to wait until page is completely loaded

yes stale element error is thrown when (taking your scenario) you have defined locator strategy to click on 'Add Item' first and then when you close the pop up the page gets refreshed hence the reference defined for 'Add Item' is lost in the memory so to overcome this you have to redefine the locator strategy for 'Add Item' again

understand it with a dummy code

// clicking on view details 
driver.findElement(By.id("")).click();
// closing the pop up 
driver.findElement(By.id("")).click();


// and when you try to click on Add Item
driver.findElement(By.id("")).click();
// you get stale element exception as reference to add item is lost 
// so to overcome this you have to re identify the locator strategy for add item 
// Please note : this is one of the way to overcome stale element exception 

// Step 1 please add a universal wait in your script like below 
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS); // just after you have initiated browser

Select single item from a list

There are two easy ways, depending on if you want to deal with exceptions or get a default value.

You can use the First<T>() or the FirstOrDefault<T>() extension method to get the first result or default(T).

var list = new List<int> { 1, 2, 4 };
var result = list.Where(i => i == 3).First(); // throws InvalidOperationException
var result = list.Where(i => i == 3).FirstOrDefault(); // = 0

trying to align html button at the center of the my page

You can center a button without using text-align on the parent div by simple using margin:auto; display:block;

For example:

HTML

<div>
  <button>Submit</button>
</div>

CSS

button {
  margin:auto;
  display:block;
}

SEE IT IN ACTION: CodePen

How to deal with persistent storage (e.g. databases) in Docker

I'm just using a predefined directory on the host to persist data for PostgreSQL. Also, this way it is possible to easily migrate existing PostgreSQL installations to Docker containers: https://crondev.com/persistent-postgresql-inside-docker/

How can I use regex to get all the characters after a specific character, e.g. comma (",")

Another idea is to do myVar.split(',')[1];

For simple case, not using a regexp is a good idea...

How to set a DateTime variable in SQL Server 2008?

2011-01-15 = 2011-16 = 1995. This is then being implicitly converted from an integer to a date, giving you the 1995th day, starting from 1st Jan 1900.

You need to use SET @test = '2011-02-15'

Prevent the keyboard from displaying on activity start

Try to declare it in menifest file

<activity android:name=".HomeActivity"
      android:label="@string/app_name"
      android:windowSoftInputMode="stateAlwaysHidden"
      >

How to compare two java objects

You have to correctly override method equals() from class Object

Edit: I think that my first response was misunderstood probably because I was not too precise. So I decided to to add more explanations.

Why do you have to override equals()? Well, because this is in the domain of a developer to decide what does it mean for two objects to be equal. Reference equality is not enough for most of the cases.

For example, imagine that you have a HashMap whose keys are of type Person. Each person has name and address. Now, you want to find detailed bean using the key. The problem is, that you usually are not able to create an instance with the same reference as the one in the map. What you do is to create another instance of class Person. Clearly, operator == will not work here and you have to use equals().

But now, we come to another problem. Let's imagine that your collection is very large and you want to execute a search. The naive implementation would compare your key object with every instance in a map using equals(). That, however, would be very expansive. And here comes the hashCode(). As others pointed out, hashcode is a single number that does not have to be unique. The important requirement is that whenever equals() gives true for two objects, hashCode() must return the same value for both of them. The inverse implication does not hold, which is a good thing, because hashcode separates our keys into kind of buckets. We have a small number of instances of class Person in a single bucket. When we execute a search, the algorithm can jump right away to a correct bucket and only now execute equals for each instance. The implementation for hashCode() therefore must distribute objects as evenly as possible across buckets.

There is one more point. Some collections require a proper implementation of a hashCode() method in classes that are used as keys not only for performance reasons. The examples are: HashSet and LinkedHashSet. If they don’t override hashCode(), the default Object hashCode() method will allow multiple objects that you might consider "meaningfully equal" to be added to your "no duplicates allowed" set.

Some of the collections that use hashCode()

  • HashSet
  • LinkedHashSet
  • HashMap

Have a look at those two classes from apache commons that will allow you to implement equals() and hashCode() easily

Android : Capturing HTTP Requests with non-rooted android device

It's 2020 now, for the latest solution, you can use Burp Suite to sniffing https traffic without rooting your Android device.

Steps:

  1. Install Burp Suite

  2. Enable Proxy

  3. Import the certification in your Android phone

  4. Change you Wifi configuration to listening to proxy

  5. Profit!

I wrote the full tutorial and screenshot on how to do it at here: https://www.yodiw.com/monitor-android-network-traffic-with-burp/

How would you do a "not in" query with LINQ?

You can take both the collections in two different lists, say list1 and list2.

Then just write

list1.RemoveAll(Item => list2.Contains(Item));

This will work.

Javascript use variable as object name

You could use eval:

eval(variablename + ".value = 'value'");

org.hibernate.MappingException: Unknown entity

You can enable entity scan by adding below annotation on Application .java @EntityScan(basePackageClasses=YourEntityClassName.class)

Or you can set the packageToScan in your session factory. sessionFactory.setPackagesToScan(“com.all.entity”);

Internet Access in Ubuntu on VirtualBox

I could get away with the following solution (works with Ubuntu 14 guest VM on Windows 7 host or Ubuntu 9.10 Casper guest VM on host Windows XP x86):

  1. Go to network connections -> Virtual Box Host-Only Network -> Select "Properties"
  2. Check VirtualBox Bridged Networking Driver
  3. Come to VirtualBox Manager, choose the network adapter as Bridged Adapter and Name to the device in Step #1.
  4. Restart the VM.

SQL Server PRINT SELECT (Print a select query result)?

If you wish (like me) to have results containing mulitple rows of various SELECT queries "labelled" and can't manage this within the constraints of the PRINT statement in concert with the Messages tab you could turn it around and simply add messages to the Results tab per the below:

SELECT 'Results from scenario 1'
SELECT
    *
FROM tblSample

enter image description here

What causes a TCP/IP reset (RST) flag to be sent?

If there is a router doing NAT, especially a low end router with few resources, it will age the oldest TCP sessions first. To do this it sets the RST flag in the packet that effectively tells the receiving station to (very ungracefully) close the connection. this is done to save resources.

MultipartException: Current request is not a multipart request

In application.properties, please add this:

spring.servlet.multipart.max-file-size=128KB
spring.servlet.multipart.max-request-size=128KB
spring.http.multipart.enabled=false

and in your html form, you need an : enctype="multipart/form-data". For example:

<form method="POST" enctype="multipart/form-data" action="/">

Hope this help!

How to set cornerRadius for only top-left and top-right corner of a UIView?

In Swift 4.2, Create it via @IBDesignable like this:

@IBDesignable

class DesignableViewCustomCorner: UIView {

    @IBInspectable var cornerRadious: CGFloat = 0 {
        didSet {
            let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: [.topLeft, .topRight], cornerRadii: CGSize(width: cornerRadious, height: cornerRadious))
            let mask = CAShapeLayer()
            mask.path = path.cgPath
            self.layer.mask = mask
        }
    }

}

What is the official name for a credit card's 3 digit code?

You can't find a consistent reference because it seems to go by at least six different names!

  • Card Security Code
  • Card Verification Value (CVV or CV2)
  • Card Verification Value Code (CVVC)
  • Card Verification Code (CVC)
  • Verification Code (V-Code or V Code)
  • Card Code Verification (CCV)

How to make "if not true condition"?

I think it can be simplified into:

grep sysa /etc/passwd || {
    echo "ERROR - The user sysa could not be looked up"
    exit 2
}

or in a single command line

$ grep sysa /etc/passwd || { echo "ERROR - The user sysa could not be looked up"; exit 2; }

How to import spring-config.xml of one project into spring-config.xml of another project?

For some reason, import as suggested by Ricardo didnt work for me. I got it working with following statement:

<import resource="classpath*:/spring-config.xml" />

How do I import an existing Java keystore (.jks) file into a Java installation?

Ok, so here was my process:

keytool -list -v -keystore permanent.jks - got me the alias.

keytool -export -alias alias_name -file certificate_name -keystore permanent.jks - got me the certificate to import.

Then I could import it with the keytool:

keytool -import -alias alias_name -file certificate_name -keystore keystore location

As @Christian Bongiorno says the alias can't already exist in your keystore.

What is VanillaJS?

This word, hence, VanillaJS is a just damn joke that changed my life. I had gone to a German company for an interview, I was very poor in JavaScript and CSS, very poor, so the Interviewer said to me: We're working here with VanillaJs, So you should know this framework.

Definitely, I understood that I'was rejected, but for one week I seek for VanillaJS, After all, I found THIS LINK.

What I am just was because of that joke.

VanillaJS === plain `JavaScript`

Best way to split string into lines

using (StringReader sr = new StringReader(text)) {
    string line;
    while ((line = sr.ReadLine()) != null) {
        // do something
    }
}

How to get data from database in javascript based on the value passed to the function

The error is coming as your query is getting formed as

SELECT * FROM Employ where number = parseInt(val);

I dont know which DB you are using but no DB will understand parseInt.

What you can do is use a variable say temp and store the value of parseInt(val) in temp variable and make the query as

SELECT * FROM Employ where number = temp;

JavaScript closures vs. anonymous functions

Editor's Note: All functions in JavaScript are closures as explained in this post. However we are only interested in identifying a subset of these functions which are interesting from a theoretical point of view. Henceforth any reference to the word closure will refer to this subset of functions unless otherwise stated.

A simple explanation for closures:

  1. Take a function. Let's call it F.
  2. List all the variables of F.
  3. The variables may be of two types:
    1. Local variables (bound variables)
    2. Non-local variables (free variables)
  4. If F has no free variables then it cannot be a closure.
  5. If F has any free variables (which are defined in a parent scope of F) then:
    1. There must be only one parent scope of F to which a free variable is bound.
    2. If F is referenced from outside that parent scope, then it becomes a closure for that free variable.
    3. That free variable is called an upvalue of the closure F.

Now let's use this to figure out who uses closures and who doesn't (for the sake of explanation I have named the functions):

Case 1: Your Friend's Program

for (var i = 0; i < 10; i++) {
    (function f() {
        var i2 = i;
        setTimeout(function g() {
            console.log(i2);
        }, 1000);
    })();
}

In the above program there are two functions: f and g. Let's see if they are closures:

For f:

  1. List the variables:
    1. i2 is a local variable.
    2. i is a free variable.
    3. setTimeout is a free variable.
    4. g is a local variable.
    5. console is a free variable.
  2. Find the parent scope to which each free variable is bound:
    1. i is bound to the global scope.
    2. setTimeout is bound to the global scope.
    3. console is bound to the global scope.
  3. In which scope is the function referenced? The global scope.
    1. Hence i is not closed over by f.
    2. Hence setTimeout is not closed over by f.
    3. Hence console is not closed over by f.

Thus the function f is not a closure.

For g:

  1. List the variables:
    1. console is a free variable.
    2. i2 is a free variable.
  2. Find the parent scope to which each free variable is bound:
    1. console is bound to the global scope.
    2. i2 is bound to the scope of f.
  3. In which scope is the function referenced? The scope of setTimeout.
    1. Hence console is not closed over by g.
    2. Hence i2 is closed over by g.

Thus the function g is a closure for the free variable i2 (which is an upvalue for g) when it's referenced from within setTimeout.

Bad for you: Your friend is using a closure. The inner function is a closure.

Case 2: Your Program

for (var i = 0; i < 10; i++) {
    setTimeout((function f(i2) {
        return function g() {
            console.log(i2);
        };
    })(i), 1000);
}

In the above program there are two functions: f and g. Let's see if they are closures:

For f:

  1. List the variables:
    1. i2 is a local variable.
    2. g is a local variable.
    3. console is a free variable.
  2. Find the parent scope to which each free variable is bound:
    1. console is bound to the global scope.
  3. In which scope is the function referenced? The global scope.
    1. Hence console is not closed over by f.

Thus the function f is not a closure.

For g:

  1. List the variables:
    1. console is a free variable.
    2. i2 is a free variable.
  2. Find the parent scope to which each free variable is bound:
    1. console is bound to the global scope.
    2. i2 is bound to the scope of f.
  3. In which scope is the function referenced? The scope of setTimeout.
    1. Hence console is not closed over by g.
    2. Hence i2 is closed over by g.

Thus the function g is a closure for the free variable i2 (which is an upvalue for g) when it's referenced from within setTimeout.

Good for you: You are using a closure. The inner function is a closure.

So both you and your friend are using closures. Stop arguing. I hope I cleared the concept of closures and how to identify them for the both of you.

Edit: A simple explanation as to why are all functions closures (credits @Peter):

First let's consider the following program (it's the control):

_x000D_
_x000D_
lexicalScope();_x000D_
_x000D_
function lexicalScope() {_x000D_
    var message = "This is the control. You should be able to see this message being alerted.";_x000D_
_x000D_
    regularFunction();_x000D_
_x000D_
    function regularFunction() {_x000D_
        alert(eval("message"));_x000D_
    }_x000D_
}
_x000D_
_x000D_
_x000D_

  1. We know that both lexicalScope and regularFunction aren't closures from the above definition.
  2. When we execute the program we expect message to be alerted because regularFunction is not a closure (i.e. it has access to all the variables in its parent scope - including message).
  3. When we execute the program we observe that message is indeed alerted.

Next let's consider the following program (it's the alternative):

_x000D_
_x000D_
var closureFunction = lexicalScope();_x000D_
_x000D_
closureFunction();_x000D_
_x000D_
function lexicalScope() {_x000D_
    var message = "This is the alternative. If you see this message being alerted then in means that every function in JavaScript is a closure.";_x000D_
_x000D_
    return function closureFunction() {_x000D_
        alert(eval("message"));_x000D_
    };_x000D_
}
_x000D_
_x000D_
_x000D_

  1. We know that only closureFunction is a closure from the above definition.
  2. When we execute the program we expect message not to be alerted because closureFunction is a closure (i.e. it only has access to all its non-local variables at the time the function is created (see this answer) - this does not include message).
  3. When we execute the program we observe that message is actually being alerted.

What do we infer from this?

  1. JavaScript interpreters do not treat closures differently from the way they treat other functions.
  2. Every function carries its scope chain along with it. Closures don't have a separate referencing environment.
  3. A closure is just like every other function. We just call them closures when they are referenced in a scope outside the scope to which they belong because this is an interesting case.

MySQL Delete all rows from table and reset ID to zero

if you want to use truncate use this:

SET FOREIGN_KEY_CHECKS = 0; 
TRUNCATE table $table_name; 
SET FOREIGN_KEY_CHECKS = 1;

SQL to add column and comment in table in single command

No, you can't.

There's no reason why you would need to. This is a one-time operation and so takes only an additional second or two to actually type and execute.

If you're adding columns in your web application this is more indicative of a flaw in your data-model as you shouldn't need to be doing it.


In response to your comment that a comment is a column attribute; it may seem so but behind the scenes Oracle stores this as an attribute of an object.

SQL> desc sys.com$
 Name                                      Null?    Type
 ----------------------------------------- -------- ----------------------------
 OBJ#                                      NOT NULL NUMBER
 COL#                                               NUMBER
 COMMENT$                                           VARCHAR2(4000)

SQL>

The column is optional and sys.col$ does not contain comment information.

I assume, I have no knowledge, that this was done in order to only have one system of dealing with comments rather than multiple.

Position DIV relative to another DIV?

You need to set postion:relative of outer DIV and position:absolute of inner div.
Try this. Here is the Demo

#one
{
    background-color: #EEE;
    margin: 62px 258px;
    padding: 5px;
    width: 200px;
    position: relative;   
}

#two
{
    background-color: #F00;
    display: inline-block;
    height: 30px;
    position: absolute;
    width: 100px;
    top:10px;
}?

Jquery bind double click and single click separately

Same as the above answer but allows for triple click. (Delay 500) http://jsfiddle.net/luenwarneke/rV78Y/1/

    var DELAY = 500,
    clicks = 0,
    timer = null;

$(document).ready(function() {
    $("a")
    .on("click", function(e){
        clicks++;  //count clicks
        timer = setTimeout(function() {
        if(clicks === 1) {
           alert('Single Click'); //perform single-click action
        } else if(clicks === 2) {
           alert('Double Click'); //perform single-click action
        } else if(clicks >= 3) {
           alert('Triple Click'); //perform Triple-click action
        }
         clearTimeout(timer);
         clicks = 0;  //after action performed, reset counter
       }, DELAY);
    })
    .on("dblclick", function(e){
        e.preventDefault();  //cancel system double-click event
    });
});

Best way to encode Degree Celsius symbol into web page?

If you really want to use the DEGREE CELSIUS character “?”, then copy and paste is OK, provided that your document is UTF-8 encoded and declared as such in HTTP headers. Using the character reference &#x2103; would work equally well, and would work independently of character encoding, but the source would be much less readable.

The problem with Blackberry is most probably a font issue. I don’t know about fonts on Blackberry, but the font repertoire might be limited. There’s nothing you can do about this in HTML, but you can use CSS, possibly with @font face.

But there is seldom any reason to use the DEGREE CELSIUS. It is a compatibility character, included in Unicode due to its use in East Asian writing. The Unicode Standard explicitly says in Chapter 15 (section 15.2, page 497):

“In normal use, it is better to represent degrees Celsius “°C” with a sequence of U+00B0 degree sign + U+0043 latin capital letter c, rather than U+2103 degree celsius.”

The degree sign “°” can be entered in many ways, including the entity reference `°, but normally it is best to insert it as a character, via copy and paste or otherwise. On Windows, you can use Alt 0176.

Caveat: Some browsers may treat the degree sign as allowing a line break after it even when no space intervenes, putting “°” and the following “C” on separate lines. There are different ways to prevent this. A simple and effective method is this: <nobr>42 °C</nobr>.

Overcoming "Display forbidden by X-Frame-Options"

I came across this issue when running a wordpress web site. I tried all sorts of things to fix it and wasn't sure how, ultimately the issue was because I was using DNS forwarding with masking, and the links to external sites were not being addressed properly. i.e. my site was hosted at http://123.456.789/index.html but was masked to run at http://somewebSite.com/index.html. When i entered http://123.456.789/index.html in the browser clicking on those same links resulted in no X-frame-origins issues in the JS console, but running http://somewebSite.com/index.html did. In order to properly mask you must add your host's DNS name servers to your domain service, i.e. godaddy.com should have name servers of example, ns1.digitalocean.com, ns2.digitalocean.com, ns3.digitalocean.com, if you were using digitalocean.com as your hosting service.

How do I declare and use variables in PL/SQL like I do in T-SQL?

In Oracle PL/SQL, if you are running a query that may return multiple rows, you need a cursor to iterate over the results. The simplest way is with a for loop, e.g.:

declare
  myname varchar2(20) := 'tom';
begin
  for result_cursor in (select * from mytable where first_name = myname) loop
    dbms_output.put_line(result_cursor.first_name);
    dbms_output.put_line(result_cursor.other_field);
  end loop;
end;

If you have a query that returns exactly one row, then you can use the select...into... syntax, e.g.:

declare 
  myname varchar2(20);
begin
  select first_name into myname 
    from mytable 
    where person_id = 123;
end;

How to recover stashed uncommitted changes

On mac this worked for me:

git stash list(see all your stashs)

git stash list

git stash apply (just the number that you want from your stash list)

like this:

git stash apply 1

What jar should I include to use javax.persistence package in a hibernate based application?

You can use the ejb3-persistence.jar that's bundled with hibernate. This jar only includes the javax.persistence package.

What does the colon (:) operator do?

The colon actually exists in conjunction with ?

int minVal = (a < b) ? a : b;

is equivalent to:

int minval;
if(a < b){ minval = a;} 
else{ minval = b; }

Also in the for each loop:

for(Node n : List l){ ... }

literally:

for(Node n = l.head; n.next != null; n = n.next)

Datatables: Cannot read property 'mData' of undefined

This one drove me crazy - how to render a DataTable successfully in a .NET MVC view. This worked:

 **@model List<Student>
 @{
    ViewData["Title"] = "Index";
}
 <h2>NEW VIEW Index</h2>
 <table id="example" class="display" style="width:100%">
   <thead>
   <tr>
   <th>ID</th>
    <th>Firstname</th>
    <th>Lastname</th> 
  </tr>
  </thead>
  <tbody>
@foreach (var element in Model)
{
    <tr>
    <td>@Html.DisplayFor(m => element.ID)</td>
    <td>@Html.DisplayFor(m => element.FirstName)</td>
    <td>@Html.DisplayFor(m => element.LastName)</td>
    </tr>

}
</tbody>
</table>**

Script in JS file:

**$(document).ready(function () {
    $('#example').DataTable();
});**

best way to preserve numpy arrays on disk

Another possibility to store numpy arrays efficiently is Bloscpack:

#!/usr/bin/python
import numpy as np
import bloscpack as bp
import time

n = 10000000

a = np.arange(n)
b = np.arange(n) * 10
c = np.arange(n) * -0.5
tsizeMB = sum(i.size*i.itemsize for i in (a,b,c)) / 2**20.

blosc_args = bp.DEFAULT_BLOSC_ARGS
blosc_args['clevel'] = 6
t = time.time()
bp.pack_ndarray_file(a, 'a.blp', blosc_args=blosc_args)
bp.pack_ndarray_file(b, 'b.blp', blosc_args=blosc_args)
bp.pack_ndarray_file(c, 'c.blp', blosc_args=blosc_args)
t1 = time.time() - t
print "store time = %.2f (%.2f MB/s)" % (t1, tsizeMB / t1)

t = time.time()
a1 = bp.unpack_ndarray_file('a.blp')
b1 = bp.unpack_ndarray_file('b.blp')
c1 = bp.unpack_ndarray_file('c.blp')
t1 = time.time() - t
print "loading time = %.2f (%.2f MB/s)" % (t1, tsizeMB / t1)

and the output for my laptop (a relatively old MacBook Air with a Core2 processor):

$ python store-blpk.py
store time = 0.19 (1216.45 MB/s)
loading time = 0.25 (898.08 MB/s)

that means that it can store really fast, i.e. the bottleneck is typically the disk. However, as the compression ratios are pretty good here, the effective speed is multiplied by the compression ratios. Here are the sizes for these 76 MB arrays:

$ ll -h *.blp
-rw-r--r--  1 faltet  staff   921K Mar  6 13:50 a.blp
-rw-r--r--  1 faltet  staff   2.2M Mar  6 13:50 b.blp
-rw-r--r--  1 faltet  staff   1.4M Mar  6 13:50 c.blp

Please note that the use of the Blosc compressor is fundamental for achieving this. The same script but using 'clevel' = 0 (i.e. disabling compression):

$ python bench/store-blpk.py
store time = 3.36 (68.04 MB/s)
loading time = 2.61 (87.80 MB/s)

is clearly bottlenecked by the disk performance.

Combining multiple commits before pushing in Git

You can squash (join) commits with an Interactive Rebase. There is a pretty nice YouTube video which shows how to do this on the command line or with SmartGit:

If you are already a SmartGit user then you can select all your outgoing commits (by holding down the Ctrl key) and open the context menu (right click) to squash your commits.

It's very comfortable:

enter image description here

There is also a very nice tutorial from Atlassian which shows how it works:

Running Java Program from Command Line Linux

(This is the KISS answer.)

Let's say you have several .java files in the current directory:

$ ls -1 *.java
javaFileName1.java
javaFileName2.java

Let's say each of them have a main() method (so they are programs, not libs), then to compile them do:

javac *.java -d .

This will generate as many subfolders as "packages" the .java files are associated to. In my case all java files where inside under the same package name packageName, so only one folder was generated with that name, so to execute each of them:

java -cp . packageName.javaFileName1
java -cp . packageName.javaFileName2

Get width height of remote image from url

The w and h variables in img.onload function are not in the same scope with those in the getMeta() function. One way to do it, is as follows:

Fiddle: http://jsfiddle.net/ppanagi/28UES/2/

function getMeta(varA, varB) {
    if (typeof varB !== 'undefined') {
       alert(varA + ' width ' + varB + ' height');
    } else {
       var img = new Image();
       img.src = varA;
       img.onload = getMeta(this.width, this.height);
    }
}


getMeta("http://snook.ca/files/mootools_83_snookca.png");

JSON encode MySQL results

$rows = json_decode($mysql_result,true);

as simple as that :-)

AutoComplete TextBox Control

Check out the AutoCompleteSource, AutoCompleteCustomSource and AutoCompleteMode properties.

textBox1.AutoCompleteMode = AutoCompleteMode.Suggest;
textBox1.AutoCompleteSource = AutoCompleteSource.CustomSource;
AutoCompleteStringCollection col = new AutoCompleteStringCollection();
col.Add("Foo");
col.Add("Bar");
textBox1.AutoCompleteCustomSource = col;

Note that the designer allows you to do that without writing any code...

I can't delete a remote master branch on git

The quickest way is to switch default branch from master to another and you can remove master branch from the web interface.

Animate element to auto height with jQuery

A better solution would not rely on JS to set the height of your element. The following is a solution that animates a fixed height element to full ("auto") height:

var $selector = $('div');
    $selector
        .data('oHeight',$selector.height())
        .css('height','auto')
        .data('nHeight',$selector.height())
        .height($selector.data('oHeight'))
        .animate({height: $selector.data('nHeight')},400);

https://gist.github.com/2023150

Android Webview - Webpage should fit the device screen

For reference, this is a Kotlin implementation of @danh32's solution:

private fun getWebviewScale (contentWidth : Int) : Int {
    val dm = DisplayMetrics()
    windowManager.defaultDisplay.getRealMetrics(dm)
    val pixWidth = dm.widthPixels;
    return (pixWidth.toFloat()/contentWidth.toFloat() * 100F)
             .toInt()
}

In my case, width was determined by three images to be 300 pix so:

webview.setInitialScale(getWebviewScale(300))

It took me hours to find this post. Thanks!

How to completely uninstall Visual Studio 2010?

Struggled with the same problem: Many applications, BUT make at least this part "pleasant": The trick is called Batch-Uninstall. So use one of these three programs i can recommend:

  • Absolute Uninstaller (+ slim,removes registry and folders, - click OK 50 times)
  • IObit Uninstaller (+ also for toolbars, removes registry and folders, - ships itself with optional toolbar)
  • dUninstaller (+ silent mode/force: no clicking for 50 applications, it does it in the background - doesn't scan registry/files)

Take no.2 in imho, 1 is nice but sometimes encounters some bugs :-)

Scheduling Python Script to run every hour accurately

The Python standard library does provide sched and threading for this task. But this means your scheduler script will have be running all the time instead of leaving its execution to the OS, which may or may not be what you want.

How to set default values in Go structs

There is a way of doing this with tags, which allows for multiple defaults.

Assume you have the following struct, with 2 default tags default0 and default1.

type A struct {
   I int    `default0:"3" default1:"42"`
   S string `default0:"Some String..." default1:"Some Other String..."`
}

Now it's possible to Set the defaults.

func main() {

ptr := &A{}

Set(ptr, "default0")
fmt.Printf("ptr.I=%d ptr.S=%s\n", ptr.I, ptr.S)
// ptr.I=3 ptr.S=Some String...

Set(ptr, "default1")
fmt.Printf("ptr.I=%d ptr.S=%s\n", ptr.I, ptr.S)
// ptr.I=42 ptr.S=Some Other String...
}

Here's the complete program in a playground.

If you're interested in a more complex example, say with slices and maps, then, take a look at creasty/defaultse

Why do I get TypeError: can't multiply sequence by non-int of type 'float'?

raw_input returns a string (a sequence of characters). In Python, multiplying a string and a float makes no defined meaning (while multiplying a string and an integer has a meaning: "AB" * 3 is "ABABAB"; how much is "L" * 3.14 ? Please do not reply "LLL|"). You need to parse the string to a numerical value.

You might want to try:

salesAmount = float(raw_input("Insert sale amount here\n"))

how to set radio button checked in edit mode in MVC razor view

To set radio button checked in edit mode in MVC razor view, please trying as follow:

<div class="col-lg-11 col-md-11">
     @Html.RadioButtonFor(m => m.Role, "1", Model.Role == 1 ? "checked" : string.Empty) 
     <span>Admin</span>
     @Html.RadioButtonFor(m => m.Role, "0", Model.Role == 0 ? "checked" : string.Empty)
     <span>User</span>
     @Html.HiddenFor(m => m.Role)
</div>

Hope it help!

How can I do width = 100% - 100px in CSS?

CSS can not be used to animation, or any style modification on events.

The only way is to use a javascript function, which will return the width of a given element, then, subtract 100px to it, and set the new width size.

Assuming you are using jQuery, you could do something like that:

oldWidth = $('#yourElem').width();
$('#yourElem').width(oldWidth-100);

And with native javascript:

oldWidth = document.getElementById('yourElem').clientWidth;
document.getElementById('yourElem').style.width = oldWidth-100+'px';

We assume that you have a css style set with 100%;

Xcode 4: create IPA file instead of .xcarchive

I had this same problem, using an old version of the route-me library. I "skipped" all the libraries, and the libraries inside of libraries (proj4), but I still had the same problem. Turns out that route-me and proj4 were installing public header files, even when the libraries were being skipped, which was messing it up in the same way! So I just went into the route-me and proj4 targets "Build Phases" tab, opened "Copy Headers", opened "Public", and dragged those headers from "Public" into "Project". Now they don't get installed in $(BUILD)/usr/local/include, and I'm able to make an ipa file from the archive!

I hope Apple fixes this horrible usability problem with XCode. It gives absolutely no indication of what's wrong, it just doesn't work. I hate dimmed out controls that don't tell you anything about why they're dimmed out. How about instead of ignoring clicks, the disabled controls could pop up a message telling you why the hell they're disabled when you click on them in frustration?

How do I compile the asm generated by GCC?

You can use GAS, which is gcc's backend assembler:

http://linux.die.net/man/1/as

How can I convert a dictionary into a list of tuples?

Create a list of namedtuples

It can often be very handy to use namedtuple. For example, you have a dictionary of 'name' as keys and 'score' as values like:

d = {'John':5, 'Alex':10, 'Richard': 7}

You can list the items as tuples, sorted if you like, and get the name and score of, let's say the player with the highest score (index=0) very Pythonically like this:

>>> player = best[0]

>>> player.name
        'Alex'
>>> player.score
         10

How to do this:

list in random order or keeping order of collections.OrderedDict:

import collections
Player = collections.namedtuple('Player', 'name score')
players = list(Player(*item) for item in d.items())

in order, sorted by value ('score'):

import collections
Player = collections.namedtuple('Player', 'score name')

sorted with lowest score first:

worst = sorted(Player(v,k) for (k,v) in d.items())

sorted with highest score first:

best = sorted([Player(v,k) for (k,v) in d.items()], reverse=True)

How to write a shell script that runs some commands as superuser and some commands not as superuser, without having to babysit it?

You should run your entire script as superuser. If you want to run some command as non-superuser, use "-u" option of sudo:

#!/bin/bash

sudo -u username command1
command2
sudo -u username command3
command4

When running as root, sudo doesn't ask for a password.

Git and nasty "error: cannot lock existing info/refs fatal"

Update:

You might need to edit your ~/.netrc file:

https://bugs.launchpad.net/ubuntu/+source/git-core/+bug/293553

Original answer:

Why did you disable ssl? I think this might have to do with you not being able to push via https. I'd set it back and try to push again:

git config –global http.sslVerify true

Create array of regex matches

Here's a simple example:

Pattern pattern = Pattern.compile(regexPattern);
List<String> list = new ArrayList<String>();
Matcher m = pattern.matcher(input);
while (m.find()) {
    list.add(m.group());
}

(if you have more capturing groups, you can refer to them by their index as an argument of the group method. If you need an array, then use list.toArray())

What's the difference between interface and @interface in java?

interface in the Java programming language is an abstract type that is used to specify a behavior that classes must implement. They are similar to protocols. Interfaces are declared using the interface keyword

@interface is used to create your own (custom) Java annotations. Annotations are defined in their own file, just like a Java class or interface. Here is custom Java annotation example:

@interface MyAnnotation {

    String   value();

    String   name();
    int      age();
    String[] newNames();

}

This example defines an annotation called MyAnnotation which has four elements. Notice the @interface keyword. This signals to the Java compiler that this is a Java annotation definition.

Notice that each element is defined similarly to a method definition in an interface. It has a data type and a name. You can use all primitive data types as element data types. You can also use arrays as data type. You cannot use complex objects as data type.

To use the above annotation, you could use code like this:

@MyAnnotation(
    value="123",
    name="Jakob",
    age=37,
    newNames={"Jenkov", "Peterson"}
)
public class MyClass {


}

Reference - http://tutorials.jenkov.com/java/annotations.html

python-How to set global variables in Flask?

With:

global index_add_counter

You are not defining, just declaring so it's like saying there is a global index_add_counter variable elsewhere, and not create a global called index_add_counter. As you name don't exists, Python is telling you it can not import that name. So you need to simply remove the global keyword and initialize your variable:

index_add_counter = 0

Now you can import it with:

from app import index_add_counter

The construction:

global index_add_counter

is used inside modules' definitions to force the interpreter to look for that name in the modules' scope, not in the definition one:

index_add_counter = 0
def test():
  global index_add_counter # means: in this scope, use the global name
  print(index_add_counter)

java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/dbname

An example of retrieving data from a table having columns column1, column2 ,column3 column4, cloumn1 and 2 hold int values and column 3 and 4 hold varchar(10)

import java.sql.*; 
// need to import this as the STEP 1. Has the classes that you mentioned  
public class JDBCexample {
    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; 
    static final String DB_URL = "jdbc:mysql://LocalHost:3306/databaseNameHere"; 
    // DON'T PUT ANY SPACES IN BETWEEN and give the name of the database (case insensitive) 

    // database credentials
    static final String USER = "root";
    // usually when you install MySQL, it logs in as root 
    static final String PASS = "";
    // and the default password is blank

    public static void main(String[] args) {
        Connection conn = null;
        Statement stmt = null;

        try {
    // registering the driver__STEP 2
            Class.forName("com.mysql.jdbc.Driver"); 
    // returns a Class object of com.mysql.jdbc.Driver
    // (forName(""); initializes the class passed to it as String) i.e initializing the
    // "suitable" driver
            System.out.println("connecting to the database");
    // opening a connection__STEP 3
            conn = DriverManager.getConnection(DB_URL, USER, PASS);
    // executing a query__STEP 4 
            System.out.println("creating a statement..");
            stmt = conn.createStatement();
    // creating an object to create statements in SQL
            String sql;
            sql = "SELECT column1, cloumn2, column3, column4 from jdbcTest;";
    // this is what you would have typed in CLI for MySQL
            ResultSet rs = stmt.executeQuery(sql);
    // executing the query__STEP 5 (and retrieving the results in an object of ResultSet)
    // extracting data from result set
            while(rs.next()){
    // retrieve by column name
                int value1 = rs.getInt("column1");
                int value2 = rs.getInt("column2");
                String value3 = rs.getString("column3");
                String value4 = rs.getString("columnm4");
    // displaying values:
                System.out.println("column1 "+ value1);
                System.out.println("column2 "+ value2);
                System.out.println("column3 "+ value3);
                System.out.println("column4 "+ value4);

            }
    // cleaning up__STEP 6
            rs.close();
            stmt.close();
            conn.close();
        } catch (SQLException e) {
    //  handle sql exception
            e.printStackTrace();
        }catch (Exception e) {
    // TODO: handle exception for class.forName
            e.printStackTrace();
        }finally{  
    //closing the resources..STEP 7
            try {
                if (stmt != null)
                    stmt.close();
            } catch (SQLException e2) {
                e2.printStackTrace();
            }try {
                if (conn != null) {
                    conn.close();
                }
            } catch (SQLException e2) {
                e2.printStackTrace();
            }
        }
        System.out.println("good bye");
    }
}

Centering floating divs within another div

First, remove the float attribute on the inner divs. Then, put text-align: center on the main outer div. And for the inner divs, use display: inline-block. Might also be wise to give them explicit widths too.


<div style="margin: auto 1.5em; display: inline-block;">
  <img title="Nadia Bjorlin" alt="Nadia Bjorlin" src="headshot.nadia.png"/>
  <br/>
  Nadia Bjorlin
</div>

How to properly validate input values with React.JS?

Your jsfiddle does not work anymore. I've fixed it: http://jsfiddle.net/tkrotoff/bgC6E/40/ using React 16 and ES6 classes.

class Adaptive_Input extends React.Component {
  handle_change(e) {
    var new_text = e.currentTarget.value;
    this.props.on_Input_Change(new_text);
  }

  render() {
    return (
      <div className="adaptive_placeholder_input_container">
        <input
          className="adaptive_input"
          type="text"
          required="required"
          onChange={this.handle_change.bind(this)} />
        <label
          className="adaptive_placeholder"
          alt={this.props.initial}
          placeholder={this.props.focused} />
      </div>
    );
  }
}

class Form extends React.Component {
  render() {
    return (
      <form>
        <Adaptive_Input
          initial={'Name Input'}
          focused={'Name Input'}
          on_Input_Change={this.props.handle_text_input} />

        <Adaptive_Input
          initial={'Value 1'}
          focused={'Value 1'}
          on_Input_Change={this.props.handle_value_1_input} />

        <Adaptive_Input
          initial={'Value 2'}
          focused={'Value 2'}
          on_Input_Change={this.props.handle_value_2_input} />
      </form>
    );
  }
}

class Page extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      Name: 'No Name',
      Value_1: '0',
      Value_2: '0',
      Display_Value: '0'
    };
  }

  handle_text_input(new_text) {
    this.setState({
      Name: new_text
    });
  }

  handle_value_1_input(new_value) {
    new_value = parseInt(new_value);
    var updated_display = new_value + parseInt(this.state.Value_2);
    updated_display = updated_display.toString();
    this.setState({
      Value_1: new_value,
      Display_Value: updated_display
    });
  }

  handle_value_2_input(new_value) {
    new_value = parseInt(new_value);
    var updated_display = parseInt(this.state.Value_1) + new_value;
    updated_display = updated_display.toString();
    this.setState({
      Value_2: new_value,
      Display_Value: updated_display
    });
  }

  render() {
    return(
      <div>
        <h2>{this.state.Name}</h2>
        <h2>Value 1 + Value 2 = {this.state.Display_Value}</h2>
        <Form
          handle_text_input={this.handle_text_input.bind(this)}
          handle_value_1_input={this.handle_value_1_input.bind(this)}
          handle_value_2_input={this.handle_value_2_input.bind(this)}
        />
      </div>
    );
  }
}

ReactDOM.render(<Page />, document.getElementById('app'));

And now the same code hacked with form validation thanks to this library: https://github.com/tkrotoff/react-form-with-constraints => http://jsfiddle.net/tkrotoff/k4qa4heg/

http://jsfiddle.net/tkrotoff/k4qa4heg/

const { FormWithConstraints, FieldFeedbacks, FieldFeedback } = ReactFormWithConstraints;

class Adaptive_Input extends React.Component {
  static contextTypes = {
    form: PropTypes.object.isRequired
  };

  constructor(props) {
    super(props);

    this.state = {
      field: undefined
    };

    this.fieldWillValidate = this.fieldWillValidate.bind(this);
    this.fieldDidValidate = this.fieldDidValidate.bind(this);
  }

  componentWillMount() {
    this.context.form.addFieldWillValidateEventListener(this.fieldWillValidate);
    this.context.form.addFieldDidValidateEventListener(this.fieldDidValidate);
  }

  componentWillUnmount() {
    this.context.form.removeFieldWillValidateEventListener(this.fieldWillValidate);
    this.context.form.removeFieldDidValidateEventListener(this.fieldDidValidate);
  }

  fieldWillValidate(fieldName) {
    if (fieldName === this.props.name) this.setState({field: undefined});
  }

  fieldDidValidate(field) {
    if (field.name === this.props.name) this.setState({field});
  }

  handle_change(e) {
    var new_text = e.currentTarget.value;
    this.props.on_Input_Change(e, new_text);
  }

  render() {
    const { field } = this.state;
    let className = 'adaptive_placeholder_input_container';
    if (field !== undefined) {
      if (field.hasErrors()) className += ' error';
      if (field.hasWarnings()) className += ' warning';
    }

    return (
      <div className={className}>
        <input
          type={this.props.type}
          name={this.props.name}
          className="adaptive_input"
          required
          onChange={this.handle_change.bind(this)} />
        <label
          className="adaptive_placeholder"
          alt={this.props.initial}
          placeholder={this.props.focused} />
      </div>
    );
  }
}

class Form extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      Name: 'No Name',
      Value_1: '0',
      Value_2: '0',
      Display_Value: '0'
    };
  }

  handle_text_input(e, new_text) {
    this.form.validateFields(e.currentTarget);

    this.setState({
      Name: new_text
    });
  }

  handle_value_1_input(e, new_value) {
    this.form.validateFields(e.currentTarget);

    if (this.form.isValid()) {
      new_value = parseInt(new_value);
      var updated_display = new_value + parseInt(this.state.Value_2);
      updated_display = updated_display.toString();
      this.setState({
        Value_1: new_value,
        Display_Value: updated_display
      });
    }
    else {
      this.setState({
        Display_Value: 'Error'
      });
    }
  }

  handle_value_2_input(e, new_value) {
    this.form.validateFields(e.currentTarget);

    if (this.form.isValid()) {
      new_value = parseInt(new_value);
      var updated_display = parseInt(this.state.Value_1) + new_value;
      updated_display = updated_display.toString();
      this.setState({
        Value_2: new_value,
        Display_Value: updated_display
      });
    }
    else {
      this.setState({
        Display_Value: 'Error'
      });
    }
  }

  render() {
    return(
      <div>
        <h2>Name: {this.state.Name}</h2>
        <h2>Value 1 + Value 2 = {this.state.Display_Value}</h2>

        <FormWithConstraints ref={form => this.form = form} noValidate>
          <Adaptive_Input
            type="text"
            name="name_input"
            initial={'Name Input'}
            focused={'Name Input'}
            on_Input_Change={this.handle_text_input.bind(this)} />
          <FieldFeedbacks for="name_input">
            <FieldFeedback when="*" error />
            <FieldFeedback when={value => !/^\w+$/.test(value)} warning>Should only contain alphanumeric characters</FieldFeedback>
          </FieldFeedbacks>

          <Adaptive_Input
            type="number"
            name="value_1_input"
            initial={'Value 1'}
            focused={'Value 1'}
            on_Input_Change={this.handle_value_1_input.bind(this)} />
          <FieldFeedbacks for="value_1_input">
            <FieldFeedback when="*" />
          </FieldFeedbacks>

          <Adaptive_Input
            type="number"
            name="value_2_input"
            initial={'Value 2'}
            focused={'Value 2'}
            on_Input_Change={this.handle_value_2_input.bind(this)} />
          <FieldFeedbacks for="value_2_input">
            <FieldFeedback when="*" />
          </FieldFeedbacks>
        </FormWithConstraints>
      </div>
    );
  }
}

ReactDOM.render(<Form />, document.getElementById('app'));

The proposed solution here is hackish as I've tried to keep it close to the original jsfiddle. For proper form validation with react-form-with-constraints, check https://github.com/tkrotoff/react-form-with-constraints#examples