Programs & Examples On #Biztalk deployment

Relates to deployment of BizTalk applications and artifacts, whether via MSI, BTSTask or the Biztalk Deployment Framework. Included are the management of dependencies, and handling of Bindings associated with a deployment.

How to enable directory listing in apache web server

Try this.

<Directory "/home/userx/Downloads">
  Options +Indexes
  AllowOverride all
  Order allow,deny 
  Allow from all 
  Require all granted
</Directory>

If that doesn't work, you probably have 'deny indexes' somewhere that's overriding your config.

milliseconds to time in javascript

Prons:

  • simple and clean code; easy to modify for your needs
  • support any amount of hours (>24 hrs is ok)
  • format time as 00:00:00.0

You can put it into a helper file

export const msecToTime = ms => {
  const milliseconds = ms % 1000
  const seconds = Math.floor((ms / 1000) % 60)
  const minutes = Math.floor((ms / (60 * 1000)) % 60)
  const hours = Math.floor((ms / (3600 * 1000)) % 3600)
  return `${hours < 10 ? '0' + hours : hours}:${minutes < 10 ? '0' + minutes : minutes}:${
    seconds < 10 ? '0' + seconds : seconds
  }.${milliseconds}`
}

How to convert CharSequence to String?

You can directly use String.valueOf()

String.valueOf(charSequence)

Though this is same as toString() it does a null check on the charSequence before actually calling toString.

This is useful when a method can return either a charSequence or null value.

ActionBarActivity: cannot be resolved to a type

I got the same problem, but things got complicated when I added few other libraries like appcompat.v7, recyclerView, CardView.

Removing appcompat.v4 from lib did not work for me.

I had to create project from start and first step I did is to remove appcompat.v4 from libs folder, and this worked.

I had just started the project so creating a new project wasn't a big issue for me!!!

angular2: how to copy object into another object

let course = {
  name: 'Angular',
};

let newCourse= Object.assign({}, course);

newCourse.name= 'React';

console.log(course.name); // writes Angular
console.log(newCourse.name); // writes React

For Nested Object we can use of 3rd party libraries, for deep copying objects. In case of lodash, use _.cloneDeep()

let newCourse= _.cloneDeep(course);

What does the term "Tuple" Mean in Relational Databases?

A tuple is used to define a slice of data from a cube; it is composed of an ordered collection of one member from one or more dimensions. A tuple is used to identify specific sections of multidimensional data from a cube; a tuple composed of one member from each dimension in a cube completely describes a cell value.

What is a good way to handle exceptions when trying to read a file in python?

fname = 'filenotfound.txt'
try:
    f = open(fname, 'rb')
except FileNotFoundError:
    print("file {} does not exist".format(fname))

file filenotfound.txt does not exist

exception FileNotFoundError Raised when a file or directory is requested but doesn’t exist. Corresponds to errno ENOENT.

https://docs.python.org/3/library/exceptions.html
This exception does not exist in Python 2.

Text file with 0D 0D 0A line breaks

The CRCRLF is known as result of a Windows XP notepad word wrap bug.

For future reference, here's an extract of relevance from the linked blog:

When you press the Enter key on Windows computers, two characters are actually stored: a carriage return (CR) and a line feed (LF). The operating system always interprets the character sequence CR LF the same way as the Enter key: it moves to the next line. However when there are extra CR or LF characters on their own, this can sometimes cause problems.

There is a bug in the Windows XP version of Notepad that can cause extra CR characters to be stored in the display window. The bug happens in the following situation:

If you have the word wrap option turned on and the display window contains long lines that wrap around, then saving the file causes Notepad to insert the characters CR CR LF at each wrap point in the display window, but not in the saved file.

The CR CR LF characters can cause oddities if you copy and paste them into other programs. They also prevent Notepad from properly re-wrapping the lines if you resize the Notepad window.

You can remove the CR CR LF characters by turning off the word wrap feature, then turning it back on if desired. However, the cursor is repositioned at the beginning of the display window when you do this.

Remove Null Value from String array in java

A gc-friendly piece of code:

public static<X> X[] arrayOfNotNull(X[] array) {
    for (int p=0, N=array.length; p<N; ++p) {
        if (array[p] == null) {
            int m=p; for (int i=p+1; i<N; ++i) if (array[i]!=null) ++m;
            X[] res = Arrays.copyOf(array, m);
            for (int i=p+1; i<N; ++i) if (array[i]!=null) res[p++] = array[i];
            return res;
        }
    }
    return array;
}

It returns the original array if it contains no nulls. It does not modify the original array.

Disabling browser print options (headers, footers, margins) from page?

Any recent version of Chrome and Opera, as well as Firefox 48 alpha 1 and greater

You can set the page margin to a size that's too small to contain the text in order to disable this (borrowing from awe's answer):

_x000D_
_x000D_
@page {
  size: auto;  /* auto is the initial value */
  margin: 0mm; /* this affects the margin in the printer settings */
}
html {
  background-color: #FFFFFF;
  margin: 0px; /* this affects the margin on the HTML before sending to printer */
}
body {
  border: solid 1px blue;
  margin: 10mm 15mm 10mm 15mm; /* margin you want for the content */
}
_x000D_
<ol>
  <li>
    <a href="data:,No Javascript :-(" target="_blank">Middle-click to open in new tab</a>
  </li>
  <li>
    <a href="javascript:print()">Print</a>
  </li>
</ol><!-- Hack to work around stack snippet restrictions --><script type=application/javascript>document.links[0].href="data:text/html;charset=utf-8,"+encodeURIComponent('<!doctype html>'+document.documentElement.outerHTML)</script>
_x000D_
_x000D_
_x000D_

For versions of Firefox up to 48 alpha 1

You can add a mozNoMarginBoxes attribute to the <html> tag to prevent the URL, page numbers and other things Firefox adds to the page margin from being printed.

It is working in Firefox 29 and onwards. You can see a screen shot of the difference here, or see here for a live example.

Note that the mozDisallowSelectionPrint attribute in the example is not required to remove the text from the margins; see What does the mozdisallowselectionprint attribute in PDF.js do?.

Other browsers

Unfortunately, there seems to be no way to resolve this problem in Internet Explorer, so you'll have to resort to PDF or ask users to disable margin texts.

The same goes for Safari; according to a comment by @Luiz Perez, the most recent versions of Safari (8, 9.1 and 10) still do not support @page for suppressing margin texts.

I can't find anything on Edge and I don't have a Windows 10 installation available to test.

How do I print the content of a .txt file in Python?

It's pretty simple

#Opening file
f= open('sample.txt')
#reading everything in file
r=f.read()
#reading at particular index
r=f.read(1)
#print
print(r)

Presenting snapshot from my visual studio IDE.

enter image description here

Formula to convert date to number

If you change the format of the cells to General then this will show the date value of a cell as behind the scenes Excel saves a date as the number of days since 01/01/1900

Screenprint 1

Screenprint 2

If your date is text and you need to convert it then DATEVALUE will do this:

Datevalue function

Adding image to JFrame

There is no specialized image component provided in Swing (which is sad in my opinion). So, there are a few options:

  1. As @Reimeus said: Use a JLabel with an icon.
  2. Create in the window builder a JPanel, that will represent the location of the image. Then add your own custom image component to the JPanel using a few lines of code you will never have to change. They should look like this:

    JImageComponent ic = new JImageComponent(myImageGoesHere);
    imagePanel.add(ic);
    

    where JImageComponent is a self created class that extends JComponent that overrides the paintComponent() method to draw the image.

How to make HTML element resizable using pure Javascript?

See my cross browser compatible resizer.

_x000D_
_x000D_
    <!doctype html>_x000D_
    <html xmlns="http://www.w3.org/1999/xhtml">_x000D_
    <head>_x000D_
        <title>resizer</title>_x000D_
        <meta name="author" content="Andrej Hristoliubov [email protected]">_x000D_
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />_x000D_
        <script type="text/javascript" src="https://rawgit.com/anhr/resizer/master/Common.js"></script>_x000D_
        <script type="text/javascript" src="https://rawgit.com/anhr/resizer/master/resizer.js"></script>_x000D_
        <style>_x000D_
            .element {_x000D_
                border: 1px solid #999999;_x000D_
                border-radius: 4px;_x000D_
                margin: 5px;_x000D_
                padding: 5px;_x000D_
            }_x000D_
        </style>_x000D_
        <script type="text/javascript">_x000D_
            function onresize() {_x000D_
                var element1 = document.getElementById("element1");_x000D_
                var element2 = document.getElementById("element2");_x000D_
                var element3 = document.getElementById("element3");_x000D_
                var ResizerY = document.getElementById("resizerY");_x000D_
                ResizerY.style.top = element3.offsetTop - 15 + "px";_x000D_
                var topElements = document.getElementById("topElements");_x000D_
                topElements.style.height = ResizerY.offsetTop - 20 + "px";_x000D_
                var height = topElements.clientHeight - 32;_x000D_
                if (height < 0)_x000D_
                    height = 0;_x000D_
                height += 'px';_x000D_
                element1.style.height = height;_x000D_
                element2.style.height = height;_x000D_
            }_x000D_
            function resizeX(x) {_x000D_
                //consoleLog("mousemove(X = " + e.pageX + ")");_x000D_
                var element2 = document.getElementById("element2");_x000D_
                element2.style.width =_x000D_
                    element2.parentElement.clientWidth_x000D_
                    + document.getElementById('rezizeArea').offsetLeft_x000D_
                    - x_x000D_
                    + 'px';_x000D_
            }_x000D_
            function resizeY(y) {_x000D_
                //consoleLog("mousemove(Y = " + e.pageY + ")");_x000D_
                var element3 = document.getElementById("element3");_x000D_
                var height =_x000D_
                    element3.parentElement.clientHeight_x000D_
                    + document.getElementById('rezizeArea').offsetTop_x000D_
                    - y_x000D_
                ;_x000D_
                //consoleLog("mousemove(Y = " + e.pageY + ") height = " + height + " element3.parentElement.clientHeight = " + element3.parentElement.clientHeight);_x000D_
                if ((height + 100) > element3.parentElement.clientHeight)_x000D_
                    return;//Limit of the height of the elemtnt 3_x000D_
                element3.style.height = height + 'px';_x000D_
                onresize();_x000D_
            }_x000D_
            var emailSubject = "Resizer example error";_x000D_
        </script>_x000D_
    </head>_x000D_
    <body>_x000D_
        <div id='Message'></div>_x000D_
        <h1>Resizer</h1>_x000D_
        <p>Please see example of resizing of the HTML element by mouse dragging.</p>_x000D_
        <ul>_x000D_
            <li>Drag the red rectangle if you want to change the width of the Element 1 and Element 2</li>_x000D_
            <li>Drag the green rectangle if you want to change the height of the Element 1 Element 2 and Element 3</li>_x000D_
            <li>Drag the small blue square at the left bottom of the Element 2, if you want to resize of the Element 1 Element 2 and Element 3</li>_x000D_
        </ul>_x000D_
        <div id="rezizeArea" style="width:1000px; height:250px; overflow:auto; position: relative;" class="element">_x000D_
            <div id="topElements" class="element" style="overflow:auto; position:absolute; left: 0; top: 0; right:0;">_x000D_
                <div id="element2" class="element" style="width: 30%; height:10px; float: right; position: relative;">_x000D_
                    Element 2_x000D_
                    <div id="resizerXY" style="width: 10px; height: 10px; background: blue; position:absolute; left: 0; bottom: 0;"></div>_x000D_
                    <script type="text/javascript">_x000D_
                        resizerXY("resizerXY", function (e) {_x000D_
                                resizeX(e.pageX + 10);_x000D_
                                resizeY(e.pageY + 50);_x000D_
                            });_x000D_
                    </script>_x000D_
                </div>_x000D_
                <div id="resizerX" style="width: 10px; height:100%; background: red; float: right;"></div>_x000D_
                <script type="text/javascript">_x000D_
                    resizerX("resizerX", function (e) {_x000D_
                        resizeX(e.pageX + 25);_x000D_
                    });_x000D_
                </script>_x000D_
                <div id="element1" class="element" style="height:10px; overflow:auto;">Element 1</div>_x000D_
            </div>_x000D_
            <div id="resizerY" style="height:10px; position:absolute; left: 0; right:0; background: green;"></div>_x000D_
            <script type="text/javascript">_x000D_
                resizerY("resizerY", function (e) {_x000D_
                    resizeY(e.pageY + 25);_x000D_
                });_x000D_
            </script>_x000D_
            <div id="element3" class="element" style="height:100px; position:absolute; left: 0; bottom: 0; right:0;">Element 3</div>_x000D_
        </div>_x000D_
        <script type="text/javascript">_x000D_
            onresize();_x000D_
        </script>_x000D_
    </body>_x000D_
    </html>
_x000D_
_x000D_
_x000D_

Also see my example of resizer

Click a button programmatically

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
        Button2_Click(Sender, e)
End Sub

This Code call button click event programmatically

What's the simplest way to list conflicted files in Git?

If you attempt to commit, and if there are conflicts, then git will give you the list of the currently unresolved conflicts... but not as a plain list. This is usually what you want when working interactively because the list gets shorter as you fix the conflicts.

How to display scroll bar onto a html table

Very easy, just wrap the table in a div that has overflow-y:scroll; and overflow-x:scroll properties, and make the div have a width and length smaller than the table. IT WILL WORK!!!

How can I get a specific number child using CSS?

For IE 7 & 8 (and other browsers without CSS3 support not including IE6) you can use the following to get the 2nd and 3rd children:

2nd Child:

td:first-child + td

3rd Child:

td:first-child + td + td

Then simply add another + td for each additional child you wish to select.

If you want to support IE6 that can be done too! You simply need to use a little javascript (jQuery in this example):

$(function() {
    $('td:first-child').addClass("firstChild");
    $(".table-class tr").each(function() {
        $(this).find('td:eq(1)').addClass("secondChild");
        $(this).find('td:eq(2)').addClass("thirdChild");
    });
});

Then in your css you simply use those class selectors to make whatever changes you like:

table td.firstChild { /*stuff here*/ }
table td.secondChild { /*stuff to apply to second td in each row*/ }

What is the purpose of shuffling and sorting phase in the reducer in Map Reduce Programming?

I've always assumed this was necessary as the output from the mapper is the input for the reducer, so it was sorted based on the keyspace and then split into buckets for each reducer input. You want to ensure all the same values of a Key end up in the same bucket going to the reducer so they are reduced together. There is no point sending K1,V2 and K1,V4 to different reducers as they need to be together in order to be reduced.

Tried explaining it as simply as possible

Get all attributes of an element using jQuery

My suggestion:

$.fn.attrs = function (fnc) {
    var obj = {};
    $.each(this[0].attributes, function() {
        if(this.name == 'value') return; // Avoid someone (optional)
        if(this.specified) obj[this.name] = this.value;
    });
    return obj;
}

var a = $(el).attrs();

How do you run `apt-get` in a dockerfile behind a proxy?

You can use the --build-arg option when you want to build using a Dockerfile.

From a link on https://github.com/docker/docker/issues/14634 , see the section "Build with --build-arg with multiple HTTP_PROXY":

[root@pppdc9prda2y java]# docker build 
  --build-arg https_proxy=$HTTP_PROXY --build-arg http_proxy=$HTTP_PROXY 
  --build-arg HTTP_PROXY=$HTTP_PROXY --build-arg HTTPS_PROXY=$HTTP_PROXY 
  --build-arg NO_PROXY=$NO_PROXY  --build-arg no_proxy=$NO_PROXY -t java .

NOTE: On your own system, make sure you have set the HTTP_PROXY and NO_PROXY environment variables.

how to change namespace of entire project?

You can use ReSharper for namespace refactoring. It will give 30 days free trial. It will change namespace as per folder structure.

Steps:

  1. Right click on the project/folder/files you want to refactor.

  2. If you have installed ReSharper then you will get an option Refactor->Adjust Namespaces.... So click on this.

enter image description here

It will automatically change the name spaces of all the selected files.

Get current url in Angular

With pure JavaScript:

console.log(window.location.href)

Using Angular:

this.router.url

import { Component } from '@angular/core';
import { Router } from '@angular/router';

@Component({
    template: 'The href is: {{href}}'
    /*
    Other component settings
    */
})
export class Component {
    public href: string = "";

    constructor(private router: Router) {}

    ngOnInit() {
        this.href = this.router.url;
        console.log(this.router.url);
    }
}

The plunkr is here: https://plnkr.co/edit/0x3pCOKwFjAGRxC4hZMy?p=preview

Generate random int value from 3 to 6

Here is the simple and single line of code

For this use the SQL Inbuild RAND() function.

Here is the formula to generate random number between two number (RETURN INT Range)

Here a is your First Number (Min) and b is the Second Number (Max) in Range

SELECT FLOOR(RAND()*(b-a)+a)

Note: You can use CAST or CONVERT function as well to get INT range number.

( CAST(RAND()*(25-10)+10 AS INT) )

Example:

SELECT FLOOR(RAND()*(25-10)+10);

Here is the formula to generate random number between two number (RETURN DECIMAL Range)

SELECT RAND()*(b-a)+a;

Example:

SELECT RAND()*(25-10)+10;

More details check this: https://www.techonthenet.com/sql_server/functions/rand.php

Testing for empty or nil-value string

The second clause does not need a !variable.nil? check—if evaluation reaches that point, variable.nil is guaranteed to be false (because of short-circuiting).

This should be sufficient:

variable = id if variable.nil? || variable.empty?

If you're working with Ruby on Rails, Object.blank? solves this exact problem:

An object is blank if it’s false, empty, or a whitespace string. For example, "", " ", nil, [], and {} are all blank.

Extracting double-digit months and days from a Python date

you can use a string formatter to pad any integer with zeros. It acts just like C's printf.

>>> d = datetime.date.today()
>>> '%02d' % d.month
'03'

Updated for py36: Use f-strings! For general ints you can use the d formatter and explicitly tell it to pad with zeros:

 >>> d = datetime.date.today()
 >>> f"{d.month:02d}"
 '07'

But datetimes are special and come with special formatters that are already zero padded:

 >>> f"{d:%d}"  # the day
 '01'
 >>> f"{d:%m}"  # the month
 '07'

Safely casting long to int in Java

One other solution can be:

public int longToInt(Long longVariable)
{
    try { 
            return Integer.valueOf(longVariable.toString()); 
        } catch(IllegalArgumentException e) { 
               Log.e(e.printstackstrace()); 
        }
}

I have tried this for cases where the client is doing a POST and the server DB understands only Integers while the client has a Long.

Multipart File Upload Using Spring Rest Template + Spring Web MVC

A correct file upload would like this:

HTTP header:

Content-Type: multipart/form-data; boundary=ABCDEFGHIJKLMNOPQ

Http body:

--ABCDEFGHIJKLMNOPQ

Content-Disposition: form-data; name="file"; filename="my.txt"

Content-Type: application/octet-stream

Content-Length: ...

<...file data in base 64...>

--ABCDEFGHIJKLMNOPQ--

and code is like this:

public void uploadFile(File file) {
        try {
            RestTemplate restTemplate = new RestTemplate();
            String url = "http://localhost:8080/file/user/upload";
            HttpMethod requestMethod = HttpMethod.POST;

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.MULTIPART_FORM_DATA);


            MultiValueMap<String, String> fileMap = new LinkedMultiValueMap<>();
            ContentDisposition contentDisposition = ContentDisposition
                    .builder("form-data")
                    .name("file")
                    .filename(file.getName())
                    .build();

            fileMap.add(HttpHeaders.CONTENT_DISPOSITION, contentDisposition.toString());
            HttpEntity<byte[]> fileEntity = new HttpEntity<>(Files.readAllBytes(file.toPath()), fileMap);

            MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
            body.add("file", fileEntity);

            HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);

            ResponseEntity<String> response = restTemplate.exchange(url, requestMethod, requestEntity, String.class);

            System.out.println("file upload status code: " + response.getStatusCode());

        } catch (IOException e) {
            e.printStackTrace();
        }

}

Get the Id of current table row with Jquery

This:

<table id="test">
      <tr  id="TEST1" >
          <td align="left" valign="middle"><div align="right">Contact</div></td>
          <td colspan="4" align="left" valign="middle">
          <input type="text" id="contact1" size="20" />  Number 
          <input type="text" id="number1" size="20" /> 
          </td>
          <td>
          <input type="button"  value="Button 1" id="contact1" /></td>
      </tr>


      <tr id="TEST2" >
          <td align="left" valign="middle"><div align="right">Contact</div></td>
          <td colspan="4" align="left" valign="middle">
          <input type="text" id="contact2" size="20" />  Number 
          <input type="text" id="number2" size="20" /> 
          </td>
          <td>
          <input type="button"  value="Button 1"  id="contact2" />
          </td> 
      </tr>

      <tr id="TEST3" >
          <td align="left" valign="middle"><div align="right">Contact</div></td>
          <td colspan="4" align="left" valign="middle">
          <input type="text" id="contact3" size="20" />  Number 
          <input type="text" id="number3" size="20" /> 
          </td>
          <td>
          <input type="button"  value="Button 1"  id="contact2" />
          </td> 
</tr>

and javascript:

$(function() {
  var bid, trid;
  $('#test tr').click(function() {
       trid = $(this).attr('id'); // table row ID 
       alert(trid);
  });

});

It worked here!

How do I render a shadow?

Use elevation to implement shadows on RN Android. Added elevation prop #27

<View elevation={5}> </View>

Laravel - Return json along with http status code

I think it is better practice to keep your response under single control and for this reason I found out the most official solution.

response()->json([...])
    ->setStatusCode(Response::HTTP_OK, Response::$statusTexts[Response::HTTP_OK]);

add this after namespace declaration:

use Illuminate\Http\Response;

Is it fine to have foreign key as primary key?

It is generally considered bad practise to have a one to one relationship. This is because you could just have the data represented in one table and achieve the same result.

However, there are instances where you may not be able to make these changes to the table you are referencing. In this instance there is no problem using the Foreign key as the primary key. It might help to have a composite key consisting of an auto incrementing unique primary key and the foreign key.

I am currently working on a system where users can log in and generate a registration code to use with an app. For reasons I won't go into I am unable to simply add the columns required to the users table. So I am going down a one to one route with the codes table.

Use -notlike to filter out multiple strings in PowerShell

Yep, but you have to put the array first in the expression:

... | where { @("user1","user2") -notlike $_.username }

-Oisin

Convert bytes to bits in python

Operations are much faster when you work at the integer level. In particular, converting to a string as suggested here is really slow.

If you want bit 7 and 8 only, use e.g.

val = (byte >> 6) & 3

(this is: shift the byte 6 bits to the right - dropping them. Then keep only the last two bits 3 is the number with the first two bits set...)

These can easily be translated into simple CPU operations that are super fast.

How to produce an csv output file from stored procedure in SQL Server

I have tried this and it is working fine for me:

sqlcmd -S servername -E -s~ -W -k1 -Q  "sql query here" > "\\file_path\file_name.csv"

<select> HTML element with height

I've used a few CSS hacks and targeted Chrome/Safari/Firefox/IE individually, as each browser renders selects a bit differently. I've tested on all browsers except IE.

For Safari/Chrome, set the height and line-height you want for your <select />.

For Firefox, we're going to kill Firefox's default padding and border, then set our own. Set padding to whatever you like.

For IE 8+, just like Chrome, we've set the height and line-height properties. These two media queries can be combined. But I kept it separate for demo purposes. So you can see what I'm doing.

Please note, for the height/line-height property to work in Chrome/Safari OSX, you must set the background to a custom value. I changed the color in my example.

Here's a jsFiddle of the below: http://jsfiddle.net/URgCB/4/

For the non-hack route, why not use a custom select plug-in via jQuery? Check out this: http://codepen.io/wallaceerick/pen/ctsCz

HTML:

<select>
    <option>Here's one option</option>
    <option>here's another option</option>
</select>

CSS:

@media screen and (-webkit-min-device-pixel-ratio:0) {  /*safari and chrome*/
    select {
        height:30px;
        line-height:30px;
        background:#f4f4f4;
    } 
}
select::-moz-focus-inner { /*Remove button padding in FF*/ 
    border: 0;
    padding: 0;
}
@-moz-document url-prefix() { /* targets Firefox only */
    select {
        padding: 15px 0!important;
    }
}        
@media screen\0 { /* IE Hacks: targets IE 8, 9 and 10 */        
    select {
        height:30px;
        line-height:30px;
    }     
}

Using an if statement to check if a div is empty

Try this:

$(document).ready(function() {
    if ($('#leftmenu').html() === "") {
        $('#menuTitleWrapper').remove();
        $('#middlemenu').css({'right' : '0', 'position' : 'absolute'});
        $('#PageContent').css({'top' : '30px', 'position' : 'relative'});
    }
});

It's not the prettiest, but it should work. It checks whether the innerHTML (the contents of #leftmenu) is an empty string (i.e. there's nothing inside of it).

php search array key and get value

The key is already the ... ehm ... key

echo $array[20120504];

If you are unsure, if the key exists, test for it

$key = 20120504;
$result = isset($array[$key]) ? $array[$key] : null;

Minor addition:

$result = @$array[$key] ?: null;

One may argue, that @ is bad, but keep it serious: This is more readable and straight forward, isn't?

Update: With PHP7 my previous example is possible without the error-silencer

$result = $array[$key] ?? null;

Maven 3 warnings about build.plugins.plugin.version

Add a <version> element after the <plugin> <artifactId> in your pom.xml file. Find the following text:

<plugin>
  <artifactId>maven-compiler-plugin</artifactId>

Add the version tag to it:

<plugin>
  <artifactId>maven-compiler-plugin</artifactId>
  <version>2.3.2</version>

The warning should be resolved.

Regarding this:

'build.plugins.plugin.version' for org.apache.maven.plugins:maven-compiler-plugin is missing

Many people have mentioned why the issue is happening, but fail to suggest a fix. All I needed to do was to go into my POM file for my project, and add the <version> tag as shown above.

To discover the version number, one way is to look in Maven's output after it finishes running. Where you are missing version numbers, Maven will display its default version:

[INFO] --- maven-compiler-plugin:2.3.2:compile (default-compile) @ entities ---

Take that version number (as in the 2.3.2 above) and add it to your POM, as shown.

View JSON file in Browser

Firefox 44 includes a built-in JSON viewer (no add-ons required). The feature is turned off by default, so turn on devtools.jsonview.enabled: How can you disable the new JSON Viewer/Reader in Firefox Developer Edition?

How to make borders collapse (on a div)?

Why not use outline? it is what you want outline:1px solid red;

Changing default startup directory for command prompt in Windows 7

One easy way to do it + bonus.

Start cmd with administrator rights, the default directory for the prompt will be C:\WINDOWS\system32.

I created a bat file in that directory (notes.bat) Opened it with notepad and wrote the following lines. Each line is followed with a comment which should not be added to the bat file.

@echo off

prompt $S$CYourNamel$F$S$G$S 
/* This is a comment, do not include it in the bat file - above line will make the prompt look like  (YourName) > */

cd C:\Your_favorite_directory
/* This is a comment, do not include it in the bat file - above line will navigate you to your desired directory */

Saved the file and that was it. Now when You open cmd with admin rights, just write: notes or notes.bat and it will execute the notes.bat file with desired changes.

Heroku: How to push different local Git branches to Heroku/master

For me, it works,

git push -f heroku otherBranch:master

The -f (force flag) is recommended in order to avoid conflicts with other developers’ pushes. Since you are not using Git for your revision control, but as a transport only, using the force flag is a reasonable practice.

source :- offical docs

How do I determine file encoding in OS X?

I implemented the bash script below, it works for me.

It first tries to iconv from the encoding returned by file --mime-encoding to utf-8.

If that fails, it goes through all encodings and shows the diff between the original and re-encoded file. It skips over encodings that produce a large diff output ("large" as defined by the MAX_DIFF_LINES variable or the second input argument), since those are most likely the wrong encoding.

If "bad things" happen as a result of using this script, don't blame me. There's a rm -f in there, so there be monsters. I tried to prevent adverse effects by using it on files with a random suffix, but I'm not making any promises.

Tested on Darwin 15.6.0.

#!/bin/bash

if [[ $# -lt 1 ]]
then
  echo "ERROR: need one input argument: file of which the enconding is to be detected."
  exit 3
fi

if [ ! -e "$1" ]
then
  echo "ERROR: cannot find file '$1'"
  exit 3
fi

if [[ $# -ge 2 ]]
then
  MAX_DIFF_LINES=$2
else
  MAX_DIFF_LINES=10
fi


#try the easy way
ENCOD=$(file --mime-encoding $1 | awk '{print $2}')
#check if this enconding is valid
iconv -f $ENCOD -t utf-8 $1 &> /dev/null
if [ $? -eq 0 ]
then
  echo $ENCOD
  exit 0
fi

#hard way, need the user to visually check the difference between the original and re-encoded files
for i in $(iconv -l | awk '{print $1}')
do
  SINK=$1.$i.$RANDOM
  iconv -f $i -t utf-8 $1 2> /dev/null > $SINK
  if [ $? -eq 0 ]
  then
    DIFF=$(diff $1 $SINK)
    if [ ! -z "$DIFF" ] && [ $(echo "$DIFF" | wc -l) -le $MAX_DIFF_LINES ]
    then
      echo "===== $i ====="
      echo "$DIFF"
      echo "Does that make sense [N/y]"
      read $ANSWER
      if [ "$ANSWER" == "y" ] || [ "$ANSWER" == "Y" ]
      then
        echo $i
        exit 0
      fi
    fi
  fi
  #clean up re-encoded file
  rm -f $SINK
done

echo "None of the encondings worked. You're stuck."
exit 3

How to stop Python closing immediately when executed in Microsoft Windows

Very simple:

  1. Open command prompt as an administrator.
  2. Type python.exe (provided you have given path of it in environmental variables)

Then, In the same command prompt window the python interpreter will start with >>>

This worked for me.

Using MySQL with Entity Framework

You would need a mapping provider for MySQL. That is an extra thing the Entity Framework needs to make the magic happen. This blog talks about other mapping providers besides the one Microsoft is supplying. I haven't found any mentionings of MySQL.

How to speed up insertion performance in PostgreSQL

Use COPY table TO ... WITH BINARY which is according to the documentation is "somewhat faster than the text and CSV formats." Only do this if you have millions of rows to insert, and if you are comfortable with binary data.

Here is an example recipe in Python, using psycopg2 with binary input.

'tsc command not found' in compiling typescript

This answer is specific for iTermV2 on MAC

  1. First of all, I needed to instal as sudo (admin) during NPM install

    sudo npm install -g typescript

  2. NPM installs the libraries under /usr/local/Cellar/node/<your latest version>/lib/node_modules/typescript folder and symlinks at /usr/local/Cellar/node/<your latest version>/bin/tsc

hence I went ~/.zshrc ( .bashrc, if you use bash)and added /usr/local/Cellar/node/<your latest version>/bin to the $PATH.

  1. reload the shell profile via source ~/.zshrc (.bashrc in your case)

Run MySQLDump without Locking Tables

As none of these approaches worked for me, I simply did a:

mysqldump [...] | grep -v "LOCK TABLE" | mysql [...]

It will exclude both LOCK TABLE <x> and UNLOCK TABLES commands.

Note: Hopefully your data doesn't contain that string in it!

How to replace a string in a SQL Server Table Column

You also can replace large text for email template at run time, here is an simple example for that.

DECLARE @xml NVARCHAR(MAX)
SET @xml = CAST((SELECT [column] AS 'td','',        
        ,[StartDate] AS 'td'
         FROM [table] 
         FOR XML PATH('tr'), ELEMENTS ) AS NVARCHAR(MAX))
select REPLACE((EmailTemplate), '[@xml]', @xml) as Newtemplate 
FROM [dbo].[template] where id = 1

Razor Views not seeing System.Web.Mvc.HtmlHelper

I used the following article on MSDN to solve this issue (in this case from MVC 4 to MVC 5)

https://docs.microsoft.com/en-us/aspnet/mvc/overview/releases/how-to-upgrade-an-aspnet-mvc-4-and-web-api-project-to-aspnet-mvc-5-and-web-api-2

Main extracts from the article are:

Main Web.config (Not the one in the Views folder)

In the runtime block update System.Web.Mvc to 5.0.0.0 ,System.Web.Helpers to 3.0.0.0 and System.Web.WebPages to 3.0.0.0

<dependentAssembly>
  <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
  <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>

<dependentAssembly>
  <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
  <bindingRedirect oldVersion="1.0.0.0-5.0.0.0" newVersion="5.0.0.0" />
</dependentAssembly>

<dependentAssembly>
  <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
  <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>

Then look for the appsettings block and update the webpages:Version value to 3.0.0.0

<appSettings>
    <add key="webpages:Version" value="3.0.0.0" />
</appSettings>

Views Web.config

Update the host factoryType block to System.Web.Mvc to 5.0.0.0

<system.web.webPages.razor>
   <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
   <pages pageBaseType="System.Web.Mvc.WebViewPage">
      <namespaces>
         <add namespace="System.Web.Mvc" />
      </namespaces>
   </pages>
</system.web.webPages.razor>

Then under the pages block update any references to System.Web.Mvc to 5.0.0.0

    <pages
      validateRequest="false"
      pageParserFilterType="System.Web.Mvc.ViewTypeParserFilter, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
      pageBaseType="System.Web.Mvc.ViewPage, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
      userControlBaseType="System.Web.Mvc.ViewUserControl, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
    <controls>
      <add assembly="System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" namespace="System.Web.Mvc" tagPrefix="mvc" />
    </controls>
  </pages>

And finally under the configuration block update the System.Web references to 3.0.0.0

<configuration>
  <configSections>
    <sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
      <section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
      <section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
    </sectionGroup>
  </configSections>

SELECT max(x) is returning null; how can I make it return 0?

In SQL 2005 / 2008:

SELECT ISNULL(MAX(X), 0) AS MaxX
FROM tbl WHERE XID = 1

img src SVG changing the styles with CSS

This might be helpful for people using PHP in combination with .svg images that they want to manipulate with CSS.

You can't overwrite properties inside a img tag with CSS. But when the svg source code is embedded in the HTML you surely can. I like to resolve this issue with a require_once function where I include a .svg.php file. It's like importing an image but you can still overwrite styles with CSS!

First include the svg file:

<?php require_once( '/assets/images/my-icon.svg.php' ); ?>

And it includes this icon for example:

<svg xmlns="http://www.w3.org/2000/svg" width="20.666" height="59.084" viewBox="0 0 20.666 59.084"><g transform="translate(-639.749 -3139)"><path d="M648.536,3173.876c0-2.875-1.725-3.8-3.471-3.8-1.683,0-3.49.9-3.49,3.8,0,3,1.786,3.8,3.49,3.8C646.811,3177.676,648.536,3176.769,648.536,3173.876Zm-3.471,2.341c-.883,0-1.437-.513-1.437-2.341,0-1.971.615-2.381,1.437-2.381.862,0,1.438.349,1.438,2.381,0,1.907-.616,2.339-1.438,2.339Z" fill="#142312"/><path d="M653.471,3170.076a1.565,1.565,0,0,0-1.416.9l-6.558,13.888h1.2a1.565,1.565,0,0,0,1.416-.9l6.559-13.887Z" fill="#142312"/><path d="M655.107,3177.263c-1.684,0-3.471.9-3.471,3.8,0,3,1.766,3.8,3.471,3.8,1.745,0,3.49-.9,3.49-3.8C658.6,3178.186,656.851,3177.263,655.107,3177.263Zm0,6.139c-.884,0-1.438-.514-1.438-2.34,0-1.972.617-2.381,1.438-2.381.862,0,1.437.349,1.437,2.381,0,1.909-.616,2.34-1.437,2.34Z" fill="#142312"/><path d="M656.263,3159.023l-1.49-14.063a1.35,1.35,0,0,0,.329-.293,1.319,1.319,0,0,0,.268-1.123l-.753-3.49a1.328,1.328,0,0,0-1.306-1.054h-6.448a1.336,1.336,0,0,0-1.311,1.068l-.71,3.493a1.344,1.344,0,0,0,.276,1.112,1.532,1.532,0,0,0,.283.262l-1.489,14.087c-1.7,1.727-4.153,4.871-4.153,8.638v28.924a1.339,1.339,0,0,0,1.168,1.49,1.357,1.357,0,0,0,.17.01h17.981a1.366,1.366,0,0,0,1.337-1.366v-29.059C660.414,3163.893,657.963,3160.749,656.263,3159.023Zm-8.307-17.349h4.274l.176.815H647.79Zm9.785,43.634v10.1H642.434v-17.253a4.728,4.728,0,0,1-2.028-4.284,4.661,4.661,0,0,1,2.028-4.215v-2c0-3.162,2.581-5.986,3.687-7.059a1.356,1.356,0,0,0,.4-.819l1.542-14.614H652.1l1.545,14.618a1.362,1.362,0,0,0,.4.819c1.109,1.072,3.688,3.9,3.688,7.059v9.153a5.457,5.457,0,0,1,0,8.5Z" fill="#142312"/></g></svg>

Now we can easily change the fill color like this with CSS:

svg path {
  fill: blue;
}

I first tried to solve this problem with file_get_contents() but the solution above is much faster.

Replace characters from a column of a data frame R

You can use the stringr library:

library('stringr')

a <- runif(10)
b <- letters[1:10]
c <- c(rep('A-B', 4), rep('A_B', 6))
data <- data.frame(a, b, c)

data

#             a b   c
# 1  0.19426707 a A-B
# 2  0.12902673 b A-B
# 3  0.78324955 c A-B
# 4  0.06469028 d A-B
# 5  0.34752264 e A_C
# 6  0.55313288 f A_C
# 7  0.31264280 g A_C
# 8  0.33759921 h A_C
# 9  0.72322599 i A_C
# 10 0.25223075 j A_C

data$c <- str_replace_all(data$c, '_', '-')

data

#             a b   c
# 1  0.19426707 a A-B
# 2  0.12902673 b A-B
# 3  0.78324955 c A-B
# 4  0.06469028 d A-B
# 5  0.34752264 e A-C
# 6  0.55313288 f A-C
# 7  0.31264280 g A-C
# 8  0.33759921 h A-C
# 9  0.72322599 i A-C
# 10 0.25223075 j A-C

Note that this does change factored variables into character.

Convert date to YYYYMM format

A more efficient method, that uses integer math rather than strings/varchars, that will result in an int type rather than a string type is:

SELECT YYYYMM = (YEAR(GETDATE()) * 100) + MONTH(GETDATE())

Adds two zeros to the right side of the year and then adds the month to the added two zeros.

Input type number "only numeric value" validation

In HTML file you can add ngIf for you pattern like this

<div class="form-control-feedback" *ngIf="Mobile.errors && (Mobile.dirty || Mobile.touched)">
        <p *ngIf="Mobile.errors.pattern" class="text-danger">Number Only</p>
      </div>

In .ts file you can add the Validators pattern - "^[0-9]*$"

this.Mobile = new FormControl('', [
  Validators.required,
  Validators.pattern("^[0-9]*$"),
  Validators.minLength(8),
]);

How to simulate browsing from various locations?

Well, DNS should be the same worldwide, wouldn't it? Of course it can take up to a day or so until your new DNS record is propagated around the world. So either something is wrong on your colleague's end or the DNS record still takes some time...

I usually use online DNS lookup tools for that, e.g. http://network-tools.com/

It can check your HTTP header as well. Only a proxy located in Europe would be better.

if checkbox is checked, do this

Probably you can go with this code to take actions as the checkbox is checked or unchecked.

$('#chk').on('click',function(){
    if(this.checked==true){
      alert('yes');
    }else{
      alert('no');
    }
});

How to check if Receiver is registered in Android?

simplest solution

in receiver:

public class MyReceiver extends BroadcastReceiver {   
    public boolean isRegistered;

    /**
    * register receiver
    * @param context - Context
    * @param filter - Intent Filter
    * @return see Context.registerReceiver(BroadcastReceiver,IntentFilter)
    */
    public Intent register(Context context, IntentFilter filter) {
        try {
              // ceph3us note:
              // here I propose to create 
              // a isRegistered(Contex) method 
              // as you can register receiver on different context  
              // so you need to match against the same one :) 
              // example  by storing a list of weak references  
              // see LoadedApk.class - receiver dispatcher 
              // its and ArrayMap there for example 
              return !isRegistered 
                     ? context.registerReceiver(this, filter) 
                     : null;
            } finally {
               isRegistered = true;
            }
    }

    /**
     * unregister received
     * @param context - context
     * @return true if was registered else false
     */
     public boolean unregister(Context context) {
         // additional work match on context before unregister
         // eg store weak ref in register then compare in unregister 
         // if match same instance
         return isRegistered 
                    && unregisterInternal(context);
     }

     private boolean unregisterInternal(Context context) {
         context.unregisterReceiver(this); 
         isRegistered = false;
         return true;
     }

    // rest implementation  here 
    // or make this an abstract class as template :)
    ...
}

in code:

MyReceiver myReceiver = new MyReceiver();
myReceiver.register(Context, IntentFilter); // register 
myReceiver.unregister(Context); // unregister 

ad 1

-- in reply to:

This really isn't that elegant because you have to remember to set the isRegistered flag after you register. – Stealth Rabbi

-- "more ellegant way" added method in receiver to register and set flag

this won't work If you restart the device or if your app got killed by OS. – amin 6 hours ago

@amin - see lifetime of in code (not system registered by manifest entry) registered receiver :)

Why Anaconda does not recognize conda command?

As other users said, the best way for Windows users is to set the global environment variable.

I install the Miniconda3 for MXNet.

Before I do something, only Anaconda Prompt works for conda.

After setting the global environment variable, The CMD and Git Bash work. But in some IDEs like RStudio, the nested Git Bash doesn't work.

After restarting my computer, the Git Bash in the RStudio works for conda.

I hope these tests helps for you.

CSS: create white glow around image

You can use CSS3 to create an effect like that, but then you're only going to see it in modern browsers that support box shadow, unless you use a polyfill like CSS3PIE. So, for example, you could do something like this: http://jsfiddle.net/cany2/

Oracle get previous day records

how about sysdate?

SELECT field,datetime_field 
FROM database
WHERE datetime_field > (sysdate-1)

WordPress: get author info from post id

I figured it out.

<?php $author_id=$post->post_author; ?>
<img src="<?php the_author_meta( 'avatar' , $author_id ); ?> " width="140" height="140" class="avatar" alt="<?php echo the_author_meta( 'display_name' , $author_id ); ?>" />
<?php the_author_meta( 'user_nicename' , $author_id ); ?> 

sklearn error ValueError: Input contains NaN, infinity or a value too large for dtype('float64')

dataset = dataset.dropna(axis=0, how='any', thresh=None, subset=None, inplace=False)

This worked for me

Jquery mouseenter() vs mouseover()

This example demonstrates the difference between the mousemove, mouseenter and mouseover events:

https://jsfiddle.net/z8g613yd/

HTML:

<div onmousemove="myMoveFunction()">
    <p>onmousemove: <br> <span id="demo">Mouse over me!</span></p>
</div>

<div onmouseenter="myEnterFunction()">
    <p>onmouseenter: <br> <span id="demo2">Mouse over me!</span></p>
</div>

<div onmouseover="myOverFunction()">
    <p>onmouseover: <br> <span id="demo3">Mouse over me!</span></p>
</div>

CSS:

div {
    width: 200px;
    height: 100px;
    border: 1px solid black;
    margin: 10px;
    float: left;
    padding: 30px;
    text-align: center;
    background-color: lightgray;
}

p {
    background-color: white;
    height: 50px;
}

p span {
    background-color: #86fcd4;
    padding: 0 20px;
}

JS:

var x = 0;
var y = 0;
var z = 0;

function myMoveFunction() {
    document.getElementById("demo").innerHTML = z += 1;
}

function myEnterFunction() {
    document.getElementById("demo2").innerHTML = x += 1;
}

function myOverFunction() {
    document.getElementById("demo3").innerHTML = y += 1;
}
  • onmousemove : occurs every time the mouse pointer is moved over the div element.
  • onmouseenter : only occurs when the mouse pointer enters the div element.
  • onmouseover : occurs when the mouse pointer enters the div element, and its child elements (p and span).

Run Batch File On Start-up

To start the batch file at the start of your system, you can also use a registry key.

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run

Here you can create a string. As name you can choose anything and the data is the full path to your file.

There is also the registry key

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce

to run something at only the next start of your system.

Create a tar.xz in one command

If you like the pipe mode, this is the most clean solution:

tar c some-dir | xz > some-dir.tar.xz

It's not necessary to put the f option in order to deal with files and then to use - to specify that the file is the standard input. It's also not necessary to specify the -z option for xz, because it's default.

It works with gzip and bzip2 too:

tar c some-dir | gzip > some-dir.tar.gz

or

tar c some-dir | bzip2 > some-dir.tar.bz2

Decompressing is also quite straightforward:

xzcat tarball.tar.xz | tar x
bzcat tarball.tar.bz2 | tar x
zcat tarball.tar.gz | tar x

If you have only tar archive, you can use cat:

cat archive.tar | tar x

If you need to list the files only, use tar t.

Create a custom event in Java

What you want is an implementation of the observer pattern. You can do it yourself completely, or use java classes like java.util.Observer and java.util.Observable

Simplest JQuery validation rules example

The examples contained in this blog post do the trick.

What are DDL and DML?

In simple words.

DDL(Data definition language): will work on structure of data. define the data structures.

DML (data manipulation language): will work on data. manipulates the data itself

Return first N key:value pairs from dict

Python's dicts are not ordered, so it's meaningless to ask for the "first N" keys.

The collections.OrderedDict class is available if that's what you need. You could efficiently get its first four elements as

import itertools
import collections

d = collections.OrderedDict((('foo', 'bar'), (1, 'a'), (2, 'b'), (3, 'c'), (4, 'd')))
x = itertools.islice(d.items(), 0, 4)

for key, value in x:
    print key, value

itertools.islice allows you to lazily take a slice of elements from any iterator. If you want the result to be reusable you'd need to convert it to a list or something, like so:

x = list(itertools.islice(d.items(), 0, 4))

When to use If-else if-else over switch statements and vice versa

This depends very much on the specific case. Preferably, I think one should use the switch over the if-else if there are many nested if-elses.

The question is how much is many?

Yesterday I was asking myself the same question:

public enum ProgramType {
    NEW, OLD
}

if (progType == OLD) {
    // ...
} else if (progType == NEW) {
    // ...
}

if (progType == OLD) {
    // ...
} else {
    // ...
}

switch (progType) {
case OLD:
    // ...
    break;
case NEW:
    // ...
    break;
default:
    break;
}

In this case, the 1st if has an unnecessary second test. The 2nd feels a little bad because it hides the NEW.

I ended up choosing the switch because it just reads better.

Is it possible to force Excel recognize UTF-8 CSV files automatically?

This is an old question but I've just encountered had a similar problem and the solution may help others:

Had the same issue where writing out CSV text data to a file, then opening the resulting .csv in Excel shifts all the text into a single column. After having a read of the above answers I tried the following, which seems to sort the problem out.

Apply an encoding of UTF-8 when you create your StreamWriter. That's it.

Example:

using (StreamWriter output = new StreamWriter(outputFileName, false, Encoding.UTF8, 2 << 22)) {
   /* ... do stuff .... */
   output.Close();
}

Free Online Team Foundation Server

Readify used to run their TFSNow hosted TFS service, but I don't think it's going any longer. The only others I've heard of, apart from CodePlex, aren't free:

Downloading images with node.js

if you want progress download try this:

var fs = require('fs');
var request = require('request');
var progress = require('request-progress');

module.exports = function (uri, path, onProgress, onResponse, onError, onEnd) {
    progress(request(uri))
    .on('progress', onProgress)
    .on('response', onResponse)
    .on('error', onError)
    .on('end', onEnd)
    .pipe(fs.createWriteStream(path))
};

how to use:

  var download = require('../lib/download');
  download("https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_150x54dp.png", "~/download/logo.png", function (state) {
            console.log("progress", state);
        }, function (response) {
            console.log("status code", response.statusCode);
        }, function (error) {
            console.log("error", error);
        }, function () {
            console.log("done");
        });

note: you should install both request & request-progress modules using:

npm install request request-progress --save

R: invalid multibyte string

This happened to me because I had the 'copyright' symbol in one of my strings! Once it was removed, problem solved.

A good rule of thumb, make sure that characters not appearing on your keyboard are removed if you are seeing this error.

How to make type="number" to positive numbers only

_x000D_
_x000D_
<input type="number" min="1" step="1">
_x000D_
_x000D_
_x000D_

Check if element is visible in DOM

Combining a couple answers above:

function isVisible (ele) {
    var style = window.getComputedStyle(ele);
    return  style.width !== "0" &&
    style.height !== "0" &&
    style.opacity !== "0" &&
    style.display!=='none' &&
    style.visibility!== 'hidden';
}

Like AlexZ said, this may be slower than some of your other options if you know more specifically what you're looking for, but this should catch all of the main ways elements are hidden.

But, it also depends what counts as visible for you. Just for example, a div's height can be set to 0px but the contents still visible depending on the overflow properties. Or a div's contents could be made the same color as the background so it is not visible to users but still rendered on the page. Or a div could be moved off screen or hidden behind other divs, or it's contents could be non-visible but the border still visible. To a certain extent "visible" is a subjective term.

Dynamically Dimensioning A VBA Array?

You need to use a constant.

CONST NumberOfZombies = 20000
Dim Zombies(NumberOfZombies) As Zombies

or if you want to use a variable you have to do it this way:

Dim NumberOfZombies As Integer
NumberOfZombies = 20000

Dim Zombies() As Zombies

ReDim Zombies(NumberOfZombies)

Postgres "psql not recognized as an internal or external command"

Even if it is a little bit late, i solved the PATH problem by removing every space.

;C:\Program Files\PostgreSQL\9.5\bin;C:\Program Files\PostgreSQL\9.5\lib

works for me now.

Android: Difference between Parcelable and Serializable?

1. Serializable

@see http://docs.oracle.com/javase/7/docs/api/java/io/Serializable.html

Interface of what?

  • is a standard Java interface

Speed

  • slower than Parcelable

2. Parcelable

@see http://developer.android.com/reference/android/os/Parcelable.html

Interface of what?

  • is android.os interface
    • which means Google developped Parcelable for better performance on android

Speed

  • faster ( because it is optimized for usage on android development)

> In Conclusion

Be aware that Serializable is a standard Java interface, and Parcelable is for Android Development

What is the meaning of "Failed building wheel for X" in pip install?

On Ubuntu 18.04, I ran into this issue because the apt package for wheel does not include the wheel command. I think pip tries to import the wheel python package, and if that succeeds assumes that the wheel command is also available. Ubuntu breaks that assumption.

The apt python3 code package is named python3-wheel. This is installed automatically because python3-pip recommends it.

The apt python3 wheel command package is named python-wheel-common. Installing this too fixes the "failed building wheel" errors for me.

How can you encode a string to Base64 in JavaScript?

Internet Explorer 10+

// Define the string
var string = 'Hello World!';

// Encode the String
var encodedString = btoa(string);
console.log(encodedString); // Outputs: "SGVsbG8gV29ybGQh"

// Decode the String
var decodedString = atob(encodedString);
console.log(decodedString); // Outputs: "Hello World!"

Cross-Browser

// Create Base64 Object
var Base64={_keyStr:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",encode:function(e){var t="";var n,r,i,s,o,u,a;var f=0;e=Base64._utf8_encode(e);while(f<e.length){n=e.charCodeAt(f++);r=e.charCodeAt(f++);i=e.charCodeAt(f++);s=n>>2;o=(n&3)<<4|r>>4;u=(r&15)<<2|i>>6;a=i&63;if(isNaN(r)){u=a=64}else if(isNaN(i)){a=64}t=t+this._keyStr.charAt(s)+this._keyStr.charAt(o)+this._keyStr.charAt(u)+this._keyStr.charAt(a)}return t},decode:function(e){var t="";var n,r,i;var s,o,u,a;var f=0;e=e.replace(/[^A-Za-z0-9\+\/\=]/g,"");while(f<e.length){s=this._keyStr.indexOf(e.charAt(f++));o=this._keyStr.indexOf(e.charAt(f++));u=this._keyStr.indexOf(e.charAt(f++));a=this._keyStr.indexOf(e.charAt(f++));n=s<<2|o>>4;r=(o&15)<<4|u>>2;i=(u&3)<<6|a;t=t+String.fromCharCode(n);if(u!=64){t=t+String.fromCharCode(r)}if(a!=64){t=t+String.fromCharCode(i)}}t=Base64._utf8_decode(t);return t},_utf8_encode:function(e){e=e.replace(/\r\n/g,"\n");var t="";for(var n=0;n<e.length;n++){var r=e.charCodeAt(n);if(r<128){t+=String.fromCharCode(r)}else if(r>127&&r<2048){t+=String.fromCharCode(r>>6|192);t+=String.fromCharCode(r&63|128)}else{t+=String.fromCharCode(r>>12|224);t+=String.fromCharCode(r>>6&63|128);t+=String.fromCharCode(r&63|128)}}return t},_utf8_decode:function(e){var t="";var n=0;var r=c1=c2=0;while(n<e.length){r=e.charCodeAt(n);if(r<128){t+=String.fromCharCode(r);n++}else if(r>191&&r<224){c2=e.charCodeAt(n+1);t+=String.fromCharCode((r&31)<<6|c2&63);n+=2}else{c2=e.charCodeAt(n+1);c3=e.charCodeAt(n+2);t+=String.fromCharCode((r&15)<<12|(c2&63)<<6|c3&63);n+=3}}return t}}

// Define the string
var string = 'Hello World!';

// Encode the String
var encodedString = Base64.encode(string);
console.log(encodedString); // Outputs: "SGVsbG8gV29ybGQh"

// Decode the String
var decodedString = Base64.decode(encodedString);
console.log(decodedString); // Outputs: "Hello World!"

jsFiddle


with Node.js

Here is how you encode normal text to base64 in Node.js:

//Buffer() requires a number, array or string as the first parameter, and an optional encoding type as the second parameter. 
// Default is utf8, possible encoding types are ascii, utf8, ucs2, base64, binary, and hex
var b = new Buffer('JavaScript');
// If we don't use toString(), JavaScript assumes we want to convert the object to utf8.
// We can make it convert to other formats by passing the encoding type to toString().
var s = b.toString('base64');

And here is how you decode base64 encoded strings:

var b = new Buffer('SmF2YVNjcmlwdA==', 'base64')
var s = b.toString();

with Dojo.js

To encode an array of bytes using dojox.encoding.base64:

var str = dojox.encoding.base64.encode(myByteArray);

To decode a base64-encoded string:

var bytes = dojox.encoding.base64.decode(str)

bower install angular-base64

<script src="bower_components/angular-base64/angular-base64.js"></script>

angular
    .module('myApp', ['base64'])
    .controller('myController', [

    '$base64', '$scope', 
    function($base64, $scope) {

        $scope.encoded = $base64.encode('a string');
        $scope.decoded = $base64.decode('YSBzdHJpbmc=');
}]);

Is it a good practice to use try-except-else in Python?

Just because no-one else has posted this opinion, I would say

avoid else clauses in try/excepts because they're unfamiliar to most people

Unlike the keywords try, except, and finally, the meaning of the else clause isn't self-evident; it's less readable. Because it's not used very often, it'll cause people that read your code to want to double-check the docs to be sure they understand what's going on.

(I'm writing this answer precisely because I found a try/except/else in my codebase and it caused a wtf moment and forced me to do some googling).

So, wherever I see code like the OP example:

try:
    try_this(whatever)
except SomeException as the_exception:
    handle(the_exception)
else:
    # do some more processing in non-exception case
    return something

I would prefer to refactor to

try:
    try_this(whatever)
except SomeException as the_exception:
    handle(the_exception)
    return  # <1>
# do some more processing in non-exception case  <2>
return something
  • <1> explicit return, clearly shows that, in the exception case, we are finished working

  • <2> as a nice minor side-effect, the code that used to be in the else block is dedented by one level.

How do you run a Python script as a service in Windows?

Yes you can. I do it using the pythoncom libraries that come included with ActivePython or can be installed with pywin32 (Python for Windows extensions).

This is a basic skeleton for a simple service:

import win32serviceutil
import win32service
import win32event
import servicemanager
import socket


class AppServerSvc (win32serviceutil.ServiceFramework):
    _svc_name_ = "TestService"
    _svc_display_name_ = "Test Service"

    def __init__(self,args):
        win32serviceutil.ServiceFramework.__init__(self,args)
        self.hWaitStop = win32event.CreateEvent(None,0,0,None)
        socket.setdefaulttimeout(60)

    def SvcStop(self):
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        win32event.SetEvent(self.hWaitStop)

    def SvcDoRun(self):
        servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
                              servicemanager.PYS_SERVICE_STARTED,
                              (self._svc_name_,''))
        self.main()

    def main(self):
        pass

if __name__ == '__main__':
    win32serviceutil.HandleCommandLine(AppServerSvc)

Your code would go in the main() method—usually with some kind of infinite loop that might be interrupted by checking a flag, which you set in the SvcStop method

java.lang.IllegalStateException: Fragment not attached to Activity

This error can happen if you are instantiating a fragment that somehow can't be instantiated:

Fragment myFragment = MyFragment.NewInstance();


public classs MyFragment extends Fragment {
  public void onCreate() {
   // Some error here, or anywhere inside the class is preventing it from being instantiated
  }
}

In my case, i have met this when i tried to use:

private String loading = getString(R.string.loading);

'Missing contentDescription attribute on image' in XML

This warning tries to improve accessibility of your application.

To disable missing content description warning in the whole project, you can add this to your application module build.gradle

android {

    ...

    lintOptions {
        disable 'ContentDescription'
    }
}

How to select an item in a ListView programmatically?

if (listView1.Items.Count > 0)
{
    listView1.FocusedItem = listView1.Items[0];
    listView1.Items[0].Selected = true;
    listView1.Select();
}

JavaScript check if variable exists (is defined/initialized)

In many cases, using:

if (elem) { // or !elem

will do the job for you!... this will check these below cases:

  1. undefined: if the value is not defined and it's undefined
  2. null: if it's null, for example, if a DOM element not exists...
  3. empty string: ''
  4. 0: number zero
  5. NaN: not a number
  6. false

So it will cover off kind of all cases, but there are always weird cases which we'd like to cover as well, for example, a string with spaces, like this ' ' one, this will be defined in javascript as it has spaces inside string... for example in this case you add one more check using trim(), like:

if(elem) {

if(typeof elem === 'string' && elem.trim()) {
///

Also, these checks are for values only, as objects and arrays work differently in Javascript, empty array [] and empty object {} are always true.

I create the image below to show a quick brief of the answer:

undefined, null, etc

How to check if running as root in a bash script

Check if you are root and quit if you are not:

if ((EUID != 0)); then
    echo "Root or Sudo  Required for script ( $(basename $0) )"
    exit
fi

Or in this example, try to create a directory in root location then try after rights were elevated.

Check if you are root and if not elevate if possible :

# Fails to create these dirs (needs sudo)
mkdir /test-dir-$(basename $0)
rmdir /test-dir-$(basename $0)

if ((EUID != 0)); then
    echo "Granting root privileges for script ( $(basename $0) )"
    if [[ -t 1 ]]; then
        sudo "$0" "$@"
    else
        exec 1> output_file
        gksu "$0" "$@"
    fi
    exit
fi
echo "Root privileges granted..."
# Creates Dirs as it now has rights
mkdir /test-dir-$(basename $0)
rmdir /test-dir-$(basename $0)

Unable to Install Any Package in Visual Studio 2015

Open the packages folder. Check if files with extension .deleteme exists, example Newtonsoft.Json.9.0.1.deleteme. Delete all the packages which have a .deleteme file manually. Delete the .deleteme files. Close and open the Nuget Explorer.

Can we set a Git default to fetch all tags during a remote pull?

I use this with magit on kernel.org

[remote "upstream"]
    url = <redacted>
    fetch = +refs/heads/*:refs/remotes/upstream/*
    tagOpt = --tags

HashMap get/put complexity

It depends on many things. It's usually O(1), with a decent hash which itself is constant time... but you could have a hash which takes a long time to compute, and if there are multiple items in the hash map which return the same hash code, get will have to iterate over them calling equals on each of them to find a match.

In the worst case, a HashMap has an O(n) lookup due to walking through all entries in the same hash bucket (e.g. if they all have the same hash code). Fortunately, that worst case scenario doesn't come up very often in real life, in my experience. So no, O(1) certainly isn't guaranteed - but it's usually what you should assume when considering which algorithms and data structures to use.

In JDK 8, HashMap has been tweaked so that if keys can be compared for ordering, then any densely-populated bucket is implemented as a tree, so that even if there are lots of entries with the same hash code, the complexity is O(log n). That can cause issues if you have a key type where equality and ordering are different, of course.

And yes, if you don't have enough memory for the hash map, you'll be in trouble... but that's going to be true whatever data structure you use.

How to set the height of an input (text) field in CSS?

The best way to do this is:

input.heighttext{
  padding: 20px 10px;
  line-height: 28px;
}

Invalid application path

I eventually tracked this down to the Anonymous Authentication Credentials. I don't know what had changed, because this application used to work, but anyway, this is what I did: Click on the Application -> Authentication. Make sure Anonymous Authentication is enabled (it was, in my case), but also click on Edit... and change the anonymous user identity to "Application pool identity" not "Specific user". Making this change worked for me.

Regards.

Disabling vertical scrolling in UIScrollView

Include the following method

-(void)viewDidLayoutSubviews{
    self.automaticallyAdjustsScrollViewInsets = NO;
}

and set the content size width of the scroll view equal to the width of the scroll view.

Match multiline text using regular expression

First, you're using the modifiers under an incorrect assumption.

Pattern.MULTILINE or (?m) tells Java to accept the anchors ^ and $ to match at the start and end of each line (otherwise they only match at the start/end of the entire string).

Pattern.DOTALL or (?s) tells Java to allow the dot to match newline characters, too.

Second, in your case, the regex fails because you're using the matches() method which expects the regex to match the entire string - which of course doesn't work since there are some characters left after (\\W)*(\\S)* have matched.

So if you're simply looking for a string that starts with User Comments:, use the regex

^\s*User Comments:\s*(.*)

with the Pattern.DOTALL option:

Pattern regex = Pattern.compile("^\\s*User Comments:\\s+(.*)", Pattern.DOTALL);
Matcher regexMatcher = regex.matcher(subjectString);
if (regexMatcher.find()) {
    ResultString = regexMatcher.group(1);
} 

ResultString will then contain the text after User Comments:

Uncaught SoapFault exception: [HTTP] Error Fetching http headers

I faced same problem and tried all the above solution. Sadly nothing work.

  1. Socket Timeout (Not worked)
  2. User Agent (Not Worked)
  3. SoapClient configuration, cache_wsdl and Keep-Alive etc..

This whole game of headers that we are passing. I solved my problem with adding the compression header property. This actually require when you are expecting response in gzip compressed format.

//set the Headers of Soap Client. 
$client = new SoapClient($wsdlUrl, array(
    'trace' => true, 
    'keep_alive' => true,
    'connection_timeout' => 5000,
    'cache_wsdl' => WSDL_CACHE_NONE,
    'compression'   => SOAP_COMPRESSION_ACCEPT | SOAP_COMPRESSION_GZIP | SOAP_COMPRESSION_DEFLATE,
));

Hope it helps.

Good luck.

How can I check for IsPostBack in JavaScript?

Here is one way (put this in Page_Load):

if (this.IsPostBack)
{
    Page.ClientScript.RegisterStartupScript(this.GetType(),"PostbackKey","<script type='text/javascript'>var isPostBack = true;</script>");
}

Then just check that variable in the JS.

C#: Printing all properties of an object

You can use the TypeDescriptor class to do this:

foreach(PropertyDescriptor descriptor in TypeDescriptor.GetProperties(obj))
{
    string name=descriptor.Name;
    object value=descriptor.GetValue(obj);
    Console.WriteLine("{0}={1}",name,value);
}

TypeDescriptor lives in the System.ComponentModel namespace and is the API that Visual Studio uses to display your object in its property browser. It's ultimately based on reflection (as any solution would be), but it provides a pretty good level of abstraction from the reflection API.

Regex select all text between tags

_x000D_
_x000D_
var str = "Lorem ipsum <pre>text 1</pre> Lorem ipsum <pre>text 2</pre>";_x000D_
    str.replace(/<pre>(.*?)<\/pre>/g, function(match, g1) { console.log(g1); });
_x000D_
_x000D_
_x000D_

Since accepted answer is without javascript code, so adding that:

Delete newline in Vim

If you are on the first line, pressing (upper case) J will join that line and the next line together, removing the newline. You can also combine this with a count, so pressing 3J will combine all 3 lines together.

How can I add a Google search box to my website?

Figured it out, folks! for the NAME of the text box, you have to use "q". I had "g" just for my own personal preferences. But apparently it has to be "q".

Anyone know why?

Error inflating class fragment

Had the same error type, where exactly the same error message in logcat was displayed. I needed to make changes in the Java Build Path located under Project->Properties. I had included Google Maps related libraries like android-support-v4.jar and google-play-services.jar; however I was missing including these on the 'Build class path' in the 'Order and Export' option menu. Maybe the error lies here.

Try including libraries to the build class path.

The order of which the classes are built might also trigger the error, so my advice is also to try to rearrange the order of the building path. The error disappeared when I used the following order: 'my_project_name/src'->'my_project_name/gen'->'Android Private Libraries'. The last unit contains the jar files mentioned earlier.

How do I install Python libraries in wheel format?

You don't need to download exclusively from the website. Just make sure you have pip (which you probably will if you have python installed). Just open your Command Prompt (CMD) and run the command:

pip install pygame

It will automatically download the correct whl version of pygame compatible with your configuration of PC. Make sure you remember the version which appears while "downloading" as this is the compatible version of .whl packages you shall be looking for in the future.

How to add manifest permission to an application?

If you are using the Eclipse ADT plugin for your development, open AndroidManifest.xml in the Android Manifest Editor (should be the default action for opening AndroidManifest.xml from the project files list).

Afterwards, select the Permissions tab along the bottom of the editor (Manifest - Application - Permissions - Instrumentation - AndroidManifest.xml), then click Add... a Uses Permission and select the desired permission from the dropdown on the right, or just copy-paste in the necessary one (such as the android.permission.INTERNET permission you required).

Check if enum exists in Java

Since Java 8, we could use streams instead of for loops. Also, it might be apropriate to return an Optional if the enum does not have an instance with such a name.

I have come up with the following three alternatives on how to look up an enum:

private enum Test {
    TEST1, TEST2;

    public Test fromNameOrThrowException(String name) {
        return Arrays.stream(values())
                .filter(e -> e.name().equals(name))
                .findFirst()
                .orElseThrow(() -> new IllegalArgumentException("No enum with name " + name));
    }

    public Test fromNameOrNull(String name) {
        return Arrays.stream(values()).filter(e -> e.name().equals(name)).findFirst().orElse(null);
    }

    public Optional<Test> fromName(String name) {
        return Arrays.stream(values()).filter(e -> e.name().equals(name)).findFirst();
    }
}

Make sure that the controller has a parameterless public constructor error

In my case, it was because of exception inside the constructor of my injected dependency (in your example - inside DashboardRepository constructor). The exception was caught somewhere inside MVC infrastructure. I found this after I added logs in relevant places.

How to escape special characters of a string with single backslashes

Just assuming this is for a regular expression, use re.escape.

How to check whether a given string is valid JSON in Java

With Google Gson you can use JsonParser:

import com.google.gson.JsonParser;

JsonParser parser = new JsonParser();
parser.parse(json_string); // throws JsonSyntaxException

SELECT * FROM in MySQLi

You can still use it (mysqli is just another way of communicating with the server, the SQL language itself is expanded, not changed). Prepared statements are safer, though - since you don't need to go through the trouble of properly escaping your values each time. You can leave them as they were, if you want to but the risk of sql piggybacking is reduced if you switch.

matplotlib.pyplot will not forget previous plots - how can I flush/refresh?

I would rather use plt.clf() after every plt.show() to just clear the current figure instead of closing and reopening it, keeping the window size and giving you a better performance and much better memory usage.

Similarly, you could do plt.cla() to just clear the current axes.

To clear a specific axes, useful when you have multiple axes within one figure, you could do for example:

fig, axes = plt.subplots(nrows=2, ncols=2)

axes[0, 1].clear()

Install a Windows service using a Windows command prompt?

Open command prompt as administrator, go to your Folder where your .exe resides. To Install Exe as service

D:\YourFolderName\YourExeName /i

To uninstall use /u.

Upload files with FTP using PowerShell

Goyuix's solution works great, but as presented it gives me this error: "The requested FTP command is not supported when using HTTP proxy."

Adding this line after $ftp.UsePassive = $true fixed the problem for me:

$ftp.Proxy = $null;

jQuery creating objects

I actually found a better way using the jQuery approach

var box = {

config:{
 color: 'red'
},

init:function(config){
 $.extend(this.config,config);
}

};

var myBox = box.init({
 color: blue
});

Javascript - How to show escape characters in a string?

You have to escape the backslash, so try this:

str = "Hello\\nWorld";

Here are more escaped characters in Javascript.

Ruby: How to get the first character of a string

In MRI 1.8.7 or greater:

'foobarbaz'.each_char.first

fastest MD5 Implementation in JavaScript

I wrote tests to compare several JavaScript hash implementations, including most MD5 implementations mentioned here. To run the tests, go to http://brillout.github.io/test-javascript-hash-implementations/ and wait a bit.

It seems that the YaMD5 implementation of R. Hill's answer is the fastest.

How to call a stored procedure (with parameters) from another stored procedure without temp table

You can call Stored Procedure like this inside Stored Procedure B.

CREATE PROCEDURE spA
@myDate DATETIME
AS
    EXEC spB @myDate

RETURN 0

nginx: how to create an alias url route?

server {
  server_name example.com;
  root /path/to/root;
  location / {
    # bla bla
  }
  location /demo {
    alias /path/to/root/production/folder/here;
  }
}

If you need to use try_files inside /demo you'll need to replace alias with a root and do a rewrite because of the bug explained here

Tried to Load Angular More Than Once

The problem for me was, I had taken backup of controller (js) file with some other changes in the same folder and bundling loaded both the controller files (original and backup js). Removing backup from the scripts folder, that was bundled solved the issue.

Find p-value (significance) in scikit-learn LinearRegression

There could be a mistake in @JARH's answer in the case of a multivariable regression. (I do not have enough reputation to comment.)

In the following line:

p_values =[2*(1-stats.t.cdf(np.abs(i),(len(newX)-1))) for i in ts_b],

the t-values follows a chi-squared distribution of degree len(newX)-1 instead of following a chi-squared distribution of degree len(newX)-len(newX.columns)-1.

So this should be:

p_values =[2*(1-stats.t.cdf(np.abs(i),(len(newX)-len(newX.columns)-1))) for i in ts_b]

(See t-values for OLS regression for more details)

Counting array elements in Perl

Maybe you want a hash instead (or in addition). Arrays are an ordered set of elements; if you create $foo[23], you implicitly create $foo[0] through $foo[22].

Android - Activity vs FragmentActivity?

If you use the Eclipse "New Android Project" wizard in a recent ADT bundle, you'll automatically get tabs implemented as a Fragments. This makes the conversion of your application to the tablet format much easier in the future.

For simple single screen layouts you may still use Activity.

How to resolve git stash conflict without commit?

git add .
git reset

git add . will stage ALL the files telling git that you have resolved the conflict

git reset will unstage ALL the staged files without creating a commit

Generate random numbers using C++11 random library

Here's something that I just wrote along those lines::

#include <random>
#include <chrono>
#include <thread>

using namespace std;

//==============================================================
// RANDOM BACKOFF TIME
//==============================================================
class backoff_time_t {
  public:
    random_device                      rd;
    mt19937                            mt;
    uniform_real_distribution<double>  dist;

    backoff_time_t() : rd{}, mt{rd()}, dist{0.5, 1.5} {}

    double rand() {
      return dist(mt);
    }
};

thread_local backoff_time_t backoff_time;


int main(int argc, char** argv) {
   double x1 = backoff_time.rand();
   double x2 = backoff_time.rand();
   double x3 = backoff_time.rand();
   double x4 = backoff_time.rand();
   return 0;
}

~

What is the purpose of the var keyword and when should I use it (or omit it)?

You should use var keyword unless you intend to have the variable attached to window object in browser. Here's a link that explains scoping and difference between glocal scoping and local scoping with and wihtout var keyword.

When variables get defined without the use of var keyword, what it looks like is a simple “assignment” operation.

When the value is assigned to a variable in javascript, the interpreter first tries to find the “variable declaration” in the same context/scope as that of assignment. When the interpreter executes dummyVariable = 20, it looks up for the declaration of dummyVariable at beginning of the function. (Since all Variable declarations are moved to the beginning of the context by javascript interpreter and this is called hoisting)

You may also want to look at hoisting in javascript

WPF Image Dynamically changing Image source during runtime

I can think of two things:

First, try loading the image with:

string strUri2 = String.Format(@"pack://application:,,,/MyAseemby;component/resources/main titles/{0}", CurrenSelection.TitleImage);
imgTitle.Source = new BitmapImage(new Uri(strUri2));

Maybe the problem is with WinForm's image resizing, if the image is stretched set Stretch on the image control to "Uniform" or "UnfirofmToFill".

Second option is that maybe the image is not aligned to the pixel grid, you can read about it on my blog at http://www.nbdtech.com/blog/archive/2008/11/20/blurred-images-in-wpf.aspx

How to expand textarea width to 100% of parent (or how to expand any HTML element to 100% of parent width)?

Add the css

  <style type="text/css">
    textarea
    {

        border:1px solid #999999
        width:99%;
        margin:5px 0;
        padding:1%;
    }
</style>

Getting last month's date in php

$time = mktime(0, 0, 0, date("m"),date("d")-date("t"), date("Y"));
$lastMonth = date("d-m-Y", $time);

OR

$lastMonth = date("m-Y", mktime() - 31*3600*24);

works on 30.03.2012

Replace multiple strings at once

String.prototype.replaceArray = function (find, replace) {
    var replaceString = this;
    for (var i = 0; i < find.length; i++) {
        // global replacement
        var pos = replaceString.indexOf(find[i]);
        while (pos > -1) {
            replaceString = replaceString.replace(find[i], replace[i]);
            pos = replaceString.indexOf(find[i]);
        }
    }
    return replaceString;
};

var textT = "Hello world,,,,, hello people.....";
var find = [".",","];
var replace = ['2', '5'];
textT = textT.replaceArray(find, replace);
// result: Hello world55555 hello people22222

Difference between partition key, composite key and clustering key in Cassandra?

There is a lot of confusion around this, I will try to make it as simple as possible.

The primary key is a general concept to indicate one or more columns used to retrieve data from a Table.

The primary key may be SIMPLE and even declared inline:

 create table stackoverflow_simple (
      key text PRIMARY KEY,
      data text      
  );

That means that it is made by a single column.

But the primary key can also be COMPOSITE (aka COMPOUND), generated from more columns.

 create table stackoverflow_composite (
      key_part_one text,
      key_part_two int,
      data text,
      PRIMARY KEY(key_part_one, key_part_two)      
  );

In a situation of COMPOSITE primary key, the "first part" of the key is called PARTITION KEY (in this example key_part_one is the partition key) and the second part of the key is the CLUSTERING KEY (in this example key_part_two)

Please note that the both partition and clustering key can be made by more columns, here's how:

 create table stackoverflow_multiple (
      k_part_one text,
      k_part_two int,
      k_clust_one text,
      k_clust_two int,
      k_clust_three uuid,
      data text,
      PRIMARY KEY((k_part_one, k_part_two), k_clust_one, k_clust_two, k_clust_three)      
  );

Behind these names ...

  • The Partition Key is responsible for data distribution across your nodes.
  • The Clustering Key is responsible for data sorting within the partition.
  • The Primary Key is equivalent to the Partition Key in a single-field-key table (i.e. Simple).
  • The Composite/Compound Key is just any multiple-column key

Further usage information: DATASTAX DOCUMENTATION


Small usage and content examples
SIMPLE KEY:

insert into stackoverflow_simple (key, data) VALUES ('han', 'solo');
select * from stackoverflow_simple where key='han';

table content

key | data
----+------
han | solo

COMPOSITE/COMPOUND KEY can retrieve "wide rows" (i.e. you can query by just the partition key, even if you have clustering keys defined)

insert into stackoverflow_composite (key_part_one, key_part_two, data) VALUES ('ronaldo', 9, 'football player');
insert into stackoverflow_composite (key_part_one, key_part_two, data) VALUES ('ronaldo', 10, 'ex-football player');
select * from stackoverflow_composite where key_part_one = 'ronaldo';

table content

 key_part_one | key_part_two | data
--------------+--------------+--------------------
      ronaldo |            9 |    football player
      ronaldo |           10 | ex-football player

But you can query with all key (both partition and clustering) ...

select * from stackoverflow_composite 
   where key_part_one = 'ronaldo' and key_part_two  = 10;

query output

 key_part_one | key_part_two | data
--------------+--------------+--------------------
      ronaldo |           10 | ex-football player

Important note: the partition key is the minimum-specifier needed to perform a query using a where clause. If you have a composite partition key, like the following

eg: PRIMARY KEY((col1, col2), col10, col4))

You can perform query only by passing at least both col1 and col2, these are the 2 columns that define the partition key. The "general" rule to make query is you have to pass at least all partition key columns, then you can add optionally each clustering key in the order they're set.

so the valid queries are (excluding secondary indexes)

  • col1 and col2
  • col1 and col2 and col10
  • col1 and col2 and col10 and col 4

Invalid:

  • col1 and col2 and col4
  • anything that does not contain both col1 and col2

Hope this helps.

Run function from the command line

Use the python-c tool (pip install python-c) and then simply write:

$ python-c foo 'hello()'

or in case you have no function name clashes in your python files:

$ python-c 'hello()'

jQuery: read text file from file system

As long as the file does not need to be dynamically generated, e.g., a simple text or html file, you can test it locally WITHOUT a web server - just use a relative path.

HTML / CSS Popup div on text click

For the sake of completeness, what you are trying to create is a "modal window".

Numerous JS solutions allow you to create them with ease, take the time to find the one which best suits your needs.

I have used Tinybox 2 for small projects : http://sandbox.scriptiny.com/tinybox2/

How to delete row in gridview using rowdeleting event?

     protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        int index = GridView1.SelectedIndex;
        int id = Convert.ToInt32(GridView1.DataKeys[index].Value);
        SqlConnection con = new SqlConnection(str);
        SqlCommand com = new SqlCommand("spDelete", con);
        com.Parameters.AddWithValue("@PatientId", id);
        con.Open();
        com.ExecuteNonQuery();

Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index

'if' statement in jinja2 template

We need to remember that the {% endif %} comes after the {% else %}.

So this is an example:

{% if someTest %}
     <p> Something is True </p>
{% else %}
     <p> Something is False </p>
{% endif %}

Deleting an element from an array in PHP

Destroy a single element of an array

unset()

$array1 = array('A', 'B', 'C', 'D', 'E');
unset($array1[2]); // Delete known index(2) value from array
var_dump($array1);

The output will be:

array(4) {
  [0]=>
  string(1) "A"
  [1]=>
  string(1) "B"
  [3]=>
  string(1) "D"
  [4]=>
  string(1) "E"
}

If you need to re index the array:

$array1 = array_values($array1);
var_dump($array1);

Then the output will be:

array(4) {
  [0]=>
  string(1) "A"
  [1]=>
  string(1) "B"
  [2]=>
  string(1) "D"
  [3]=>
  string(1) "E"
}

Pop the element off the end of array - return the value of the removed element

mixed array_pop(array &$array)

$stack = array("orange", "banana", "apple", "raspberry");
$last_fruit = array_pop($stack);
print_r($stack);
print_r('Last Fruit:'.$last_fruit); // Last element of the array

The output will be

Array
(
    [0] => orange
    [1] => banana
    [2] => apple
)
Last Fruit: raspberry

Remove the first element (red) from an array, - return the value of the removed element

mixed array_shift ( array &$array )

$color = array("a" => "red", "b" => "green" , "c" => "blue");
$first_color = array_shift($color);
print_r ($color);
print_r ('First Color: '.$first_color);

The output will be:

Array
(
    [b] => green
    [c] => blue
)
First Color: red

Fastest way of finding differences between two files in unix?

You could also try to include md5-hash-sums or similar do determine whether there are any differences at all. Then, only compare files which have different hashes...

Appending a byte[] to the end of another byte[]

First you need to allocate an array of the combined length, then use arraycopy to fill it from both sources.

byte[] ciphertext = blah;
byte[] mac = blah;
byte[] out = new byte[ciphertext.length + mac.length];


System.arraycopy(ciphertext, 0, out, 0, ciphertext.length);
System.arraycopy(mac, 0, out, ciphertext.length, mac.length);

How to check if a symlink exists

You can check the existence of a symlink and that it is not broken with:

[ -L ${my_link} ] && [ -e ${my_link} ]

So, the complete solution is:

if [ -L ${my_link} ] ; then
   if [ -e ${my_link} ] ; then
      echo "Good link"
   else
      echo "Broken link"
   fi
elif [ -e ${my_link} ] ; then
   echo "Not a link"
else
   echo "Missing"
fi

-L tests whether there is a symlink, broken or not. By combining with -e you can test whether the link is valid (links to a directory or file), not just whether it exists.

Filter Extensions in HTML form upload

Another solution with a few lines

function checkFile(i){
  i = i.substr(i.length - 4, i.length).toLowerCase();
  i = i.replace('.','');
  switch(i){
    case 'jpg':
    case 'jpeg':
    case 'png':
    case 'gif':
      // do OK stuff
      break;
    default:
      // do error stuff
      break;
  }
}

Disable Auto Zoom in Input "Text" tag - Safari on iPhone

Amazing, there are dozens of answers here with javascript and viewports, and only one other mentions text-size-adjust which is what I believe is the best solution.

You can just set this to none.

Add the following CSS:

* {
 -webkit-text-size-adjust: none;
  text-size-adjust: none;
}

From Arraylist to Array

There are two styles to convert a collection to an array: either using a pre-sized array (like c.toArray(new String[c.size()])) or using an empty array (like c.toArray(new String[0])). In older Java versions using pre-sized array was recommended, as the reflection call which is necessary to create an array of proper size was quite slow. However since late updates of OpenJDK 6 this call was intrinsified, making the performance of the empty array version the same and sometimes even better, compared to the pre-sized version. Also passing pre-sized array is dangerous for a concurrent or synchronized collection as a data race is possible between the size and toArray call which may result in extra nulls at the end of the array, if the collection was concurrently shrunk during the operation. You can follow the uniform style: either using an empty array (which is recommended in modern Java) or using a pre-sized array (which might be faster in older Java versions or non-HotSpot based JVMs).

int to hex string

Use ToString("X4").

The 4 means that the string will be 4 digits long.

Reference: The Hexadecimal ("X") Format Specifier on MSDN.

how to convert milliseconds to date format in android?

You can construct java.util.Date on milliseconds. And then converted it to string with java.text.DateFormat.

Get name of current class?

You can access it by the class' private attributes:

cls_name = self.__class__.__name__

EDIT:

As said by Ned Batcheler, this wouldn't work in the class body, but it would in a method.

Convert NULL to empty string - Conversion failed when converting from a character string to uniqueidentifier

Select ID, IsNull(Cast(ParentID as varchar(max)),'') from Patients

This is needed because field ParentID is not varchar/nvarchar type. This will do the trick:

Select ID, IsNull(ParentID,'') from Patients

Is there a way to get the source code from an APK file?

Apktool for reverse engineering 3rd party, closed, binary Android apps.

It can decode resources to nearly original form and rebuild them after making some modifications.

It makes possible to debug smali code step by step. Also it makes working with an app easier because of project-like file structure and automation of some repetitive tasks like building apk, etc.

http://ibotpeaches.github.io/Apktool/

NuGet: 'X' already has a dependency defined for 'Y'

I faced this error on outdated version of Visual Studio 2010. Due to project configuration I was not able to update this version to newer. Therefore, update of NuGet advised above did not fix things for me.

Root reason for the error in this and similar situations is in dependencies of the package you try to install, which are not compatible with .NET version available in your project.

Universal solution is not obligatory update of Visual Studio or .NET but in installation of older NuGet versions of the same package compatible with your system.

It is not possible to tell for sure, which of earlier versions will work. In my case, this command installed the package without any NuGet updates.

Install-Package X -Version [compatible version number]

Wait on the Database Engine recovery handle failed. Check the SQL server error log for potential causes

Below worked for me:

When you come to Server Configuration Screen, Change the Account Name of Database Engine Service to NT AUTHORITY\NETWORK SERVICE and continue installation and it will successfully install all components without any error. - See more at: https://superpctricks.com/sql-install-error-database-engine-recovery-handle-failed/

What is the syntax for adding an element to a scala.collection.mutable.Map?

Create a mutable map without initial value:

scala> var d= collection.mutable.Map[Any, Any]()
d: scala.collection.mutable.Map[Any,Any] = Map()

Create a mutable map with initial values:

scala> var d= collection.mutable.Map[Any, Any]("a"->3,1->234,2->"test")
d: scala.collection.mutable.Map[Any,Any] = Map(2 -> test, a -> 3, 1 -> 234)

Update existing key-value:

scala> d("a")= "ABC"

Add new key-value:

scala> d(100)= "new element"

Check the updated map:

scala> d
res123: scala.collection.mutable.Map[Any,Any] = Map(2 -> test, 100 -> new element, a -> ABC, 1 -> 234)

Pandas read in table without headers

Previous answers were good and correct, but in my opinion, an extra names parameter will make it perfect, and it should be the recommended way, especially when the csv has no headers.

Solution

Use usecols and names parameters

df = pd.read_csv(file_path, usecols=[3,6], names=['colA', 'colB'])

Additional reading

or use header=None to explicitly tells people that the csv has no headers (anyway both lines are identical)

df = pd.read_csv(file_path, usecols=[3,6], names=['colA', 'colB'], header=None)

So that you can retrieve your data by

# with `names` parameter
df['colA']
df['colB'] 

instead of

# without `names` parameter
df[0]
df[1]

Explain

Based on read_csv, when names are passed explicitly, then header will be behaving like None instead of 0, so one can skip header=None when names exist.

Execution order of events when pressing PrimeFaces p:commandButton

I just love getting information like BalusC gives here - and he is kind enough to help SO many people with such GOOD information that I regard his words as gospel, but I was not able to use that order of events to solve this same kind of timing issue in my project. Since BalusC put a great general reference here that I even bookmarked, I thought I would donate my solution for some advanced timing issues in the same place since it does solve the original poster's timing issues as well. I hope this code helps someone:

        <p:pickList id="formPickList" 
                    value="#{mediaDetail.availableMedia}" 
                    converter="MediaPicklistConverter" 
                    widgetVar="formsPicklistWidget" 
                    var="mediaFiles" 
                    itemLabel="#{mediaFiles.mediaTitle}" 
                    itemValue="#{mediaFiles}" >
            <f:facet name="sourceCaption">Available Media</f:facet>
            <f:facet name="targetCaption">Chosen Media</f:facet>
        </p:pickList>

        <p:commandButton id="viewStream_btn" 
                         value="Stream chosen media" 
                         icon="fa fa-download"
                         ajax="true"
                         action="#{mediaDetail.prepareStreams}"                                              
                         update=":streamDialogPanel"
                         oncomplete="PF('streamingDialog').show()"
                         styleClass="ui-priority-primary"
                         style="margin-top:5px" >
            <p:ajax process="formPickList"  />
        </p:commandButton>

The dialog is at the top of the XHTML outside this form and it has a form of its own embedded in the dialog along with a datatable which holds additional commands for streaming the media that all needed to be primed and ready to go when the dialog is presented. You can use this same technique to do things like download customized documents that need to be prepared before they are streamed to the user's computer via fileDownload buttons in the dialog box as well.

As I said, this is a more complicated example, but it hits all the high points of your problem and mine. When the command button is clicked, the result is to first insure the backing bean is updated with the results of the pickList, then tell the backing bean to prepare streams for the user based on their selections in the pick list, then update the controls in the dynamic dialog with an update, then show the dialog box ready for the user to start streaming their content.

The trick to it was to use BalusC's order of events for the main commandButton and then to add the <p:ajax process="formPickList" /> bit to ensure it was executed first - because nothing happens correctly unless the pickList updated the backing bean first (something that was not happening for me before I added it). So, yea, that commandButton rocks because you can affect previous, pending and current components as well as the backing beans - but the timing to interrelate all of them is not easy to get a handle on sometimes.

Happy coding!

@UniqueConstraint and @Column(unique = true) in hibernate annotation

As said before, @Column(unique = true) is a shortcut to UniqueConstraint when it is only a single field.

From the example you gave, there is a huge difference between both.

@Column(unique = true)
@ManyToOne(optional = false, fetch = FetchType.EAGER)
private ProductSerialMask mask;

@Column(unique = true)
@ManyToOne(optional = false, fetch = FetchType.EAGER)
private Group group;

This code implies that both mask and group have to be unique, but separately. That means that if, for example, you have a record with a mask.id = 1 and tries to insert another record with mask.id = 1, you'll get an error, because that column should have unique values. The same aplies for group.

On the other hand,

@Table(
   name = "product_serial_group_mask", 
   uniqueConstraints = {@UniqueConstraint(columnNames = {"mask", "group"})}
)

Implies that the values of mask + group combined should be unique. That means you can have, for example, a record with mask.id = 1 and group.id = 1, and if you try to insert another record with mask.id = 1 and group.id = 2, it'll be inserted successfully, whereas in the first case it wouldn't.

If you'd like to have both mask and group to be unique separately and to that at class level, you'd have to write the code as following:

@Table(
        name = "product_serial_group_mask",
        uniqueConstraints = {
                @UniqueConstraint(columnNames = "mask"),
                @UniqueConstraint(columnNames = "group")
        }
)

This has the same effect as the first code block.

How to append one DataTable to another DataTable

use loop

  for (int i = 0; i < dt1.Rows.Count; i++)
        {      
           dt2.Rows.Add(dt1.Rows[i][0], dt1.Rows[i][1], ...);//you have to insert all Columns...
        }

How to write URLs in Latex?

Here is all the information you need in order to format clickable hyperlinks in LaTeX:

http://en.wikibooks.org/wiki/LaTeX/Hyperlinks

Essentially, you use the hyperref package and use the \url or \href tag depending on what you're trying to achieve.

Factorial in numpy and scipy

    from numpy import prod

    def factorial(n):
        print prod(range(1,n+1))

or with mul from operator:

    from operator import mul

    def factorial(n):
        print reduce(mul,range(1,n+1))

or completely without help:

    def factorial(n):
        print reduce((lambda x,y: x*y),range(1,n+1))

Source file not compiled Dev C++

You can always try doing it manually from the command prompt. Navigate to the path of the file and type:

gcc filename.c -o filename

What is the difference between match_parent and fill_parent?

FILL_PARENT is deprecated from the API level 8 and higher and it is renamed for the upper versions as MATCH_PARENT

Both are same FILL_PARENT and MATCH_PARENT,FILL_PARENT was used in the lower version less than API level 8 and MATCH_PATENT are used in higher API level greater than 8.

FILL_PARENT (renamed MATCH_PARENT in API Level 8 and higher), which means that the view wants to be as big as its parent (minus padding)

fill_parent: The view should be as big as its parent (minus padding). This constant is deprecated starting from API Level 8 and is replaced by match_parent.

For more details please visit this page

make sounds (beep) with c++

std::cout << '\7';

How to shut down the computer from C#

I had trouble trying to use the WMI method accepted above because i always got privilige not held exceptions despite running the program as an administrator.

The solution was for the process to request the privilege for itself. I found the answer at http://www.dotnet247.com/247reference/msgs/58/292150.aspx written by a guy called Richard Hill.

I've pasted my basic use of his solution below in case that link gets old.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Management;
using System.Runtime.InteropServices;
using System.Security;
using System.Diagnostics;

namespace PowerControl
{
    public class PowerControl_Main
    {


        public void Shutdown()
        {
            ManagementBaseObject mboShutdown = null;
            ManagementClass mcWin32 = new ManagementClass("Win32_OperatingSystem");
            mcWin32.Get();

            if (!TokenAdjuster.EnablePrivilege("SeShutdownPrivilege", true))
            {
                Console.WriteLine("Could not enable SeShutdownPrivilege");
            }
            else
            {
                Console.WriteLine("Enabled SeShutdownPrivilege");
            }

            // You can't shutdown without security privileges
            mcWin32.Scope.Options.EnablePrivileges = true;
            ManagementBaseObject mboShutdownParams = mcWin32.GetMethodParameters("Win32Shutdown");

            // Flag 1 means we want to shut down the system
            mboShutdownParams["Flags"] = "1";
            mboShutdownParams["Reserved"] = "0";

            foreach (ManagementObject manObj in mcWin32.GetInstances())
            {
                try
                {
                    mboShutdown = manObj.InvokeMethod("Win32Shutdown",
                                                   mboShutdownParams, null);
                }
                catch (ManagementException mex)
                {
                    Console.WriteLine(mex.ToString());
                    Console.ReadKey();
                }
            }
        }


    }


    public sealed class TokenAdjuster
    {
        // PInvoke stuff required to set/enable security privileges
        [DllImport("advapi32", SetLastError = true),
        SuppressUnmanagedCodeSecurityAttribute]
        static extern int OpenProcessToken(
        System.IntPtr ProcessHandle, // handle to process
        int DesiredAccess, // desired access to process
        ref IntPtr TokenHandle // handle to open access token
        );

        [DllImport("kernel32", SetLastError = true),
        SuppressUnmanagedCodeSecurityAttribute]
        static extern bool CloseHandle(IntPtr handle);

        [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        static extern int AdjustTokenPrivileges(
        IntPtr TokenHandle,
        int DisableAllPrivileges,
        IntPtr NewState,
        int BufferLength,
        IntPtr PreviousState,
        ref int ReturnLength);

        [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        static extern bool LookupPrivilegeValue(
        string lpSystemName,
        string lpName,
        ref LUID lpLuid);

        [StructLayout(LayoutKind.Sequential)]
        internal struct LUID
        {
            internal int LowPart;
            internal int HighPart;
        }

        [StructLayout(LayoutKind.Sequential)]
        struct LUID_AND_ATTRIBUTES
        {
            LUID Luid;
            int Attributes;
        }

        [StructLayout(LayoutKind.Sequential)]
        struct _PRIVILEGE_SET
        {
            int PrivilegeCount;
            int Control;
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)] // ANYSIZE_ARRAY = 1
            LUID_AND_ATTRIBUTES[] Privileges;
        }

        [StructLayout(LayoutKind.Sequential)]
        internal struct TOKEN_PRIVILEGES
        {
            internal int PrivilegeCount;
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)]
            internal int[] Privileges;
        }
        const int SE_PRIVILEGE_ENABLED = 0x00000002;
        const int TOKEN_ADJUST_PRIVILEGES = 0X00000020;
        const int TOKEN_QUERY = 0X00000008;
        const int TOKEN_ALL_ACCESS = 0X001f01ff;
        const int PROCESS_QUERY_INFORMATION = 0X00000400;

        public static bool EnablePrivilege(string lpszPrivilege, bool
        bEnablePrivilege)
        {
            bool retval = false;
            int ltkpOld = 0;
            IntPtr hToken = IntPtr.Zero;
            TOKEN_PRIVILEGES tkp = new TOKEN_PRIVILEGES();
            tkp.Privileges = new int[3];
            TOKEN_PRIVILEGES tkpOld = new TOKEN_PRIVILEGES();
            tkpOld.Privileges = new int[3];
            LUID tLUID = new LUID();
            tkp.PrivilegeCount = 1;
            if (bEnablePrivilege)
                tkp.Privileges[2] = SE_PRIVILEGE_ENABLED;
            else
                tkp.Privileges[2] = 0;
            if (LookupPrivilegeValue(null, lpszPrivilege, ref tLUID))
            {
                Process proc = Process.GetCurrentProcess();
                if (proc.Handle != IntPtr.Zero)
                {
                    if (OpenProcessToken(proc.Handle, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY,
                    ref hToken) != 0)
                    {
                        tkp.PrivilegeCount = 1;
                        tkp.Privileges[2] = SE_PRIVILEGE_ENABLED;
                        tkp.Privileges[1] = tLUID.HighPart;
                        tkp.Privileges[0] = tLUID.LowPart;
                        const int bufLength = 256;
                        IntPtr tu = Marshal.AllocHGlobal(bufLength);
                        Marshal.StructureToPtr(tkp, tu, true);
                        if (AdjustTokenPrivileges(hToken, 0, tu, bufLength, IntPtr.Zero, ref ltkpOld) != 0)
                        {
                            // successful AdjustTokenPrivileges doesn't mean privilege could be changed
                            if (Marshal.GetLastWin32Error() == 0)
                            {
                                retval = true; // Token changed
                            }
                        }
                        TOKEN_PRIVILEGES tokp = (TOKEN_PRIVILEGES)Marshal.PtrToStructure(tu,
                        typeof(TOKEN_PRIVILEGES));
                        Marshal.FreeHGlobal(tu);
                    }
                }
            }
            if (hToken != IntPtr.Zero)
            {
                CloseHandle(hToken);
            }
            return retval;
        }

    }
}

Change visibility of ASP.NET label with JavaScript

You need to be wary of XSS when doing stuff like this:

document.getElementById('<%= Label1.ClientID %>').style.display

The chances are that no-one will be able to tamper with the ClientID of Label1 in this instance, but just to be on the safe side you might want pass it's value through one of the AntiXss library's methods:

document.getElementById('<%= AntiXss.JavaScriptEncode(Label1.ClientID) %>').style.display

linq query to return distinct field values from a list of objects

I wanted to bind a particular data to dropdown and it should be distinct. I did the following:

List<ClassDetails> classDetails;
List<string> classDetailsData = classDetails.Select(dt => dt.Data).Distinct.ToList();
ddlData.DataSource = classDetailsData;
ddlData.Databind();

See if it helps

Convert UTC to local time in Rails 3

Time#localtime will give you the time in the current time zone of the machine running the code:

> moment = Time.now.utc
  => 2011-03-14 15:15:58 UTC 
> moment.localtime
  => 2011-03-14 08:15:58 -0700 

Update: If you want to conver to specific time zones rather than your own timezone, you're on the right track. However, instead of worrying about EST vs EDT, just pass in the general Eastern Time zone -- it will know based on the day whether it is EDT or EST:

> Time.now.utc.in_time_zone("Eastern Time (US & Canada)")
  => Mon, 14 Mar 2011 11:21:05 EDT -04:00 
> (Time.now.utc + 10.months).in_time_zone("Eastern Time (US & Canada)")
  => Sat, 14 Jan 2012 10:21:18 EST -05:00 

PHP error: "The zip extension and unzip command are both missing, skipping."

Not to belabor the point, but if you are working in a Dockerfile, you would solve this particular issue with Composer by installing the unzip utility. Below is an example using the official PHP image to install unzip and the zip PHP extension for good measure.

FROM php:7.4-apache

# Install Composer
COPY --from=composer /usr/bin/composer /usr/bin/composer

# Install unzip utility and libs needed by zip PHP extension 
RUN apt-get update && apt-get install -y \
    zlib1g-dev \
    libzip-dev \
    unzip
RUN docker-php-ext-install zip

This is a helpful GitHub issue where the above is lovingly lifted from.

Search a text file and print related lines in Python?

searchfile = open("file.txt", "r")
for line in searchfile:
    if "searchphrase" in line: print line
searchfile.close()

To print out multiple lines (in a simple way)

f = open("file.txt", "r")
searchlines = f.readlines()
f.close()
for i, line in enumerate(searchlines):
    if "searchphrase" in line: 
        for l in searchlines[i:i+3]: print l,
        print

The comma in print l, prevents extra spaces from appearing in the output; the trailing print statement demarcates results from different lines.

Or better yet (stealing back from Mark Ransom):

with open("file.txt", "r") as f:
    searchlines = f.readlines()
for i, line in enumerate(searchlines):
    if "searchphrase" in line: 
        for l in searchlines[i:i+3]: print l,
        print

Hibernate Criteria Join with 3 Tables

The fetch mode only says that the association must be fetched. If you want to add restrictions on an associated entity, you must create an alias, or a subcriteria. I generally prefer using aliases, but YMMV:

Criteria c = session.createCriteria(Dokument.class, "dokument");
c.createAlias("dokument.role", "role"); // inner join by default
c.createAlias("role.contact", "contact");
c.add(Restrictions.eq("contact.lastName", "Test"));
return c.list();

This is of course well explained in the Hibernate reference manual, and the javadoc for Criteria even has examples. Read the documentation: it has plenty of useful information.

Merge / convert multiple PDF files into one PDF

You can use sejda-console, free and open source. Unzip it and run sejda-console merge -f file1.pdf file2.pdf -o merged.pdf

It preserves bookmarks, link annotations, acroforms etc.. it actually has quite a lot of options you can play with, just run sejda-console merge -h to see them all.

How to solve "Could not establish trust relationship for the SSL/TLS secure channel with authority"

Please do following steps:

  1. Open service link in IE.

  2. Click on the certificate error mention in address bar and click on View certificates.

  3. Check issued to: name.

  4. Take the issued name and replace localhost mention in service and client endpoint base address name with A fully qualified domain name (FQDN).

For Example: https://localhost:203/SampleService.svc To https://INL-126166-.groupinfra.com:203/SampleService.svc

Get file version in PowerShell

Just another way to do it is to use the built-in file access technique:

(get-item .\filename.exe).VersionInfo | FL

You can also get any particular property off the VersionInfo, thus:

(get-item .\filename.exe).VersionInfo.FileVersion

This is quite close to the dir technique.

Convert int to a bit array in .NET

Use Convert.ToString (value, 2)

so in your case

string binValue = Convert.ToString (3, 2);

Setting "checked" for a checkbox with jQuery

$(".myCheckBox").prop("checked","checked");

What does "commercial use" exactly mean?

"Commercial use" in cases like this is actually just a shorthand to indicate that the product is dual-licensed under both an open source and a traditional paid-for commercial license.

Any "true" open source license will not discriminate against commercial use. (See clause 6 of the Open Source Definition.) However, open source licenses like the GPL contain clauses that are incompatible with most companies' approach to commercial software (since the GPL requires that you make your source code available if you incorporate GPL'ed code into your product).

Duel-licensing is a way to accommodate this and also provides a revenue stream for the company providing the software. For users that don't mind the restrictions of the GPL and don't need support, the product is available under an open source license. For users for whom the GPL's restrictions would be incompatible with their business model, and for users that do need support, a commercial license is available.

You gave the specific example of the Screwturn wiki, which is dual-licensed under the GPL and a commercial license. Under the terms of the GPL (i.e., without getting a "commercial" license), you can do the following:

  • Use it internally as much as you want (see here)
  • Run it on your internal servers for external users / clients / customers, or run it on your internal servers for paying clients if you're an ISP / hosting provider. (If Screwturn were licensed under the AGPL instead of the GPL, that might restrict this.)
  • Distribute it to others, either free of charge or for a payment that covers the shipping, as long as you're willing to also distribute the source code
  • Incorporate it into your product, as long as you're willing to also distribute the source code, and as long as either (a) it remains a separate program that you merely aggregate with your product or (b) you release the source code to your product under an open source license compatible with the GPL

In other words, there's a lot that you can do without getting a commercial license. This is especially true for web-based software, since people can use web-based software without it being distributed to them. Screwturn's web site even acknowledges this: they state that the commercial license is for "either integrating it in a commercial application, or using it in an enterprise environment where free software is not allowed," not for any use related to commerce.

All of the preceding is merely my understanding and is not intended to be legal advice. Consult your lawyer to be certain.

Get access to parent control from user control - C#

Not Ideal, but try this...

Change the usercontrol to Component class (In the code editor), build the solution and remove all the code with errors (Related to usercontrols but not available in components so the debugger complains about it)

Change the usercontrol back to usercontrol class...

Now it recognises the name and parent property but shows the component as non-visual as it is no longer designable.

How to approach a "Got minus one from a read call" error when connecting to an Amazon RDS Oracle instance

We faced the same issue and fixed it. Below is the reason and solution.

Problem

When the connection pool mechanism is used, the application server (in our case, it is JBOSS) creates connections according to the min-connection parameter. If you have 10 applications running, and each has a min-connection of 10, then a total of 100 sessions will be created in the database. Also, in every database, there is a max-session parameter, if your total number of connections crosses that border, then you will get Got minus one from a read call.

FYI: Use the query below to see your total number of sessions:

SELECT username, count(username) FROM v$session 
WHERE username IS NOT NULL group by username

Solution: With the help of our DBA, we increased that max-session parameter, so that all our application min-connection can accommodate.

jquery datatables hide column

$(document).ready(function() {
$('#example').DataTable( {
    "columnDefs": [
        {
            "targets": [ 2 ],
            "visible": false,
            "searchable": false
        },
        {
            "targets": [ 3 ],
            "visible": false
        }
    ]
});});

How to customize a Spinner in Android

This worked for me :

ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),R.layout.simple_spinner_item,areas);
            Spinner areasSpinner = (Spinner) view.findViewById(R.id.area_spinner);
            areasSpinner.setAdapter(adapter);

and in my layout folder I created simple_spinner_item:

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/text1"
android:layout_width="match_parent"
// add custom fields here 
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceListItemSmall"
android:gravity="center_vertical"
android:paddingStart="?android:attr/listPreferredItemPaddingStart"
android:paddingEnd="?android:attr/listPreferredItemPaddingEnd"
android:minHeight="?android:attr/listPreferredItemHeightSmall"
android:paddingLeft="?android:attr/listPreferredItemPaddingLeft"
android:paddingRight="?android:attr/listPreferredItemPaddingRight" />

Using Javamail to connect to Gmail smtp server ignores specified port and tries to use 25

In Java you would do something similar to:

Transport transport = session.getTransport("smtps");
transport.connect (smtp_host, smtp_port, smtp_username, smtp_password);
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();    

Note 'smtpS' protocol. Also socketFactory properties is no longer necessary in modern JVMs but you might need to set 'mail.smtps.auth' and 'mail.smtps.starttls.enable' to 'true' for Gmail. 'mail.smtps.debug' could be helpful too.

The intel x86 emulator accelerator (HAXM installer) revision 6.0.5 is showing not compatible with windows

You likely have Hyper-V enabled. The manual installer provides this detailed notice when it refuses to install on a Windows with it on.

This computer does not support Intel Virtualization Technology (VT-x) or it is being exclusively used by Hyper-V. HAXM cannot be installed. Please ensure Hyper-V is disabled in Windows Features, or refer to the Intel HAXM documentation for more information.

Do Java arrays have a maximum size?

Haven't seen the right answer, even though it's very easy to test.

In a recent HotSpot VM, the correct answer is Integer.MAX_VALUE - 5. Once you go beyond that:

public class Foo {
  public static void main(String[] args) {
    Object[] array = new Object[Integer.MAX_VALUE - 4];
  }
}

You get:

Exception in thread "main" java.lang.OutOfMemoryError:
  Requested array size exceeds VM limit

How to use GROUP BY to concatenate strings in MySQL?

SELECT id, GROUP_CONCAT( string SEPARATOR ' ') FROM table GROUP BY id

More details here.

From the link above, GROUP_CONCAT: This function returns a string result with the concatenated non-NULL values from a group. It returns NULL if there are no non-NULL values.

How to calculate the number of occurrence of a given character in each row of a column of strings?

You could just use string division

require(roperators)
my_strings <- c('apple', banana', 'pear', 'melon')
my_strings %s/% 'a'

Which will give you 1, 3, 1, 0. You can also use string division with regular expressions and whole words.

What is the best way to get all the divisors of a number?

I like Greg solution, but I wish it was more python like. I feel it would be faster and more readable; so after some time of coding I came out with this.

The first two functions are needed to make the cartesian product of lists. And can be reused whnever this problem arises. By the way, I had to program this myself, if anyone knows of a standard solution for this problem, please feel free to contact me.

"Factorgenerator" now returns a dictionary. And then the dictionary is fed into "divisors", who uses it to generate first a list of lists, where each list is the list of the factors of the form p^n with p prime. Then we make the cartesian product of those lists, and we finally use Greg' solution to generate the divisor. We sort them, and return them.

I tested it and it seem to be a bit faster than the previous version. I tested it as part of a bigger program, so I can't really say how much is it faster though.

Pietro Speroni (pietrosperoni dot it)

from math import sqrt


##############################################################
### cartesian product of lists ##################################
##############################################################

def appendEs2Sequences(sequences,es):
    result=[]
    if not sequences:
        for e in es:
            result.append([e])
    else:
        for e in es:
            result+=[seq+[e] for seq in sequences]
    return result


def cartesianproduct(lists):
    """
    given a list of lists,
    returns all the possible combinations taking one element from each list
    The list does not have to be of equal length
    """
    return reduce(appendEs2Sequences,lists,[])

##############################################################
### prime factors of a natural ##################################
##############################################################

def primefactors(n):
    '''lists prime factors, from greatest to smallest'''  
    i = 2
    while i<=sqrt(n):
        if n%i==0:
            l = primefactors(n/i)
            l.append(i)
            return l
        i+=1
    return [n]      # n is prime


##############################################################
### factorization of a natural ##################################
##############################################################

def factorGenerator(n):
    p = primefactors(n)
    factors={}
    for p1 in p:
        try:
            factors[p1]+=1
        except KeyError:
            factors[p1]=1
    return factors

def divisors(n):
    factors = factorGenerator(n)
    divisors=[]
    listexponents=[map(lambda x:k**x,range(0,factors[k]+1)) for k in factors.keys()]
    listfactors=cartesianproduct(listexponents)
    for f in listfactors:
        divisors.append(reduce(lambda x, y: x*y, f, 1))
    divisors.sort()
    return divisors



print divisors(60668796879)

P.S. it is the first time I am posting to stackoverflow. I am looking forward for any feedback.

C++ String Declaring

In C++ you can declare a string like this:

#include <string>

using namespace std;

int main()
{
    string str1("argue2000"); //define a string and Initialize str1 with "argue2000"    
    string str2 = "argue2000"; // define a string and assign str2 with "argue2000"
    string str3;  //just declare a string, it has no value
    return 1;
}

No tests found with test runner 'JUnit 4'

I found out that Eclipse seems to only perform JUnit 3 style tests if your test-class extends from TestCase. If you remove the inheritance, the annotations worked for me.

Beware that you need to statically import all the required assert* methods like import static org.junit.Assert.*.

How do I find a stored procedure containing <text>?

How to Find a Stored Procedure Containing Text or String

Many time we need to find the text or string in the stored procedure. Here is the query to find the containing text.

SELECT OBJECT_NAME(id) 
FROM SYSCOMMENTS 
WHERE [text] LIKE '%Text%' 
AND OBJECTPROPERTY(id, 'IsProcedure') = 1 
GROUP BY OBJECT_NAME(id)

For more information please check the given URL given below.

http://www.freshcodehub.com/Article/34/how-to-find-a-stored-procedure-containing-text-or-string

android - listview get item view by position

Use this :

public View getViewByPosition(int pos, ListView listView) {
    final int firstListItemPosition = listView.getFirstVisiblePosition();
    final int lastListItemPosition = firstListItemPosition + listView.getChildCount() - 1;

    if (pos < firstListItemPosition || pos > lastListItemPosition ) {
        return listView.getAdapter().getView(pos, null, listView);
    } else {
        final int childIndex = pos - firstListItemPosition;
        return listView.getChildAt(childIndex);
    }
}

Reshaping data.frame from wide to long format

Using reshape package:

#data
x <- read.table(textConnection(
"Code Country        1950    1951    1952    1953    1954
AFG  Afghanistan    20,249  21,352  22,532  23,557  24,555
ALB  Albania        8,097   8,986   10,058  11,123  12,246"), header=TRUE)

library(reshape)

x2 <- melt(x, id = c("Code", "Country"), variable_name = "Year")
x2[,"Year"] <- as.numeric(gsub("X", "" , x2[,"Year"]))

installing cPickle with python 3.5

cPickle comes with the standard library… in python 2.x. You are on python 3.x, so if you want cPickle, you can do this:

>>> import _pickle as cPickle

However, in 3.x, it's easier just to use pickle.

No need to install anything. If something requires cPickle in python 3.x, then that's probably a bug.

How to display an unordered list in two columns?

This is the simplest way to do it. CSS only.

  1. add width to the ul element.
  2. add display:inline-block and width of the new column (should be less than half of the ul width).
_x000D_
_x000D_
ul.list {_x000D_
  width: 300px;  _x000D_
}_x000D_
_x000D_
ul.list li{_x000D_
  display:inline-block;_x000D_
  width: 100px;_x000D_
}
_x000D_
<ul class="list">_x000D_
    <li>A</li>_x000D_
    <li>B</li>_x000D_
    <li>C</li>_x000D_
    <li>D</li>_x000D_
    <li>E</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

How do I set the timeout for a JAX-WS webservice client?

ProxyWs proxy = (ProxyWs) factory.create();
Client client = ClientProxy.getClient(proxy);
HTTPConduit http = (HTTPConduit) client.getConduit();
HTTPClientPolicy httpClientPolicy = new HTTPClientPolicy();
httpClientPolicy.setConnectionTimeout(0);
httpClientPolicy.setReceiveTimeout(0);
http.setClient(httpClientPolicy);

This worked for me.

The FastCGI process exited unexpectedly

For user using PHP 5.6.x follow this link and install the x86 version.

What is the purpose of the single underscore "_" variable in Python?

It's just a variable name, and it's conventional in python to use _ for throwaway variables. It just indicates that the loop variable isn't actually used.

Using If/Else on a data frame

Use ifelse:

frame$twohouses <- ifelse(frame$data>=2, 2, 1)
frame
   data twohouses
1     0         1
2     1         1
3     2         2
4     3         2
5     4         2
...
16    0         1
17    2         2
18    1         1
19    2         2
20    0         1
21    4         2

The difference between if and ifelse:

  • if is a control flow statement, taking a single logical value as an argument
  • ifelse is a vectorised function, taking vectors as all its arguments.

The help page for if, accessible via ?"if" will also point you to ?ifelse

How to hide the soft keyboard from inside a fragment?

In Kotlin:

(activity?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager).hideSoftInputFromWindow(view?.windowToken,0)

List(of String) or Array or ArrayList

You can use IList(Of String) in the function :

Private Function getWriteBits() As IList(Of String)


Dim temp1 As String
Dim temp2 As Boolean
Dim temp3 As Boolean


'Pallet Destination Unique
Dim temp4 As Boolean
Dim temp5 As Boolean
Dim temp6 As Boolean

Dim lstWriteBits As Ilist = {temp1, temp2, temp3, temp4, temp5, temp6}

Return lstWriteBits
End Function

use list1.AddRange(list2) to add lists

Hope it helps.

How to map a composite key with JPA and Hibernate?

Let's take a simple example. Let's say two tables named test and customer are there described as:

create table test(
  test_id int(11) not null auto_increment,
  primary key(test_id));

create table customer(
  customer_id int(11) not null auto_increment,
  name varchar(50) not null,
  primary key(customer_id));

One more table is there which keeps the track of tests and customer:

create table tests_purchased(
  customer_id int(11) not null,
  test_id int(11) not null,
  created_date datetime not null,
  primary key(customer_id, test_id));

We can see that in the table tests_purchased the primary key is a composite key, so we will use the <composite-id ...>...</composite-id> tag in the hbm.xml mapping file. So the PurchasedTest.hbm.xml will look like:

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
  "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
  "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
  <class name="entities.PurchasedTest" table="tests_purchased">

    <composite-id name="purchasedTestId">
      <key-property name="testId" column="TEST_ID" />
      <key-property name="customerId" column="CUSTOMER_ID" />
    </composite-id>

    <property name="purchaseDate" type="timestamp">
      <column name="created_date" />
    </property>

  </class>
</hibernate-mapping>

But it doesn't end here. In Hibernate we use session.load (entityClass, id_type_object) to find and load the entity using primary key. In case of composite keys, the ID object should be a separate ID class (in above case a PurchasedTestId class) which just declares the primary key attributes like below:

import java.io.Serializable;

public class PurchasedTestId implements Serializable {
  private Long testId;
  private Long customerId;

  // an easy initializing constructor
  public PurchasedTestId(Long testId, Long customerId) {
    this.testId = testId;
    this.customerId = customerId;
  }

  public Long getTestId() {
    return testId;
  }

  public void setTestId(Long testId) {
    this.testId = testId;
  }

  public Long getCustomerId() {
    return customerId;
  }

  public void setCustomerId(Long customerId) {
    this.customerId = customerId;
  }

  @Override
  public boolean equals(Object arg0) {
    if(arg0 == null) return false;
    if(!(arg0 instanceof PurchasedTestId)) return false;
    PurchasedTestId arg1 = (PurchasedTestId) arg0;
    return (this.testId.longValue() == arg1.getTestId().longValue()) &&
           (this.customerId.longValue() == arg1.getCustomerId().longValue());
  }

  @Override
  public int hashCode() {
    int hsCode;
    hsCode = testId.hashCode();
    hsCode = 19 * hsCode+ customerId.hashCode();
    return hsCode;
  }
}

Important point is that we also implement the two functions hashCode() and equals() as Hibernate relies on them.