Programs & Examples On #Lexicographic

String Comparison in Java

Leading from answers from @Bozho and @aioobe, lexicographic comparisons are similar to the ordering that one might find in a dictionary.

The Java String class provides the .compareTo () method in order to lexicographically compare Strings. It is used like this "apple".compareTo ("banana").

The return of this method is an int which can be interpreted as follows:

  • returns < 0 then the String calling the method is lexicographically first (comes first in a dictionary)
  • returns == 0 then the two strings are lexicographically equivalent
  • returns > 0 then the parameter passed to the compareTo method is lexicographically first.

More specifically, the method provides the first non-zero difference in ASCII values.

Thus "computer".compareTo ("comparison") will return a value of (int) 'u' - (int) 'a' (20). Since this is a positive result, the parameter ("comparison") is lexicographically first.

There is also a variant .compareToIgnoreCase () which will return 0 for "a".compareToIgnoreCase ("A"); for example.

Get the ID of a drawable in ImageView

As of today, there is no support on this function. However, I found a little hack on this one.

 imageView.setImageResource(R.drawable.ic_star_black_48dp);
 imageView.setTag(R.drawable.ic_star_black_48dp);

So if you want to get the ID of the view, just get it's tag.

if (imageView.getTag() != null) {
   int resourceID = (int) imageView.getTag();

   //
   // drawable id.
   //   
}

Exclude subpackages from Spring autowiring?

One thing that seems to work for me is this:

@ComponentScan(basePackageClasses = {SomeTypeInYourPackage.class}, resourcePattern = "*.class")

Or in XML:

<context:component-scan base-package="com.example" resource-pattern="*.class"/>

This overrides the default resourcePattern which is "**/*.class".

This would seem like the most type-safe way to ONLY include your base package since that resourcePattern would always be the same and relative to your base package.

How to assign string to bytes array

Go, convert a string to a bytes slice

You need a fast way to convert a []string to []byte type. To use in situations such as storing text data into a random access file or other type of data manipulation that requires the input data to be in []byte type.

package main

func main() {

    var s string

    //...

    b := []byte(s)

    //...
}

which is useful when using ioutil.WriteFile, which accepts a bytes slice as its data parameter:

WriteFile func(filename string, data []byte, perm os.FileMode) error

Another example

package main

import (
    "fmt"
    "strings"
)

func main() {

    stringSlice := []string{"hello", "world"}

    stringByte := strings.Join(stringSlice, " ")

    // Byte array value
    fmt.Println([]byte(stringByte))

    // Corresponding string value
    fmt.Println(string([]byte(stringByte)))
}

Output:

[104 101 108 108 111 32 119 111 114 108 100] hello world

Please check the link playground

How to convert all elements in an array to integer in JavaScript?

Using jQuery, you can like the map() method like so;

 $.map(arr, function(val,i) { 
     return parseInt(val); 
 });

How to create own dynamic type or dynamic object in C#?

 var data = new { studentId = 1, StudentName = "abc" };  

Or value is present

  var data = new { studentId, StudentName };

Facebook Javascript SDK Problem: "FB is not defined"

If you're using JQuery, try putting FB withing Jquery call

e.g.

$(document).ready(function(){
    FB.Event.subscribe('auth.login', function(){
        alert('logged in!');
    });
});

that worked for me

What is __future__ in Python used for and how/when to use it, and how it works

__future__ is a pseudo-module which programmers can use to enable new language features which are not compatible with the current interpreter. For example, the expression 11/4 currently evaluates to 2. If the module in which it is executed had enabled true division by executing:

from __future__ import division

the expression 11/4 would evaluate to 2.75. By importing the __future__ module and evaluating its variables, you can see when a new feature was first added to the language and when it will become the default:

  >>> import __future__
  >>> __future__.division
  _Feature((2, 2, 0, 'alpha', 2), (3, 0, 0, 'alpha', 0), 8192)

Multiple maven repositories in one gradle file

you have to do like this in your project level gradle file

allprojects {
    repositories {
        jcenter()
        maven { url "http://dl.appnext.com/" }
        maven { url "https://maven.google.com" }
    }
}

What is the difference between prefix and postfix operators?

In fact return (i++) will only return 10.

The ++ and -- operators can be placed before or after the variable, with different effects. If they are before, then they will be processed and returned and essentially treated just like (i-1) or (i+1), but if you place the ++ or -- after the i, then the return is essentailly

return i;
i + 1;

So it will return 10 and never increment it.

JQuery Redirect to URL after specified time

You could use the setTimeout() function:

// Your delay in milliseconds
var delay = 1000; 
setTimeout(function(){ window.location = URL; }, delay);

Display PNG image as response to jQuery AJAX request

Method 1

You should not make an ajax call, just put the src of the img element as the url of the image.

This would be useful if you use GET instead of POST

<script type="text/javascript" > 

  $(document).ready( function() { 
      $('.div_imagetranscrits').html('<img src="get_image_probes_via_ajax.pl?id_project=xxx" />')
  } );

</script>

Method 2

If you want to POST to that image and do it the way you do (trying to parse the contents of the image on the client side, you could try something like this: http://en.wikipedia.org/wiki/Data_URI_scheme

You'll need to encode the data to base64, then you could put data:[<MIME-type>][;charset=<encoding>][;base64],<data> into the img src

as example:

<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot img" />

To encode to base64:

Removing duplicate values from a PowerShell array

$a | sort -unique

This works with case-insensitive, therefore removing duplicates strings with differing cases. Solved my problem.

$ServerList = @(
    "FS3",
    "HQ2",
    "hq2"
) | sort -Unique

$ServerList

The above outputs:

FS3
HQ2

Convert 24 Hour time to 12 Hour plus AM/PM indication Oracle SQL

For the 24-hour time, you need to use HH24 instead of HH.

For the 12-hour time, the AM/PM indicator is written as A.M. (if you want periods in the result) or AM (if you don't). For example:

SELECT invoice_date,
       TO_CHAR(invoice_date, 'DD-MM-YYYY HH24:MI:SS') "Date 24Hr",
       TO_CHAR(invoice_date, 'DD-MM-YYYY HH:MI:SS AM') "Date 12Hr"
  FROM invoices
;

For more information on the format models you can use with TO_CHAR on a date, see http://docs.oracle.com/cd/E16655_01/server.121/e17750/ch4datetime.htm#NLSPG004.

How do I tell CMake to link in a static library in the source directory?

If you don't want to include the full path, you can do

add_executable(main main.cpp)
target_link_libraries(main bingitup)

bingitup is the same name you'd give a target if you create the static library in a CMake project:

add_library(bingitup STATIC bingitup.cpp)

CMake automatically adds the lib to the front and the .a at the end on Linux, and .lib at the end on Windows.

If the library is external, you might want to add the path to the library using

link_directories(/path/to/libraries/)

Use of the MANIFEST.MF file in Java

The content of the Manifest file in a JAR file created with version 1.0 of the Java Development Kit is the following.

Manifest-Version: 1.0

All the entries are as name-value pairs. The name of a header is separated from its value by a colon. The default manifest shows that it conforms to version 1.0 of the manifest specification. The manifest can also contain information about the other files that are packaged in the archive. Exactly what file information is recorded in the manifest will depend on the intended use for the JAR file. The default manifest file makes no assumptions about what information it should record about other files, so its single line contains data only about itself. Special-Purpose Manifest Headers

Depending on the intended role of the JAR file, the default manifest may have to be modified. If the JAR file is created only for the purpose of archival, then the MANIFEST.MF file is of no purpose. Most uses of JAR files go beyond simple archiving and compression and require special information to be in the manifest file. Summarized below are brief descriptions of the headers that are required for some special-purpose JAR-file functions

Applications Bundled as JAR Files: If an application is bundled in a JAR file, the Java Virtual Machine needs to be told what the entry point to the application is. An entry point is any class with a public static void main(String[] args) method. This information is provided in the Main-Class header, which has the general form:

Main-Class: classname

The value classname is to be replaced with the application's entry point.

Download Extensions: Download extensions are JAR files that are referenced by the manifest files of other JAR files. In a typical situation, an applet will be bundled in a JAR file whose manifest references a JAR file (or several JAR files) that will serve as an extension for the purposes of that applet. Extensions may reference each other in the same way. Download extensions are specified in the Class-Path header field in the manifest file of an applet, application, or another extension. A Class-Path header might look like this, for example:

Class-Path: servlet.jar infobus.jar acme/beans.jar

With this header, the classes in the files servlet.jar, infobus.jar, and acme/beans.jar will serve as extensions for purposes of the applet or application. The URLs in the Class-Path header are given relative to the URL of the JAR file of the applet or application.

Package Sealing: A package within a JAR file can be optionally sealed, which means that all classes defined in that package must be archived in the same JAR file. A package might be sealed to ensure version consistency among the classes in your software or as a security measure. To seal a package, a Name header needs to be added for the package, followed by a Sealed header, similar to this:

Name: myCompany/myPackage/
Sealed: true

The Name header's value is the package's relative pathname. Note that it ends with a '/' to distinguish it from a filename. Any headers following a Name header, without any intervening blank lines, apply to the file or package specified in the Name header. In the above example, because the Sealed header occurs after the Name: myCompany/myPackage header, with no blank lines between, the Sealed header will be interpreted as applying (only) to the package myCompany/myPackage.

Package Versioning: The Package Versioning specification defines several manifest headers to hold versioning information. One set of such headers can be assigned to each package. The versioning headers should appear directly beneath the Name header for the package. This example shows all the versioning headers:

Name: java/util/
Specification-Title: "Java Utility Classes" 
Specification-Version: "1.2"
Specification-Vendor: "Sun Microsystems, Inc.".
Implementation-Title: "java.util" 
Implementation-Version: "build57"
Implementation-Vendor: "Sun Microsystems, Inc."

javascript - match string against the array of regular expressions

let expressions = [ '/something/', '/something_else/', '/and_something_else/'];

let str = 'else';

here will be the check for following expressions:

if( expressions.find(expression => expression.includes(str) ) ) {

}

using Array .find() method to traverse array and .include to check substring

Twitter Bootstrap Form File Element Upload Button

I have Created a Custom upload button to accept only images, which can be modified as per your requirement.

Hope this helps!! :)

(Used Bootstrap framework)

Codepen-link

HTML

<center>
 <br />
 <br />
 <span class="head">Upload Button Re-Imagined</span>
 <br />
 <br />
 <div class="fileUpload blue-btn btn width100">
   <span>Upload your Organizations logo</span>
   <input type="file" class="uploadlogo" />
 </div>
</center>

CSS

 .head {
   font-size: 25px;
   font-weight: 200;
 }

 .blue-btn:hover,
 .blue-btn:active,
 .blue-btn:focus,
 .blue-btn {
   background: transparent;
   border: solid 1px #27a9e0;
   border-radius: 3px;
   color: #27a9e0;
   font-size: 16px;
   margin-bottom: 20px;
   outline: none !important;
   padding: 10px 20px;
 }

 .fileUpload {
   position: relative;
   overflow: hidden;
   height: 43px;
   margin-top: 0;
 }

 .fileUpload input.uploadlogo {
   position: absolute;
   top: 0;
   right: 0;
   margin: 0;
   padding: 0;
   font-size: 20px;
   cursor: pointer;
   opacity: 0;
   filter: alpha(opacity=0);
   width: 100%;
   height: 42px;
 }


 /*Chrome fix*/

 input::-webkit-file-upload-button {
   cursor: pointer !important;
 }

JS

// You can modify the upload files to pdf's, docs etc
//Currently it will upload only images
$(document).ready(function($) {

  // Upload btn
  $(".uploadlogo").change(function() {
    readURL(this);
  });

  function readURL(input) {
    var url = input.value;
    var ext = url.substring(url.lastIndexOf('.') + 1).toLowerCase();
    if (input.files && input.files[0] && (ext == "png" || ext == "jpeg" || ext == "jpg" || ext == "gif" || ext == "svg")) {
      var path = $('.uploadlogo').val();
      var filename = path.replace(/^.*\\/, "");
      $('.fileUpload span').html('Uploaded logo : ' + filename);
      // console.log(filename);
    } else {
      $(".uploadlogo").val("");
      $('.fileUpload span').html('Only Images Are Allowed!');
    }
  }
});

How can I use a local image as the base image with a dockerfile?

You can use it without doing anything special. If you have a local image called blah you can do FROM blah. If you do FROM blah in your Dockerfile, but don't have a local image called blah, then Docker will try to pull it from the registry.

In other words, if a Dockerfile does FROM ubuntu, but you have a local image called ubuntu different from the official one, your image will override it.

How can I get browser to prompt to save password?

I have been struggling with this myself, and I finally was able to track down the issue and what was causing it to fail.

It all stemmed from the fact that my login form was being dynamically injected into the page (using backbone.js). As soon as I embed my login form directly into my index.html file, everything worked like a charm.

I think this is because the browser has to be aware that there is an existing login form, but since mine was being dynamically injected into the page, it didn't know that a "real" login form ever existed.

Fastest way to duplicate an array in JavaScript - slice vs. 'for' loop

Remember .slice() won't work for two-dimensional arrays. You'll need a function like this:

function copy(array) {
  return array.map(function(arr) {
    return arr.slice();
  });
}

How to declare array of zeros in python (or an array of a certain size)

The simplest solution would be

"\x00" * size # for a buffer of binary zeros
[0] * size # for a list of integer zeros

In general you should use more pythonic code like list comprehension (in your example: [0 for unused in xrange(100)]) or using string.join for buffers.

Get element by id - Angular2

if you want to set value than you can do the same in some function on click or on some event fire.

also you can get value using ViewChild using local variable like this

<input type='text' id='loginInput' #abc/>

and get value like this

this.abc.nativeElement.value

here is working example

Update

okay got it , you have to use ngAfterViewInit method of angualr2 for the same like this

ngAfterViewInit(){
    document.getElementById('loginInput').value = '123344565';
  }

ngAfterViewInit will not throw any error because it will render after template loading

Laravel 5 not finding css files

I used:

"{{asset('css/custom.css')}}"
"{{asset('css/app.css') }}"

First one is my own file the second one came with laravel. I'm using version 5.

http://spanibox.com/css/app.css works but http://spanibox.com/css/custom.css does not. I find this very weird.

Installing tensorflow with anaconda in windows

If you have anaconda version 2.7 installed on your windows, then go to anaconda prompt, type these two commands:

  1. Create a conda environment for tensorflow using conda create -n tensorflow_env tensorflow
  2. activate the tensorflow using conda activate tensorflow_env

If it is activated, then the base will be replaced by tensorflow_env i.e. now it will show (tensorflow_env) C:\Users>

You can now use import tensorflow as tf for using tensorflow in your code.

iOS 7 UIBarButton back button arrow color

It is possible to change only arrow's color (not back button title's color) on this way:

[[self.navigationController.navigationBar.subviews lastObject] setTintColor:[UIColor blackColor]];

Navigation bar contains subview of _UINavigationBarBackIndicatorView type (last item in subviews array) which represents arrow.

Result is navigation bar with different colors of back button arrow and back button title

How do I make HttpURLConnection use a proxy?

This is fairly easy to answer from the internet. Set system properties http.proxyHost and http.proxyPort. You can do this with System.setProperty(), or from the command line with the -D syntax.

fs: how do I locate a parent folder?

This works fine

path.join(__dirname + '/../client/index.html')
const path = require('path')
const fs = require('fs')
    fs.readFile(path.join(__dirname + '/../client/index.html'))

Replace first occurrence of pattern in a string

There are a number of ways that you could do this, but the fastest might be to use IndexOf to find the index position of the letter you want to replace and then substring out the text before and after what you want to replace.

django - get() returned more than one topic

To add to CrazyGeek's answer, get or get_or_create queries work only when there's one instance of the object in the database, filter is for two or more.

If a query can be for single or multiple instances, it's best to add an ID to the div and use an if statement e.g.

def updateUserCollection(request):
    data = json.loads(request.body)
    card_id = data['card_id']
    action = data['action']

    user = request.user
    card = Cards.objects.get(card_id=card_id)

    if data-action == 'add':
        collection = Collection.objects.get_or_create(user=user, card=card)
        collection.quantity + 1
        collection.save()

    elif data-action == 'remove':
        collection = Cards.objects.filter(user=user, card=card)
        collection.quantity = 0
        collection.update()

Note: .save() becomes .update() for updating multiple objects. Hope this helps someone, gave me a long day's headache.

How to create JSON object Node.js

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

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

How to reload a page using Angularjs?

You can also try this, after injecting $window service.

$window.location.reload();

Difference between "while" loop and "do while" loop

while(wdlen<2){
  ...
 }  

If wdlen (assuming it's a stack variable) is not initialized or assigned a value before the while loop is entered, it will contain whatever was in that space in memory before (i.e. garbage). So if the garbage value is < 2, the loop executes, otherwise it doesn't.

do{
 ...
}while(wdlen<2)

will execute once and then checks on condition to run loop again, and this time it might succeed if by chance wdlen which is uninitialized is found to be less than 2.

R: Break for loop

your break statement should break out of the for (in in 1:n).

Personally I am always wary with break statements and double check it by printing to the console to double check that I am in fact breaking out of the right loop. So before you test add the following statement, which will let you know if you break before it reaches the end. However, I have no idea how you are handling the variable n so I don't know if it would be helpful to you. Make a n some test value where you know before hand if it is supposed to break out or not before reaching n.

for (in in 1:n)
{
    if (in == n)         #add this statement
    {
        "sorry but the loop did not break"
    }

    id_novo <- new_table_df$ID[in]
    if(id_velho==id_novo)
    {
        break
    }
    else if(in == n)
    {
        sold_df <- rbind(sold_df,old_table_df[out,])
    }
}

How do I get the current location of an iframe?

Ok, so in this application, there is an iframe in which the user is supplied with links or some capacity that allows that iframe to browse to some external site. You are then looking to capture the URL to which the user has browsed.

Something to keep in mind. Since the URL is to an external source, you will be limited in how much you can interact with this iframe via javascript (or an client side access for that matter), this is known as browser cross-domain security, as apparently you have discovered. There are clever work arounds, as presented here Cross-domain, cross-frame Javascript, although I do not think this work around applies in this case.

About all you can access is the location, as you need.

I would suggest making the code presented more resilitant and less error prone. Try browsing the web sometime with IE or FF configured to show javascript errors. You will be surprised just how many javascript errors are thrown, largely because there is a lot of error prone javascript out there, which just continues to proliferate.

This solution assumes that the iframe in question is the same "window" context where you are running the javascript. (Meaning, it is not embedded within another frame or iframe, in which case, the javascript code gets more involved, and you likely need to recursively search through the window hierarchy.)

<iframe name='frmExternal' id='frmExternal' src='http://www.stackoverflow.com'></frame>
<input type='text' id='txtUrl' />
<input type='button' id='btnGetUrl' value='Get URL' onclick='GetIFrameUrl();' />

<script language='javascript' type='text/javascript'>
function GetIFrameUrl()
{
    if (!document.getElementById)
    {
        return;
    }

    var frm = document.getElementById("frmExternal");
    var txt = document.getElementById("txtUrl");

    if (frm == null || txt == null)
    {
        // not great user feedback but slightly better than obnoxious script errors
       alert("There was a problem with this page, please refresh.");
       return;
    }

    txt.value = frm.src;
}
</script>

Hope this helps.

Indexing vectors and arrays with +:

Description and examples can be found in IEEE Std 1800-2017 § 11.5.1 "Vector bit-select and part-select addressing". First IEEE appearance is IEEE 1364-2001 (Verilog) § 4.2.1 "Vector bit-select and part-select addressing". Here is an direct example from the LRM:

logic [31: 0] a_vect;
logic [0 :31] b_vect;
logic [63: 0] dword;
integer sel;
a_vect[ 0 +: 8] // == a_vect[ 7 : 0]
a_vect[15 -: 8] // == a_vect[15 : 8]
b_vect[ 0 +: 8] // == b_vect[0 : 7]
b_vect[15 -: 8] // == b_vect[8 :15]
dword[8*sel +: 8] // variable part-select with fixed width

If sel is 0 then dword[8*(0) +: 8] == dword[7:0]
If sel is 7 then dword[8*(7) +: 8] == dword[63:56]

The value to the left always the starting index. The number to the right is the width and must be a positive constant. the + and - indicates to select the bits of a higher or lower index value then the starting index.

Assuming address is in little endian ([msb:lsb]) format, then if(address[2*pointer+:2]) is the equivalent of if({address[2*pointer+1],address[2*pointer]})

R data formats: RData, Rda, Rds etc

Rda is just a short name for RData. You can just save(), load(), attach(), etc. just like you do with RData.

Rds stores a single R object. Yet, beyond that simple explanation, there are several differences from a "standard" storage. Probably this R-manual Link to readRDS() function clarifies such distinctions sufficiently.

So, answering your questions:

  • The difference is not about the compression, but serialization (See this page)
  • Like shown in the manual page, you may wanna use it to restore a certain object with a different name, for instance.
  • You may readRDS() and save(), or load() and saveRDS() selectively.

Fixed page header overlaps in-page anchors

If you can’t or don’t want to set a new class, add a fixed-height ::before pseudo-element to the :target pseudo-class in CSS:

:target::before {
  content: "";
  display: block;
  height: 60px; /* fixed header height*/
  margin: -60px 0 0; /* negative fixed header height */
}

Or scroll the page relative to :target with jQuery:

var offset = $(':target').offset();
var scrollto = offset.top - 60; // minus fixed header height
$('html, body').animate({scrollTop:scrollto}, 0);

Plotting a 3d cube, a sphere and a vector in Matplotlib

My answer is an amalgamation of the above two with extension to drawing sphere of user-defined opacity and some annotation. It finds application in b-vector visualization on a sphere for magnetic resonance image (MRI). Hope you find it useful:

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.gca(projection='3d')

# draw sphere
u, v = np.mgrid[0:2*np.pi:50j, 0:np.pi:50j]
x = np.cos(u)*np.sin(v)
y = np.sin(u)*np.sin(v)
z = np.cos(v)
# alpha controls opacity
ax.plot_surface(x, y, z, color="g", alpha=0.3)


# a random array of 3D coordinates in [-1,1]
bvecs= np.random.randn(20,3)

# tails of the arrows
tails= np.zeros(len(bvecs))

# heads of the arrows with adjusted arrow head length
ax.quiver(tails,tails,tails,bvecs[:,0], bvecs[:,1], bvecs[:,2],
          length=1.0, normalize=True, color='r', arrow_length_ratio=0.15)

ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')
ax.set_zlabel('Z-axis')

ax.set_title('b-vectors on unit sphere')

plt.show()

Use querystring variables in MVC controller

I had this problem while inheriting from ApiController instead of the regular Controller class. I solved it by using var container = Request.GetQueryNameValuePairs().ToLookup(x => x.Key, x => x.Value);

I followed this thread How to get Request Querystring values?

EDIT: After trying to filter through the container I was getting odd error messages. After going to my project properties and I unchecked the Optimize Code checkbox which changed so that all of a sudden the parameters in my controller where filled up from the url as I wanted.

Hopefully this will help someone with the same problem..

How to extract IP Address in Spring MVC Controller get call?

Below is the Spring way, with autowired request bean in @Controller class:

@Autowired 
private HttpServletRequest request;

System.out.println(request.getRemoteHost());

How do you do relative time in Rails?

I've written this, but have to check the existing methods mentioned to see if they are better.

module PrettyDate
  def to_pretty
    a = (Time.now-self).to_i

    case a
      when 0 then 'just now'
      when 1 then 'a second ago'
      when 2..59 then a.to_s+' seconds ago' 
      when 60..119 then 'a minute ago' #120 = 2 minutes
      when 120..3540 then (a/60).to_i.to_s+' minutes ago'
      when 3541..7100 then 'an hour ago' # 3600 = 1 hour
      when 7101..82800 then ((a+99)/3600).to_i.to_s+' hours ago' 
      when 82801..172000 then 'a day ago' # 86400 = 1 day
      when 172001..518400 then ((a+800)/(60*60*24)).to_i.to_s+' days ago'
      when 518400..1036800 then 'a week ago'
      else ((a+180000)/(60*60*24*7)).to_i.to_s+' weeks ago'
    end
  end
end

Time.send :include, PrettyDate

How do you create vectors with specific intervals in R?

In R the equivalent function is seq and you can use it with the option by:

seq(from = 5, to = 100, by = 5)
# [1]   5  10  15  20  25  30  35  40  45  50  55  60  65  70  75  80  85  90  95 100

In addition to by you can also have other options such as length.out and along.with.

length.out: If you want to get a total of 10 numbers between 0 and 1, for example:

seq(0, 1, length.out = 10)
# gives 10 equally spaced numbers from 0 to 1

along.with: It takes the length of the vector you supply as input and provides a vector from 1:length(input).

seq(along.with=c(10,20,30))
# [1] 1 2 3

Although, instead of using the along.with option, it is recommended to use seq_along in this case. From the documentation for ?seq

seq is generic, and only the default method is described here. Note that it dispatches on the class of the first argument irrespective of argument names. This can have unintended consequences if it is called with just one argument intending this to be taken as along.with: it is much better to use seq_along in that case.

seq_along: Instead of seq(along.with(.))

seq_along(c(10,20,30))
# [1] 1 2 3

Hope this helps.

Combining border-top,border-right,border-left,border-bottom in CSS

No, you cannot set them all in a single statement.
At the general case, you need at least three properties:

border-color: red green white blue;
border-style: solid dashed dotted solid;
border-width: 1px 2px 3px 4px;

However, that would be quite messy. It would be more readable and maintainable with four:

border-top:    1px solid  #ff0;
border-right:  2px dashed #f0F;
border-bottom: 3px dotted #f00;
border-left:   5px solid  #09f;

How can I list all tags for a Docker image on a remote registry?

Here's a Powershell script I wrote for Windows. Handles v1 and v2 repos:

Get-DockerImageVersions.ps1:

param (
  [Parameter (Mandatory=$true)]$ImageName,
  [Parameter (Mandatory=$false)]$RegistryURL
)

if (!$RegistryURL) 
{
  $RegistryURL = "https://registry.hub.docker.com/v1/repositories"
}

$list = ""
if ($RegistryURL -like "*v2*") 
{
  $list = "/list"
}

$URL = "$RegistryURL/$ImageName/tags$list"

write-debug $URL
$resp = Invoke-WebRequest -UseBasicParsing $URL | ConvertFrom-Json

if ($RegistryURL -like "*v2*") 
{
  $tags = $resp | select tags
  $tags.tags
} else {
  $tags = $resp | select name
  $tags.name
}

What is the difference between npm install and npm run build?

npm install installs dependencies into the node_modules/ directory, for the node project you're working on. You can call install on another node.js project (module), to install it as a dependency for your project.

npm run build does nothing unless you specify what "build" does in your package.json file. It lets you perform any necessary building/prep tasks for your project, prior to it being used in another project.

npm build is an internal command and is called by link and install commands, according to the documentation for build:

This is the plumbing command called by npm link and npm install.

You will not be calling npm build normally as it is used internally to build native C/C++ Node addons using node-gyp.

How do I find the length (or dimensions, size) of a numpy matrix in python?

matrix.size according to the numpy docs returns the Number of elements in the array. Hope that helps.

How to make JavaScript execute after page load?

Working Fiddle on <body onload="myFunction()">

<!DOCTYPE html>
<html>
 <head>
  <script type="text/javascript">
   function myFunction(){
    alert("Page is loaded");
   }
  </script>
 </head>

 <body onload="myFunction()">
  <h1>Hello World!</h1>
 </body>    
</html>

Convert pandas data frame to series

Another way -

Suppose myResult is the dataFrame that contains your data in the form of 1 col and 23 rows

# label your columns by passing a list of names
myResult.columns = ['firstCol']

# fetch the column in this way, which will return you a series
myResult = myResult['firstCol']

print(type(myResult))

In similar fashion, you can get series from Dataframe with multiple columns.

How to overlay images

If you're only wanting the magnifing glass on hover then you can use

a:hover img { cursor: url(glass.cur); }

http://www.javascriptkit.com/dhtmltutors/csscursors.shtml

If you want it there permanently you should probably either have it included in the original thumnail, or add it using JavaScript rather than adding it to the HTML (this is purely style and shouldn't be in the content).

Let me know if you want help on the JavaScript side.

Oracle 'Partition By' and 'Row_Number' keyword

I often use row_number() as a quick way to discard duplicate records from my select statements. Just add a where clause. Something like...

select a,b,rn 
  from (select a, b, row_number() over (partition by a,b order by a,b) as rn           
          from table) 
 where rn=1;

How do I iterate through the files in a directory in Java?

For Java 7+, there is also https://docs.oracle.com/javase/7/docs/api/java/nio/file/DirectoryStream.html

Example taken from the Javadoc:

List<Path> listSourceFiles(Path dir) throws IOException {
   List<Path> result = new ArrayList<>();
   try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir, "*.{c,h,cpp,hpp,java}")) {
       for (Path entry: stream) {
           result.add(entry);
       }
   } catch (DirectoryIteratorException ex) {
       // I/O error encounted during the iteration, the cause is an IOException
       throw ex.getCause();
   }
   return result;
}

Angular - POST uploaded file

In my project , I use the XMLHttpRequest to send multipart/form-data. I think it will fit you to.

and the uploader code

let xhr = new XMLHttpRequest();
xhr.open('POST', 'http://www.example.com/rest/api', true);
xhr.withCredentials = true;
xhr.send(formData);

Here is example : https://github.com/wangzilong/angular2-multipartForm

Get current time in seconds since the Epoch on Linux, Bash

use this bash script (my ~/bin/epoch):

#!/bin/bash

# get seconds since epoch
test "x$1" == x && date +%s && exit 0

# or convert epoch seconds to date format (see "man date" for options)
EPOCH="$1"
shift
date -d @"$EPOCH" "$@"

Example use of "continue" statement in Python?

import random  

for i in range(20):  
    x = random.randint(-5,5)  
    if x == 0: continue  
    print 1/x  

continue is an extremely important control statement. The above code indicates a typical application, where the result of a division by zero can be avoided. I use it often when I need to store the output from programs, but dont want to store the output if the program has crashed. Note, to test the above example, replace the last statement with print 1/float(x), or you'll get zeros whenever there's a fraction, since randint returns an integer. I omitted it for clarity.

In C - check if a char exists in a char array

Assuming your input is a standard null-terminated C string, you want to use strchr:

#include <string.h>

char* foo = "abcdefghijkl";
if (strchr(foo, 'a') != NULL)
{
  // do stuff
}

If on the other hand your array is not null-terminated (i.e. just raw data), you'll need to use memchr and provide a size:

#include <string.h>

char foo[] = { 'a', 'b', 'c', 'd', 'e' }; // note last element isn't '\0'
if (memchr(foo, 'a', sizeof(foo)))
{
  // do stuff
}

How to catch exception correctly from http.request()?

Perhaps you can try adding this in your imports:

import 'rxjs/add/operator/catch';

You can also do:

return this.http.request(request)
  .map(res => res.json())
  .subscribe(
    data => console.log(data),
    err => console.log(err),
    () => console.log('yay')
  );

Per comments:

EXCEPTION: TypeError: Observable_1.Observable.throw is not a function

Similarly, for that, you can use:

import 'rxjs/add/observable/throw';

Given the lat/long coordinates, how can we find out the city/country?

Another option:

  • Download the cities database from http://download.geonames.org/export/dump/
  • Add each city as a lat/long -> City mapping to a spatial index such as an R-Tree (some DBs also have the functionality)
  • Use nearest-neighbour search to find the closest city for any given point

Advantages:

  • Does not depend on an external server to be available
  • Very fast (easily does thousands of lookups per second)

Disadvantages:

  • Not automatically up to date
  • Requires extra code if you want to distinguish the case where the nearest city is dozens of miles away
  • May give weird results near the poles and the international date line (though there aren't any cities in those places anyway

What is the difference between single-quoted and double-quoted strings in PHP?

Here some possibilities of single and double quotes with variable

$world = "world";

"Hello '.$world.' ";

'hello ".$world."';

Running JAR file on Windows

There is way without requiring user to do changes on his PC. Runtime.getRuntime.exec() allows us to start cmd.exe and execute commands inside of it. So, it's possible for java program to run itself in command prompt when user clicks .jar file.

public static void main(String[] args) throws IOException {
    if(args.length == 0) {
        Process p = Runtime.getRuntime().exec("cmd.exe /c start java -jar " + (new File(NameOfClass.class.getProtectionDomain().getCodeSource().getLocation().getPath())).getAbsolutePath() + " cmd");
    } else {
        //code to be executed
    }
}

How to copy a file along with directory structure/path using python?

To create all intermediate-level destination directories you could use os.makedirs() before copying:

import os
import shutil

srcfile = 'a/long/long/path/to/file.py'
dstroot = '/home/myhome/new_folder'


assert not os.path.isabs(srcfile)
dstdir =  os.path.join(dstroot, os.path.dirname(srcfile))

os.makedirs(dstdir) # create all directories, raise an error if it already exists
shutil.copy(srcfile, dstdir)

Blurring an image via CSS?

With CSS3 we can easily adjust an image. But remember this does not change the image. It only displays the adjusted image.

See the following code for more details.

To make an image gray:

img {
 -webkit-filter: grayscale(100%);
}

To give a sepia look:

img {
 -webkit-filter: sepia(100%);
}

To adjust brightness:

img {
 -webkit-filter: brightness(50%);
}

To adjust contrast:

img {
 -webkit-filter: contrast(200%);
}

To Blur an image:

img {
 -webkit-filter: blur(10px);
}

You should also do it for different browser. That is include all css statements

  filter: grayscale(100%);
 -webkit-filter: grayscale(100%);
 -moz-filter: grayscale(100%);

To use multiple

 filter: blur(5px) grayscale(1);

Codepen Demo

An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll

using (var cmd = new SqlCommand("SELECT EmpName FROM [Employee] WHERE EmpID = @id", con))

put [] around table name ;)

Unzip files (7-zip) via cmd command

Regarding Phil Street's post:

It may actually be installed in your 32-bit program folder instead of your default x64, if you're running 64-bit OS. Check to see where 7-zip is installed, and if it is in Program Files (x86) then try using this instead:

PATH=%PATH%;C:\Program Files (x86)\7-Zip

Trigger a Travis-CI rebuild without pushing a commit?

If the build never occurred (perhaps you didn't get the Pull-Request build switch set to on in time), you can mark the Pull Request on Github as closed then mark it as opened and a new build will be triggered.

Formatting struct timespec

I wanted to ask the same question. Here is my current solution to obtain a string like this: 2013-02-07 09:24:40.749355372 I am not sure if there is a more straight forward solution than this, but at least the string format is freely configurable with this approach.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

#define NANO 1000000000L

// buf needs to store 30 characters
int timespec2str(char *buf, uint len, struct timespec *ts) {
    int ret;
    struct tm t;

    tzset();
    if (localtime_r(&(ts->tv_sec), &t) == NULL)
        return 1;

    ret = strftime(buf, len, "%F %T", &t);
    if (ret == 0)
        return 2;
    len -= ret - 1;

    ret = snprintf(&buf[strlen(buf)], len, ".%09ld", ts->tv_nsec);
    if (ret >= len)
        return 3;

    return 0;
}

int main(int argc, char **argv) {
    clockid_t clk_id = CLOCK_REALTIME;
    const uint TIME_FMT = strlen("2012-12-31 12:59:59.123456789") + 1;
    char timestr[TIME_FMT];

    struct timespec ts, res;
    clock_getres(clk_id, &res);
    clock_gettime(clk_id, &ts);

    if (timespec2str(timestr, sizeof(timestr), &ts) != 0) {
        printf("timespec2str failed!\n");
        return EXIT_FAILURE;
    } else {
        unsigned long resol = res.tv_sec * NANO + res.tv_nsec;
        printf("CLOCK_REALTIME: res=%ld ns, time=%s\n", resol, timestr);
        return EXIT_SUCCESS;
    }
}

output:

gcc mwe.c -lrt 
$ ./a.out 
CLOCK_REALTIME: res=1 ns, time=2013-02-07 13:41:17.994326501

Undefined Symbols error when integrating Apptentive iOS SDK via Cocoapods

We have found that adding the Apptentive cocoa pod to an existing Xcode project may potentially not include some of our required frameworks.

Check your linker flags:

Target > Build Settings > Other Linker Flags 

You should see -lApptentiveConnect listed as a linker flag:

... -ObjC -lApptentiveConnect ... 

You should also see our required Frameworks listed:

  • Accelerate
  • CoreData
  • CoreText
  • CoreGraphics
  • CoreTelephony
  • Foundation
  • QuartzCore
  • StoreKit
  • SystemConfiguration
  • UIKit

    -ObjC -lApptentiveConnect -framework Accelerate -framework CoreData -framework CoreGraphics -framework CoreText -framework Foundation -framework QuartzCore -framework SystemConfiguration -framework UIKit -framework CoreTelephony -framework StoreKit  

Does Java have an exponential operator?

In case if anyone wants to create there own exponential function using recursion, below is for your reference.

public static double power(double value, double p) {
        if (p <= 0)
            return 1;

        return value * power(value, p - 1);
    }

Abstract methods in Java

Abstract methods means there is no default implementation for it and an implementing class will provide the details.

Essentially, you would have

abstract class AbstractObject {
   public abstract void method();
}

class ImplementingObject extends AbstractObject {
  public void method() {
    doSomething();
  }
}

So, it's exactly as the error states: your abstract method can not have a body.

There's a full tutorial on Oracle's site at: http://download.oracle.com/javase/tutorial/java/IandI/abstract.html

The reason you would do something like this is if multiple objects can share some behavior, but not all behavior.

A very simple example would be shapes:

You can have a generic graphic object, which knows how to reposition itself, but the implementing classes will actually draw themselves.

(This is taken from the site I linked above)

abstract class GraphicObject {
    int x, y;
    ...
    void moveTo(int newX, int newY) {
        ...
    }
    abstract void draw();
    abstract void resize();
}

class Circle extends GraphicObject {
    void draw() {
        ...
    }
    void resize() {
        ...
    }
}
class Rectangle extends GraphicObject {
    void draw() {
        ...
    }
    void resize() {
        ...
    }
}

Write to CSV file and export it?

A comment about Will's answer, you might want to replace HttpContext.Current.Response.End(); with HttpContext.Current.ApplicationInstance.CompleteRequest(); The reason is that Response.End() throws a System.Threading.ThreadAbortException. It aborts a thread. If you have an exception logger, it will be littered with ThreadAbortExceptions, which in this case is expected behavior.

Intuitively, sending a CSV file to the browser should not raise an exception.

See here for more Is Response.End() considered harmful?

How does Tomcat locate the webapps directory?

Find server.xml at $CATALINA_BASE/conf/server.xml

Find appBase attribute in <Host> element

by default it will be something like : <Host name="localhost" appBase="webapps ...>

Change appBase to your required path. There are different way people put it, but I use

/c:/myfolder/newwebapps

Remember, no slash at the end, but at start. Also note it's direction as well.

jquery data selector

Here's a plugin that simplifies life https://github.com/rootical/jQueryDataSelector

Use it like that:

data selector           jQuery selector
  $$('name')              $('[data-name]')
  $$('name', 10)          $('[data-name=10]')
  $$('name', false)       $('[data-name=false]')
  $$('name', null)        $('[data-name]')
  $$('name', {})          Syntax error

OS X Terminal shortcut: Jump to beginning/end of line

This worked for me Option + left-arrow or Option + right-arrow for moving the cursor to the start or end of the line.

Mac Os Version: Catalina

Capture the screen shot using .NET

It's certainly possible to grab a screenshot using the .NET Framework. The simplest way is to create a new Bitmap object and draw into that using the Graphics.CopyFromScreen method.

Sample code:

using (Bitmap bmpScreenCapture = new Bitmap(Screen.PrimaryScreen.Bounds.Width, 
                                            Screen.PrimaryScreen.Bounds.Height))
using (Graphics g = Graphics.FromImage(bmpScreenCapture))
{
    g.CopyFromScreen(Screen.PrimaryScreen.Bounds.X,
                     Screen.PrimaryScreen.Bounds.Y,
                     0, 0,
                     bmpScreenCapture.Size,
                     CopyPixelOperation.SourceCopy);
}

Caveat: This method doesn't work properly for layered windows. Hans Passant's answer here explains the more complicated method required to get those in your screen shots.

Reading an Excel file in python using pandas

Here is an updated method with syntax that is more common in python code. It also prevents you from opening the same file multiple times.

import pandas as pd

sheet1, sheet2 = None, None
with pd.ExcelFile("PATH\FileName.xlsx") as reader:
    sheet1 = pd.read_excel(reader, sheet_name='Sheet1')
    sheet2 = pd.read_excel(reader, sheet_name='Sheet2')

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_excel.html

How to make nginx to listen to server_name:port

The server_namedocs directive is used to identify virtual hosts, they're not used to set the binding.

netstat tells you that nginx listens on 0.0.0.0:80 which means that it will accept connections from any IP.

If you want to change the IP nginx binds on, you have to change the listendocs rule.
So, if you want to set nginx to bind to localhost, you'd change that to:

listen 127.0.0.1:80;

In this way, requests that are not coming from localhost are discarded (they don't even hit nginx).

SQL Server - after insert trigger - update another column in the same table

Yea...having an additional step to update a table in which you can set the value in the inital insert is probably an extra, avoidable process. Do you have access to the original insert statement where you can actually just insert the part_description into the part_description_upper column using UPPER(part_description) value?

After thinking, you probably don't have access as you would have probably done that so should also give some options as well...

1) Depends on the need for this part_description_upper column, if just for "viewing" then can just use the returned part_description value and "ToUpper()" it (depending on programming language).

2) If want to avoid "realtime" processing, can just create a sql job to go through your values once a day during low traffic periods and update that column to the UPPER part_description value for any that are currently not set.

3) go with your trigger (and watch for recursion as others have mentioned)...

HTH

Dave

Benefits of using the conditional ?: (ternary) operator

The conditional operator is great for short conditions, like this:

varA = boolB ? valC : valD;

I use it occasionally because it takes less time to write something that way... unfortunately, this branching can sometimes be missed by another developer browsing over your code. Plus, code isn't usually that short, so I usually help readability by putting the ? and : on separate lines, like this:

doSomeStuffToSomething(shouldSomethingBeDone()
    ? getTheThingThatNeedsStuffDone()
    : getTheOtherThingThatNeedsStuffDone());

However, the big advantage to using if/else blocks (and why I prefer them) is that it's easier to come in later and add some additional logic to the branch,

if (shouldSomethingBeDone()) {
    doSomeStuffToSomething(getTheThingThatNeedsStuffDone());
    doSomeAdditionalStuff();
} else {
doSomeStuffToSomething(getTheOtherThingThatNeedsStuffDone());
}

or add another condition:

if (shouldSomethingBeDone()) {
    doSomeStuffToSomething(getTheThingThatNeedsStuffDone());
    doSomeAdditionalStuff();
} else if (shouldThisOtherThingBeDone()){
    doSomeStuffToSomething(getTheOtherThingThatNeedsStuffDone());
}

So, in the end, it's about convenience for you now (shorter to use :?) vs. convenience for you (and others) later. It's a judgment call... but like all other code-formatting issues, the only real rule is to be consistent, and be visually courteous to those who have to maintain (or grade!) your code.

(all code eye-compiled)

Convert generic list to dataset in C#

Have you tried binding the list to the datagridview directly? If not, try that first because it will save you lots of pain. If you have tried it already, please tell us what went wrong so we can better advise you. Data binding gives you different behaviour depending on what interfaces your data object implements. For example, if your data object only implements IEnumerable (e.g. List), you will get very basic one-way binding, but if it implements IBindingList as well (e.g. BindingList, DataView), then you get two-way binding.

How to run two jQuery animations simultaneously?

While it's true that consecutive calls to animate will give the appearance they are running at the same time, the underlying truth is they're distinct animations running very close to parallel.

To insure the animations are indeed running at the same time use:

$(function() {
    $('#first').animate({..., queue: 'my-animation'});
    $('#second').animate({..., queue: 'my-animation'}).dequeue('my-animation');
});

Further animations can be added to the 'my-animation' queue and all can be initiated provided the last animation dequeue's them.

Cheers, Anthony

How to parse freeform street/postal address out of text, and into components

libpostal: an open-source library to parse addresses, training with data from OpenStreetMap, OpenAddresses and OpenCage.

https://github.com/openvenues/libpostal (more info about it)

Other tools/services:

Ternary operator (?:) in Bash

Code:

a=$([ "$b" == 5 ] && echo "$c" || echo "$d")

Split string into tokens and save them in an array

Why strtok() is a bad idea

Do not use strtok() in normal code, strtok() uses static variables which have some problems. There are some use cases on embedded microcontrollers where static variables make sense but avoid them in most other cases. strtok() behaves unexpected when more than 1 thread uses it, when it is used in a interrupt or when there are some other circumstances where more than one input is processed between successive calls to strtok(). Consider this example:

#include <stdio.h>
#include <string.h>

//Splits the input by the / character and prints the content in between
//the / character. The input string will be changed
void printContent(char *input)
{
    char *p = strtok(input, "/");
    while(p)
    {
        printf("%s, ",p);
        p = strtok(NULL, "/");
    }
}

int main(void)
{
    char buffer[] = "abc/def/ghi:ABC/DEF/GHI";
    char *p = strtok(buffer, ":");
    while(p)
    {
        printContent(p);
        puts(""); //print newline
        p = strtok(NULL, ":");
    }
    return 0;
}

You may expect the output:

abc, def, ghi,
ABC, DEF, GHI,

But you will get

abc, def, ghi,

This is because you call strtok() in printContent() resting the internal state of strtok() generated in main(). After returning, the content of strtok() is empty and the next call to strtok() returns NULL.

What you should do instead

You could use strtok_r() when you use a POSIX system, this versions does not need static variables. If your library does not provide strtok_r() you can write your own version of it. This should not be hard and Stackoverflow is not a coding service, you can write it on your own.

HTTP 404 Page Not Found in Web Api hosted in IIS 7.5

i do nothing, just add this tag in web.config, its working this issue come up one of the following points

  1. Use Web Api in the same project using MVC or asp.net forms

  2. Use RouteConfig and WebApiConfig in Global.asax as GlobalConfiguration.Configure(WebApiConfig.Register); RouteConfig.RegisterRoutes(RouteTable.Routes);

  3. Use RouteConfig for 2 purposes, asp.net forms using with friendlyurl and mvc routing for MVC routing

we just use this tag in web.config, it will work.

<system.webServer>
<modules runAllManagedModulesForAllRequests="true">
   .........................
</modules>
</system.webServer>

Get selected row item in DataGrid WPF

There are a lot of answers here that probably work in a specific context, but I was simply trying to get the text value of the first cell in a selected row. While the accepted answer here was the closest for me, it still required creating a type and casting the row into that type. I was looking for a simpler solution, and this is what I came up with:

MessageBox.Show(((DataRowView)DataGrid.SelectedItem).Row[0].ToString());

This gives me the first column in the selected row. Hopefully this helps someone else.

Convert seconds into days, hours, minutes and seconds

The solution for this one I used (back to the days while learning PHP) without any in-functions:

$days = (int)($uptime/86400); //1day = 86400seconds
$rdays = (uptime-($days*86400)); 
//seconds remaining after uptime was converted into days
$hours = (int)($rdays/3600);//1hour = 3600seconds,converting remaining seconds into hours
$rhours = ($rdays-($hours*3600));
//seconds remaining after $rdays was converted into hours
$minutes = (int)($rhours/60); // 1minute = 60seconds, converting remaining seconds into minutes
echo "$days:$hours:$minutes";

Though this was an old question, new learners who come across this, may find this answer useful.

JavaScript function in href vs. onclick

In terms of javascript, one difference is that the this keyword in the onclick handler will refer to the DOM element whose onclick attribute it is (in this case the <a> element), whereas this in the href attribute will refer to the window object.

In terms of presentation, if an href attribute is absent from a link (i.e. <a onclick="[...]">) then, by default, browsers will display the text cursor (and not the often-desired pointer cursor) since it is treating the <a> as an anchor, and not a link.

In terms of behavior, when specifying an action by navigation via href, the browser will typically support opening that href in a separate window using either a shortcut or context menu. This is not possible when specifying an action only via onclick.


However, if you're asking what is the best way to get dynamic action from the click of a DOM object, then attaching an event using javascript separate from the content of the document is the best way to go. You could do this in a number of ways. A common way is to use a javascript library like jQuery to bind an event:

<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<a id="link" href="http://example.com/action">link text</a>
<script type="text/javascript">
    $('a#link').click(function(){ /* ... action ... */ })
</script>

Dynamically create Bootstrap alerts box through JavaScript

FWIW I created a JavaScript class that can be used at run-time.
It's over on GitHub, here.

There is a readme there with a more in-depth explanation, but I'll do a quick example below:

var ba = new BootstrapAlert();
ba.addP("Some content here");
$("body").append(ba.render());

The above would create a simple primary alert with a paragraph element inside containing the text "Some content here".

There are also options that can be set on initialisation.
For your requirement you'd do:

var ba = new BootstrapAlert({
    dismissible: true,
    background: 'warning'
});
ba.addP("Invalid Credentials");
$("body").append(ba.render());

The render method will return an HTML element, which can then be inserted into the DOM. In this case, we append it to the bottom of the body tag.

This is a work in progress library, but it still is in a very good working order.

Check if a key is down?

$('#mytextbox').keydown(function (e) {
            if (e.keyCode == 13) {
                if (e.altKey) {
                    alert("alt is pressed");
                }
            }
 });

if you press alt + enter, you will see the alert.

Delete all documents from index/type without deleting type

You can delete documents from type with following query:

POST /index/type/_delete_by_query
{
    "query" : { 
        "match_all" : {}
    }
}

I tested this query in Kibana and Elastic 5.5.2

Change background color for selected ListBox item

You have to create a new template for item selection like this.

<Setter Property="Template">
    <Setter.Value>
        <ControlTemplate TargetType="ListBoxItem">
            <Border
                BorderThickness="{TemplateBinding Border.BorderThickness}"
                Padding="{TemplateBinding Control.Padding}"
                BorderBrush="{TemplateBinding Border.BorderBrush}"
                Background="{TemplateBinding Panel.Background}"
                SnapsToDevicePixels="True">
                <ContentPresenter
                    Content="{TemplateBinding ContentControl.Content}"
                    ContentTemplate="{TemplateBinding ContentControl.ContentTemplate}"
                    HorizontalAlignment="{TemplateBinding Control.HorizontalContentAlignment}"
                    VerticalAlignment="{TemplateBinding Control.VerticalContentAlignment}"
                    SnapsToDevicePixels="{TemplateBinding UIElement.SnapsToDevicePixels}" />
            </Border>
        </ControlTemplate>
    </Setter.Value>
</Setter>

Call to undefined function oci_connect()

Download from Instant Client for Microsoft Windows (x64) and extract the files below to "c:\oracle":

instantclient-basic-windows.x64-12.1.0.2.0.zip

instantclient-sqlplus-windows.x64-12.1.0.2.0.zip

instantclient-sdk-windows.x64-12.1.0.2.0.zip This will create the following folder "C:\Oracle\instantclient_12_1".

Finally, add the "C:\Oracle\instantclient_12_1" folder to the PATH enviroment variable, placing it on the leftmost place.

Then Restart your server.

how to check and set max_allowed_packet mysql variable

The following PHP worked for me (using mysqli extension but queries should be the same for other extensions):

$db = new mysqli( 'localhost', 'user', 'pass', 'dbname' );
// to get the max_allowed_packet
$maxp = $db->query( 'SELECT @@global.max_allowed_packet' )->fetch_array();
echo $maxp[ 0 ];
// to set the max_allowed_packet to 500MB
$db->query( 'SET @@global.max_allowed_packet = ' . 500 * 1024 * 1024 );

So if you've got a query you expect to be pretty long, you can make sure that mysql will accept it with something like:

$sql = "some really long sql query...";
$db->query( 'SET @@global.max_allowed_packet = ' . strlen( $sql ) + 1024 );
$db->query( $sql );

Notice that I added on an extra 1024 bytes to the length of the string because according to the manual,

The value should be a multiple of 1024; nonmultiples are rounded down to the nearest multiple.

That should hopefully set the max_allowed_packet size large enough to handle your query. I haven't tried this on a shared host, so the same caveat as @Glebushka applies.

Python Requests package: Handling xml response

requests does not handle parsing XML responses, no. XML responses are much more complex in nature than JSON responses, how you'd serialize XML data into Python structures is not nearly as straightforward.

Python comes with built-in XML parsers. I recommend you use the ElementTree API:

import requests
from xml.etree import ElementTree

response = requests.get(url)

tree = ElementTree.fromstring(response.content)

or, if the response is particularly large, use an incremental approach:

    response = requests.get(url, stream=True)
    # if the server sent a Gzip or Deflate compressed response, decompress
    # as we read the raw stream:
    response.raw.decode_content = True

    events = ElementTree.iterparse(response.raw)
    for event, elem in events:
        # do something with `elem`

The external lxml project builds on the same API to give you more features and power still.

How can I install Python's pip3 on my Mac?

You could use Homebrew.

Then just run:

brew install python3

Explain ggplot2 warning: "Removed k rows containing missing values"

The behavior you're seeing is due to how ggplot2 deals with data that are outside the axis ranges of the plot. You can change this behavior depending on whether you use scale_y_continuous (or, equivalently, ylim) or coord_cartesian to set axis ranges, as explained below.

library(ggplot2)

# All points are visible in the plot
ggplot(mtcars, aes(mpg, hp)) + 
  geom_point()

In the code below, one point with hp = 335 is outside the y-range of the plot. Also, because we used scale_y_continuous to set the y-axis range, this point is not included in any other statistics or summary measures calculated by ggplot, such as the linear regression line.

ggplot(mtcars, aes(mpg, hp)) + 
  geom_point() +
  scale_y_continuous(limits=c(0,300)) +  # Change this to limits=c(0,335) and the warning disappars
  geom_smooth(method="lm")

Warning messages:
1: Removed 1 rows containing missing values (stat_smooth). 
2: Removed 1 rows containing missing values (geom_point).

In the code below, the point with hp = 335 is still outside the y-range of the plot, but this point is nevertheless included in any statistics or summary measures that ggplot calculates, such as the linear regression line. This is because we used coord_cartesian to set the y-axis range, and this function does not exclude points that are outside the plot ranges when it does other calculations on the data.

If you compare this and the previous plot, you can see that the linear regression line in the second plot has a slightly steeper slope, because the point with hp=335 is included when calculating the regression line, even though it's not visible in the plot.

ggplot(mtcars, aes(mpg, hp)) + 
  geom_point() +
  coord_cartesian(ylim=c(0,300)) +
  geom_smooth(method="lm")

Java word count program

Use split(regex) method. The result is an array of strings that was splited by regex.

String s = "Today is Holdiay Day";
System.out.println("Word count is = " + s.split(" ").length);

How does JavaScript .prototype work?

Javascript doesn't have inheritance in the usual sense, but it has the prototype chain.

prototype chain

If a member of an object can't be found in the object it looks for it in the prototype chain. The chain consists of other objects. The prototype of a given instance can be accessed with the __proto__ variable. Every object has one, as there is no difference between classes and instances in javascript.

The advantage of adding a function / variable to the prototype is that it has to be in the memory only once, not for every instance.

It's also useful for inheritance, because the prototype chain can consist of many other objects.

What is the difference between gravity and layout_gravity in Android?

android:gravity is used to specify how to place the content of the object within the object itself. In another word, android:gravity is used to specify the gravity of the content of the view.

android:layout_gravity is an attribution the child can supply to its parent, to specify the gravity the view within its parents.

For more details you can visit

http://developer.android.com/reference/android/widget/LinearLayout.LayoutParams.html

How to embed a SWF file in an HTML page?

I use http://wiltgen.net/objecty/, it helps to embed media content and avoid the IE "click to activate" problem.

Creating an Instance of a Class with a variable in Python

I think you can use eval. Something like this

def toclass(strcls):
    return eval(strcls)()

Access a function variable outside the function without using "global"

The problem is you were calling print x.bye after you set x as a string. When you run x = hi() it runs hi() and sets the value of x to 5 (the value of bye; it does NOT set the value of x as a reference to the bye variable itself). EX: bye = 5; x = bye; bye = 4; print x; prints 5, not 4

Also, you don't have to run hi() twice, just run x = hi(), not hi();x=hi() (the way you had it it was running hi(), not doing anything with the resulting value of 5, and then rerunning the same hi() and saving the value of 5 to the x variable.

So full code should be

def hi():
    something
    something
    bye = 5
    return bye 
x = hi()
print x

If you wanted to return multiple variables, one option would be to use a list, or dictionary, depending on what you need.

ex:

def hi():
    something
    xyz = { 'bye': 7, 'foobar': 8}
    return xyz
x = hi()
print x['bye']

more on python dictionaries at http://docs.python.org/2/tutorial/datastructures.html#dictionaries

Could not load file or assembly ... An attempt was made to load a program with an incorrect format (System.BadImageFormatException)

You may need to change the Appication Pool setting "Enable 32bit Applications" to TRUE in IIS7 if you have at least 1 32bit dll\exe in your project.

How to install an apk on the emulator in Android Studio?

1.Install Android studio. 2.Launch AVD Manager 3.Verify environment variable in set properly based on OS(.bash_profile in mac and environment Variable in windows) 4. launch emulator 5. verify via adb devices command. 6.use adb install apkFileName.apk

How to break a while loop from an if condition inside the while loop?

The break keyword does exactly that. Here is a contrived example:

public static void main(String[] args) {
  int i = 0;
  while (i++ < 10) {
    if (i == 5) break;
  }
  System.out.println(i); //prints 5
}

If you were actually using nested loops, you would be able to use labels.

How do you clear a stringstream variable?

You can clear the error state and empty the stringstream all in one line

std::stringstream().swap(m); // swap m with a default constructed stringstream

This effectively resets m to a default constructed state

json.dumps vs flask.jsonify

The choice of one or another depends on what you intend to do. From what I do understand:

  • jsonify would be useful when you are building an API someone would query and expect json in return. E.g: The REST github API could use this method to answer your request.

  • dumps, is more about formating data/python object into json and work on it inside your application. For instance, I need to pass an object to my representation layer where some javascript will display graph. You'll feed javascript with the Json generated by dumps.

Difference between modes a, a+, w, w+, and r+ in built-in open function?

The opening modes are exactly the same as those for the C standard library function fopen().

The BSD fopen manpage defines them as follows:

 The argument mode points to a string beginning with one of the following
 sequences (Additional characters may follow these sequences.):

 ``r''   Open text file for reading.  The stream is positioned at the
         beginning of the file.

 ``r+''  Open for reading and writing.  The stream is positioned at the
         beginning of the file.

 ``w''   Truncate file to zero length or create text file for writing.
         The stream is positioned at the beginning of the file.

 ``w+''  Open for reading and writing.  The file is created if it does not
         exist, otherwise it is truncated.  The stream is positioned at
         the beginning of the file.

 ``a''   Open for writing.  The file is created if it does not exist.  The
         stream is positioned at the end of the file.  Subsequent writes
         to the file will always end up at the then current end of file,
         irrespective of any intervening fseek(3) or similar.

 ``a+''  Open for reading and writing.  The file is created if it does not
         exist.  The stream is positioned at the end of the file.  Subse-
         quent writes to the file will always end up at the then current
         end of file, irrespective of any intervening fseek(3) or similar.

How to create JSON string in JavaScript?

Javascript doesn't handle Strings over multiple lines.

You will need to concatenate those:

var obj = '{'
       +'"name" : "Raj",'
       +'"age"  : 32,'
       +'"married" : false'
       +'}';

You can also use template literals in ES6 and above: (See here for the documentation)

var obj = `{
           "name" : "Raj",
           "age" : 32,
           "married" : false,
           }`;

Finding the 'type' of an input element

If you want to check the type of input within form, use the following code:

<script>
    function getFind(obj) {
    for (i = 0; i < obj.childNodes.length; i++) {
        if (obj.childNodes[i].tagName == "INPUT") {
            if (obj.childNodes[i].type == "text") {
                alert("this is Text Box.")
            }
            if (obj.childNodes[i].type == "checkbox") {
                alert("this is CheckBox.")
            }
            if (obj.childNodes[i].type == "radio") {
                alert("this is Radio.")
            }
        }
        if (obj.childNodes[i].tagName == "SELECT") {
            alert("this is Select")
        }
    }
}
</script>     

<script>    
    getFind(document.myform);  
</script>

How to pass a value from Vue data to href?

Or you can do that with ES6 template literal:

<a :href="`/job/${r.id}`"

How do I close a single buffer (out of many) in Vim?

You can map next and previous to function keys too, making cycling through buffers a breeze

map <F2> :bprevious<CR>
map <F3> :bnext<CR>

from my vimrc

Where can I find the TypeScript version installed in Visual Studio?

The tsc -v command run technically reads the TypeScript compiler version within the SDK directory set within the Windows Path variable. This doesn't necessarily reflect the latest version installed as the Path variable is not updated with subsequent installations.

The version that VS.NET uses to compile the TypeScript is what's in the project's configuration:

<TypeScriptToolsVersion>1.5</TypeScriptToolsVersion>

To help explain this more in detail I created the following post which has the specifics on the TypeScript versions installed, and which version VS.NET uses to compile the TypeScript files.

Which Version of TypeScript is Installed and Which Version is Visual Studio Using?

I also added a feature request on Microsoft Connect to make viewing and switching the TypeScript targeted version in VS.NET easier. This isn't really a TypeScript feature request as much as it is a VS.NET IDE enhancement.

Allow switching TypeScript configured version from Project Properties IDE

Is there a standard sign function (signum, sgn) in C/C++?

In general, there is no standard signum function in C/C++, and the lack of such a fundamental function tells you a lot about these languages.

Apart from that, I believe both majority viewpoints about the right approach to define such a function are in a way correct, and the "controversy" about it is actually a non-argument once you take into account two important caveats:

  • A signum function should always return the type of its operand, similarly to an abs() function, because signum is usually used for multiplication with an absolute value after the latter has been processed somehow. Therefore, the major use case of signum is not comparisons but arithmetic, and the latter shouldn't involve any expensive integer-to/from-floating-point conversions.

  • Floating point types do not feature a single exact zero value: +0.0 can be interpreted as "infinitesimally above zero", and -0.0 as "infinitesimally below zero". That's the reason why comparisons involving zero must internally check against both values, and an expression like x == 0.0 can be dangerous.

Regarding C, I think the best way forward with integral types is indeed to use the (x > 0) - (x < 0) expression, as it should be translated in a branch-free fashion, and requires only three basic operations. Best define inline functions that enforce a return type matching the argument type, and add a C11 define _Generic to map these functions to a common name.

With floating point values, I think inline functions based on C11 copysignf(1.0f, x), copysign(1.0, x), and copysignl(1.0l, x) are the way to go, simply because they're also highly likely to be branch-free, and additionally do not require casting the result from integer back into a floating point value. You should probably comment prominently that your floating point implementations of signum will not return zero because of the peculiarities of floating point zero values, processing time considerations, and also because it is often very useful in floating point arithmetic to receive the correct -1/+1 sign, even for zero values.

"Could not find Developer Disk Image"

I am facing the same issue on Xcode 7.3 and my device version is iOS 10.

This error is shown when your Xcode is old and the related device you are using is updated to latest version. First of all, install the latest Xcode version.

We can solve this issue by following the below steps:-

  • Open Finder select Applications
  • Right click on Xcode 8, select "Show Package Contents", "Contents", "Developer", "Platforms", "iPhoneOS.Platform", "Device Support"
  • Copy the 10.0 folder (or above for later version).
  • Back in Finder select Applications again
  • Right click on Xcode 7.3, select "Show Package Contents", "Contents", "Developer", "Platforms", "iPhoneOS.Platform", "Device Support"
  • Paste the 10.0 folder

If everything worked properly, your Xcode has a new developer disk image. Close the finder now, and quit your Xcode. Open your Xcode and the error will be gone. Now you can connect your latest device to old Xcode versions.

Thanks

Get index of array element faster than O(n)

Convert the array into a hash. Then look for the key.

array = ['a', 'b', 'c']
hash = Hash[array.map.with_index.to_a]    # => {"a"=>0, "b"=>1, "c"=>2}
hash['b'] # => 1

How to start color picker on Mac OS?

You can call up the color picker from any Cocoa application (TextEdit, Mail, Keynote, Pages, etc.) by hitting Shift-Command-C

The following article explains more about using Mac OS's Color Picker.

http://www.macworld.com/article/46746/2005/09/colorpickersecrets.html

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

Kindly use this one liner:

Sheets.Add(After:=Sheets(Sheets.Count)).Name = "new_sheet_name"

How can I use external JARs in an Android project?

If you are using gradle build system, follow these steps:

  1. put jar files inside respective libs folder of your android app. You will generally find it at Project > app > libs. If libs folder is missing, create one.

  2. add this to your build.gradle file your app. (Not to your Project's build.gradle)

    dependencies {
        compile fileTree(dir: 'libs', include: '*.jar')
        // other dependencies
    }
    

    This will include all your jar files available in libs folder.

If don't want to include all jar files, then you can add it individually.

compile fileTree(dir: 'libs', include: 'file.jar')

Get the name of an object's type

You can use the instanceof operator to see if an object is an instance of another, but since there are no classes, you can't get a class name.

How do I collapse a table row in Bootstrap?

You are using collapse on the div inside of your table row (tr). So when you collapse the div, the row is still there. You need to change it to where your id and class are on the tr instead of the div.

Change this:

<tr><td><div class="collapse out" id="collapseme">Should be collapsed</div></td></tr>

to this:

<tr class="collapse out" id="collapseme"><td><div>Should be collapsed</div></td></tr>

JSFiddle: http://jsfiddle.net/KnuU6/21/

EDIT: If you are unable to upgrade to 3.0.0, I found a JQuery workaround in 2.3.2:

Remove your data-toggle and data-target and add this JQuery to your button.

$(".btn").click(function() {
    if($("#collapseme").hasClass("out")) {
        $("#collapseme").addClass("in");
        $("#collapseme").removeClass("out");
    } else {
        $("#collapseme").addClass("out");
        $("#collapseme").removeClass("in");
    }
});

JSFiddle: http://jsfiddle.net/KnuU6/25/

Escape curly brace '{' in String.Format

Use double braces {{ or }} so your code becomes:

sb.AppendLine(String.Format("public {0} {1} {{ get; private set; }}", 
prop.Type, prop.Name));

// For prop.Type of "Foo" and prop.Name of "Bar", the result would be:
// public Foo Bar { get; private set; }

How to get DropDownList SelectedValue in Controller in MVC

If you're looking for something lightweight, I'd append a parameter to your action.

[HttpPost]
public ActionResult ShowAllMobileDetails(MobileViewModel MV, string ddlVendor)
{           
    string strDDLValue = ddlVendor; // Of course, this becomes silly.

    return View(MV);
}

What's happening in your code now, is you're passing the first string argument of "ddlVendor" to Html.DropDownList, and that's telling the MVC framework to create a <select> element with a name of "ddlVendor." When the user submits the form client-side, then, it will contain a value to that key.

When MVC tries to parse that request into MV, it's going to look for MobileList and Vendor and not find either, so it's not going to be populated. By adding this parameter, or using FormCollection as another answer has suggested, you're asking MVC to specifically look for a form element with that name, so it should then populate the parameter value with the posted value.

Fail to create Android virtual Device, "No system image installed for this Target"

If you use Android Studio .Open the SDK-Manager, checked "Show Package Details" you will find out "Android Wear ARM EABI v7a System Image" download it , success !

Change / Add syntax highlighting for a language in Sublime 2/3

Syntax highlighting is controlled by the theme you use, accessible through Preferences -> Color Scheme. Themes highlight different keywords, functions, variables, etc. through the use of scopes, which are defined by a series of regular expressions contained in a .tmLanguage file in a language's directory/package. For example, the JavaScript.tmLanguage file assigns the scopes source.js and variable.language.js to the this keyword. Since Sublime Text 3 is using the .sublime-package zip file format to store all the default settings it's not very straightforward to edit the individual files.

Unfortunately, not all themes contain all scopes, so you'll need to play around with different ones to find one that looks good, and gives you the highlighting you're looking for. There are a number of themes that are included with Sublime Text, and many more are available through Package Control, which I highly recommend installing if you haven't already. Make sure you follow the ST3 directions.

As it so happens, I've developed the Neon Color Scheme, available through Package Control, that you might want to take a look at. My main goal, besides trying to make a broad range of languages look as good as possible, was to identify as many different scopes as I could - many more than are included in the standard themes. While the JavaScript language definition isn't as thorough as Python's, for example, Neon still has a lot more diversity than some of the defaults like Monokai or Solarized.

jQuery highlighted with Neon Theme

I should note that I used @int3h's Better JavaScript language definition for this image instead of the one that ships with Sublime. It can be installed via Package Control.

UPDATE

Of late I've discovered another JavaScript replacement language definition - JavaScriptNext - ES6 Syntax. It has more scopes than the base JavaScript or even Better JavaScript. It looks like this on the same code:

JavaScriptNext

Also, since I originally wrote this answer, @skuroda has released PackageResourceViewer via Package Control. It allows you to seamlessly view, edit and/or extract parts of or entire .sublime-package packages. So, if you choose, you can directly edit the color schemes included with Sublime.

ANOTHER UPDATE

With the release of nearly all of the default packages on Github, changes have been coming fast and furiously. The old JS syntax has been completely rewritten to include the best parts of JavaScript Next ES6 Syntax, and now is as fully ES6-compatible as can be. A ton of other changes have been made to cover corner and edge cases, improve consistency, and just overall make it better. The new syntax has been included in the (at this time) latest dev build 3111.

If you'd like to use any of the new syntaxes with the current beta build 3103, simply clone the Github repo someplace and link the JavaScript (or whatever language(s) you want) into your Packages directory - find it on your system by selecting Preferences -> Browse Packages.... Then, simply do a git pull in the original repo directory from time to time to refresh any changes, and you can enjoy the latest and greatest! I should note that the repo uses the new .sublime-syntax format instead of the old .tmLanguage one, so they will not work with ST3 builds prior to 3084, or with ST2 (in both cases, you should have upgraded to the latest beta or dev build anyway).

I'm currently tweaking my Neon Color Scheme to handle all of the new scopes in the new JS syntax, but most should be covered already.

Restrict varchar() column to specific values?

Have you already looked at adding a check constraint on that column which would restrict values? Something like:

CREATE TABLE SomeTable
(
   Id int NOT NULL,
   Frequency varchar(200),
   CONSTRAINT chk_Frequency CHECK (Frequency IN ('Daily', 'Weekly', 'Monthly', 'Yearly'))
)

Android difference between Two Dates

I use this: send start and end date in millisecond

public int GetDifference(long start,long end){
    Calendar cal = Calendar.getInstance();
    cal.setTimeInMillis(start);
    int hour = cal.get(Calendar.HOUR_OF_DAY);
    int min = cal.get(Calendar.MINUTE);
    long t=(23-hour)*3600000+(59-min)*60000;

    t=start+t;

    int diff=0;
    if(end>t){
        diff=(int)((end-t)/ TimeUnit.DAYS.toMillis(1))+1;
    }

    return  diff;
}

JavaScript alert box with timer

I finished my time alert with a unwanted effect.... Browsers add stuff to windows. My script is an aptated one and I will show after the following text.

I found a CSS script for popups, which doesn't have unwanted browser stuff. This was written by Prakash:- https://codepen.io/imprakash/pen/GgNMXO. This script I will show after the following text.

This CSS script above looks professional and is alot more tidy. This button could be a clickable company logo image. By suppressing this button/image from running a function, this means you can run this function from inside javascript or call it with CSS, without it being run by clicking it.

This popup alert stays inside the window that popped it up. So if you are a multi-tasker you won't have trouble knowing what alert goes with what window.

The statements above are valid ones.... (Please allow). How these are achieved will be down to experimentation, as my knowledge of CSS is limited at the moment, but I learn fast.

CSS menus/DHTML use mouseover(valid statement).

I have a CSS menu script of my own which is adapted from 'Javascript for dummies' that pops up a menu alert. This works, but text size is limited. This hides under the top window banner. This could be set to be timed alert. This isn't great, but I will show this after the following text.

The Prakash script above I feel could be the answer if you can adapt it.

Scripts that follow:- My adapted timed window alert, Prakash's CSS popup script, my timed menu alert.

1.

<html>
      <head>
            <title></title>
            <script language="JavaScript">
        // Variables
            leftposition=screen.width-350
            strfiller0='<table border="1" cellspacing="0" width="98%"><tr><td><br>'+'Alert: '+'<br><hr width="98%"><br>'
            strfiller1='&nbsp;&nbsp;&nbsp;&nbsp; This alert is a timed one.'+'<br><br><br></td></tr></table>'
            temp=strfiller0+strfiller1
        // Javascript
            // This code belongs to Stephen Mayes Date: 25/07/2016 time:8:32 am


            function preview(){
                            preWindow= open("", "preWindow","status=no,toolbar=no,menubar=yes,width=350,height=180,left="+leftposition+",top=0");
                            preWindow.document.open();
                            preWindow.document.write(temp);
                            preWindow.document.close();
                    setTimeout(function(){preWindow.close()},4000); 
            }

             </script>
      </head>
<body>
    <input type="button" value=" Open " onclick="preview()">
</body>
</html>

2.

<style>
body {
  font-family: Arial, sans-serif;
  background: url(http://www.shukatsu-note.com/wp-content/uploads/2014/12/computer-564136_1280.jpg) no-repeat;
  background-size: cover;
  height: 100vh;
}

h1 {
  text-align: center;
  font-family: Tahoma, Arial, sans-serif;
  color: #06D85F;
  margin: 80px 0;
}

.box {
  width: 40%;
  margin: 0 auto;
  background: rgba(255,255,255,0.2);
  padding: 35px;
  border: 2px solid #fff;
  border-radius: 20px/50px;
  background-clip: padding-box;
  text-align: center;
}

.button {
  font-size: 1em;
  padding: 10px;
  color: #fff;
  border: 2px solid #06D85F;
  border-radius: 20px/50px;
  text-decoration: none;
  cursor: pointer;
  transition: all 0.3s ease-out;
}
.button:hover {
  background: #06D85F;
}

.overlay {
  position: fixed;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.7);
  transition: opacity 500ms;
  visibility: hidden;
  opacity: 0;
}
.overlay:target {
  visibility: visible;
  opacity: 1;
}

.popup {
  margin: 70px auto;
  padding: 20px;
  background: #fff;
  border-radius: 5px;
  width: 30%;
  position: relative;
  transition: all 5s ease-in-out;
}

.popup h2 {
  margin-top: 0;
  color: #333;
  font-family: Tahoma, Arial, sans-serif;
}
.popup .close {
  position: absolute;
  top: 20px;
  right: 30px;
  transition: all 200ms;
  font-size: 30px;
  font-weight: bold;
  text-decoration: none;
  color: #333;
}
.popup .close:hover {
  color: #06D85F;
}
.popup .content {
  max-height: 30%;
  overflow: auto;
}

@media screen and (max-width: 700px){
  .box{
    width: 70%;
  }
  .popup{
    width: 70%;
  }
}
</style>
<script>
    // written by Prakash:- https://codepen.io/imprakash/pen/GgNMXO 
</script>
<body>
<h1>Popup/Modal Windows without JavaScript</h1>
<div class="box">
    <a class="button" href="#popup1">Let me Pop up</a>
</div>

<div id="popup1" class="overlay">
    <div class="popup">
        <h2>Here i am</h2>
        <a class="close" href="#">&times;</a>
        <div class="content">
            Thank to pop me out of that button, but now i'm done so you can close this window.
        </div>
    </div>
</div>
</body>

3.

<HTML>
<HEAD>
<TITLE>Using DHTML to Create Sliding Menus (From JavaScript For Dummies, 4th Edition)</TITLE>
<SCRIPT LANGUAGE="JavaScript" TYPE="text/javascript">
<!-- Hide from older browsers

function displayMenu(currentPosition,nextPosition) {

    // Get the menu object located at the currentPosition on the screen
    var whichMenu = document.getElementById(currentPosition).style;

    if (displayMenu.arguments.length == 1) {
        // Only one argument was sent in, so we need to
        // figure out the value for "nextPosition"

        if (parseInt(whichMenu.top) == -5) {
            // Only two values are possible: one for mouseover
            // (-5) and one for mouseout (-90). So we want
            // to toggle from the existing position to the
            // other position: i.e., if the position is -5,
            // set nextPosition to -90...
            nextPosition = -90;
        }
        else {
            // Otherwise, set nextPosition to -5
            nextPosition = -5;
        }
    }

    // Redisplay the menu using the value of "nextPosition"
    whichMenu.top = nextPosition + "px";
}

// End hiding-->
</SCRIPT>

<STYLE TYPE="text/css">
<!--

.menu {position:absolute; font:10px arial, helvetica, sans-serif; background-color:#ffffcc; layer-background-color:#ffffcc; top:-90px}
#resMenu {right:10px; width:-130px}
A {text-decoration:none; color:#000000}
A:hover {background-color:pink; color:blue}

 -->

</STYLE>

</HEAD>

<BODY BGCOLOR="white">

<div id="resMenu" class="menu" onmouseover="displayMenu('resMenu',-5)" onmouseout="displayMenu('resMenu',-90)"><br />
<a href="#"> Alert:</a><br>
<a href="#"> </a><br>
<a href="#"> You pushed that button again... Didn't yeah? </a><br>
<a href="#"> </a><br>
<a href="#"> </a><br>
<a href="#"> </a><br>
</div>
ddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd
<input type="button" value="Wake that alert up" onclick="displayMenu('resMenu',-5)">
</BODY>
</HTML>

Dynamically add event listener

I will add a StackBlitz example and a comment to the answer from @tahiche.

The return value is a function to remove the event listener after you have added it. It is considered good practice to remove event listeners when you don't need them anymore. So you can store this return value and call it inside your ngOnDestroy method.

I admit that it might seem confusing at first, but it is actually a very useful feature. How else can you clean up after yourself?

export class MyComponent implements OnInit, OnDestroy {

  public removeEventListener: () => void;

  constructor(
    private renderer: Renderer2, 
    private elementRef: ElementRef
  ) {
  }

  public ngOnInit() {
    this.removeEventListener = this.renderer.listen(this.elementRef.nativeElement, 'click', (event) => {
      if (event.target instanceof HTMLAnchorElement) {
        // Prevent opening anchors the default way
        event.preventDefault();
        // Your custom anchor click event handler
        this.handleAnchorClick(event);
      }
    });
  }

  public ngOnDestroy() {
    this.removeEventListener();
  }
}

You can find a StackBlitz here to show how this could work for catching clicking on anchor elements.

I added a body with an image as follows:
<img src="x" onerror="alert(1)"></div>
to show that the sanitizer is doing its job.

Here in this fiddle you find the same body attached to an innerHTML without sanitizing it and it will demonstrate the issue.

How to retrieve data from a SQL Server database in C#?

create a class called DbManager:

Class DbManager
{
 SqlConnection connection;
 SqlCommand command;

       public DbManager()
      {
        connection = new SqlConnection();
        connection.ConnectionString = @"Data Source=.     \SQLEXPRESS;AttachDbFilename=|DataDirectory|DatabaseName.mdf;Integrated Security=True;User Instance=True";
        command = new SqlCommand();
        command.Connection = connection;
        command.CommandType = CommandType.Text;
     } // constructor

 public bool GetUsersData(ref string lastname, ref string firstname, ref string age)
     {
        bool returnvalue = false;
        try
        {
            command.CommandText = "select * from TableName where firstname=@firstname and lastname=@lastname";
            command.Parameters.Add("firstname",SqlDbType.VarChar).Value = firstname;
 command.Parameters.Add("lastname",SqlDbType.VarChar).Value = lastname; 
            connection.Open();
            SqlDataReader reader= command.ExecuteReader();
            if (reader.HasRows)
            {
                while (reader.Read())
                {

                    lastname = reader.GetString(1);
                    firstname = reader.GetString(2);

                    age = reader.GetString(3);


                }
            }
            returnvalue = true;
        }
        catch
        { }
        finally
        {
            connection.Close();
        }
        return returnvalue;

    }

then double click the retrieve button(e.g btnretrieve) on your form and insert the following code:

 private void btnretrieve_Click(object sender, EventArgs e)
    {
        try
        {
            string lastname = null;
            string firstname = null;
            string age = null;

            DbManager db = new DbManager();

            bool status = db.GetUsersData(ref surname, ref firstname, ref age);
                if (status)
                {
                txtlastname.Text = surname;
                txtfirstname.Text = firstname;
                txtAge.Text = age;       
               }
          }
       catch
          {

          }
   }

How can I create an error 404 in PHP?

Create custom error pages through .htaccess file

1. 404 - page not found

 RewriteEngine On
 ErrorDocument 404 /404.html

2. 500 - Internal Server Error

RewriteEngine On
ErrorDocument 500 /500.html

3. 403 - Forbidden

RewriteEngine On
ErrorDocument 403 /403.html

4. 400 - Bad request

RewriteEngine On
ErrorDocument 400 /400.html

5. 401 - Authorization Required

RewriteEngine On
ErrorDocument 401 /401.html

You can also redirect all error to single page. like

RewriteEngine On
ErrorDocument 404 /404.html
ErrorDocument 500 /404.html
ErrorDocument 403 /404.html
ErrorDocument 400 /404.html
ErrorDocument 401 /401.html

Is there any kind of hash code function in JavaScript?

The JavaScript specification defines indexed property access as performing a toString conversion on the index name. For example,

myObject[myProperty] = ...;

is the same as

myObject[myProperty.toString()] = ...;

This is necessary as in JavaScript

myObject["someProperty"]

is the same as

myObject.someProperty

And yes, it makes me sad as well :-(

How can I copy the output of a command directly into my clipboard?

Based on previous posts, I ended up with the following light-weigh alias solution that can be added to .bashrc:

if [ -n "$(type -P xclip)" ]
then
  alias xclip='xclip -selection clipboard'
  alias clipboard='if [ -p /dev/stdin ]; then xclip -in; fi; xclip -out'
fi

Examples:

# Copy
$ date | clipboard
Sat Dec 29 14:12:57 PST 2018

# Paste
$ date
Sat Dec 29 14:12:57 PST 2018

# Chain
$ date | clipboard | wc
   1       6      29

Efficient way to remove keys with empty strings from a dict

If you have a nested dictionary, and you want this to work even for empty sub-elements, you can use a recursive variant of BrenBarn's suggestion:

def scrub_dict(d):
    if type(d) is dict:
        return dict((k, scrub_dict(v)) for k, v in d.iteritems() if v and scrub_dict(v))
    else:
        return d

Calling variable defined inside one function from another function

def anotherFunction(word):
    for letter in word:              
        print("_", end=" ")

def oneFunction(lists):
    category = random.choice(list(lists.keys()))
    word = random.choice(lists[category])
    return anotherFunction(word)

Java to Jackson JSON serialization: Money fields

You can use a custom serializer at your money field. Here's an example with a MoneyBean. The field amount gets annotated with @JsonSerialize(using=...).

public class MoneyBean {
    //...

    @JsonProperty("amountOfMoney")
    @JsonSerialize(using = MoneySerializer.class)
    private BigDecimal amount;

    //getters/setters...
}

public class MoneySerializer extends JsonSerializer<BigDecimal> {
    @Override
    public void serialize(BigDecimal value, JsonGenerator jgen, SerializerProvider provider) throws IOException,
            JsonProcessingException {
        // put your desired money style here
        jgen.writeString(value.setScale(2, BigDecimal.ROUND_HALF_UP).toString());
    }
}

That's it. A BigDecimal is now printed in the right way. I used a simple testcase to show it:

@Test
public void jsonSerializationTest() throws Exception {
     MoneyBean m = new MoneyBean();
     m.setAmount(new BigDecimal("20.3"));

     ObjectMapper mapper = new ObjectMapper();
     assertEquals("{\"amountOfMoney\":\"20.30\"}", mapper.writeValueAsString(m));
}

C compile error: "Variable-sized object may not be initialized"

I am assuming that you are using a C99 compiler (with support for dynamically sized arrays). The problem in your code is that at the time when the compilers sees your variable declaration it cannot know how many elements there are in the array (I am also assuming here, from the compiler error that length is not a compile time constant).

You must manually initialize that array:

int boardAux[length][length];
memset( boardAux, 0, length*length*sizeof(int) );

Error Code: 1062. Duplicate entry '1' for key 'PRIMARY'

The problem is related with your file - you are trying to create a DB using a copy - at the top of your file you will find something like this:

CREATE DATABASE IF NOT EXISTS *THE_NAME_OF_YOUR_DB* DEFAULT CHARACTER SET latin1 COLLATE latin1_general_ci; USE *THE_NAME_OF_YOUR_DB*;

and I'm sure that you already have a DB with this name - IN THE SAME SERVER - please check. Just change the name OR ERASE THIS LINE!

Coding Conventions - Naming Enums

enum MyEnum {VALUE_1,VALUE_2}

is (approximately) like saying

class MyEnum {

    public static final MyEnum VALUE_1 = new MyEnum("VALUE_1");
    public static final MyEnum VALUE_2 = new MyEnum("VALUE_2");

    private final name;

    private MyEnum(String name) {
        this.name = name;
    }

    public String name() { return this.name }
}

so I guess the all caps is strictly more correct, but still I use the class name convention since I hate all caps wherever

Using multiple case statements in select query

There are two ways to write case statements, you seem to be using a combination of the two

case a.updatedDate
    when 1760 then 'Entered on' + a.updatedDate
    when 1710 then 'Viewed on' + a.updatedDate
    else 'Last Updated on' + a.updateDate
end

or

case 
    when a.updatedDate = 1760 then 'Entered on' + a.updatedDate
    when a.updatedDate = 1710 then 'Viewed on' + a.updatedDate
    else 'Last Updated on' + a.updateDate
end

are equivalent. They may not work because you may need to convert date types to varchars to append them to other varchars.

Plotting in a non-blocking way with Matplotlib

I spent a long time looking for solutions, and found this answer.

It looks like, in order to get what you (and I) want, you need the combination of plt.ion(), plt.show() (not with block=False) and, most importantly, plt.pause(.001) (or whatever time you want). The pause is needed because the GUI events happen while the main code is sleeping, including drawing. It's possible that this is implemented by picking up time from a sleeping thread, so maybe IDEs mess with that—I don't know.

Here's an implementation that works for me on python 3.5:

import numpy as np
from matplotlib import pyplot as plt

def main():
    plt.axis([-50,50,0,10000])
    plt.ion()
    plt.show()

    x = np.arange(-50, 51)
    for pow in range(1,5):   # plot x^1, x^2, ..., x^4
        y = [Xi**pow for Xi in x]
        plt.plot(x, y)
        plt.draw()
        plt.pause(0.001)
        input("Press [enter] to continue.")

if __name__ == '__main__':
    main()

How to add a button to UINavigationBar?

In Swift 2, you would do:

let rightButton: UIBarButtonItem = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Done, target: nil, action: nil)
self.navigationItem.rightBarButtonItem = rightButton

(Not a major change) In Swift 4/5, it will be:

let rightButton: UIBarButtonItem = UIBarButtonItem(title: "Done", style: UIBarButtonItem.Style.done, target: nil, action: nil)
self.navigationItem.rightBarButtonItem = rightButton

Flutter- wrapping text

Container(
  color: Color.fromRGBO(224, 251, 253, 1.0),
  child: ListTile(
    dense: true,
    title: Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        RichText(
          textAlign: TextAlign.left,
          softWrap: true,
          text: TextSpan(children: <TextSpan>
          [
            TextSpan(text: "hello: ",
                style: TextStyle(
                    color: Colors.black, fontWeight: FontWeight.bold)),
            TextSpan(text: "I hope this helps",
                style: TextStyle(color: Colors.black)),
          ]
          ),
        ),
      ],
    ),
  ),
),

One-line list comprehension: if-else variants

You can do that with list comprehension too:

A=[[x*100, x][x % 2 != 0] for x in range(1,11)]
print A

regex with space and letters only?

$('#input').on('keyup', function() {
     var RegExpression = /^[a-zA-Z\s]*$/;  
     ...

});

\s will allow the space

java.net.SocketException: Connection reset by peer: socket write error When serving a file

I face this problem but resolution is very simple. I am writing the 1 MB file in 1024 Byte Buffer causing this issue. To Understand refer code before and After Fix.

Code with Excepion

DataOutputStream dos = new DataOutputStream(s.getOutputStream());
        FileInputStream fis = new FileInputStream(file);
        byte[] buffer = new byte[1024];
        
        while (fis.read(buffer) > 0) {
            dos.write(buffer);
        }
    

After Fixes:

DataOutputStream dos = new DataOutputStream(s.getOutputStream());
        FileInputStream fis = new FileInputStream(file);
        byte[] buffer = new byte[102400];
        
        while (fis.read(buffer) > 0) {
            dos.write(buffer);
        }

    

How to add a new column to an existing sheet and name it?

For your question as asked

Columns(3).Insert
Range("c1:c4") = Application.Transpose(Array("Loc", "uk", "us", "nj"))

If you had a way of automatically looking up the data (ie matching uk against employer id) then you could do that in VBA

How to solve ERR_CONNECTION_REFUSED when trying to connect to localhost running IISExpress - Error 502 (Cannot debug from Visual Studio)?

If you are using "real" IIS, this can occur if the W3SVC (World Wide Web Publishing) service is stopped.

Should seem obvious but if you accidentally stopped the service or have it set to manual this could happen to you.

I know the title says IIS express however google doesn't seem to filter out the express even when using a -Express hint so hopefully this helps someone else who found this page instead of an IIS-specific one.

LaTeX: Prevent line break in a span of text

Define myurl command:


\def\myurl{\hfil\penalty 100 \hfilneg \hbox}

I don't want to cause line overflows, 
I'd just rather LaTeX insert linebreaks before 
\myurl{\tt http://stackoverflow.com/questions/1012799/} 
regions rather than inside them.

Sort an Array by keys based on another Array?

Just use array_merge or array_replace. Array_merge works by starting with the array you give it (in the proper order) and overwriting/adding the keys with data from your actual array:

$customer['address'] = '123 fake st';
$customer['name'] = 'Tim';
$customer['dob'] = '12/08/1986';
$customer['dontSortMe'] = 'this value doesnt need to be sorted';

$properOrderedArray = array_merge(array_flip(array('name', 'dob', 'address')), $customer);
//Or:
$properOrderedArray = array_replace(array_flip(array('name', 'dob', 'address')), $customer);

//$properOrderedArray -> array('name' => 'Tim', 'address' => '123 fake st', 'dob' => '12/08/1986', 'dontSortMe' => 'this value doesnt need to be sorted')

ps - I'm answering this 'stale' question, because I think all the loops given as previous answers are overkill.

Remove non-ASCII characters from CSV

# -i (inplace)

sed -i 's/[\d128-\d255]//g' FILENAME

How to properly ignore exceptions

It's generally considered best-practice to only catch the errors you are interested in. In the case of shutil.rmtree it's probably OSError:

>>> shutil.rmtree("/fake/dir")
Traceback (most recent call last):
    [...]
OSError: [Errno 2] No such file or directory: '/fake/dir'

If you want to silently ignore that error, you would do:

try:
    shutil.rmtree(path)
except OSError:
    pass

Why? Say you (somehow) accidently pass the function an integer instead of a string, like:

shutil.rmtree(2)

It will give the error "TypeError: coercing to Unicode: need string or buffer, int found" - you probably don't want to ignore that, which can be difficult to debug.

If you definitely want to ignore all errors, catch Exception rather than a bare except: statement. Again, why?

Not specifying an exception catches every exception, including the SystemExit exception which for example sys.exit() uses:

>>> try:
...     sys.exit(1)
... except:
...     pass
... 
>>>

Compare this to the following, which correctly exits:

>>> try:
...     sys.exit(1)
... except Exception:
...     pass
... 
shell:~$ 

If you want to write ever better behaving code, the OSError exception can represent various errors, but in the example above we only want to ignore Errno 2, so we could be even more specific:

import errno

try:
    shutil.rmtree(path)
except OSError as e:
    if e.errno != errno.ENOENT:
        # ignore "No such file or directory", but re-raise other errors
        raise

How to get current class name including package name in Java?

use this.getClass().getName() to get packageName.className and use this.getClass().getSimpleName() to get only class name

Chrome violation : [Violation] Handler took 83ms of runtime

It seems you have found your solution, but still it will be helpful to others, on this page on point based on Chrome 59.

4.Note the red triangle in the top-right of the Animation Frame Fired event. Whenever you see a red triangle, it's a warning that there may be an issue related to this event.

If you hover on these triangle you can see those are the violation handler errors and as per point 4. yes there is some issue related to that event.

MySQL error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near

MYSQL PROCEDURE steps:

  1. change delimiter from default ' ; ' to ' // '

DELIMITER //

  1. create PROCEDURE, you can refer syntax

    NOTE: Don't forget to end statement with ' ; '

create procedure ProG() 
begin 
SELECT * FROM hs_hr_employee_leave_quota;
end;//
  1. Change delimiter back to ' ; '

delimiter ;

  1. Now to execute:

call ProG();

What's better at freeing memory with PHP: unset() or $var = null

unset code if not freeing immediate memory is still very helpful and would be a good practice to do this each time we pass on code steps before we exit a method. take note its not about freeing immediate memory. immediate memory is for CPU, what about secondary memory which is RAM.

and this also tackles about preventing memory leaks.

please see this link http://www.hackingwithphp.com/18/1/11/be-wary-of-garbage-collection-part-2

i have been using unset for a long time now.

better practice like this in code to instanly unset all variable that have been used already as array.

$data['tesst']='';
$data['test2']='asdadsa';
....
nth.

and just unset($data); to free all variable usage.

please see related topic to unset

How important is it to unset variables in PHP?

[bug]

Accessing the index in 'for' loops?

In your question, you write "how do I access the loop index, from 1 to 5 in this case?"

However, the index for a list runs from zero. So, then we need to know if what you actually want is the index and item for each item in a list, or whether you really want numbers starting from 1. Fortunately, in Python, it is easy to do either or both.

First, to clarify, the enumerate function iteratively returns the index and corresponding item for each item in a list.

alist = [1, 2, 3, 4, 5]

for n, a in enumerate(alist):
    print("%d %d" % (n, a))

The output for the above is then,

0 1
1 2
2 3
3 4
4 5

Notice that the index runs from 0. This kind of indexing is common among modern programming languages including Python and C.

If you want your loop to span a part of the list, you can use the standard Python syntax for a part of the list. For example, to loop from the second item in a list up to but not including the last item, you could use

for n, a in enumerate(alist[1:-1]):
    print("%d %d" % (n, a))

Note that once again, the output index runs from 0,

0 2
1 3
2 4

That brings us to the start=n switch for enumerate(). This simply offsets the index, you can equivalently simply add a number to the index inside the loop.

for n, a in enumerate(alist, start=1):
    print("%d %d" % (n, a))

for which the output is

1 1
2 2
3 3
4 4
5 5

Disabled href tag

You can use one of these solutions:

HTML

<a>link</a>

JavaScript

<a href="javascript:function() { return false; }">link</a>
<a href="/" onclick="return false;">link</a>

CSS

<a href="www.page.com" disabled="disabled">link</a>

<style type="text/css">
    a[disabled="disabled"] {
        pointer-events: none;
    }
</style>

How to determine whether an object has a given property in JavaScript

Underscore.js or Lodash

if (_.has(x, "y")) ...

:)

How to center buttons in Twitter Bootstrap 3?

<div class="container-fluid">
   <div class="col-sm-12 text-center">
       <button class="btn btn-primary" title="Submit"></button>
       <button class="btn btn-warning" title="Cancel"></button>
   </div>
</div>

Numpy matrix to array

Or you could try to avoid some temps with

A = M.view(np.ndarray)
A.shape = -1

QLabel: set color of text and background

You can use QPalette, however you must set setAutoFillBackground(true); to enable background color

QPalette sample_palette;
sample_palette.setColor(QPalette::Window, Qt::white);
sample_palette.setColor(QPalette::WindowText, Qt::blue);

sample_label->setAutoFillBackground(true);
sample_label->setPalette(sample_palette);
sample_label->setText("What ever text");

It works fine on Windows and Ubuntu, I haven't played with any other OS.

Note: Please see QPalette, color role section for more details

Facebook share link without JavaScript

Adding to @rybo111's solution, here's what a LinkedIn share would be:

<a href="http://www.linkedin.com/shareArticle?mini=true&url={articleUrl}&title={articleTitle}&summary={articleSummary}&source={articleSource}" target="_blank" class="share-popup">Share on LinkedIn</a>

and add this to your Javascript:

case "www.linkedin.com":
    window_size = "width=570,height=494";
    break;

As per the LinkedIn documentation: https://developer.linkedin.com/docs/share-on-linkedin (See "Customized Url" section)

For anyone who's interested, I used this in a Rails app with a LinkedIn logo, so here's my code if it might help:

<%= link_to image_tag('linkedin.png', size: "50x50"), "http://www.linkedin.com/shareArticle?mini=true&url=#{job_url(@job)}&title=#{full_title(@job.title).html_safe}&summary=#{strip_tags(@job.description)}&source=SOURCE_URL", class: "share-popup" %>

Remove all newlines from inside a string

If the file includes a line break in the middle of the text neither strip() nor rstrip() will not solve the problem,

strip family are used to trim from the began and the end of the string

replace() is the way to solve your problem

>>> my_name = "Landon\nWO"
>>> print my_name
   Landon
   WO

>>> my_name = my_name.replace('\n','')
>>> print my_name
LandonWO

How can Perl's print add a newline by default?

Perhaps you want to change your output record separator to linefeed with:

local $\ = "\n";

$ perl -e 'print q{hello};print q{goodbye}' | od -c
0000000    h   e   l   l   o   g   o   o   d   b   y   e                
0000014
$ perl -e '$\ = qq{\n}; print q{hello};print q{goodbye}' | od -c
0000000    h   e   l   l   o  \n   g   o   o   d   b   y   e  \n        
0000016

Update: my answer speaks to capability rather than advisability. I don't regard adding "\n" at the end of lines to be a "pesky" chore, but if someone really wants to avoid them, this is one way. If I had to maintain a bit of code that uses this technique, I'd probably refactor it out pronto.

jQuery onclick toggle class name

jQuery has a toggleClass function:

<button class="switch">Click me</button>

<div class="text-block collapsed pressed">some text</div>

<script>    
    $('.switch').on('click', function(e) {
      $('.text-block').toggleClass("collapsed pressed"); //you can list several class names 
      e.preventDefault();
    });
</script>

Horizontal line using HTML/CSS

I have try this my new code and it might be helpful to you, it works perfectly in google chromr

hr {
     color: #f00;
     background: #f00; 
     width: 75%; 
     height: 5px;
}

How do I get the old value of a changed cell in Excel VBA?

I have read this old post, and I would like to provide another solution.

The problem with running Application.Undo is that Woksheet_Change runs again. We have the same problem when we restore.

To avoid that, I use a piece of code to avoid the second steps through Worksheet_Change.

Before we begin, we must create a Boolean static variable BlnAlreadyBeenHere, to tell Excel not to run Worksheet_Change again

Here you can see it:

    Private Sub Worksheet_Change(ByVal Target As Range)

    Static blnAlreadyBeenHere As Boolean

    'This piece avoid to execute Worksheet_Change again
    If blnAlreadyBeenHere Then
        blnAlreadyBeenHere = False
        Exit Sub
    End If

    'Now, we will store the old and new value
    Dim vOldValue As Variant
    Dim vNewValue As Variant

    'To store new value
    vNewValue = Target.Value

    'Undo to retrieve old value

    'To avoid new Worksheet_Change execution
    blnAlreadyBeenHere = True

    Application.Undo

    'To store old value
    vOldValue = Target.Value

    'To rewrite new value

    'To avoid new Worksheet_Change execution agein
    blnAlreadyBeenHere = True
    Target.Value = vNewValue

    'Done! I've two vaules stored
    Debug.Print vOldValue, vNewValue

End Sub

The advantage of this method is that it is not necessary to run Worksheet_SelectionChange.

If we want the routine to work from another module, we just have to take the declaration of the variable blnAlreadyBeenHere out of the routine, and declare it with Dim.

Same operation with vOldValue and vNewValue, in the header of a module

Dim blnAlreadyBeenHere As Boolean
Dim vOldValue As Variant
Dim vNewValue As Variant

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

You can call it like that:

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

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

Look here: http://jsfiddle.net/HWreP/

Best regards!

Problems with jQuery getJSON using local files in Chrome

This code worked fine with sheet.jsonlocally with browser-sync as the local server. -But when on my remote server I got a 404 for the sheet.json file using Chrome. It worked fine in Safari and Firefox. -Changed the name sheet.json to sheet.JSON. Then it worked on the remote server. Anyone else have this experience?

getthejason = function(){
var dataurl = 'data/sheet.JSON';
var xhr = new XMLHttpRequest();
xhr.open('GET', dataurl, true);
xhr.responseType = 'text';
xhr.send();
console.log('getthejason!');

xhr.onload = function() {
.....
}

How to give credentials in a batch script that copies files to a network location?

Try using the net use command in your script to map the share first, because you can provide it credentials. Then, your copy command should use those credentials.

net use \\<network-location>\<some-share> password /USER:username

Don't leave a trailing \ at the end of the

Why do I need to configure the SQL dialect of a data source?

Dialect means "the variant of a language". Hibernate, as we know, is database agnostic. It can work with different databases. However, databases have proprietary extensions/native SQL variations, and set/sub-set of SQL standard implementations. Therefore at some point hibernate has to use database specific SQL. Hibernate uses "dialect" configuration to know which database you are using so that it can switch to the database specific SQL generator code wherever/whenever necessary.

Insert line after first match using sed

I had to do this recently as well for both Mac and Linux OS's and after browsing through many posts and trying many things out, in my particular opinion I never got to where I wanted to which is: a simple enough to understand solution using well known and standard commands with simple patterns, one liner, portable, expandable to add in more constraints. Then I tried to looked at it with a different perspective, that's when I realized i could do without the "one liner" option if a "2-liner" met the rest of my criteria. At the end I came up with this solution I like that works in both Ubuntu and Mac which i wanted to share with everyone:

insertLine=$(( $(grep -n "foo" sample.txt | cut -f1 -d: | head -1) + 1 ))
sed -i -e "$insertLine"' i\'$'\n''bar'$'\n' sample.txt

In first command, grep looks for line numbers containing "foo", cut/head selects 1st occurrence, and the arithmetic op increments that first occurrence line number by 1 since I want to insert after the occurrence. In second command, it's an in-place file edit, "i" for inserting: an ansi-c quoting new line, "bar", then another new line. The result is adding a new line containing "bar" after the "foo" line. Each of these 2 commands can be expanded to more complex operations and matching.

Grouping into interval of 5 minutes within a time range

I came across the same issue.

I found that it is easy to group by any minute interval is just dividing epoch by minutes in amount of seconds and then either rounding or using floor to get ride of the remainder. So if you want to get interval in 5 minutes you would use 300 seconds.

    SELECT COUNT(*) cnt, 
    to_timestamp(floor((extract('epoch' from timestamp_column) / 300 )) * 300) 
    AT TIME ZONE 'UTC' as interval_alias
    FROM TABLE_NAME GROUP BY interval_alias
interval_alias       cnt
-------------------  ----  
2010-11-16 10:30:00  2
2010-11-16 10:35:00  10
2010-11-16 10:45:00  8
2010-11-16 10:55:00  11 

This will return the data correctly group by the selected minutes interval; however, it will not return the intervals that don't contains any data. In order to get those empty intervals we can use the function generate_series.

    SELECT generate_series(MIN(date_trunc('hour',timestamp_column)),
    max(date_trunc('minute',timestamp_column)),'5m') as interval_alias FROM 
    TABLE_NAME

Result:

interval_alias       
-------------------    
2010-11-16 10:30:00  
2010-11-16 10:35:00
2010-11-16 10:40:00   
2010-11-16 10:45:00
2010-11-16 10:50:00   
2010-11-16 10:55:00   

Now to get the result with interval with zero occurrences we just outer join both result sets.

    SELECT series.minute as interval,  coalesce(cnt.amnt,0) as count from 
       (
       SELECT count(*) amnt,
       to_timestamp(floor((extract('epoch' from timestamp_column) / 300 )) * 300)
       AT TIME ZONE 'UTC' as interval_alias
       from TABLE_NAME  group by interval_alias
       ) cnt
    
    RIGHT JOIN 
       (    
       SELECT generate_series(min(date_trunc('hour',timestamp_column)),
       max(date_trunc('minute',timestamp_column)),'5m') as minute from TABLE_NAME 
       ) series
  on series.minute = cnt.interval_alias

The end result will include the series with all 5 minute intervals even those that have no values.

interval             count
-------------------  ----  
2010-11-16 10:30:00  2
2010-11-16 10:35:00  10
2010-11-16 10:40:00  0
2010-11-16 10:45:00  8
2010-11-16 10:50:00  0 
2010-11-16 10:55:00  11 

The interval can be easily changed by adjusting the last parameter of generate_series. In our case we use '5m' but it could be any interval we want.

Cannot resolve the collation conflict between "SQL_Latin1_General_CP1_CI_AS" and "Latin1_General_CI_AS" in the equal to operation

If this occurs across the whole of your DB then it's better to change your DB collation like so:

USE master;  
GO  
ALTER DATABASE MyOptionsTest  
COLLATE << INSERT COLATION REQUIRED >> ;  
GO  

--Verify the collation setting.  
SELECT name, collation_name  
FROM sys.databases  
WHERE name = N'<< INSERT DATABASE NAME >>';  
GO 

Reference here

Certificate has either expired or has been revoked

I had this issue after changing my Email account.

After trying out so many possible solutions, the only one that worked was the to just delete the certificate that was created in that day from my Apple developer account. (It was not the only certificate in my account) It seems that a new certificate was created automatically and it was conflicting with the main one.

How do I print a datetime in the local timezone?

I wrote something like this the other day:

import time, datetime
def nowString():
    # we want something like '2007-10-18 14:00+0100'
    mytz="%+4.4d" % (time.timezone / -(60*60) * 100) # time.timezone counts westwards!
    dt  = datetime.datetime.now()
    dts = dt.strftime('%Y-%m-%d %H:%M')  # %Z (timezone) would be empty
    nowstring="%s%s" % (dts,mytz)
    return nowstring

So the interesting part for you is probably the line starting with "mytz=...". time.timezone returns the local timezone, albeit with opposite sign compared to UTC. So it says "-3600" to express UTC+1.

Despite its ignorance towards Daylight Saving Time (DST, see comment), I'm leaving this in for people fiddling around with time.timezone.

How do I find the location of Python module sources?

Running python -v from the command line should tell you what is being imported and from where. This works for me on Windows and Mac OS X.

C:\>python -v
# installing zipimport hook
import zipimport # builtin
# installed zipimport hook
# C:\Python24\lib\site.pyc has bad mtime
import site # from C:\Python24\lib\site.py
# wrote C:\Python24\lib\site.pyc
# C:\Python24\lib\os.pyc has bad mtime
import os # from C:\Python24\lib\os.py
# wrote C:\Python24\lib\os.pyc
import nt # builtin
# C:\Python24\lib\ntpath.pyc has bad mtime
...

I'm not sure what those bad mtime's are on my install!

Get child Node of another Node, given node name

You should read it recursively, some time ago I had the same question and solve with this code:

public void proccessMenuNodeList(NodeList nl, JMenuBar menubar) {
    for (int i = 0; i < nl.getLength(); i++) {
        proccessMenuNode(nl.item(i), menubar);
    }
}

public void proccessMenuNode(Node n, Container parent) {
    if(!n.getNodeName().equals("menu"))
        return;
    Element element = (Element) n;
    String type = element.getAttribute("type");
    String name = element.getAttribute("name");
    if (type.equals("menu")) {
        NodeList nl = element.getChildNodes();
        JMenu menu = new JMenu(name);

        for (int i = 0; i < nl.getLength(); i++)
            proccessMenuNode(nl.item(i), menu);

        parent.add(menu);
    } else if (type.equals("item")) {
        JMenuItem item = new JMenuItem(name);
        parent.add(item);
    }
}

Probably you can adapt it for your case.

Removing all empty elements from a hash / YAML?

class Hash   
  def compact
    def _empty?(val)
      case val
      when Hash     then val.compact.empty?
      when Array    then val.all? { |v| _empty?(v) }
      when String   then val.empty?
      when NilClass then true
      # ... custom checking 
      end
    end

    delete_if { |_key, val| _empty?(val) }   
  end 
end

Creating a border like this using :before And :after Pseudo-Elements In CSS?

#footer:after
{
   content: "";
    width: 40px;
    height: 3px;
    background-color: #529600;
    left: 0;
    position: relative;
    display: block;
    top: 10px;
}

Where can I download mysql jdbc jar from?

If you have WL server installed, pick it up from under
\Oracle\Middleware\wlserver_10.3\server\lib\mysql-connector-java-commercial-5.1.17-bin.jar

Otherwise, download it from:
http://www.java2s.com/Code/JarDownload/mysql/mysql-connector-java-5.1.17-bin.jar.zip

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

Migh below code works for you, It works for me perfectly fine:

private void viewDialog() {
    try {
        Intent vpnIntent = new Intent(context, UtilityVpnService.class);
        context.startService(vpnIntent);
        final View Dialogview = View.inflate(getBaseContext(), R.layout.alert_open_internet, null);
        final WindowManager.LayoutParams params = new WindowManager.LayoutParams(
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.TYPE_SYSTEM_ALERT,
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                        | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL | WindowManager.LayoutParams.FLAG_DIM_BEHIND,
                PixelFormat.TRANSLUCENT);
        params.gravity = Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL;
        windowManager.addView(Dialogview, params);

        Button btn_cancel = (Button) Dialogview.findViewById(R.id.btn_canceldialog_internetblocked);
        Button btn_okay = (Button) Dialogview.findViewById(R.id.btn_openmainactivity);
        RelativeLayout relativeLayout = (RelativeLayout) Dialogview.findViewById(R.id.rellayout_dialog);

            btn_cancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Handler handler = new Handler(Looper.getMainLooper());
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                if (Dialogview != null) {
//                                ( (WindowManager) getApplicationContext().getSystemService(WINDOW_SERVICE)).removeView(Dialogview);
                                    windowManager.removeView(Dialogview);
                                }
                            } catch (final IllegalArgumentException e) {
                                e.printStackTrace();
                                // Handle or log or ignore
                            } catch (final Exception e) {
                                e.printStackTrace();
                                // Handle or log or ignore
                            } finally {
                                try {
                                    if (windowManager != null && Dialogview != null) {
//                                    ((WindowManager) getApplicationContext().getSystemService(WINDOW_SERVICE)).removeView(Dialogview);
                                        windowManager.removeView(Dialogview);
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                            //    ((WindowManager) getApplicationContext().getSystemService(WINDOW_SERVICE)).removeView(Dialogview);
//                        windowManager.removeView(Dialogview);


                        }
                    });
                }
            });
            btn_okay.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Handler handler = new Handler(Looper.getMainLooper());
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            //        ((WindowManager) getApplicationContext().getSystemService(WINDOW_SERVICE)).removeView(Dialogview);
                            try {
                                if (windowManager != null && Dialogview != null)
                                    windowManager.removeView(Dialogview);
                                Intent intent = new Intent(getBaseContext(), SplashActivity.class);
                                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
//                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);


                                context.startActivity(intent);
                            } catch (Exception e) {
                                windowManager.removeView(Dialogview);
                                e.printStackTrace();
                            }
                        }
                    });
                }
            });
        } catch (Exception e) {
            //` windowManager.removeView(Dialogview);
            e.printStackTrace();
        }
    }

Do not define your view globally if u call it from background service.

How to clear variables in ipython?

%reset seems to clear defined variables.

Paste multiple columns together

Using tidyr package, this can be easily handled in 1 function call.

data <- data.frame('a' = 1:3, 
                   'b' = c('a','b','c'), 
                   'c' = c('d', 'e', 'f'), 
                   'd' = c('g', 'h', 'i'))

tidyr::unite_(data, paste(colnames(data)[-1], collapse="_"), colnames(data)[-1])

  a b_c_d
1 1 a_d_g
2 2 b_e_h
3 3 c_f_i

Edit: Exclude first column, everything else gets pasted.

# tidyr_0.6.3

unite(data, newCol, -a) 
# or by column index unite(data, newCol, -1)

#   a newCol
# 1 1  a_d_g
# 2 2  b_e_h
# 3 3  c_f_i

how to programmatically fake a touch event to a UIButton?

An update to this answer for Swift

buttonObj.sendActionsForControlEvents(.TouchUpInside)

EDIT: Updated for Swift 3

buttonObj.sendActions(for: .touchUpInside)

Installing jQuery?

jQuery is just a JavaScript library (simply put, a JavaScript file). All you have to do is put it into your website directory and reference it in your HTML to use it.

For example, in the head tag of your webpage

<script type="text/javascript" src="../Js/jquery.js"></script>

You can download the current jQuery release from Downloading jQuery.

Sorting Values of Set

Strings are sorted lexicographically. The behavior you're seeing is correct.

Define your own comparator to sort the strings however you prefer.

It would also work the way you're expecting (5 as the first element) if you changed your collections to Integer instead of using String.

Select unique or distinct values from a list in UNIX shell script

With AWK you can do, I find it faster than sort

 ./yourscript.ksh | awk '!a[$0]++'

Convert date formats in bash

Just with bash:

convert_date () {
    local months=( JAN FEB MAR APR MAY JUN JUL AUG SEP OCT NOV DEC )
    local i
    for (( i=0; i<11; i++ )); do
        [[ $2 = ${months[$i]} ]] && break
    done
    printf "%4d%02d%02d\n" $3 $(( i+1 )) $1
}

And invoke it like this

d=$( convert_date 27 JUN 2011 )

Or if the "old" date string is stored in a variable

d_old="27 JUN 2011"
d=$( convert_date $d_old )  # not quoted

SQLAlchemy: print the actual query

We can use compile method for this purpose. From the docs:

from sqlalchemy.sql import text
from sqlalchemy.dialects import postgresql

stmt = text("SELECT * FROM users WHERE users.name BETWEEN :x AND :y")
stmt = stmt.bindparams(x="m", y="z")

print(stmt.compile(dialect=postgresql.dialect(),compile_kwargs={"literal_binds": True}))

Result:

SELECT * FROM users WHERE users.name BETWEEN 'm' AND 'z'

Warning from docs:

Never use this technique with string content received from untrusted input, such as from web forms or other user-input applications. SQLAlchemy’s facilities to coerce Python values into direct SQL string values are not secure against untrusted input and do not validate the type of data being passed. Always use bound parameters when programmatically invoking non-DDL SQL statements against a relational database.

HTML / CSS Popup div on text click

You can simply use jQuery UI Dialog

Example:

_x000D_
_x000D_
$(function() {_x000D_
  $("#dialog").dialog();_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<html lang="en">_x000D_
_x000D_
<head>_x000D_
  <meta charset="utf-8" />_x000D_
  <title>jQuery UI Dialog - Default functionality</title>_x000D_
  <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />_x000D_
  <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>_x000D_
  <link rel="stylesheet" href="/resources/demos/style.css" />_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <div id="dialog" title="Basic dialog">_x000D_
    <p>This is the default dialog which is useful for displaying information. The dialog window can be moved, resized and closed with the 'x' icon.</p>_x000D_
  </div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Console errors. Failed to load resource: net::ERR_INSECURE_RESPONSE

I had this problem with chrome when I was working on a WordPress site. I added this code

$_SERVER['HTTPS'] = false;

into the theme's functions.php file - it asks you to log in again when you save the file but once it's logged in it works straight away.

Ball to Ball Collision - Detection and Handling

A good way of reducing the number of collision checks is to split the screen into different sections. You then only compare each ball to the balls in the same section.

What do 1.#INF00, -1.#IND00 and -1.#IND mean?

For anyone wondering about the difference between -1.#IND00 and -1.#IND (which the question specifically asked, and none of the answers address):

-1.#IND00

This specifically means a non-zero number divided by zero, e.g. 3.14 / 0 (source)

-1.#IND (a synonym for NaN)

This means one of four things (see wiki from source):

1) sqrt or log of a negative number

2) operations where both variables are 0 or infinity, e.g. 0 / 0

3) operations where at least one variable is already NaN, e.g. NaN * 5

4) out of range trig, e.g. arcsin(2)

How do I echo and send console output to a file in a bat script?

I like atn's answer, but it was not as trivial for me to download as wintee, which is also open source and only gives the tee functionality (useful if you just want tee and not the entire set of unix utilities). I learned about this from davor's answer to Displaying Windows command prompt output and redirecting it to a file, where you also find reference to the unix utilities.