Programs & Examples On #Jetty

Eclipse Jetty is a widely-used async Java-based HTTP server and servlet engine supporting HTTP/1.0, HTTP/1.1, HTTP/2, and WebSocket protocols.

Is there a way to pass jvm args via command line to maven?

I think MAVEN_OPTS would be most appropriate for you. See here: http://maven.apache.org/configure.html

In Unix:

Add the MAVEN_OPTS environment variable to specify JVM properties, e.g. export MAVEN_OPTS="-Xms256m -Xmx512m". This environment variable can be used to supply extra options to Maven.

In Win, you need to set environment variable via the dialogue box

Add ... environment variable by opening up the system properties (WinKey + Pause),... In the same dialog, add the MAVEN_OPTS environment variable in the user variables to specify JVM properties, e.g. the value -Xms256m -Xmx512m. This environment variable can be used to supply extra options to Maven.

Jetty: HTTP ERROR: 503/ Service Unavailable

2012-04-20 11:14:32.617:WARN:oejx.XmlParser:FATAL@file:/C:/Users/***/workspace/Test/WEB-INF/web.xml line:1 col:7 : org.xml.sax.SAXParseException: The processing instruction target matching "[xX][mM][lL]" is not allowed.

You Log says, that you web.xml is malformed. Line 1, colum 7. It may be a UTF-8 Byte-Order-Marker

Try to verify, that your xml is wellformed and does not have a BOM. Java doesn't use BOMs.

websocket closing connection automatically

In answer to your third question: your client wants to be able to cope with temporary network problems anyway, e.g. let's say the user closes their laptop between meetings which hibernates it, or the network simply goes down temporarily.

The solution is to listen to onclose events on the web socket client and when they occur, set a client side timeout to re-open the connection, say in a second:

function setupWebSocket(){
    this.ws = new WebSocket('wss://host:port/path');
    this.ws.onerror = ...;
    this.ws.onopen = ...;
    this.ws.onmessage = ...;
    this.ws.onclose = function(){
        setTimeout(setupWebSocket, 1000);
    };
}

java.io.IOException: Broken pipe

I agree with @arcy, the problem is on client side, on my case it was because of nginx, let me elaborate I am using nginx as the frontend (so I can distribute load, ssl, etc ...) and using proxy_pass http://127.0.0.1:8080 to forward the appropiate requests to tomcat.

There is a default value for the nginx variable proxy_read_timeout of 60s that should be enough, but on some peak moments my setup would error with the java.io.IOException: Broken pipe changing the value will help until the root cause (60s should be enough) can be fixed.

NOTE: I made a new answer so I could expand a bit more with my case (it was the only mention I found about this error on internet after looking quite a lot)

How to check heap usage of a running JVM from the command line?

If you start execution with gc logging turned on you get the info on file. Otherwise 'jmap -heap ' will give you what you want. See the jmap doc page for more.

Please note that jmap should not be used in a production environment unless absolutely needed as the tool halts the application to be able to determine actual heap usage. Usually this is not desired in a production environment.

IOException: Too many open files

Don't know the nature of your app, but I have seen this error manifested multiple times because of a connection pool leak, so that would be worth checking out. On Linux, socket connections consume file descriptors as well as file system files. Just a thought.

How to use JQuery with ReactJS

You should try and avoid jQuery in ReactJS. But if you really want to use it, you'd put it in componentDidMount() lifecycle function of the component.

e.g.

class App extends React.Component {
  componentDidMount() {
    // Jquery here $(...)...
  }

  // ...
}

Ideally, you'd want to create a reusable Accordion component. For this you could use Jquery, or just use plain javascript + CSS.

class Accordion extends React.Component {
  constructor() {
    super();
    this._handleClick = this._handleClick.bind(this);
  }

  componentDidMount() {
    this._handleClick();
  }

  _handleClick() {
    const acc = this._acc.children;
    for (let i = 0; i < acc.length; i++) {
      let a = acc[i];
      a.onclick = () => a.classList.toggle("active");
    }
  }

  render() {
    return (
      <div 
        ref={a => this._acc = a} 
        onClick={this._handleClick}>
        {this.props.children}
      </div>
    )
  }
}

Then you can use it in any component like so:

class App extends React.Component {
  render() {
    return (
      <div>
        <Accordion>
          <div className="accor">
            <div className="head">Head 1</div>
            <div className="body"></div>
          </div>
        </Accordion>
      </div>
    );
  }
}

Codepen link here: https://codepen.io/jzmmm/pen/JKLwEA?editors=0110 (I changed this link to https ^)

Is it possible to center text in select box?

You have to put the CSS rule into the select class.

Use CSS text-indent

Example

<select class="day"> /* option 1 option 2 option 3 option 4 option 5 here */ </select>

CSS code

select { text-indent: 5px; }

Generating Fibonacci Sequence

My 2 cents:

_x000D_
_x000D_
function fibonacci(num) {_x000D_
  return Array.apply(null, Array(num)).reduce(function(acc, curr, idx) {_x000D_
    return idx > 2 ? acc.concat(acc[idx-1] + acc[idx-2]) : acc;_x000D_
  }, [0, 1, 1]);_x000D_
}_x000D_
_x000D_
console.log(fibonacci(10));
_x000D_
_x000D_
_x000D_

Pandas sort by group aggregate and column

Here's a more concise approach...

df['a_bsum'] = df.groupby('A')['B'].transform(sum)
df.sort(['a_bsum','C'], ascending=[True, False]).drop('a_bsum', axis=1)

The first line adds a column to the data frame with the groupwise sum. The second line performs the sort and then removes the extra column.

Result:

    A       B           C
5   baz     -2.301539   True
2   baz     -0.528172   False
1   bar     -0.611756   True
4   bar      0.865408   False
3   foo     -1.072969   True
0   foo      1.624345   False

NOTE: sort is deprecated, use sort_values instead

ActionBarCompat: java.lang.IllegalStateException: You need to use a Theme.AppCompat

Check and make sure that you do not have another values folder that references theme.styled and does not use AppCompat theme

ie values-v11 folder

Open an image using URI in Android's default gallery image viewer

I use this it works for me

Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,
"Select Picture"), 1);

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

I usually add separate safe pipe reusable component as following

# Add Safe Pipe

import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';

@Pipe({name: 'mySafe'})
export class SafePipe implements PipeTransform {
    constructor(private sanitizer: DomSanitizer) {
    }

    public transform(url) {
        return this.sanitizer.bypassSecurityTrustResourceUrl(url);
    }
}
# then create shared pipe module as following 

import { NgModule } from '@angular/core'; 
import { SafePipe } from './safe.pipe';
@NgModule({
    declarations: [
        SafePipe
    ],
    exports: [
        SafePipe
    ]
})
export class SharedPipesModule {
}
# import shared pipe module in your native module

@NgModule({
    declarations: [],
    imports: [
        SharedPipesModule,
    ],
})
export class SupportModule {
}
<!-------------------
call your url (`trustedUrl` for me) and add `mySafe` as defined in Safe Pipe
---------------->
<div class="container-fluid" *ngIf="trustedUrl">
    <iframe [src]="trustedUrl | mySafe" align="middle" width="100%" height="800" frameborder="0"></iframe>
</div>

How do you Hover in ReactJS? - onMouseLeave not registered during fast hover over

you can use onMouseOver={this.onToggleOpen} and onMouseOut={this.onToggleOpen} to muse over and out on component

How to loop through array in jQuery?

Option 1 : The traditional for-loop

The basics

A traditional for-loop has three components :

  1. the initialization : executed before the look block is executed the first time
  2. the condition : checks a condition every time before the loop block is executed, and quits the loop if false
  3. the afterthought : performed every time after the loop block is executed

These three components are seperated from each other by a ; symbol. Content for each of these three components is optional, which means that the following is the most minimal for-loop possible :

for (;;) {
    // Do stuff
}

Of course, you will need to include an if(condition === true) { break; } or an if(condition === true) { return; } somewhere inside that for-loop to get it to stop running.

Usually, though, the initialization is used to declare an index, the condition is used to compare that index with a minimum or maximum value, and the afterthought is used to increment the index :

for (var i = 0, length = 10; i < length; i++) {
    console.log(i);
}

Using a tradtional for-loop to loop through an array

The traditional way to loop through an array, is this :

for (var i = 0, length = myArray.length; i < length; i++) {
    console.log(myArray[i]);
}

Or, if you prefer to loop backwards, you do this :

for (var i = myArray.length - 1; i > -1; i--) {
    console.log(myArray[i]);
}

There are, however, many variations possible, like eg. this one :

for (var key = 0, value = myArray[key], var length = myArray.length; key < length; value = myArray[++key]) {
    console.log(value);
}

... or this one ...

var i = 0, length = myArray.length;
for (; i < length;) {
    console.log(myArray[i]);
    i++;
}

... or this one :

var key = 0, value;
for (; value = myArray[key++];){ 
    console.log(value);
}

Whichever works best is largely a matter of both personal taste and the specific use case you're implementing.

Note :

Each of these variations is supported by all browsers, including véry old ones!


Option 2 : The while-loop

One alternative to a for-loop is a while-loop. To loop through an array, you could do this :

var key = 0;
while(value = myArray[key++]){
    console.log(value);
}
Note :

Like traditional for-loops, while-loops are supported by even the oldest of browsers.

Also, every while loop can be rewritten as a for-loop. For example, the while-loop hereabove behaves the exact same way as this for-loop :

for(var key = 0;value = myArray[key++];){
    console.log(value);
}

Option 3 : for...in and for...of

In JavaScript, you can also do this :

for (i in myArray) {
    console.log(myArray[i]);
}

This should be used with care, however, as it doesn't behave the same as a traditonal for-loop in all cases, and there are potential side-effects that need to be considered. See Why is using "for...in" with array iteration a bad idea? for more details.

As an alternative to for...in, there's now also for for...of. The following example shows the difference between a for...of loop and a for...in loop :

var myArray = [3, 5, 7];
myArray.foo = "hello";

for (var i in myArray) {
  console.log(i); // logs 0, 1, 2, "foo"
}

for (var i of myArray) {
  console.log(i); // logs 3, 5, 7
}
Note :

You also need to consider that no version of Internet Explorer supports for...of (Edge 12+ does) and that for...in requires at least IE10.


Option 4 : Array.prototype.forEach()

An alternative to For-loops is Array.prototype.forEach(), which uses the following syntax :

myArray.forEach(function(value, key, myArray) {
    console.log(value);
});
Note :

Array.prototype.forEach() is supported by all modern browsers, as well as IE9+.


Option 5 : jQuery.each()

Additionally to the four other options mentioned, jQuery also had its own foreach variation.

It uses the following syntax :

$.each(myArray, function(key, value) {
    console.log(value);
});

Clear History and Reload Page on Login/Logout Using Ionic Framework

I tried many methods, but found this method is absolutely correct:

$window.location.reload();

Hope this help others stuck for days like me with version: angular 1.5.5, ionic 1.2.4, angular-ui-router 1.0.0

Group By Multiple Columns

var Results= query.GroupBy(f => new { /* add members here */  });

'innerText' works in IE, but not in Firefox

jQuery provides a .text() method that can be used in any browser. For example:

$('#myElement').text("Foo");

PHP 5.4 Call-time pass-by-reference - Easy fix available?

PHP and references are somewhat unintuitive. If used appropriately references in the right places can provide large performance improvements or avoid very ugly workarounds and unusual code.

The following will produce an error:

 function f(&$v){$v = true;}
 f(&$v);

 function f($v){$v = true;}
 f(&$v);

None of these have to fail as they could follow the rules below but have no doubt been removed or disabled to prevent a lot of legacy confusion.

If they did work, both involve a redundant conversion to reference and the second also involves a redundant conversion back to a scoped contained variable.

The second one used to be possible allowing a reference to be passed to code that wasn't intended to work with references. This is extremely ugly for maintainability.

This will do nothing:

 function f($v){$v = true;}
 $r = &$v;
 f($r);

More specifically, it turns the reference back into a normal variable as you have not asked for a reference.

This will work:

 function f(&$v){$v = true;}
 f($v);

This sees that you are passing a non-reference but want a reference so turns it into a reference.

What this means is that you can't pass a reference to a function where a reference is not explicitly asked for making it one of the few areas where PHP is strict on passing types or in this case more of a meta type.

If you need more dynamic behaviour this will work:

 function f(&$v){$v = true;}
 $v = array(false,false,false);
 $r = &$v[1];
 f($r);

Here it sees that you want a reference and already have a reference so leaves it alone. It may also chain the reference but I doubt this.

How can I clear the input text after clicking

Update: I took your saying "click" literally, which was a bit dumb of me. You can substitute focus for click in all of the below if you also want the action to happen when the user tabs to the input, which seems likely.

Update 2: My guess is that you're looking to do placeholders; see note and example at the end.


Original answer:

You can do this:

$("selector_for_the_input").click(function() {
    this.value = '';
});

...but that will clear the text regardless of what it is. If you only want to clear it if it's a specific value:

$("selector_for_the_input").click(function() {
    if (this.value === "TEXT") {
        this.value = '';
    }
});

So for example, if the input has an id, you could do:

$("#theId").click(function() {
    if (this.value === "TEXT") {
        this.value = '';
    }
});

Or if it's in a form with an id (say, "myForm") and you want to do this for every form field:

$("#myForm input").click(function() {
    if (this.value === "TEXT") {
        this.value = '';
    }
});

You may also be able to do it with delegation:

$("#myForm").delegate("input", "click", function() {
    if (this.value === "TEXT") {
        this.value = '';
    }
});

That uses delegate to hook up a handler on the form but apply it to the inputs on the form, rather than hooking up a handler to each individual input.


If you're trying to do placeholders, there's more to it than that and you may want to find a good plug-in to do it. But here's the basics:

HTML:

<form id='theForm'>
  <label>Field 1:
    <input type='text' value='provide a value for field 1'>
  </label>
  <br><label>Field 2:
    <input type='text' value='provide a value for field 2'>
  </label>
  <br><label>Field 3:
    <input type='text' value='provide a value for field 3'>
  </label>
</form>

JavaScript using jQuery:

jQuery(function($) {

  // Save the initial values of the inputs as placeholder text
  $('#theForm input').attr("data-placeholdertext", function() {
    return this.value;
  });

  // Hook up a handler to delete the placeholder text on focus,
  // and put it back on blur
  $('#theForm')
    .delegate('input', 'focus', function() {
      if (this.value === $(this).attr("data-placeholdertext")) {
        this.value = '';
      }
    })
    .delegate('input', 'blur', function() {
      if (this.value.length == 0) {
        this.value = $(this).attr("data-placeholdertext");
      }
    });

});

Live copy

Of course, you can also use the new placeholder attribute from HTML5 and only do the above if your code is running on a browser that doesn't support it, in which case you want to invert the logic I used above:

HTML:

<form id='theForm'>
  <label>Field 1:
    <input type='text' placeholder='provide a value for field 1'>
  </label>
  <br><label>Field 2:
    <input type='text' placeholder='provide a value for field 2'>
  </label>
  <br><label>Field 3:
    <input type='text' placeholder='provide a value for field 3'>
  </label>
</form>

JavaScript with jQuery:

jQuery(function($) {

  // Is placeholder supported?
  if ('placeholder' in document.createElement('input')) {
    // Yes, no need for us to do it
    display("This browser supports automatic placeholders");
  }
  else {
    // No, do it manually
    display("Manual placeholders");

    // Set the initial values of the inputs as placeholder text
    $('#theForm input').val(function() {
      if (this.value.length == 0) {
        return $(this).attr('placeholder');
      }
    });

    // Hook up a handler to delete the placeholder text on focus,
    // and put it back on blur
    $('#theForm')
      .delegate('input', 'focus', function() {
        if (this.value === $(this).attr("placeholder")) {
          this.value = '';
        }
      })
      .delegate('input', 'blur', function() {
        if (this.value.length == 0) {
          this.value = $(this).attr("placeholder");
        }
      });
  }

  function display(msg) {
    $("<p>").html(msg).appendTo(document.body);
  }

});

Live copy

(Kudos to diveintohtml5.ep.io for the placholder feature-detection code.)

Show/Hide the console window of a C# console application

"Just to hide" you can:

Change the output type from Console Application to Windows Application,

And Instead of Console.Readline/key you can use new ManualResetEvent(false).WaitOne() at the end to keep the app running.

printf not printing on console

You could try writing to stderr, rather than stdout.

fprintf(stderr, "Hello, please enter your age\n");

You should also have a look at this relevant thread.

Host binding and Host listening

This is the simple example to use both of them:

import {
  Directive, HostListener, HostBinding
}
from '@angular/core';

@Directive({
  selector: '[Highlight]'
})
export class HighlightDirective {
  @HostListener('mouseenter') mouseover() {
    this.backgroundColor = 'green';
  };

  @HostListener('mouseleave') mouseleave() {
    this.backgroundColor = 'white';
  }

  @HostBinding('style.backgroundColor') get setColor() {
     return this.backgroundColor;
  };

  private backgroundColor = 'white';
  constructor() {}

}

Introduction:

  1. HostListener can bind an event to the element.

  2. HostBinding can bind a style to the element.

  3. this is directive, so we can use it for

    Some Text
  4. So according to the debug, we can find that this div has been binded style = "background-color:white"

    Some Text
  5. we also can find that EventListener of this div has two event: mouseenter and mouseleave. So when we move the mouse into the div, the colour will become green, mouse leave, the colour will become white.

Unable to start debugging on the web server. Could not start ASP.NET debugging VS 2010, II7, Win 7 x64

I had the same problem when I created application in Visual Studio, and then in properties created virtual directory for use with local IIS. If someone has this error it is because VS creates application under wrong AppPool, i.e. under AppPool which doesn't suit your needs.
If this is the case, go to IIS Manager, select App, Go to Basic settings and change AppPool for App and you are good to go.

Could not calculate build plan: Plugin org.apache.maven.plugins:maven-resources-plugin:2.5 or one of its dependencies could not be resolved

JackDev's option 3 works for me after I changed the default repository to another folder.

Below is what I see after M2E plugin automatically download the maven-resources-plugin-2.6. Maybe this could give you some hint if you want to take the manual approach. The necessary files can be downloaded from here: https://repo.maven.apache.org/maven2/org/apache/maven/plugins/maven-resources-plugin/2.6/

enter image description here

What is 'Context' on Android?

Context is an "interface" to the global information about an application environment. In practice, Context is actually an abstract class, whose implementation is provided by the Android system.

It allows access to application-specific resources and classes, as well as up-calls for application-level operations, such as launching activities, broadcasting and receiving intents, etc.

In the following picture, you can see a hierarchy of classes, where Context is the root class of this hierarchy. In particular, it's worth emphasizing that Activity is a descendant of Context.

Activity diagram

How can I write text on a HTML5 canvas element?

Yes of course you can write a text on canvas with ease, and you can set the font name, font size and font color. There are two method to build a text on Canvas, i.e. fillText() and strokeText(). fillText() method is used to make a text that can only be filled with color, whereas strokeText() is used to make a text that can only be given an outline color. So if we want to build a text that filled with color and have outline color, we must use both of them.

here the full example, how to write text on canvas :

<canvas id="Canvas01" width="400" height="200" style="border:2px solid #bbb; margin-left:10px; margin-top:10px;"></canvas>

<script>
  var canvas = document.getElementById('Canvas01');
  var ctx = canvas.getContext('2d');

  ctx.fillStyle= "red";
  ctx.font = "italic bold 35pt Tahoma";
  //syntax : .fillText("text", x, y)
  ctx.fillText("StacOverFlow",30,80);

</script>

Here the demo for this, and you can try your self for any modification: http://okeschool.com/examples/canvas/html5-canvas-text-color

Unable to specify the compiler with CMake

I had the same issue. And in my case the fix was pretty simple. The trick is to simply add the ".exe" to your compilers path. So, instead of :

SET(CMAKE_C_COMPILER C:/MinGW/bin/gcc)

It should be

SET(CMAKE_C_COMPILER C:/MinGW/bin/gcc.exe)

The same applies for g++.

When should iteritems() be used instead of items()?

As the dictionary documentation for python 2 and python 3 would tell you, in python 2 items returns a list, while iteritems returns a iterator.

In python 3, items returns a view, which is pretty much the same as an iterator.

If you are using python 2, you may want to user iteritems if you are dealing with large dictionaries and all you want to do is iterate over the items (not necessarily copy them to a list)

How to use pip with Python 3.x alongside Python 2.x

The approach you should take is to install pip for Python 3.2.

You do this in the following way:

$ curl -O https://bootstrap.pypa.io/get-pip.py
$ sudo python3.2 get-pip.py

Then, you can install things for Python 3.2 with pip-3.2, and install things for Python 2-7 with pip-2.7. The pip command will end up pointing to one of these, but I'm not sure which, so you will have to check.

How to call controller from the button click in asp.net MVC 4

You are mixing razor and aspx syntax,if your view engine is razor just do this:

<button class="btn btn-info" type="button" id="addressSearch"   
          onclick="location.href='@Url.Action("List", "Search")'">

C++ - struct vs. class

The other difference is that

template<class T> ...

is allowed, but

template<struct T> ...

is not.

jQuery: keyPress Backspace won't fire?

If you want to fire the event only on changes of your input use:

$('.s').bind('input', function(){
  console.log("search!");
  doSearch();
});

How to strip HTML tags from a string in SQL Server?

Try this. It's a modified version of the one posted by RedFilter ... this SQL removes all tags except BR, B, and P with any accompanying attributes:

CREATE FUNCTION [dbo].[StripHtml] (@HTMLText VARCHAR(MAX))
RETURNS VARCHAR(MAX)
AS
BEGIN
 DECLARE @Start  INT
 DECLARE @End    INT
 DECLARE @Length INT
 DECLARE @TempStr varchar(255)

 SET @Start = CHARINDEX('<',@HTMLText)
 SET @End = CHARINDEX('>',@HTMLText,CHARINDEX('<',@HTMLText))
 SET @Length = (@End - @Start) + 1

 WHILE @Start > 0 AND @End > 0 AND @Length > 0
 BEGIN
   IF (UPPER(SUBSTRING(@HTMLText, @Start, 3)) <> '<BR') AND (UPPER(SUBSTRING(@HTMLText, @Start, 2)) <> '<P') AND (UPPER(SUBSTRING(@HTMLText, @Start, 2)) <> '<B') AND (UPPER(SUBSTRING(@HTMLText, @Start, 3)) <> '</B')
   BEGIN
      SET @HTMLText = STUFF(@HTMLText,@Start,@Length,'')
   END
    
   SET @Start = CHARINDEX('<',@HTMLText, @End)
   SET @End = CHARINDEX('>',@HTMLText,CHARINDEX('<',@HTMLText, @Start))
   SET @Length = (@End - @Start) - 1
 END

 RETURN RTRIM(LTRIM(@HTMLText))
END

Handling the TAB character in Java

You can also use the tab character '\t' to represent a tab, instead of "\t".

char c ='t';
char c =(char)9;

Specify a Root Path of your HTML directory for script links?

/ means the root of the current drive;

./ means the current directory;

../ means the parent of the current directory.

Cannot resolve symbol 'AppCompatActivity'

Today (22 April) you can use the new AppCompatActivity released with the support libraries v 22.1.0.

Just change your dependency :

compile "com.android.support:appcompat-v7:22.1.0"

Here you can find more info about this new class.

What is the C++ function to raise a number to a power?

Note that the use of pow(x,y) is less efficient than x*x*x y times as shown and answered here https://stackoverflow.com/a/2940800/319728.

So if you're going for efficiency use x*x*x.

How to split/partition a dataset into training and test datasets for, e.g., cross validation?

If you want to split the data set once in two halves, you can use numpy.random.shuffle, or numpy.random.permutation if you need to keep track of the indices:

import numpy
# x is your dataset
x = numpy.random.rand(100, 5)
numpy.random.shuffle(x)
training, test = x[:80,:], x[80:,:]

or

import numpy
# x is your dataset
x = numpy.random.rand(100, 5)
indices = numpy.random.permutation(x.shape[0])
training_idx, test_idx = indices[:80], indices[80:]
training, test = x[training_idx,:], x[test_idx,:]

There are many ways to repeatedly partition the same data set for cross validation. One strategy is to resample from the dataset, with repetition:

import numpy
# x is your dataset
x = numpy.random.rand(100, 5)
training_idx = numpy.random.randint(x.shape[0], size=80)
test_idx = numpy.random.randint(x.shape[0], size=20)
training, test = x[training_idx,:], x[test_idx,:]

Finally, sklearn contains several cross validation methods (k-fold, leave-n-out, ...). It also includes more advanced "stratified sampling" methods that create a partition of the data that is balanced with respect to some features, for example to make sure that there is the same proportion of positive and negative examples in the training and test set.

List Highest Correlation Pairs from a Large Correlation Matrix in Pandas?

Use the code below to view the correlations in the descending order.

# See the correlations in descending order

corr = df.corr() # df is the pandas dataframe
c1 = corr.abs().unstack()
c1.sort_values(ascending = False)

How to format code in Xcode?

  1. Select the block of code that you want indented.

  2. Right-click (or, on Mac, Ctrl-click).

  3. Structure → Re-indent

Change x axes scale in matplotlib

I find the simple solution

pylab.ticklabel_format(axis='y',style='sci',scilimits=(1,4))

Remove first Item of the array (like popping from stack)

Just use arr.slice(startingIndex, endingIndex).

If you do not specify the endingIndex, it returns all the items starting from the index provided.

In your case arr=arr.slice(1).

Unresolved external symbol on static class members

If you are using C++ 17 you can just use the inline specifier (see https://stackoverflow.com/a/11711082/55721)


If using older versions of the C++ standard, you must add the definitions to match your declarations of X and Y

unsigned char test::X;
unsigned char test::Y;

somewhere. You might want to also initialize a static member

unsigned char test::X = 4;

and again, you do that in the definition (usually in a CXX file) not in the declaration (which is often in a .H file)

Import Python Script Into Another?

I highly recommend the reading of a lecture in SciPy-lectures organization:

https://scipy-lectures.org/intro/language/reusing_code.html

It explains all the commented doubts.

But, new paths can be easily added and avoiding duplication with the following code:

import sys
new_path = 'insert here the new path'

if new_path not in sys.path:
    sys.path.append(new_path)
import funcoes_python #Useful python functions saved in a different script

How does Content Security Policy (CSP) work?

Apache 2 mod_headers

You could also enable Apache 2 mod_headers. On Fedora it's already enabled by default. If you use Ubuntu/Debian, enable it like this:

# First enable headers module for Apache 2,
# and then restart the Apache2 service
a2enmod headers
apache2 -k graceful

On Ubuntu/Debian you can configure headers in the file /etc/apache2/conf-enabled/security.conf

#
# Setting this header will prevent MSIE from interpreting files as something
# else than declared by the content type in the HTTP headers.
# Requires mod_headers to be enabled.
#
#Header set X-Content-Type-Options: "nosniff"

#
# Setting this header will prevent other sites from embedding pages from this
# site as frames. This defends against clickjacking attacks.
# Requires mod_headers to be enabled.
#
Header always set X-Frame-Options: "sameorigin"
Header always set X-Content-Type-Options nosniff
Header always set X-XSS-Protection "1; mode=block"
Header always set X-Permitted-Cross-Domain-Policies "master-only"
Header always set Cache-Control "no-cache, no-store, must-revalidate"
Header always set Pragma "no-cache"
Header always set Expires "-1"
Header always set Content-Security-Policy: "default-src 'none';"
Header always set Content-Security-Policy: "script-src 'self' www.google-analytics.com adserver.example.com www.example.com;"
Header always set Content-Security-Policy: "style-src 'self' www.example.com;"

Note: This is the bottom part of the file. Only the last three entries are CSP settings.

The first parameter is the directive, the second is the sources to be white-listed. I've added Google analytics and an adserver, which you might have. Furthermore, I found that if you have aliases, e.g, www.example.com and example.com configured in Apache 2 you should add them to the white-list as well.

Inline code is considered harmful, and you should avoid it. Copy all the JavaScript code and CSS to separate files and add them to the white-list.

While you're at it you could take a look at the other header settings and install mod_security

Further reading:

https://developers.google.com/web/fundamentals/security/csp/

https://www.w3.org/TR/CSP/

Error in installation a R package

After using the wrong quotation mark characters in install.packages(), correcting the quote marks yielded the "cannot remove prior installation" error. Closing and restarting R worked.

Pad left or right with string.format (not padleft or padright) with arbitrary string

Edit: I misunderstood your question, I thought you were asking how to pad with spaces.

What you are asking is not possible using the string.Format alignment component; string.Format always pads with whitespace. See the Alignment Component section of MSDN: Composite Formatting.

According to Reflector, this is the code that runs inside StringBuilder.AppendFormat(IFormatProvider, string, object[]) which is called by string.Format:

int repeatCount = num6 - str2.Length;
if (!flag && (repeatCount > 0))
{
    this.Append(' ', repeatCount);
}
this.Append(str2);
if (flag && (repeatCount > 0))
{
    this.Append(' ', repeatCount);
}

As you can see, blanks are hard coded to be filled with whitespace.

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

This is a quick and simple add of a named tab to the current worksheet:

Sheets.Add.Name = "Tempo"

How to print out all the elements of a List in Java?

The objects in the list must have toString implemented for them to print something meaningful to screen.

Here's a quick test to see the differences:

public class Test {

    public class T1 {
        public Integer x;
    }

    public class T2 {
        public Integer x;

        @Override
        public String toString() {
            return x.toString();
        }
    }

    public void run() {
        T1 t1 = new T1();
        t1.x = 5;
        System.out.println(t1);

        T2 t2 = new T2();
        t2.x = 5;
        System.out.println(t2);

    }

    public static void main(String[] args) {        
        new Test().run();
    }
}

And when this executes, the results printed to screen are:

t1 = Test$T1@19821f
t2 = 5

Since T1 does not override the toString method, its instance t1 prints out as something that isn't very useful. On the other hand, T2 overrides toString, so we control what it prints when it is used in I/O, and we see something a little better on screen.

Service Temporarily Unavailable Magento?

In Magento 2 You have to remove file located in /var/.maintenance.flag - just realized that after some searching, so i shall share.

How can I see function arguments in IPython Notebook Server 3?

Try Shift-Tab-Tab a bigger documentation appears, than with Shift-Tab. It's the same but you can scroll down.

Shift-Tab-Tab-Tab and the tooltip will linger for 10 seconds while you type.

Shift-Tab-Tab-Tab-Tab and the docstring appears in the pager (small part at the bottom of the window) and stays there.

Checking on a thread / remove from list

As TokenMacGuy says, you should use thread.is_alive() to check if a thread is still running. To remove no longer running threads from your list you can use a list comprehension:

for t in my_threads:
    if not t.is_alive():
        # get results from thread
        t.handled = True
my_threads = [t for t in my_threads if not t.handled]

This avoids the problem of removing items from a list while iterating over it.

fatal error: iostream.h no such file or directory

Using standard C++ calling (note that you should use namespace std for cout or add using namespace std;)

#include <iostream>

int main()
{
    std::cout<<"Hello World!\n";
    return 0;
}

C# find highest array value and index

int[] Data= { 1, 212, 333,2,12,3311,122,23 };
int large = Data.Max();
Console.WriteLine(large);

Sending HTML mail using a shell script

I've been trying to just make a simple bash script that emails out html formatted content-type and all these are great but I don't want to be creating local files on the filesystem to be passing into the script and also on our version of mailx(12.5+) the -a parameter for mail doesn't work anymore since it adds an attachment and I couldn't find any replacement parameter for additional headers so the easiest way for me was to use sendmail.

Below is the simplest 1 liner I created to run in our bash script that works for us. It just basically passes the Content-Type: text/html, subject, and the body and works.

printf "Content-Type: text/html\nSubject: Test Email\nHTML BODY<b>test bold</b>" | sendmail <Email Address To>

If you wanted to create an entire html page from a variable an alternative method I used in the bash script was to pass the variable as below.

emailBody="From: <Email Address From>
Subject: Test
Content-Type: text/html; charset=\"us-ascii\"
<html>
<body>
body
<b> test bold</b>

</body>
</html>
"
echo "$emailBody" | sendmail <Email Address To>

ssh server connect to host xxx port 22: Connection timed out on linux-ubuntu

Update the security group of that instance. Your local IP must have updated. Every time it’s IP flips. You will have to go update the Security group.

How can I turn a string into a list in Python?

The list() function [docs] will convert a string into a list of single-character strings.

>>> list('hello')
['h', 'e', 'l', 'l', 'o']

Even without converting them to lists, strings already behave like lists in several ways. For example, you can access individual characters (as single-character strings) using brackets:

>>> s = "hello"
>>> s[1]
'e'
>>> s[4]
'o'

You can also loop over the characters in the string as you can loop over the elements of a list:

>>> for c in 'hello':
...     print c + c,
... 
hh ee ll ll oo

How can you dynamically create variables via a while loop?

For free-dom:

import random

alphabet = tuple('abcdefghijklmnopqrstuvwxyz')

globkeys = globals().keys()
globkeys.append('globkeys') # because name 'globkeys' is now also in globals()

print 'globkeys==',globkeys
print
print "globals().keys()==",globals().keys()

for i in xrange(8):
    globals()[''.join(random.sample(alphabet,random.randint(3,26)))] = random.choice(alphabet)
del i

newnames = [ x for x in globals().keys() if x not in globkeys ]
print
print 'newnames==',newnames

print
print "globals().keys()==",globals().keys()

print
print '\n'.join(repr((u,globals()[u])) for u in newnames)

Result

globkeys== ['__builtins__', 'alphabet', 'random', '__package__', '__name__', '__doc__', 'globkeys']

globals().keys()== ['__builtins__', 'alphabet', 'random', '__package__', '__name__', 'globkeys', '__doc__']

newnames== ['fztkebyrdwcigsmulnoaph', 'umkfcvztleoij', 'kbutmzfgpcdqanrivwsxly', 'lxzmaysuornvdpjqfetbchgik', 'wznptbyermclfdghqxjvki', 'lwg', 'vsolxgkz', 'yobtlkqh']

globals().keys()== ['fztkebyrdwcigsmulnoaph', 'umkfcvztleoij', 'newnames', 'kbutmzfgpcdqanrivwsxly', '__builtins__', 'alphabet', 'random', 'lxzmaysuornvdpjqfetbchgik', '__package__', 'wznptbyermclfdghqxjvki', 'lwg', 'x', 'vsolxgkz', '__name__', 'globkeys', '__doc__', 'yobtlkqh']

('fztkebyrdwcigsmulnoaph', 't')
('umkfcvztleoij', 'p')
('kbutmzfgpcdqanrivwsxly', 'a')
('lxzmaysuornvdpjqfetbchgik', 'n')
('wznptbyermclfdghqxjvki', 't')
('lwg', 'j')
('vsolxgkz', 'w')
('yobtlkqh', 'c')

Another way:

import random

pool_of_names = []
for i in xrange(1000):
    v = 'LXM'+str(random.randrange(10,100000))
    if v not in globals():
        pool_of_names.append(v)

alphabet = 'abcdefghijklmnopqrstuvwxyz' 

print 'globals().keys()==',globals().keys()

print
for j in xrange(8):
    globals()[pool_of_names[j]] = random.choice(alphabet)
newnames = pool_of_names[0:j+1]

print
print 'globals().keys()==',globals().keys()

print
print '\n'.join(repr((u,globals()[u])) for u in newnames)

result:

globals().keys()== ['__builtins__', 'alphabet', 'random', '__package__', 'i', 'v', '__name__', '__doc__', 'pool_of_names']


globals().keys()== ['LXM7646', 'random', 'newnames', 'LXM95826', 'pool_of_names', 'LXM66380', 'alphabet', 'LXM84070', '__package__', 'LXM8644', '__doc__', 'LXM33579', '__builtins__', '__name__', 'LXM58418', 'i', 'j', 'LXM24703', 'v']

('LXM66380', 'v')
('LXM7646', 'a')
('LXM8644', 'm')
('LXM24703', 'r')
('LXM58418', 'g')
('LXM84070', 'c')
('LXM95826', 'e')
('LXM33579', 'j')

Minimum 6 characters regex expression

If I understand correctly, you need a regex statement that checks for at least 6 characters (letters & numbers)?

/[0-9a-zA-Z]{6,}/

Efficiently updating database using SQLAlchemy ORM

If it is because of the overhead in terms of creating objects, then it probably can't be sped up at all with SA.

If it is because it is loading up related objects, then you might be able to do something with lazy loading. Are there lots of objects being created due to references? (IE, getting a Company object also gets all of the related People objects).

How to set a Timer in Java?

Ok, I think I understand your problem now. You can use a Future to try to do something and then timeout after a bit if nothing has happened.

E.g.:

FutureTask<Void> task = new FutureTask<Void>(new Callable<Void>() {
  @Override
  public Void call() throws Exception {
    // Do DB stuff
    return null;
  }
});

Executor executor = Executors.newSingleThreadScheduledExecutor();
executor.execute(task);

try {
  task.get(5, TimeUnit.SECONDS);
}
catch(Exception ex) {
  // Handle your exception
}

MongoDB Data directory /data/db not found

MongoDB needs data directory to store data. Default path is /data/db

When you start MongoDB engine, it searches this directory which is missing in your case. Solution is create this directory and assign rwx permission to user.

If you want to change the path of your data directory then you should specify it while starting mongod server like,

mongod --dbpath /data/<path> --port <port no> 

This should help you start your mongod server with custom path and port.

How do I create a sequence in MySQL?

SEQUENCES like it works on firebird:

-- =======================================================

CREATE TABLE SEQUENCES  
(  
  NM_SEQUENCE VARCHAR(32) NOT NULL UNIQUE,  
  VR_SEQUENCE BIGINT      NOT NULL  
);  

-- =======================================================
-- Creates a sequence sSeqName and set its initial value.
-- =======================================================

DROP PROCEDURE IF EXISTS CreateSequence;  

DELIMITER :)  
CREATE PROCEDURE CreateSequence( sSeqName VARCHAR(32), iSeqValue BIGINT )  
BEGIN  
  IF NOT EXISTS ( SELECT * FROM SEQUENCES WHERE (NM_SEQUENCE = sSeqName) ) THEN  
    INSERT INTO SEQUENCES (NM_SEQUENCE, VR_SEQUENCE)  
    VALUES (sSeqName   , iSeqValue  );  
  END IF;  
END :)  
DELIMITER ;  

-- CALL CreateSequence( 'MySequence', 0 );  

-- =======================================================================
-- Increments the sequence value of sSeqName by iIncrement and returns it.
-- If iIncrement is zero, returns the current value of sSeqName.
-- =======================================================================

DROP FUNCTION IF EXISTS GetSequenceVal;  

DELIMITER :)  
CREATE FUNCTION GetSequenceVal( sSeqName VARCHAR(32), iIncrement INTEGER )  
RETURNS BIGINT  -- iIncrement can be negative  
BEGIN  
  DECLARE iSeqValue BIGINT;  

  SELECT VR_SEQUENCE FROM SEQUENCES  
  WHERE  ( NM_SEQUENCE = sSeqName )  
  INTO   @iSeqValue;  

  IF ( iIncrement <> 0 ) THEN  
    SET @iSeqValue = @iSeqValue + iIncrement;  

    UPDATE SEQUENCES SET VR_SEQUENCE = @iSeqValue  
    WHERE  ( NM_SEQUENCE = sSeqName );  
  END IF;

  RETURN @iSeqValue;
END :)  
DELIMITER ;  

-- SELECT GetSequenceVal('MySequence', 1);  -- Adds 1 to MySequence value and returns it.

-- ===================================================================

Getting the difference between two sets

Try this

test2.removeAll(test1);

Set#removeAll

Removes from this set all of its elements that are contained in the specified collection (optional operation). If the specified collection is also a set, this operation effectively modifies this set so that its value is the asymmetric set difference of the two sets.

Getting the text from a drop-down box

function getValue(obj)
{  
   // it will return the selected text
   // obj variable will contain the object of check box
   var text = obj.options[obj.selectedIndex].innerHTML ; 

}

HTML Snippet

 <asp:DropDownList ID="ddl" runat="server" CssClass="ComboXXX" 
  onchange="getValue(this)">
</asp:DropDownList>

adding text to an existing text element in javascript via DOM

remove .textContent from var t = document.getElementById("p").textContent;

_x000D_
_x000D_
var t = document.getElementById("p");_x000D_
var y = document.createTextNode("This just got added");_x000D_
_x000D_
t.appendChild(y);
_x000D_
<p id ="p">This is some text</p>
_x000D_
_x000D_
_x000D_

Get a random boolean in python?

random.choice([True, False])

would also work.

Python: One Try Multiple Except

Yes, it is possible.

try:
   ...
except FirstException:
   handle_first_one()

except SecondException:
   handle_second_one()

except (ThirdException, FourthException, FifthException) as e:
   handle_either_of_3rd_4th_or_5th()

except Exception:
   handle_all_other_exceptions()

See: http://docs.python.org/tutorial/errors.html

The "as" keyword is used to assign the error to a variable so that the error can be investigated more thoroughly later on in the code. Also note that the parentheses for the triple exception case are needed in python 3. This page has more info: Catch multiple exceptions in one line (except block)

Define css class in django Forms

Here is another solution for adding class definitions to the widgets after declaring the fields in the class.

def __init__(self, *args, **kwargs):
    super(SampleClass, self).__init__(*args, **kwargs)
    self.fields['name'].widget.attrs['class'] = 'my_class'

Super-simple example of C# observer/observable with delegates

The observer pattern is usually implemented with events.

Here's an example:

using System;

class Observable
{
    public event EventHandler SomethingHappened;

    public void DoSomething() =>
        SomethingHappened?.Invoke(this, EventArgs.Empty);
}

class Observer
{
    public void HandleEvent(object sender, EventArgs args)
    {
        Console.WriteLine("Something happened to " + sender);
    }
}

class Test
{
    static void Main()
    {
        Observable observable = new Observable();
        Observer observer = new Observer();
        observable.SomethingHappened += observer.HandleEvent;

        observable.DoSomething();
    }
}

See the linked article for a lot more detail.

Note that the above example uses C# 6 null-conditional operator to implement DoSomething safely to handle cases where SomethingHappened has not been subscribed to, and is therefore null. If you're using an older version of C#, you'd need code like this:

public void DoSomething()
{
    var handler = SomethingHappened;
    if (handler != null)
    {
        handler(this, EventArgs.Empty);
    }
}

Huge performance difference when using group by vs distinct

The two queries express the same question. Apparently the query optimizer chooses two different execution plans. My guess would be that the distinct approach is executed like:

  • Copy all business_key values to a temporary table
  • Sort the temporary table
  • Scan the temporary table, returning each item that is different from the one before it

The group by could be executed like:

  • Scan the full table, storing each value of business key in a hashtable
  • Return the keys of the hashtable

The first method optimizes for memory usage: it would still perform reasonably well when part of the temporary table has to be swapped out. The second method optimizes for speed, but potentially requires a large amount of memory if there are a lot of different keys.

Since you either have enough memory or few different keys, the second method outperforms the first. It's not unusual to see performance differences of 10x or even 100x between two execution plans.

center MessageBox in parent form

I have changed a little bit previous answer and compose WPF version of the MessageBoxEx. This code works for me great. Feel free to notify about issues of the code.

Please note: I use GeneralObjects.MainWindowInstance at ctor to initialize class with my main window, but actually I use it for any window due to some kind of cache for last parent window. Therefore you can simple remove out everything from ctor.

public class MessageBoxEx
{
    private static HwndSource source_ = null;
    private static HwndSourceHook hook_ = null;

    static MessageBoxEx()
    {
        try
        {
            // create cached 
            createHwndSource_(GeneralObjects.MainWindowInstance);

            hook_ = new HwndSourceHook(HwndSourceHook);
        }
        finally
        {
            if (null == source_ ||
                null == hook_)
            {
                source_ = null;
                hook_ = null;
            }
        }


    }

    private static void createHwndSource_(Window owner)
    {
        source_ = (HwndSource)PresentationSource.FromVisual(owner);
    }

    public static void Initialize_(Window owner = null)
    {
        try
        {
            if (null != owner)
            {
                if(source_.RootVisual != owner)
                {
                    createHwndSource_(owner);
                }

            }
        }
        finally
        {
            if (null == source_ ||
                null == hook_)
            {
                source_ = null;
                hook_ = null;
            }
        }


        if (null != source_ &&
            null != hook_)
        {
            source_.AddHook(hook_);
        }

    }

    public static MessageBoxResult Show(string messageBoxText)
    {
        Initialize_();
        return System.Windows.MessageBox.Show(messageBoxText);
    }


    public static MessageBoxResult Show(string messageBoxText, string caption)
    {
        Initialize_();
        return System.Windows.MessageBox.Show(messageBoxText, caption);
    }


    public static MessageBoxResult Show(Window owner, string messageBoxText)
    {
        Initialize_(owner);
        return System.Windows.MessageBox.Show(owner, messageBoxText);
    }


    public static MessageBoxResult Show(string messageBoxText, string caption, MessageBoxButton button)
    {
        Initialize_();
        return System.Windows.MessageBox.Show(messageBoxText, caption, button);
    }


    public static MessageBoxResult Show(Window owner, string messageBoxText, string caption)
    {
        Initialize_(owner);
        return System.Windows.MessageBox.Show(owner, messageBoxText, caption);
    }


    public static MessageBoxResult Show(string messageBoxText, string caption, MessageBoxButton button, MessageBoxImage icon)
    {
        Initialize_();
        return System.Windows.MessageBox.Show(messageBoxText, caption, button, icon);
    }


    public static MessageBoxResult Show(Window owner, string messageBoxText, string caption, MessageBoxButton button)
    {
        Initialize_(owner);
        return System.Windows.MessageBox.Show(owner, messageBoxText, caption, button);
    }


    public static MessageBoxResult Show(string messageBoxText, string caption, MessageBoxButton button, MessageBoxImage icon, MessageBoxResult defaultResult)
    {
        Initialize_();
        return System.Windows.MessageBox.Show(messageBoxText, caption, button, icon, defaultResult);
    }


    public static MessageBoxResult Show(Window owner, string messageBoxText, string caption, MessageBoxButton button, MessageBoxImage icon)
    {
        Initialize_(owner);
        return System.Windows.MessageBox.Show(owner, messageBoxText, caption, button, icon);
    }


    public static MessageBoxResult Show(string messageBoxText, string caption, MessageBoxButton button, MessageBoxImage icon, MessageBoxResult defaultResult, System.Windows.MessageBoxOptions options)
    {
        Initialize_();
        return System.Windows.MessageBox.Show(messageBoxText, caption, button, icon, defaultResult, options);
    }


    public static MessageBoxResult Show(Window owner, string messageBoxText, string caption, MessageBoxButton button, MessageBoxImage icon, MessageBoxResult defaultResult)
    {
        Initialize_(owner);
        return System.Windows.MessageBox.Show(owner, messageBoxText, caption, button, icon, defaultResult);
    }


    public static MessageBoxResult Show(Window owner, string messageBoxText, string caption, MessageBoxButton button, MessageBoxImage icon, MessageBoxResult defaultResult, System.Windows.MessageBoxOptions options)
    {
        Initialize_(owner);
        return System.Windows.MessageBox.Show(owner, messageBoxText, caption, button, icon, defaultResult, options);
    }

    private enum WM : int
    {
        WM_ACTIVATE = 0x0006
    }

    private static IntPtr HwndSourceHook(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
    {

        if ((int)WM.WM_ACTIVATE == msg &&
            source_.Handle == hwnd &&
            0 == (int)wParam)
        {

            try
            {
                CenterWindow(lParam);
            }
            finally
            {
                // remove hook at once after moved message box window.
                source_.RemoveHook(hook_);
            }
        }
        return IntPtr.Zero;
    }

    [DllImport("user32.dll")]
    private static extern bool GetWindowRect(IntPtr hWnd, ref Rectangle lpRect);


    [DllImport("user32.dll")]
    private static extern int MoveWindow(IntPtr hWnd, int X, int Y, int nWidth, int nHeight, bool bRepaint);

    private static void CenterWindow(IntPtr hChildWnd)
    {
        System.Drawing.Rectangle recChild = new System.Drawing.Rectangle(0, 0, 0, 0);

        bool success = GetWindowRect(hChildWnd, ref recChild);

        int width = recChild.Width - recChild.X;
        int height = recChild.Height - recChild.Y;

        System.Drawing.Rectangle recParent = new System.Drawing.Rectangle(0, 0, 0, 0);
        success = GetWindowRect(source_.Handle, ref recParent);

        System.Drawing.Point ptCenter = new System.Drawing.Point(0, 0);
        ptCenter.X = recParent.X + ((recParent.Width - recParent.X) / 2);
        ptCenter.Y = recParent.Y + ((recParent.Height - recParent.Y) / 2);


        System.Drawing.Point ptStart = new System.Drawing.Point(0, 0);
        ptStart.X = (ptCenter.X - (width / 2));
        ptStart.Y = (ptCenter.Y - (height / 2));

        // I have commented this code because of I have 2 monitors
        // so If application located at 1st monitor
        // message box can appear at second one.

        /*
        ptStart.X = (ptStart.X < 0) ? 0 : ptStart.X;
        ptStart.Y = (ptStart.Y < 0) ? 0 : ptStart.Y;
        */

        int result = MoveWindow(hChildWnd, ptStart.X, ptStart.Y, width,
                                height, false);

    }


}

Breaking out of nested loops

If you're going to raise an exception, you might raise a StopIteration exception. That will at least make the intent obvious.

How can one run multiple versions of PHP 5.x on a development LAMP server?

For testing I just run multiple instances of httpd on different IP addresses, so I have php7 running on 192.168.0.70 and php5.6 running on 192.168.0.56. In production I have a site running an old oscommerce running php5.3 and I just have a different conf file for the site

httpd -f /etc/apache2/php70.conf
httpd -f /etc/apache2/php53.conf

It's also a clean way to have different php.ini files for different sites. If you just have a couple of sites if a nice way to keep things organized and you don't have to worry about more then 1 site at a time when you upgrade something

How to get base URL in Web API controller?

In ASP.NET Core ApiController the Request property is only the message. But there is still Context.Request where you can get expected info. Personally I use this extension method:

public static string GetBaseUrl(this HttpRequest request)
{
    // SSL offloading
    var scheme = request.Host.Host.Contains("localhost") ? request.Scheme : "https";
    return $"{scheme}://{request.Host}{request.PathBase}";
}

SSH Port forwarding in a ~/.ssh/config file?

You can use the LocalForward directive in your host yam section of ~/.ssh/config:

LocalForward 5901 computer.myHost.edu:5901

Is there any way to redraw tmux window when switching smaller monitor to bigger one?

tmux limits the dimensions of a window to the smallest of each dimension across all the sessions to which the window is attached. If it did not do this there would be no sensible way to display the whole window area for all the attached clients.

The easiest thing to do is to detach any other clients from the sessions when you attach:

tmux attach -d

Alternately, you can move any other clients to a different session before attaching to the session:

takeover() {
    # create a temporary session that displays the "how to go back" message
    tmp='takeover temp session'
    if ! tmux has-session -t "$tmp"; then
        tmux new-session -d -s "$tmp"
        tmux set-option -t "$tmp" set-remain-on-exit on
        tmux new-window -kt "$tmp":0 \
            'echo "Use Prefix + L (i.e. ^B L) to return to session."'
    fi

    # switch any clients attached to the target session to the temp session
    session="$1"
    for client in $(tmux list-clients -t "$session" | cut -f 1 -d :); do
        tmux switch-client -c "$client" -t "$tmp"
    done

    # attach to the target session
    tmux attach -t "$session"
}
takeover 'original session' # or the session number if you do not name sessions

The screen will shrink again if a smaller client switches to the session.

There is also a variation where you only "take over" the window (link the window into a new session, set aggressive-resize, and switch any other sessions that have that window active to some other window), but it is harder to script in the general case (and different to “exit” since you would want to unlink the window or kill the session instead of just detaching from the session).

How can I reference a dll in the GAC from Visual Studio?

May be it's too late to answer, but i found a very simple way to do this(without a hack).

  1. Put your dll in GAC (for 3.5 Drag Drop inside "C:\Windows\assembly\")
  2. GoTo Projects --> Properties
  3. Click Reference Path (for 3.5 it's "C:\Windows\assembly\")
  4. and Build

Hope it helps

Write a formula in an Excel Cell using VBA

The correct character to use in this case is a full colon (:), not a semicolon (;).

Android ImageView Animation

imgDics = (ImageView) v.findViewById(R.id.img_player_tab2_dics);
    imgDics.setOnClickListener(onPlayer2Click);
    anim = new RotateAnimation(0f, 360f,
            Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,
                            0.5f);
    anim.setInterpolator(new LinearInterpolator());
    anim.setRepeatCount(Animation.INFINITE);
    anim.setDuration(4000);

    // Start animating the image
    imgDics.startAnimation(anim);

How to run multiple SQL commands in a single SQL connection?

Just enable this property in your connection string:

sqb.MultipleActiveResultSets = true;

This property allows one open connection for multiple datareaders.

Is it possible to change the content HTML5 alert messages?

Yes:

<input required title="Enter something OR ELSE." /> 

The title attribute will be used to notify the user of a problem.

How to make the overflow CSS property work with hidden as value

Actually...

To hide an absolute positioned element, the container position must be anything except for static. It can be relative or fixed in addition to absolute.

How to print variable addresses in C?

To print the address of a variable, you need to use the %p format. %d is for signed integers. For example:

#include<stdio.h>

void main(void)
{
  int a;

  printf("Address is %p:",&a);
}

How to disable mouse right click on a web page?

Please do not do that, it is very annoying.

The right menu is there for a reason, and it should be left there. Many browser extensions add entries to the right click menu and the user should be able to use it in any page he visits.

Moreover you can use all of the functionality of the right click menu in other ways (keyboard shortcuts, browser menu etc etc etc) so blocking the right click menu has the only effect of annoying the user.

PS: If really you cannot resist the urge to block it at least do not put a popup saying "no right click allowed".

HTTP test server accepting GET/POST requests

You might don't need any web site for that, only open up the browser, press F12 to get access to developer tools > console, then in console write some JavaScript Code to do that.

Here I share some ways to accomplish that:

For GET request: *.Using jQuery:

$.get("http://someurl/status/?messageid=597574445", function(data, status){
    console.log(data, status);
  });

For POST request: 1. Using jQuery $.ajax:

var url= "http://someurl/",
        api_key = "6136-bc16-49fb-bacb-802358",
        token1 = "Just for test",
        result;
    $.ajax({
          url: url,
          type: "POST",
          data: {
            api_key: api_key,
            token1: token1
          },
        }).done(function(result) {
                console.log("done successfuly", result);
        }).fail(function(error) {

          console.log(error.responseText, error);

        });
  1. Using jQuery, append and submit

     var merchantId = "AA86E",
            token = "4107120133142729",
            url = "https://payment.com/Index";
    
        var form = `<form id="send-by-post" method="post" action="${url}">
                                    <input id="token" type="hidden" name="token" value="${merchantId}"/>
                                    <input id="merchantId" name="merchantId" type="hidden" value="${token}"/>
                                    <button type="submit" >Pay</button>
                        </div>
                    </form> `; 
        $('body').append(form);
        $("#send-by-post").submit();//Or $(form).appendTo("body").submit();
    
    1. Using Pure JavaScript:

    var api_key = "73736-bc16-49fb-bacb-643e58", recipient = "095552565", token1 = "4458", url = 'http://smspanel.com/send/';

var form = `<form id="send-by-post" method="post" action="${url}"> <input id="api_key" type="hidden" name="api_key" value="${api_key}"/> <input id="recipient" type="hidden" name="recipient" value="${recipient}"/> <input id="token1" name="token1" type="hidden" value="${token1}"/> <button type="submit" >Send</button> </div> </form>`;

document.querySelector("body").insertAdjacentHTML('beforeend',form);
document.querySelector("#send-by-post").submit();
  1. Or even using ASP.Net:

    var url = "https://Payment.com/index"; Response.Clear(); var sb = new System.Text.StringBuilder();

    sb.Append(""); sb.AppendFormat(""); sb.AppendFormat("", url); sb.AppendFormat("", "C668"); sb.AppendFormat("", "22720281459"); sb.Append(""); sb.Append(""); sb.Append(""); Response.Write(sb.ToString()); Response.End();

(Note: Since I have backtick character (`) in my code the code format ruined, I have no idea how to correct it)

How to compile C++ under Ubuntu Linux?

To compile source.cpp, run

g++ source.cpp

This command will compile source.cpp to file a.out in the same directory. To run the compiled file, run

./a.out

If you compile another source file, with g++ source2.cpp, the new compiled file a.out will overwrite the a.out generated with source.cpp

If you want to compile source.cpp to a specific file, say compiledfile, run

g++ source.cpp -o compiledfile

or

g++ -o compiledfile source.cpp

This will create the compiledfile which is the compiled binary file. to run the compiledfile, run

./compiledfile

If g++ is not in your $PATH, replace g++ with /usr/bin/g++.

Attribute Error: 'list' object has no attribute 'split'

I think you've actually got a wider confusion here.

The initial error is that you're trying to call split on the whole list of lines, and you can't split a list of strings, only a string. So, you need to split each line, not the whole thing.

And then you're doing for points in Type, and expecting each such points to give you a new x and y. But that isn't going to happen. Types is just two values, x and y, so first points will be x, and then points will be y, and then you'll be done. So, again, you need to loop over each line and get the x and y values from each line, not loop over a single Types from a single line.

So, everything has to go inside a loop over every line in the file, and do the split into x and y once for each line. Like this:

def getQuakeData():
    filename = input("Please enter the quake file: ")
    readfile = open(filename, "r")

    for line in readfile:
        Type = line.split(",")
        x = Type[1]
        y = Type[2]
        print(x,y)

getQuakeData()

As a side note, you really should close the file, ideally with a with statement, but I'll get to that at the end.


Interestingly, the problem here isn't that you're being too much of a newbie, but that you're trying to solve the problem in the same abstract way an expert would, and just don't know the details yet. This is completely doable; you just have to be explicit about mapping the functionality, rather than just doing it implicitly. Something like this:

def getQuakeData():
    filename = input("Please enter the quake file: ")
    readfile = open(filename, "r")
    readlines = readfile.readlines()
    Types = [line.split(",") for line in readlines]
    xs = [Type[1] for Type in Types]
    ys = [Type[2] for Type in Types]
    for x, y in zip(xs, ys):
        print(x,y)

getQuakeData()

Or, a better way to write that might be:

def getQuakeData():
    filename = input("Please enter the quake file: ")
    # Use with to make sure the file gets closed
    with open(filename, "r") as readfile:
        # no need for readlines; the file is already an iterable of lines
        # also, using generator expressions means no extra copies
        types = (line.split(",") for line in readfile)
        # iterate tuples, instead of two separate iterables, so no need for zip
        xys = ((type[1], type[2]) for type in types)
        for x, y in xys:
            print(x,y)

getQuakeData()

Finally, you may want to take a look at NumPy and Pandas, libraries which do give you a way to implicitly map functionality over a whole array or frame of data almost the same way you were trying to.

add class with JavaScript

document.getElementsByClassName returns a node list. So you'll have to iterate over the list and bind the event to individual elements. Like this...

var buttons = document.getElementsByClassName("navButton");

for(var i = 0; i < buttons.length; ++i){
    buttons[i].onmouseover = function() {
        this.setAttribute("class", "active");
        this.setAttribute("src", "images/arrows/top_o.png");
    }
}

Are the shift operators (<<, >>) arithmetic or logical in C?

Left shift <<

This is somehow easy and whenever you use the shift operator, it is always a bit-wise operation, so we can't use it with a double and float operation. Whenever we left shift one zero, it is always added to the least significant bit (LSB).

But in right shift >> we have to follow one additional rule and that rule is called "sign bit copy". Meaning of "sign bit copy" is if the most significant bit (MSB) is set then after a right shift again the MSB will be set if it was reset then it is again reset, means if the previous value was zero then after shifting again, the bit is zero if the previous bit was one then after the shift it is again one. This rule is not applicable for a left shift.

The most important example on right shift if you shift any negative number to right shift, then after some shifting the value finally reach to zero and then after this if shift this -1 any number of times the value will remain same. Please check.

data type not understood

Try:

mmatrix = np.zeros((nrows, ncols))

Since the shape parameter has to be an int or sequence of ints

http://docs.scipy.org/doc/numpy/reference/generated/numpy.zeros.html

Otherwise you are passing ncols to np.zeros as the dtype.

convert ArrayList<MyCustomClass> to JSONArray

I know its already answered, but theres a better solution here use this code :

for ( Field f : context.getFields() ) {
     if ( f.getType() == String.class ) || ( f.getType() == String.class ) ) {
           //DO String To JSON
     }
     /// And so on...
}

This way you can access variables from class without manually typing them..

Faster and better .. Hope this helps.

Cheers. :D

How to exit from the application and show the home screen?

If you want to end an activity you can simply call finish(). It is however bad practice to have an exit button on the screen.

Fastest way to check a string contain another substring in JavaScript?

For finding a simple string, using the indexOf() method and using regex is pretty much the same: http://jsperf.com/substring - so choose which ever one that seems easier to write.

Allowed memory size of 33554432 bytes exhausted (tried to allocate 43148176 bytes) in php

It is unfortunately easy to program in PHP in a way that consumes memory faster than you realise. Copying strings, arrays and objects instead of using references will do it, though PHP 5 is supposed to do this more automatically than in PHP 4. But dealing with your data set in entirety over several steps is also wasteful compared to processing the smallest logical unit at a time. The classic example is working with large resultsets from a database: most programmers fetch the entire resultset into an array and then loop over it one or more times with foreach(). It is much more memory efficient to use a while() loop to fetch and process one row at a time. The same thing applies to processing a file.

What does "-ne" mean in bash?

This is one of those things that can be difficult to search for if you don't already know where to look.

[ is actually a command, not part of the bash shell syntax as you might expect. It happens to be a Bash built-in command, so it's documented in the Bash manual.

There's also an external command that does the same thing; on many systems, it's provided by the GNU Coreutils package.

[ is equivalent to the test command, except that [ requires ] as its last argument, and test does not.

Assuming the bash documentation is installed on your system, if you type info bash and search for 'test' or '[' (the apostrophes are part of the search), you'll find the documentation for the [ command, also known as the test command. If you use man bash instead of info bash, search for ^ *test (the word test at the beginning of a line, following some number of spaces).

Following the reference to "Bash Conditional Expressions" will lead you to the description of -ne, which is the numeric inequality operator ("ne" stands for "not equal). By contrast, != is the string inequality operator.

You can also find bash documentation on the web.

The official definition of the test command is the POSIX standard (to which the bash implementation should conform reasonably well, perhaps with some extensions).

Java recursive Fibonacci sequence

In pseudo code, where n = 5, the following takes place:

fibonacci(4) + fibonnacci(3)

This breaks down into:

(fibonacci(3) + fibonnacci(2)) + (fibonacci(2) + fibonnacci(1))

This breaks down into:

(((fibonacci(2) + fibonnacci(1)) + ((fibonacci(1) + fibonnacci(0))) + (((fibonacci(1) + fibonnacci(0)) + 1))

This breaks down into:

((((fibonacci(1) + fibonnacci(0)) + 1) + ((1 + 0)) + ((1 + 0) + 1))

This breaks down into:

((((1 + 0) + 1) + ((1 + 0)) + ((1 + 0) + 1))

This results in: 5

Given the fibonnacci sequence is 1 1 2 3 5 8 ..., the 5th element is 5. You can use the same methodology to figure out the other iterations.

Autocompletion in Vim

Here is link! for PHP.

press the Ctrl + x followed by Ctrl + o keys while writing some PHP functions.

Thanks to Oseems Solutions for the tutorial

Copy folder recursively in Node.js

It looks like ncp and wrench both are no longer maintained. Probably the best option is to use fs-extra

The Developer of Wrench directs users to use fs-extra as he has deprecated his library

copySync & moveSync both will copy and move folders even if they have files or subfolders and you can easily move or copy files using it

const fse = require('fs-extra');

const srcDir = `path/to/file`;
const destDir = `path/to/destination/directory`;
                              
// To copy a folder or file  
fse.copySync(srcDir, destDir, function (err) {
  if (err) {                 ^
    console.error(err);      |___{ overwrite: true } // add if you want to replace existing folder or file with same name
  } else {
    console.log("success!");
  }
});

OR

// To copy a folder or file  
fse.moveSync(srcDir, destDir, function (err) {
  if (err) {                 ^
    console.error(err);      |___{ overwrite: true } // add if you want to replace existing folder or file with same name
  } else {
    console.log("success!");
  }
});

How to write to file in Ruby?

You can use the short version:

File.write('/path/to/file', 'Some glorious content')

It returns the length written; see ::write for more details and options.

To append to the file, if it already exists, use:

File.write('/path/to/file', 'Some glorious content', mode: 'a')

'MOD' is not a recognized built-in function name

If using JDBC driver you may use function escape sequence like this:

select {fn MOD(5, 2)}
#Result 1

select  mod(5, 2)
#SQL Error [195] [S00010]: 'mod' is not a recognized built-in function name.

How to compare only date in moment.js

Meanwhile you can use the isSameOrAfter method:

moment('2010-10-20').isSameOrAfter('2010-10-20', 'day');

Docs: https://momentjs.com/docs/#/query/is-same-or-after/

Unable to copy ~/.ssh/id_rsa.pub

In case you are trying to use xclip on remote host just add -X to your ssh command

ssh user@host -X

More detailed information can be found here : https://askubuntu.com/a/305681

How to render pdfs using C#

Google has open sourced its excellent PDF rendering engine - PDFium - that it wrote with Foxit Software.

There is a C# nuget package called PdfiumViewer which gives a C# wrapper around PDFium and allows PDFs to be displayed and printed.

I have used it and was very impressed with the quality of the rendering.


PDFium works directly with streams so it doesn't require any data to be written to disk.

This is my example from a WinForms app

    public void LoadPdf(byte[] pdfBytes)
    {
        var stream = new MemoryStream(pdfBytes);
        LoadPdf(stream)
    }

    public void LoadPdf(Stream stream)
    {
        // Create PDF Document
        var pdfDocument = PdfDocument.Load(stream);

        // Load PDF Document into WinForms Control
        pdfRenderer.Load(pdfDocument);
    }

Edit: To get the pdfRenderer control in WinForm: Add the PdfiumViewer NuGet package to the project; open the projects packages folder in Windows Explorer and drag the PdfiumViewer.dll file onto the Toolbox window; A control called PdfRenderer will be available to add:

Adding PdfRenderer control to WinForms

File Upload without Form

You can use FormData to submit your data by a POST request. Here is a simple example:

var myFormData = new FormData();
myFormData.append('pictureFile', pictureInput.files[0]);

$.ajax({
  url: 'upload.php',
  type: 'POST',
  processData: false, // important
  contentType: false, // important
  dataType : 'json',
  data: myFormData
});

You don't have to use a form to make an ajax request, as long as you know your request setting (like url, method and parameters data).

How to convert InputStream to FileInputStream

You need something like:

    URL resource = this.getClass().getResource("/path/to/resource.res");
    File is = null;
    try {
        is = new File(resource.toURI());
    } catch (URISyntaxException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    try {
        FileInputStream input = new FileInputStream(is);
    } catch (FileNotFoundException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

But it will work only within your IDE, not in runnable JAR. I had same problem explained here.

Java: String - add character n-times

You are able to do this using Java 8 stream APIs. The following code creates the string "cccc" from "c":

String s = "c";
int n = 4;
String sRepeated = IntStream.range(0, n).mapToObj(i -> s).collect(Collectors.joining(""));

Install a Python package into a different directory using pip?

Installing a Python package often only includes some pure Python files. If the package includes data, scripts and or executables, these are installed in different directories from the pure Python files.

Assuming your package has no data/scripts/executables, and that you want your Python files to go into /python/packages/package_name (and not some subdirectory a few levels below /python/packages as when using --prefix), you can use the one time command:

pip install --install-option="--install-purelib=/python/packages" package_name

If you want all (or most) of your packages to go there, you can edit your ~/.pip/pip.conf to include:

[install]
install-option=--install-purelib=/python/packages

That way you can't forget about having to specify it again and again.

Any excecutables/data/scripts included in the package will still go to their default places unless you specify addition install options (--prefix/--install-data/--install-scripts, etc., for details look at the custom installation options).

Cannot connect to the Docker daemon at unix:/var/run/docker.sock. Is the docker daemon running?

enter image description here

I just simply forget running the Docker Desktop in my mac, after running Docker Desktop, you will be good to go.

Netbeans how to set command line arguments in Java

For a Maven project using NetBeans 8.x:

  1. Click Run >> Set Project Configuration >> Customise
  2. Select Actions
  3. Select Run file via main()
  4. Set name/value pair to include the arguments.
  5. Click OK

An example name/value pair might resemble:

javax.persistence.jdbc.password=PASSWORD

Then run your project:

  1. Open and focus the Java class that includes main(...).
  2. Press F6 to run the program.

The command line parameters should appear in the Run window.

Note that to obtain the value form with the program, use System.getProperty().

Additional actions for Test file, Run project, and other ways to run the application can have arguments defined. Repeat the steps above for the different actions to accomplish this task.

Round to 5 (or other number) in Python

No one actually wrote this yet I guess but you can do:

round(12, -1) --> 10
round(18, -1) --> 20

How can I access a hover state in reactjs?

I know the accepted answer is great but for anyone who is looking for a hover like feel you can use setTimeout on mouseover and save the handle in a map (of let's say list ids to setTimeout Handle). On mouseover clear the handle from setTimeout and delete it from the map

onMouseOver={() => this.onMouseOver(someId)}
onMouseOut={() => this.onMouseOut(someId)

And implement the map as follows:

onMouseOver(listId: string) {
  this.setState({
    ... // whatever
  });

  const handle = setTimeout(() => {
    scrollPreviewToComponentId(listId);
  }, 1000); // Replace 1000ms with any time you feel is good enough for your hover action
  this.hoverHandleMap[listId] = handle;
}

onMouseOut(listId: string) {
  this.setState({
    ... // whatever
  });

  const handle = this.hoverHandleMap[listId];
  clearTimeout(handle);
  delete this.hoverHandleMap[listId];
}

And the map is like so,

hoverHandleMap: { [listId: string]: NodeJS.Timeout } = {};

I prefer onMouseOver and onMouseOut because it also applies to all the children in the HTMLElement. If this is not required you may use onMouseEnter and onMouseLeave respectively.

Should you always favor xrange() over range()?

range() returns a list, xrange() returns an xrange object.

xrange() is a bit faster, and a bit more memory efficient. But the gain is not very large.

The extra memory used by a list is of course not just wasted, lists have more functionality (slice, repeat, insert, ...). Exact differences can be found in the documentation. There is no bonehard rule, use what is needed.

Python 3.0 is still in development, but IIRC range() will very similar to xrange() of 2.X and list(range()) can be used to generate lists.

Iterating through a List Object in JSP

you can read empList directly in forEach tag.Try this

 <table>
       <c:forEach items="${sessionScope.empList}" var="employee">
            <tr>
                <td>Employee ID: <c:out value="${employee.eid}"/></td>
                <td>Employee Pass: <c:out value="${employee.ename}"/></td>  
            </tr>
        </c:forEach>
    </table>

Codeigniter : calling a method of one controller from other

I agree that the way to do is to redirect to the new controller in usual cases.

I came across a use case where I needed to display the same page to 2 different kind of users (backend user previewing the page of a frontend user) so in my opinion what I needed was genuinely to call the frontend controller from the backend controller.

I solved the problem by making the frontend method static and wrapping it in another method. Hope it helps!

//==========
// Frontend
//==========
function profile()
{
   //Access check

   //Get profile id
   $id = get_user_id();

   return self::_profile($id);
}

static function _profile($id)
{
   $CI = &get_instance();
   //Prepare page
   //Load view
}

//==========
// Backend
//==========
function preview_profile($id)
{
   $this->load->file('controllers/frontend.php', false);

   Frontend::_profile($id);
}

Replace a string in a file with nodejs

Expanding on @Sanbor's answer, the most efficient way to do this is to read the original file as a stream, and then also stream each chunk into a new file, and then lastly replace the original file with the new file.

async function findAndReplaceFile(regexFindPattern, replaceValue, originalFile) {
  const updatedFile = `${originalFile}.updated`;

  return new Promise((resolve, reject) => {
    const readStream = fs.createReadStream(originalFile, { encoding: 'utf8', autoClose: true });
    const writeStream = fs.createWriteStream(updatedFile, { encoding: 'utf8', autoClose: true });

    // For each chunk, do the find & replace, and write it to the new file stream
    readStream.on('data', (chunk) => {
      chunk = chunk.toString().replace(regexFindPattern, replaceValue);
      writeStream.write(chunk);
    });

    // Once we've finished reading the original file...
    readStream.on('end', () => {
      writeStream.end(); // emits 'finish' event, executes below statement
    });

    // Replace the original file with the updated file
    writeStream.on('finish', async () => {
      try {
        await _renameFile(originalFile, updatedFile);
        resolve();
      } catch (error) {
        reject(`Error: Error renaming ${originalFile} to ${updatedFile} => ${error.message}`);
      }
    });

    readStream.on('error', (error) => reject(`Error: Error reading ${originalFile} => ${error.message}`));
    writeStream.on('error', (error) => reject(`Error: Error writing to ${updatedFile} => ${error.message}`));
  });
}

async function _renameFile(oldPath, newPath) {
  return new Promise((resolve, reject) => {
    fs.rename(oldPath, newPath, (error) => {
      if (error) {
        reject(error);
      } else {
        resolve();
      }
    });
  });
}

// Testing it...
(async () => {
  try {
    await findAndReplaceFile(/"some regex"/g, "someReplaceValue", "someFilePath");
  } catch(error) {
    console.log(error);
  }
})()

Add Variables to Tuple

Tuples are immutable; you can't change which variables they contain after construction. However, you can concatenate or slice them to form new tuples:

a = (1, 2, 3)
b = a + (4, 5, 6)  # (1, 2, 3, 4, 5, 6)
c = b[1:]  # (2, 3, 4, 5, 6)

And, of course, build them from existing values:

name = "Joe"
age = 40
location = "New York"
joe = (name, age, location)

Java Regex Replace with Capturing Group

How about:

if (regexMatcher.find()) {
    resultString = regexMatcher.replaceAll(
            String.valueOf(3 * Integer.parseInt(regexMatcher.group(1))));
}

To get the first match, use #find(). After that, you can use #group(1) to refer to this first match, and replace all matches by the first maches value multiplied by 3.

And in case you want to replace each match with that match's value multiplied by 3:

    Pattern p = Pattern.compile("(\\d{1,2})");
    Matcher m = p.matcher("12 54 1 65");
    StringBuffer s = new StringBuffer();
    while (m.find())
        m.appendReplacement(s, String.valueOf(3 * Integer.parseInt(m.group(1))));
    System.out.println(s.toString());

You may want to look through Matcher's documentation, where this and a lot more stuff is covered in detail.

Jquery validation plugin - TypeError: $(...).validate is not a function

You didn't include the base jQuery Validation library:

<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.js"></script>

Put that before the additional methods library. (BTW this is a hosted version, download your own if you want)

Oracle: is there a tool to trace queries, like Profiler for sql server?

You can use The Oracle Enterprise Manager to monitor the active sessions, with the query that is being executed, its execution plan, locks, some statistics and even a progress bar for the longer tasks.

See: http://download.oracle.com/docs/cd/B10501_01/em.920/a96674/db_admin.htm#1013955

Go to Instance -> sessions and watch the SQL Tab of each session.

There are other ways. Enterprise manager just puts with pretty colors what is already available in specials views like those documented here: http://www.oracle.com/pls/db92/db92.catalog_views?remark=homepage

And, of course you can also use Explain PLAN FOR, TRACE tool and tons of other ways of instrumentalization. There are some reports in the enterprise manager for the top most expensive SQL Queries. You can also search recent queries kept on the cache.

How do I make the method return type generic?

As you said passing a class would be OK, you could write this:

public <T extends Animal> T callFriend(String name, Class<T> clazz) {
   return (T) friends.get(name);
}

And then use it like this:

jerry.callFriend("spike", Dog.class).bark();
jerry.callFriend("quacker", Duck.class).quack();

Not perfect, but this is pretty much as far as you get with Java generics. There is a way to implement Typesafe Heterogenous Containers (THC) using Super Type Tokens, but that has its own problems again.

List of Java processes

To know the list of java running on the linux machine. ps -e | grep java

Difference between a virtual function and a pure virtual function

A pure virtual function is usually not (but can be) implemented in a base class and must be implemented in a leaf subclass.

You denote that fact by appending the "= 0" to the declaration, like this:

class AbstractBase
{
    virtual void PureVirtualFunction() = 0;
}

Then you cannot declare and instantiate a subclass without it implementing the pure virtual function:

class Derived : public AbstractBase
{
    virtual void PureVirtualFunction() override { }
}

By adding the override keyword, the compiler will ensure that there is a base class virtual function with the same signature.

Xcode 10 Error: Multiple commands produce

In my case, Build archive error vs Xcode10

-1: Multiple commands produce '/Users/kk/Library/Developer/Xcode/DerivedData/react_carday_app-hjahojxsbvmmiyaklrhhuqljdfwv/Build/Intermediates.noindex/ArchiveIntermediates/react_carday_app/IntermediateBuildFilesPath/UninstalledProducts/iphoneos/libyoga.a': 1) Target 'yoga' has a command with output '/Users/kk/Library/Developer/Xcode/DerivedData/react_carday_app-hjahojxsbvmmiyaklrhhuqljdfwv/Build/Intermediates.noindex/ArchiveIntermediates/react_carday_app/IntermediateBuildFilesPath/UninstalledProducts/iphoneos/libyoga.a' 2) Target 'yoga' has a command with output '/Users/kk/Library/Developer/Xcode/DerivedData/react_carday_app-hjahojxsbvmmiyaklrhhuqljdfwv/Build/Intermediates.noindex/ArchiveIntermediates/react_carday_app/IntermediateBuildFilesPath/UninstalledProducts/iphoneos/libyoga.a'

There should something like bellow in your Podfile

post_install do |installer|
  installer.pods_project.targets.each do |target|
    if target.name == "React"
      target.remove_from_project
    end

    if target.name == "yoga"
      target.remove_from_project
    end
  end
end

and then run pod install

How to write to files using utl_file in oracle

Here's an example of code which uses the UTL_FILE.PUT and UTL_FILE.PUT_LINE calls:

declare 
  fHandle  UTL_FILE.FILE_TYPE;
begin
  fHandle := UTL_FILE.FOPEN('my_directory', 'test_file', 'w');

  UTL_FILE.PUT(fHandle, 'This is the first line');
  UTL_FILE.PUT(fHandle, 'This is the second line');
  UTL_FILE.PUT_LINE(fHandle, 'This is the third line');

  UTL_FILE.FCLOSE(fHandle);
EXCEPTION
  WHEN OTHERS THEN
    DBMS_OUTPUT.PUT_LINE('Exception: SQLCODE=' || SQLCODE || '  SQLERRM=' || SQLERRM);
    RAISE;
end;

The output from this looks like:

This is the first lineThis is the second lineThis is the third line

Share and enjoy.

Fixed Table Cell Width

table td 
{
  table-layout:fixed;
  width:20px;
  overflow:hidden;
  word-wrap:break-word;
}

Deep-Learning Nan loss reasons

I'd like to plug in some (shallow) reasons I have experienced as follows:

  1. we may have updated our dictionary(for NLP tasks) but the model and the prepared data used a different one.
  2. we may have reprocessed our data(binary tf_record) but we loaded the old model. The reprocessed data may conflict with the previous one.
  3. we may should train the model from scratch but we forgot to delete the checkpoints and the model loaded the latest parameters automatically.

Hope that helps.

Practical uses for AtomicInteger

The primary use of AtomicInteger is when you are in a multithreaded context and you need to perform thread safe operations on an integer without using synchronized. The assignation and retrieval on the primitive type int are already atomic but AtomicInteger comes with many operations which are not atomic on int.

The simplest are the getAndXXX or xXXAndGet. For instance getAndIncrement() is an atomic equivalent to i++ which is not atomic because it is actually a short cut for three operations: retrieval, addition and assignation. compareAndSet is very useful to implements semaphores, locks, latches, etc.

Using the AtomicInteger is faster and more readable than performing the same using synchronization.

A simple test:

public synchronized int incrementNotAtomic() {
    return notAtomic++;
}

public void performTestNotAtomic() {
    final long start = System.currentTimeMillis();
    for (int i = 0 ; i < NUM ; i++) {
        incrementNotAtomic();
    }
    System.out.println("Not atomic: "+(System.currentTimeMillis() - start));
}

public void performTestAtomic() {
    final long start = System.currentTimeMillis();
    for (int i = 0 ; i < NUM ; i++) {
        atomic.getAndIncrement();
    }
    System.out.println("Atomic: "+(System.currentTimeMillis() - start));
}

On my PC with Java 1.6 the atomic test runs in 3 seconds while the synchronized one runs in about 5.5 seconds. The problem here is that the operation to synchronize (notAtomic++) is really short. So the cost of the synchronization is really important compared to the operation.

Beside atomicity AtomicInteger can be use as a mutable version of Integer for instance in Maps as values.

Add data dynamically to an Array

Fastest way I think

       $newArray = array();

for($count == 0;$row = mysql_fetch_assoc($getResults);$count++)
    {
    foreach($row as $key => $value)
    { 
    $newArray[$count]{$key} = $row[$key];
    }
}

delete vs delete[] operators in C++

The operators delete and delete [] are used respectively to destroy the objects created with new and new[], returning to the allocated memory left available to the compiler's memory manager.

Objects created with new must necessarily be destroyed with delete, and that the arrays created with new[] should be deleted with delete[].

Mockito: List Matchers with generics

In addition to anyListOf above, you can always specify generics explicitly using this syntax:

when(mock.process(Matchers.<List<Bar>>any(List.class)));

Java 8 newly allows type inference based on parameters, so if you're using Java 8, this may work as well:

when(mock.process(Matchers.any()));

Remember that neither any() nor anyList() will apply any checks, including type or null checks. In Mockito 2.x, any(Foo.class) was changed to mean "any instanceof Foo", but any() still means "any value including null".

NOTE: The above has switched to ArgumentMatchers in newer versions of Mockito, to avoid a name collision with org.hamcrest.Matchers. Older versions of Mockito will need to keep using org.mockito.Matchers as above.

C# switch statement limitations - why?

Mostly, those restrictions are in place because of language designers. The underlying justification may be compatibility with languange history, ideals, or simplification of compiler design.

The compiler may (and does) choose to:

  • create a big if-else statement
  • use a MSIL switch instruction (jump table)
  • build a Generic.Dictionary<string,int32>, populate it on first use, and call Generic.Dictionary<>::TryGetValue() for a index to pass to a MSIL switch instruction (jump table)
  • use a combination of if-elses & MSIL "switch" jumps

The switch statement IS NOT a constant time branch. The compiler may find short-cuts (using hash buckets, etc), but more complicated cases will generate more complicated MSIL code with some cases branching out earlier than others.

To handle the String case, the compiler will end up (at some point) using a.Equals(b) (and possibly a.GetHashCode() ). I think it would be trival for the compiler to use any object that satisfies these constraints.

As for the need for static case expressions... some of those optimisations (hashing, caching, etc) would not be available if the case expressions weren't deterministic. But we've already seen that sometimes the compiler just picks the simplistic if-else-if-else road anyway...

Edit: lomaxx - Your understanding of the "typeof" operator is not correct. The "typeof" operator is used to obtain the System.Type object for a type (nothing to do with its supertypes or interfaces). Checking run-time compatibility of an object with a given type is the "is" operator's job. The use of "typeof" here to express an object is irrelevant.

Add / remove input field dynamically with jQuery

You can try this:

<input type="hidden" name="image" id="input-image{{ image_row }}" />

inputt= '<input type="hidden" name="product_image' value="somevalue">

$("#input-image"+row).remove().append(inputt);

How to prevent XSS with HTML/PHP?

Many frameworks help handle XSS in various ways. When rolling your own or if there's some XSS concern, we can leverage filter_input_array (available in PHP 5 >= 5.2.0, PHP 7.) I typically will add this snippet to my SessionController, because all calls go through there before any other controller interacts with the data. In this manner, all user input gets sanitized in 1 central location. If this is done at the beginning of a project or before your database is poisoned, you shouldn't have any issues at time of output...stops garbage in, garbage out.

/* Prevent XSS input */
$_GET   = filter_input_array(INPUT_GET, FILTER_SANITIZE_STRING);
$_POST  = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
/* I prefer not to use $_REQUEST...but for those who do: */
$_REQUEST = (array)$_POST + (array)$_GET + (array)$_REQUEST;

The above will remove ALL HTML & script tags. If you need a solution that allows safe tags, based on a whitelist, check out HTML Purifier.


If your database is already poisoned or you want to deal with XSS at time of output, OWASP recommends creating a custom wrapper function for echo, and using it EVERYWHERE you output user-supplied values:

//xss mitigation functions
function xssafe($data,$encoding='UTF-8')
{
   return htmlspecialchars($data,ENT_QUOTES | ENT_HTML401,$encoding);
}
function xecho($data)
{
   echo xssafe($data);
}

CSS Image size, how to fill, but not stretch?

Building off of @Dominic Green's answer using jQuery, here is a solution that should work for images that are either wider than they are high or higher than they are wide.

http://jsfiddle.net/grZLR/4/

There is probably a more elegant way of doing the JavaScript, but this does work.

function myTest() {
  var imgH = $("#my-img").height();
  var imgW = $("#my-img").width();
  if(imgW > imgH) {
    $(".container img").css("height", "100%");
    var conWidth = $(".container").width();
    var imgWidth = $(".container img").width();
    var gap = (imgWidth - conWidth)/2;
    $(".container img").css("margin-left", -gap);
  } else {
    $(".container img").css("width", "100%");
    var conHeight = $(".container").height();
    var imgHeight = $(".container img").height();
    var gap = (imgHeight - conHeight)/2;
    $(".container img").css("margin-top", -gap);
  }
}
myTest();

Iterate through DataSet

Just loop...

foreach(var table in DataSet1.Tables) {
    foreach(var col in table.Columns) {
       ...
    }
    foreach(var row in table.Rows) {
        object[] values = row.ItemArray;
        ...
    }
}

Read from a gzip file in python

Try gzipping some data through the gzip libary like this...

import gzip
content = "Lots of content here"
f = gzip.open('Onlyfinnaly.log.gz', 'wb')
f.write(content)
f.close()

... then run your code as posted ...

import gzip
f=gzip.open('Onlyfinnaly.log.gz','rb')
file_content=f.read()
print file_content

This method worked for me as for some reason the gzip library fails to read some files.

How to check if a user is logged in (how to properly use user.is_authenticated)?

For Django 2.0+ versions use:

    if request.auth:
       # Only for authenticated users.

For more info visit https://www.django-rest-framework.org/api-guide/requests/#auth

request.user.is_authenticated() has been removed in Django 2.0+ versions.

ldconfig error: is not a symbolic link

You need to include the path of the libraries inside /etc/ld.so.conf, and rerun ldconfig to upate the list

Other possibility is to include in the env variable LD_LIBRARY_PATH the path to your library, and rerun the executable.

check the symbolic links if they point to a valid library ...

You can add the path directly in /etc/ld.so.conf, without include...

run ldconfig -p to see whether your library is well included in the cache.

MySQL Data - Best way to implement paging?

This tutorial shows a great way to do pagination. Efficient Pagination Using MySQL

In short, avoid to use OFFSET or large LIMIT

Converting an object to a string

There is actually one easy option (for recent browsers and Node.js) missing in the existing answers:

console.log('Item: %o', o);

I would prefer this as JSON.stringify() has certain limitations (e.g. with circular structures).

How to set ID using javascript?

Do you mean like this?

var hello1 = document.getElementById('hello1');
hello1.id = btoa(hello1.id);

To further the example, say you wanted to get all elements with the class 'abc'. We can use querySelectorAll() to accomplish this:

HTML

<div class="abc"></div>
<div class="abc"></div>

JS

var abcElements = document.querySelectorAll('.abc');

// Set their ids
for (var i = 0; i < abcElements.length; i++)
    abcElements[i].id = 'abc-' + i;

This will assign the ID 'abc-<index number>' to each element. So it would come out like this:

<div class="abc" id="abc-0"></div>
<div class="abc" id="abc-1"></div>

To create an element and assign an id we can use document.createElement() and then appendChild().

var div = document.createElement('div');
div.id = 'hello1';

var body = document.querySelector('body');
body.appendChild(div);

Update

You can set the id on your element like this if your script is in your HTML file.

<input id="{{str(product["avt"]["fto"])}}" >
<span>New price :</span>
<span class="assign-me">

<script type="text/javascript">
    var s = document.getElementsByClassName('assign-me')[0];
    s.id = btoa({{str(produit["avt"]["fto"])}});
</script>

Your requirements still aren't 100% clear though.

Populating spinner directly in the layout xml

I'm not sure about this, but give it a shot.

In your strings.xml define:

<string-array name="array_name">
<item>Array Item One</item>
<item>Array Item Two</item>
<item>Array Item Three</item>
</string-array>

In your layout:

<Spinner 
        android:id="@+id/spinner"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:drawSelectorOnTop="true"
        android:entries="@array/array_name"
    />

I've heard this doesn't always work on the designer, but it compiles fine.

Hadoop cluster setup - java.net.ConnectException: Connection refused

hduser@marta-komputer:/usr/local/hadoop$ jps

11696 ResourceManager

11842 NodeManager

11171 NameNode

11523 SecondaryNameNode

12167 Jps

Where is your DataNode? Connection refused problem might also be due to no active DataNode. Check datanode logs for issues.

UPDATED:

For this error:

15/03/01 00:59:34 INFO client.RMProxy: Connecting to ResourceManager at /0.0.0.0:8032 java.net.ConnectException: Call From marta-komputer.home/192.168.1.8 to marta-komputer:9000 failed on connection exception: java.net.ConnectException: Connection refused; For more details see: http://wiki.apache.org/hadoop/ConnectionRefused

Add these lines in yarn-site.xml:

<property>
<name>yarn.resourcemanager.address</name>
<value>192.168.1.8:8032</value>
</property>
<property>
<name>yarn.resourcemanager.scheduler.address</name>
<value>192.168.1.8:8030</value>
</property>
<property>
<name>yarn.resourcemanager.resource-tracker.address</name>
<value>192.168.1.8:8031</value>
</property>

Restart the hadoop processes.

How to update-alternatives to Python 3 without breaking apt?

Somehow python 3 came back (after some updates?) and is causing big issues with apt updates, so I've decided to remove python 3 completely from the alternatives:

root:~# python -V
Python 3.5.2

root:~# update-alternatives --config python
There are 2 choices for the alternative python (providing /usr/bin/python).

  Selection    Path                Priority   Status
------------------------------------------------------------
* 0            /usr/bin/python3.5   3         auto mode
  1            /usr/bin/python2.7   2         manual mode
  2            /usr/bin/python3.5   3         manual mode


root:~# update-alternatives --remove python /usr/bin/python3.5

root:~# update-alternatives --config python
There is 1 choice for the alternative python (providing /usr/bin/python).

    Selection    Path                Priority   Status
------------------------------------------------------------
  0            /usr/bin/python2.7   2         auto mode
* 1            /usr/bin/python2.7   2         manual mode

Press <enter> to keep the current choice[*], or type selection number: 0


root:~# python -V
Python 2.7.12

root:~# update-alternatives --config python
There is only one alternative in link group python (providing /usr/bin/python): /usr/bin/python2.7
Nothing to configure.

Display TIFF image in all web browser

I found this resource that details the various methods: How to embed TIFF files in HTML documents

As mentioned, it will very much depend on browser support for the format. Viewing that page in Chrome on Windows didn't display any of the images.

It would also be helpful if you posted the code you've tried already.

SyntaxError: expected expression, got '<'

The main idea is that somehow HTML has been returned instead of Javascript.

The reason may be:

  • wrong paths
  • assets itself

It may be caused by wrong assets precompilation. In my case, I caught this error because of wrong encoding.

When I opened my application.js I saw application error Encoding::UndefinedConversionError at /assets/application.js

There was full backtrace of error formatted as HTML instead of Javasript.

Make sure that assets had been successfully precompiled.

How to show soft-keyboard when edittext is focused

call requestFocus() method on editText in onCrete() method of activity() and call clearFocus() method on the same editText when click done in keypad.

FFmpeg: How to split video efficiently?

Here's a useful script, it helps you split automatically: A script for splitting videos using ffmpeg

#!/bin/bash
 
# Written by Alexis Bezverkhyy <[email protected]> in 2011
# This is free and unencumbered software released into the public domain.
# For more information, please refer to <http://unlicense.org/>
 
function usage {
        echo "Usage : ffsplit.sh input.file chunk-duration [output-filename-format]"
        echo -e "\t - input file may be any kind of file reconginzed by ffmpeg"
        echo -e "\t - chunk duration must be in seconds"
        echo -e "\t - output filename format must be printf-like, for example myvideo-part-%04d.avi"
        echo -e "\t - if no output filename format is given, it will be computed\
 automatically from input filename"
}
 
IN_FILE="$1"
OUT_FILE_FORMAT="$3"
typeset -i CHUNK_LEN
CHUNK_LEN="$2"
 
DURATION_HMS=$(ffmpeg -i "$IN_FILE" 2>&1 | grep Duration | cut -f 4 -d ' ')
DURATION_H=$(echo "$DURATION_HMS" | cut -d ':' -f 1)
DURATION_M=$(echo "$DURATION_HMS" | cut -d ':' -f 2)
DURATION_S=$(echo "$DURATION_HMS" | cut -d ':' -f 3 | cut -d '.' -f 1)
let "DURATION = ( DURATION_H * 60 + DURATION_M ) * 60 + DURATION_S"
 
if [ "$DURATION" = '0' ] ; then
        echo "Invalid input video"
        usage
        exit 1
fi
 
if [ "$CHUNK_LEN" = "0" ] ; then
        echo "Invalid chunk size"
        usage
        exit 2
fi
 
if [ -z "$OUT_FILE_FORMAT" ] ; then
        FILE_EXT=$(echo "$IN_FILE" | sed 's/^.*\.\([a-zA-Z0-9]\+\)$/\1/')
        FILE_NAME=$(echo "$IN_FILE" | sed 's/^\(.*\)\.[a-zA-Z0-9]\+$/\1/')
        OUT_FILE_FORMAT="${FILE_NAME}-%03d.${FILE_EXT}"
        echo "Using default output file format : $OUT_FILE_FORMAT"
fi
 
N='1'
OFFSET='0'
let 'N_FILES = DURATION / CHUNK_LEN + 1'
 
while [ "$OFFSET" -lt "$DURATION" ] ; do
        OUT_FILE=$(printf "$OUT_FILE_FORMAT" "$N")
        echo "writing $OUT_FILE ($N/$N_FILES)..."
        ffmpeg -i "$IN_FILE" -vcodec copy -acodec copy -ss "$OFFSET" -t "$CHUNK_LEN" "$OUT_FILE"
        let "N = N + 1"
        let "OFFSET = OFFSET + CHUNK_LEN"
done

Failed to resolve: com.google.android.gms:play-services in IntelliJ Idea with gradle

I just replaced version 11.2.0 with 11.0.0 and then it seemed to work fine, so that had to mean that 11.2.0 wasn't included with the latest Android SDK.

So, after struggling with all the available scattered documentation, I reached this document by pure chance (I guess it is not indexed high enough by Google): https://developers.google.com/android/guides/releases

I quote from there:

Highlights from the Google Play services 11.2 release. Google Play services dependencies are now available via maven.google.com

Now, even when that shouldn't necessarily mean that they are not available with the downloaded SDK anymore, it seems that this is actually the case.

Anyway, adding google() to my build.gradle didn't work (not found, undefined, or whatever...), so I used a different approach that I found in this document referenced from the previous one:

https://developer.android.com/studio/build/dependencies.html#google-maven

I modified my build.gradle file adding that line to allprojects/repositories, as in:

allprojects {
...
    repositories {
...
        maven { url "https://maven.google.com/"}
    }
}

And then also in the android section in the same build.gradle file:

project(":android") {
...
    dependencies {
...
        compile 'com.google.android.gms:play-services-ads:11.2.0'
    }
}

Those two lines were enough to make Gradle sync without problems. I didn't need to add any plugins apart from the ones that are already added in my libGDX project by default.

After that, I got a few different errors, but none about Gradle or dependencies. In a brief, JFTR:

First, I had a minSdkVersion of 8. Solved by raising it to 14. I think I could live without supporting all those devices below 14.

Second, I had problems with the dex upper limit of references. I've never faced this problem before, but maybe you've already noticed the solution I used: instead of compiling the whole 'com.google.android.gms:play-services' I used only 'com.google.android.gms:play-services-ads' that's the API I'm actually interested right now. For those other particular cases where a solution like this may not be useful, this document could provide some better insight: https://developer.android.com/studio/build/multidex.html

Third, even after that I got this "jumbo" thing problem described and answered here: https://stackoverflow.com/a/26248495/1160360

And that's it. As of now, everything builds and my game does finally shows those Admob banners.

I've spent hours with this, thought, which makes me wonder if all these building automation systems we are using lately are worth the extra load they add.

I mean, the first time I had to add Admob to an app five years ago or so, I just had to download a .jar file and put it on a directory on my project. It was pretty obvious and the whole process, from googling "how to setup Admob in my android project" to have my app showing an Admob banner took me just a few minutes. I'm gonna leave it here, since this is not the place for such kind of debate.

Nonetheless, I hope my own experience is useful for someone else further.

Parsing boolean values with argparse

oneliner:

parser.add_argument('--is_debug', default=False, type=lambda x: (str(x).lower() == 'true'))

python ignore certificate validation urllib2

The easiest way:

python 2

import urllib2, ssl

request = urllib2.Request('https://somedomain.co/')
response = urllib2.urlopen(request, context=ssl._create_unverified_context())

python 3

from urllib.request import urlopen
import ssl

response = urlopen('https://somedomain.co', context=ssl._create_unverified_context())

XPath contains(text(),'some string') doesn't work when used with node with more than one Text subnode

[contains(text(),'')] only returns true or false. It won't return any element results.

How to check if a String contains only ASCII?

try this:

for (char c: string.toCharArray()){
  if (((int)c)>127){
    return false;
  } 
}
return true;

Disable beep of Linux Bash on Windows 10

@Andrea Tulimiero 's answer works for local, but when you ssh to a remote server, the beep turns on again. My suggestion is to disable from the Windows 10 taskbar. There is volume mixer in the right bottom corner, which works for me.

Why is using a wild card with a Java import statement bad?

  1. It helps to identify classname conflicts: two classes in different packages that have the same name. This can be masked with the * import.
  2. It makes dependencies explicit, so that anyone who has to read your code later knows what you meant to import and what you didn't mean to import.
  3. It can make some compilation faster because the compiler doesn't have to search the whole package to identify depdencies, though this is usually not a huge deal with modern compilers.
  4. The inconvenient aspects of explicit imports are minimized with modern IDEs. Most IDEs allow you to collapse the import section so it's not in the way, automatically populate imports when needed, and automatically identify unused imports to help clean them up.

Most places I've worked that use any significant amount of Java make explicit imports part of the coding standard. I sometimes still use * for quick prototyping and then expand the import lists (some IDEs will do this for you as well) when productizing the code.

How to update data in one table from corresponding data in another table in SQL Server 2005

this works wonders - no its turn to call this procedure form code with DataTable with schema exactly matching the custType create table customer ( id int identity(1,1) primary key, name varchar(50), cnt varchar(10) )

 create type custType as table
 (
 ctId int,
 ctName varchar(20)
 )

 insert into customer values('y1', 'c1')
 insert into customer values('y2', 'c2')
 insert into customer values('y3', 'c3')
 insert into customer values('y4', 'c4')
 insert into customer values('y5', 'c5')

 declare @ct as custType 
 insert @ct (ctid, ctName) values(3, 'y33'), (4, 'y44')
 exec multiUpdate @ct

 create Proc multiUpdate (@ct custType readonly) as begin
 update customer set  Name = t.ctName  from @ct t where t.ctId = customer.id
 end

public DataTable UpdateLevels(DataTable dt)
        {
            DataTable dtRet = new DataTable();
            using (SqlConnection con = new SqlConnection(datalayer.bimCS))
            {
                SqlCommand command = new SqlCommand();
                command.CommandText = "UpdateLevels";
                command.Parameters.Clear();
                command.CommandType = CommandType.StoredProcedure;
                command.Parameters.AddWithValue("@ct", dt).SqlDbType = SqlDbType.Structured;
                command.Connection = con;
                using (SqlDataAdapter dataAdapter = new SqlDataAdapter(command))
                {
                    dataAdapter.SelectCommand = command;
                    dataAdapter.Fill(dtRet);
                }
            }
}

How to exit git log or git diff

You're in the less program, which makes the output of git log scrollable.

Type q to exit this screen. Type h to get help.

If you don't want to read the output in a pager and want it to be just printed to the terminal define the environment variable GIT_PAGER to cat or set core.pager to cat (execute git config --global core.pager cat).

I am getting "java.lang.ClassNotFoundException: com.google.gson.Gson" error even though it is defined in my classpath

I was just having the same issue...

To resolve the problem (at least in my case) ensure you have included the lib folder in your bundle classpath:

Manifest-Version: 1.0
... 
Bundle-ClassPath: lib/gson-1.6.jar,
 .
...

Or if you want to include all jar's in the folder:

Bundle-ClassPath: lib/

You will still need to place the jar files on the java build path as shown above. Then your imported jar's should appear in the folder "Referenced Libraries"

laravel foreach loop in controller

Hi, this will throw an error:

foreach ($product->sku as $sku){ 
// Code Here
}

because you cannot loop a model with a specific column ($product->sku) from the table.
So you must loop on the whole model:

foreach ($product as $p) {
// code
}

Inside the loop you can retrieve whatever column you want just adding "->[column_name]"

foreach ($product as $p) {
echo $p->sku;
}

Have a great day

javascript how to create a validation error message without using alert

You need to stop the submission if an error occured:

HTML

<form name ="myform" onsubmit="return validation();"> 

JS

if (document.myform.username.value == "") {
     document.getElementById('errors').innerHTML="*Please enter a username*";
     return false;
}

How to access the request body when POSTing using Node.js and Express?

Try this:

response.write(JSON.stringify(request.body));

That will take the object which bodyParser has created for you and turn it back into a string and write it to the response. If you want the exact request body (with the same whitespace, etc), you will need data and end listeners attached to the request before and build up the string chunk by chunk as you can see in the json parsing source code from connect.

How to connect to remote Oracle DB with PL/SQL Developer?

The problem is not the TNS file, in PLSQL Developer, if you don't have the oracle installation, you need to provide the location of the OCI.DLL file.

In PLSQL DEV app go to Tools-Preferences-Oracle/connections-OCI Library.

In my case I put the next address C:\Oracle\InstantClient-win32-11.2.0.1.0\oci.dll.

If have Weblogic app installed, I didnt tried but if you want try to put the next location

C:\Oracle\Middleware\wlserver_10.3\server\adr.

Cannot use string offset as an array in php

I believe what are you asking about is a variable interpolation in PHP.

Let's do a simple fixture:

$obj = (object) array('foo' => array('bar'), 'property' => 'value');
$var = 'foo';

Now we have an object, where:

print_r($obj);

Will give output:

stdClass Object
    (
        [foo] => Array
            (
                [0] => bar
            )

        [property] => value
    )

And we have variable $var containing string "foo".

If you'll try to use:

$give_me_foo = $obj->$var[0];

Instead of:

$give_me_foo = $obj->foo[0];

You get "Cannot use string offset as an array [...]" error message as a result, because what you are trying to do, is in fact sending message $var[0] to object $obj. And - as you can see from fixture - there is no content of $var[0] defined. Variable $var is a string and not an array.

What you can do in this case is to use curly braces, which will assure that at first is called content of $var, and subsequently the rest of message-sent:

$give_me_foo = $obj->{$var}[0];

The result is "bar", as you would expect.

Simple calculations for working with lat/lon and km distance?

Thanks Jim Lewis for his great answer and I would like to illustrate this solution by my function in Swift:

func getRandomLocation(forLocation location: CLLocation, withOffsetKM offset: Double) -> CLLocation {
        let latDistance = (Double(arc4random()) / Double(UInt32.max)) * offset * 2.0 - offset
        let longDistanceMax = sqrt(offset * offset - latDistance * latDistance)
        let longDistance = (Double(arc4random()) / Double(UInt32.max)) * longDistanceMax * 2.0 - longDistanceMax

        let lat: CLLocationDegrees = location.coordinate.latitude + latDistance / 110.574
        let lng: CLLocationDegrees = location.coordinate.longitude + longDistance / (111.320 * cos(lat / .pi / 180))
        return CLLocation(latitude: lat, longitude: lng)
    }

In this function to convert distance I use following formulas:

latDistance / 110.574
longDistance / (111.320 * cos(lat / .pi / 180))

How could I create a function with a completion handler in Swift?

I'm a little confused about custom made completion handlers. In your example:

Say you have a download function to download a file from network,and want to be notified when download task has finished.

typealias CompletionHandler = (success:Bool) -> Void

func downloadFileFromURL(url: NSURL,completionHandler: CompletionHandler) {

    // download code.

    let flag = true // true if download succeed,false otherwise

    completionHandler(success: flag)
}

Your // download code will still be ran asynchronously. Why wouldn't the code go straight to your let flag = true and completion Handler(success: flag) without waiting for your download code to be finished?

Remove duplicates from an array of objects in JavaScript

_x000D_
_x000D_
var things = new Object();_x000D_
_x000D_
things.thing = new Array();_x000D_
_x000D_
things.thing.push({place:"here",name:"stuff"});_x000D_
things.thing.push({place:"there",name:"morestuff"});_x000D_
things.thing.push({place:"there",name:"morestuff"});_x000D_
console.log(things);_x000D_
function removeDuplicate(result, id) {_x000D_
    let duplicate = {};_x000D_
    return result.filter(ele => !duplicate[ele[id]] &&                   (duplicate[ele[id]] = true));_x000D_
}_x000D_
let resolverarray = removeDuplicate(things.thing,'place')_x000D_
console.log(resolverarray);
_x000D_
_x000D_
_x000D_

How to create a link to another PHP page

echo "<a href='index.php'>Index Page</a>";

if you wanna use html tag like anchor tag you have to put in echo

Python speed testing - Time Difference - milliseconds

Here is a custom function that mimic's Matlab's/Octave's tic toc functions.

Example of use:

time_var = time_me(); # get a variable with the current timestamp

... run operation ...

time_me(time_var); # print the time difference (e.g. '5 seconds 821.12314 ms')

Function :

def time_me(*arg):
    if len(arg) != 0: 
        elapsedTime = time.time() - arg[0];
        #print(elapsedTime);
        hours = math.floor(elapsedTime / (60*60))
        elapsedTime = elapsedTime - hours * (60*60);
        minutes = math.floor(elapsedTime / 60)
        elapsedTime = elapsedTime - minutes * (60);
        seconds = math.floor(elapsedTime);
        elapsedTime = elapsedTime - seconds;
        ms = elapsedTime * 1000;
        if(hours != 0):
            print ("%d hours %d minutes %d seconds" % (hours, minutes, seconds)) 
        elif(minutes != 0):
            print ("%d minutes %d seconds" % (minutes, seconds))
        else :
            print ("%d seconds %f ms" % (seconds, ms))
    else:
        #print ('does not exist. here you go.');
        return time.time()

Filtering DataSet

You can use DataTable.Select:

var strExpr = "CostumerID = 1 AND OrderCount > 2";
var strSort = "OrderCount DESC";

// Use the Select method to find all rows matching the filter.
foundRows = ds.Table[0].Select(strExpr, strSort);  

Or you can use DataView:

ds.Tables[0].DefaultView.RowFilter = strExpr;  

UPDATE I'm not sure why you want to have a DataSet returned. But I'd go with the following solution:

var dv = ds.Tables[0].DefaultView;
dv.RowFilter = strExpr;
var newDS = new DataSet();
var newDT = dv.ToTable();
newDS.Tables.Add(newDT);

Getting data from selected datagridview row and which event?

Simple solution would be as below. This is improvement of solution from vale.

private void dgMapTable_SelectionChanged(object sender, EventArgs e) 
{
    int active_map=0;
    if(dgMapTable.SelectedRows.Count>0)
        active_map = dgMapTable.SelectedRows[0].Index;
    // User code if required Process_ROW(active_map);
}

Note for other reader, for above code to work FullRowSelect selection mode for datagridview should be used. You may extend this to give message if more than two rows selected.

Get href attribute on jQuery

Very simply, use this as the context: http://api.jquery.com/jQuery/#selector-context

var a_href = $('div.cpt', this).find('h2 a').attr('href');

Which says, find 'div.cpt' only inside this

Adding a library/JAR to an Eclipse Android project

Go to build path in eclipse, then click order and export, then check the library/jar, and then click the up button to move it to the top of the list to compile it first.

Displaying splash screen for longer than default seconds

You can also use NSThread:

[NSThread sleepForTimeInterval:(NSTimeInterval)];

You can put this code in to first line of applicationDidFinishLaunching method.

For example, display default.png for 5 seconds.

- (void) applicationDidFinishLaunching:(UIApplication*)application
{
   [NSThread sleepForTimeInterval:5.0];
}

Code coverage with Mocha

You need an additional library for code coverage, and you are going to be blown away by how powerful and easy istanbul is. Try the following, after you get your mocha tests to pass:

npm install nyc

Now, simply place the command nyc in front of your existing test command, for example:

{
  "scripts": {
    "test": "nyc mocha"
  }
}

Why do I keep getting 'SVN: Working Copy XXXX locked; try performing 'cleanup'?

This type of problem can happen when you delete/move files around - in essence making changes to your directory structure. Subversion only checks for changes made in files already added to subversion, not changes made to the directory structure. Instead of using your OS's copy etc commands rather use svn copy etc. Please see http://svnbook.red-bean.com/en/1.7/svn.tour.cycle.html

Further, upon committing changes svn first stores a "summary" of changes in a todo list. Upon performing the svn operations in this todo list it locks the file to prevent other changes while these svn actions are performed. If the svn action is interrupted midway, say by a crash, the file will remain locked until svn could complete the actions in the todo list. This can be "reactivated" by using the svn cleanup command. Please see http://svnbook.red-bean.com/en/1.7/svn.tour.cleanup.html

jasmine: Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL

This error can also be caused by leaving out inject when initializing a service/factory or whatever. For example, it can be thrown by doing this:

var service;
beforeEach(function(_TestService_) {
    service = _TestService_;
});

To fix it just wrap the function with inject to properly retrieve the service:

var service;
beforeEach(inject(function(_TestService_) {
    service = _TestService_;
}));

C#: List All Classes in Assembly

I'd just like to add to Jon's example. To get a reference to your own assembly, you can use:

Assembly myAssembly = Assembly.GetExecutingAssembly();

System.Reflection namespace.

If you want to examine an assembly that you have no reference to, you can use either of these:

Assembly assembly = Assembly.ReflectionOnlyLoad(fullAssemblyName);
Assembly assembly = Assembly.ReflectionOnlyLoadFrom(fileName);

If you intend to instantiate your type once you've found it:

Assembly assembly = Assembly.Load(fullAssemblyName);
Assembly assembly = Assembly.LoadFrom(fileName);

See the Assembly class documentation for more information.

Once you have the reference to the Assembly object, you can use assembly.GetTypes() like Jon already demonstrated.

Initialise numpy array of unknown length

Build a Python list and convert that to a Numpy array. That takes amortized O(1) time per append + O(n) for the conversion to array, for a total of O(n).

    a = []
    for x in y:
        a.append(x)
    a = np.array(a)

How can I decrypt MySQL passwords

If a proper encryption method was used, it's not going to be possible to easily retrieve them.

Just reset them with new passwords.

Edit: The string looks like it is using PASSWORD():

UPDATE user SET password = PASSWORD("newpassword");

How to vertically align an image inside a div

Background image solution

I removed the image element altogether and set it as background of the div with a class of .frame

http://jsfiddle.net/URVKa/2/

This at least works fine on Internet Explorer 8, Firefox 6 and Chrome  13.

I checked, and this solution will not work to shrink images larger than 25 pixels height. There is a property called background-size which does set the size of the element, but it is CSS 3 which would conflict with Internet Explorer 7 requirements.

I would advice you to either redo your browser priorities and design for the best available browsers, or get some server-side code to resize the images if you'd want to use this solution.

Populate a Drop down box from a mySQL table in PHP

Since mysql_connect has been deprecated, connect and query instead with mysqli:

$mysqli = new mysqli("hostname","username","password","database_name");
$sqlSelect="SELECT your_fieldname FROM your_table";
$result = $mysqli -> query ($sqlSelect);

And then, if you have more than one option list with the same values on the same page, put the values in an array:

while ($row = mysqli_fetch_array($result)) {
    $rows[] = $row;
}

And then you can loop the array multiple times on the same page:

foreach ($rows as $row) {
    print "<option value='" . $row['your_fieldname'] . "'>" . $row['your_fieldname'] . "</option>";
}

how to activate a textbox if I select an other option in drop down box

Simply

<select id = 'color2'
        name = 'color'
        onchange = "if ($('#color2').val() == 'others') {
                      $('#color').show();
                    } else {
                      $('#color').hide();
                    }">
  <option value="red">RED</option>
  <option value="blue">BLUE</option>
  <option value="others">others</option>
</select>

<input type = 'text'
       name = 'color'
       id = 'color' />

edit: requires JQuery plugin

java.nio.file.Path for a classpath resource

It turns out you can do this, with the help of the built-in Zip File System provider. However, passing a resource URI directly to Paths.get won't work; instead, one must first create a zip filesystem for the jar URI without the entry name, then refer to the entry in that filesystem:

static Path resourceToPath(URL resource)
throws IOException,
       URISyntaxException {

    Objects.requireNonNull(resource, "Resource URL cannot be null");
    URI uri = resource.toURI();

    String scheme = uri.getScheme();
    if (scheme.equals("file")) {
        return Paths.get(uri);
    }

    if (!scheme.equals("jar")) {
        throw new IllegalArgumentException("Cannot convert to Path: " + uri);
    }

    String s = uri.toString();
    int separator = s.indexOf("!/");
    String entryName = s.substring(separator + 2);
    URI fileURI = URI.create(s.substring(0, separator));

    FileSystem fs = FileSystems.newFileSystem(fileURI,
        Collections.<String, Object>emptyMap());
    return fs.getPath(entryName);
}

Update:

It’s been rightly pointed out that the above code contains a resource leak, since the code opens a new FileSystem object but never closes it. The best approach is to pass a Consumer-like worker object, much like how Holger’s answer does it. Open the ZipFS FileSystem just long enough for the worker to do whatever it needs to do with the Path (as long as the worker doesn’t try to store the Path object for later use), then close the FileSystem.

Date to milliseconds and back to date in Swift

As @Travis Solution works but in some cases

var millisecondsSince1970:Int WILL CAUSE CRASH APPLICATION ,

with error

Double value cannot be converted to Int because the result would be greater than Int.max if it occurs Please update your answer with Int64

Here is Updated Answer

extension Date {
 var millisecondsSince1970:Int64 {
        return Int64((self.timeIntervalSince1970 * 1000.0).rounded()) 
        //RESOLVED CRASH HERE
    }

    init(milliseconds:Int) {
        self = Date(timeIntervalSince1970: TimeInterval(milliseconds / 1000))
    }
}

About Int definitions.

On 32-bit platforms, Int is the same size as Int32, and on 64-bit platforms, Int is the same size as Int64.

Generally, I encounter this problem in iPhone 5, which runs in 32-bit env. New devices run 64-bit env now. Their Int will be Int64.

Hope it is helpful to someone who also has same problem

How to check if an object is an array?

You can try this:

var arr = []; (or) arr = new Array();
var obj = {}; (or) arr = new Object();

arr.constructor.prototype.hasOwnProperty('push') //true

obj.constructor.prototype.hasOwnProperty('push') // false

Tomcat - maxThreads vs maxConnections

Tomcat can work in 2 modes:

  • BIO – blocking I/O (one thread per connection)
  • NIOnon-blocking I/O (many more connections than threads)

Tomcat 7 is BIO by default, although consensus seems to be "don't use Bio because Nio is better in every way". You set this using the protocol parameter in the server.xml file.

  • BIO will be HTTP/1.1 or org.apache.coyote.http11.Http11Protocol
  • NIO will be org.apache.coyote.http11.Http11NioProtocol

If you're using BIO then I believe they should be more or less the same.

If you're using NIO then actually "maxConnections=1000" and "maxThreads=10" might even be reasonable. The defaults are maxConnections=10,000 and maxThreads=200. With NIO, each thread can serve any number of connections, switching back and forth but retaining the connection so you don't need to do all the usual handshaking which is especially time-consuming with HTTPS but even an issue with HTTP. You can adjust the "keepAlive" parameter to keep connections around for longer and this should speed everything up.

MySQL COUNT DISTINCT

 Select
     Count(Distinct user_id) As countUsers
   , Count(site_id) As countVisits
   , site_id As site
 From cp_visits
 Where ts >= DATE_SUB(NOW(), INTERVAL 1 DAY)
 Group By site_id

Does .NET provide an easy way convert bytes to KB, MB, GB, etc.?

https://github.com/logary/logary/blob/master/src/Logary/DataModel.fs#L832-L837

let scaleBytes (value : float) : float * string =
    let log2 x = log x / log 2.
    let prefixes = [| ""; "Ki"; "Mi"; "Gi"; "Ti"; "Pi" |] // note the capital K and the 'i'
    let index = int (log2 value) / 10
    1. / 2.**(float index * 10.),
sprintf "%s%s" prefixes.[index] (Units.symbol Bytes)

(DISCLAIMER: I wrote this code, even the code in the link!)

How to install packages offline?

Using wheel compiled packages.

bundle up:

$ tempdir=$(mktemp -d /tmp/wheelhouse-XXXXX)
$ pip wheel -r requirements.txt --wheel-dir=$tempdir
$ cwd=`pwd`
$ (cd "$tempdir"; tar -cjvf "$cwd/bundled.tar.bz2" *)

copy tarball and install:

$ tempdir=$(mktemp -d /tmp/wheelhouse-XXXXX)
$ (cd $tempdir; tar -xvf /path/to/bundled.tar.bz2)
$ pip install --force-reinstall --ignore-installed --upgrade --no-index --no-deps $tempdir/*

Note wheel binary packages are not across machines.

More ref. here: https://pip.pypa.io/en/stable/user_guide/#installation-bundles

Applications are expected to have a root view controller at the end of application launch

To add to Mike Flynn's answer, since upgrading to Xcode 7 and running my app on an iOS 9 device, I added this to my (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

// Hide any window that isn't the main window
NSArray *windows = [[UIApplication sharedApplication] windows];
for (UIWindow *window in windows) {
    if (window != self.window) {
        window.hidden = YES;
    }
}

Angular - Can't make ng-repeat orderBy work

in Eike Thies's response above, if we use underscore.js, filter could be simplified to :

var app = angular.module('myApp', []).filter('object2Array', function() {
  return function(input) {
    return _.toArray(input);
  }
});

How to see data from .RData file?

You can also import the data via the "Import Dataset" tab in RStudio, under "global environment." Use the text data option in the drop down list and select your .RData file from the folder. Once the import is complete, it will display the data in the console. Hope this helps.

android - setting LayoutParams programmatically

For Xamarin Android align to the left of an object

int dp24 = (int)TypedValue.ApplyDimension( ComplexUnitType.Dip, 24, Resources.System.DisplayMetrics );
            RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams( dp24, dp24 );
            lp.AddRule( LayoutRules.CenterInParent, 1 );
            lp.AddRule( LayoutRules.LeftOf, //Id of the field Eg m_Button.Id ); 
            m_Button.LayoutParameters = lp;

How does one check if a table exists in an Android SQLite database?

I know nothing about the Android SQLite API, but if you're able to talk to it in SQL directly, you can do this:

create table if not exists mytable (col1 type, col2 type);

Which will ensure that the table is always created and not throw any errors if it already existed.

Add custom buttons on Slick Carousel

That's because they use an icon font for the buttons. They use "Slick" font as you can see in this image:

enter image description here

Basically, the make the letter "A" the form of an icon, the letter "B" the form of another one and so on.

For example:

enter image description here

If you want to know more about icon fonts click here

If you want to change the icons, you need to replace the whole button code or you can go to www.fontastic.me and create your own icon font. After that, replace the font file for the current one and you'll have your own icon.

Getting a POST variable

In addition to using Request.Form and Request.QueryString and depending on your specific scenario, it may also be useful to check the Page's IsPostBack property.

if (Page.IsPostBack)
{
  // HTTP Post
}
else
{
  // HTTP Get
}

C++ Fatal Error LNK1120: 1 unresolved externals

My problem was int Main() instead of int main()

good luck

Java Enum return Int

First you should ask yourself the following question: Do you really need an int?

The purpose of enums is to have a collection of items (constants), that have a meaning in the code without relying on an external value (like an int). Enums in Java can be used as an argument on switch statments and they can safely be compared using "==" equality operator (among others).

Proposal 1 (no int needed) :

Often there is no need for an integer behind it, then simply use this:

private enum DownloadType{
    AUDIO, VIDEO, AUDIO_AND_VIDEO
}

Usage:

DownloadType downloadType = MyObj.getDownloadType();
if (downloadType == DownloadType.AUDIO) {
    //...
}
//or
switch (downloadType) {
  case AUDIO:  //...
          break;
  case VIDEO: //...
          break;
  case AUDIO_AND_VIDEO: //...
          break;
}

Proposal 2 (int needed) :

Nevertheless, sometimes it may be useful to convert an enum to an int (for instance if an external API expects int values). In this case I would advise to mark the methods as conversion methods using the toXxx()-Style. For printing override toString().

private enum DownloadType {
    AUDIO(2), VIDEO(5), AUDIO_AND_VIDEO(11);
    private final int code;

    private DownloadType(int code) {
        this.code = code;
    }

    public int toInt() {
        return code;
    }

    public String toString() {
        //only override toString, if the returned value has a meaning for the
        //human viewing this value 
        return String.valueOf(code);
    }
}

System.out.println(DownloadType.AUDIO.toInt());           //returns 2
System.out.println(DownloadType.AUDIO);                   //returns 2 via `toString/code`
System.out.println(DownloadType.AUDIO.ordinal());         //returns 0
System.out.println(DownloadType.AUDIO.name());            //returns AUDIO
System.out.println(DownloadType.VIDEO.toInt());           //returns 5
System.out.println(DownloadType.VIDEO.ordinal());         //returns 1
System.out.println(DownloadType.AUDIO_AND_VIDEO.toInt()); //returns 11

Summary

  • Don't use an Integer together with an enum if you don't have to.
  • Don't rely on using ordinal() for getting an integer of an enum, because this value may change, if you change the order (for example by inserting a value). If you are considering to use ordinal() it might be better to use proposal 1.
  • Normally don't use int constants instead of enums (like in the accepted answer), because you will loose type-safety.

How to execute multiple SQL statements from java

you can achieve that using Following example uses addBatch & executeBatch commands to execute multiple SQL commands simultaneously.

Batch Processing allows you to group related SQL statements into a batch and submit them with one call to the database. reference

When you send several SQL statements to the database at once, you reduce the amount of communication overhead, thereby improving performance.

  • JDBC drivers are not required to support this feature. You should use the DatabaseMetaData.supportsBatchUpdates() method to determine if the target database supports batch update processing. The method returns true if your JDBC driver supports this feature.
  • The addBatch() method of Statement, PreparedStatement, and CallableStatement is used to add individual statements to the batch. The executeBatch() is used to start the execution of all the statements grouped together.
  • The executeBatch() returns an array of integers, and each element of the array represents the update count for the respective update statement.
  • Just as you can add statements to a batch for processing, you can remove them with the clearBatch() method. This method removes all the statements you added with the addBatch() method. However, you cannot selectively choose which statement to remove.

EXAMPLE:

import java.sql.*;

public class jdbcConn {
   public static void main(String[] args) throws Exception{
      Class.forName("org.apache.derby.jdbc.ClientDriver");
      Connection con = DriverManager.getConnection
      ("jdbc:derby://localhost:1527/testDb","name","pass");

      Statement stmt = con.createStatement
      (ResultSet.TYPE_SCROLL_SENSITIVE,
      ResultSet.CONCUR_UPDATABLE);
      String insertEmp1 = "insert into emp values
      (10,'jay','trainee')";
      String insertEmp2 = "insert into emp values
      (11,'jayes','trainee')";
      String insertEmp3 = "insert into emp values
      (12,'shail','trainee')";
      con.setAutoCommit(false);
      stmt.addBatch(insertEmp1);//inserting Query in stmt
      stmt.addBatch(insertEmp2);
      stmt.addBatch(insertEmp3);
      ResultSet rs = stmt.executeQuery("select * from emp");
      rs.last();
      System.out.println("rows before batch execution= "
      + rs.getRow());
      stmt.executeBatch();
      con.commit();
      System.out.println("Batch executed");
      rs = stmt.executeQuery("select * from emp");
      rs.last();
      System.out.println("rows after batch execution= "
      + rs.getRow());
   }
} 

refer http://www.tutorialspoint.com/javaexamples/jdbc_executebatch.htm