Programs & Examples On #Carrington

jQuery Uncaught TypeError: Cannot read property 'fn' of undefined (anonymous function)

I agree with MarsPeople regarding loading libraries in the wrong order. My example is from working with owl.carousel.

I got the same error when importing jquery after owl.carousel:

<script src="owl.carousel.js"></script>
<script src="jquery-3.1.1.min.js"></script>

and fixed it by importing jquery before owl.carousel:

<script src="jquery-3.1.1.min.js"></script>
<script src="owl.carousel.js"></script>

What is the opposite of evt.preventDefault();

I would suggest the following pattern:

document.getElementById("foo").onsubmit = function(e) {
    if (document.getElementById("test").value == "test") {
        return true;
    } else {
        e.preventDefault();
    }
}

<form id="foo">
    <input id="test"/>
    <input type="submit"/>
</form>

...unless I'm missing something.

http://jsfiddle.net/DdvcX/

Set left margin for a paragraph in html

<p style="margin-left:5em;">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut lacinia vestibulum quam sit amet aliquet. Phasellus tempor nisi eget tellus venenatis tempus. Aliquam dapibus porttitor convallis. Praesent pretium luctus orci, quis ullamcorper lacus lacinia a. Integer eget molestie purus. Vestibulum porta mollis tempus. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. </p>

That'll do it, there's a few improvements obviously, but that's the basics. And I use 'em' as the measurement, you may want to use other units, like 'px'.

EDIT: What they're describing above is a way of associating groups of styles, or classes, with elements on a web page. You can implement that in a few ways, here's one which may suit you:

In your HTML page, containing the <p> tagged content from your DB add in a new 'style' node and wrap the styles you want to declare in a class like so:

<head>
  <style type="text/css">
    p { margin-left:5em; /* Or another measurement unit, like px */ }
  </style>
</head>
<body>
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut lacinia vestibulum quam sit amet aliquet.</p>
</body>

So above, all <p> elements in your document will have that style rule applied. Perhaps you are pumping your paragraph content into a container of some sort? Try this:

<head>
  <style type="text/css">
    .container p { margin-left:5em; /* Or another measurement unit, like px */ }
  </style>
</head>
<body>
  <div class="container">
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut lacinia vestibulum quam sit amet aliquet.</p>
  </div>
  <p>Vestibulum porta mollis tempus. Class aptent taciti sociosqu ad litora torquent per conubia nostra.</p>
</body>

In the example above, only the <p> element inside the div, whose class name is 'container', will have the styles applied - and not the <p> element outside the container.

In addition to the above, you can collect your styles together and remove the style element from the <head> tag, replacing it with a <link> tag, which points to an external CSS file. This external file is where you'd now put your <p> tag styles. This concept is known as 'seperating content from style' and is considered good practice, and is also an extendible way to create styles, and can help with low maintenance.

Determine .NET Framework version for dll

In PowerShell you can use the following to get the target runtime:

$path = "C:\Some.dll"
[Reflection.Assembly]::ReflectionOnlyLoadFrom($path).ImageRuntimeVersion

I adapted this to PowerShell from Ben Griswold's answer.

If you want to know the target framework version specified in Visual Studio, use:

$path = "C:\Some.dll"
[Reflection.Assembly]::ReflectionOnlyLoadFrom($path).CustomAttributes |
Where-Object {$_.AttributeType.Name -eq "TargetFrameworkAttribute" } | 
Select-Object -ExpandProperty ConstructorArguments | 
Select-Object -ExpandProperty value

You should get something like

.NETFramework,Version=v4.5.2

What does "javascript:void(0)" mean?

void is an operator that is used to return a undefined value so the browser will not be able to load a new page.

Web browsers will try and take whatever is used as a URL and load it unless it is a JavaScript function that returns null. For example, if we click a link like this:

<a href="javascript: alert('Hello World')">Click Me</a>

then an alert message will show up without loading a new page, and that is because alert is a function that returns a null value. This means that when the browser attempts to load a new page it sees null and has nothing to load.

An important thing to note about the void operator is that it requires a value and cannot be used by itself. We should use it like this:

<a href="javascript: void(0)">I am a useless link</a>

How to override a JavaScript function

You can do it like this:

alert(parseFloat("1.1531531414")); // alerts the float
parseFloat = function(input) { return 1; };
alert(parseFloat("1.1531531414")); // alerts '1'

Check out a working example here: http://jsfiddle.net/LtjzW/1/

To show a new Form on click of a button in C#

Try this:

private void Button1_Click(Object sender, EventArgs e ) 
{
   var myForm = new Form1();
   myForm.Show();
}

In Java, how do I convert a byte array to a string of hex digits while keeping leading zeros?

I've been looking for the same thing ... some good ideas here, but I ran a few micro benchmarks. I found the following to be the fastest (modified from Ayman's above and about 2x as fast, and about 50% faster than Steve's just above this one):

public static String hash(String text, String algorithm)
        throws NoSuchAlgorithmException {
    byte[] hash = MessageDigest.getInstance(algorithm).digest(text.getBytes());
    return new BigInteger(1, hash).toString(16);
}

Edit: Oops - missed that this is essentially the same as kgiannakakis's and so may strip off a leading 0. Still, modifying this to the following, it's still the fastest:

public static String hash(String text, String algorithm)
        throws NoSuchAlgorithmException {
    byte[] hash = MessageDigest.getInstance(algorithm).digest(text.getBytes());
    BigInteger bi = new BigInteger(1, hash);
    String result = bi.toString(16);
    if (result.length() % 2 != 0) {
        return "0" + result;
    }
    return result;
}

Listing available com ports with Python

one line solution with pySerial package.

python -m serial.tools.list_ports

Angular IE Caching issue for $http

you may add an interceptor .

myModule.config(['$httpProvider', function($httpProvider) {
 $httpProvider.interceptors.push('noCacheInterceptor');
}]).factory('noCacheInterceptor', function () {
            return {
                request: function (config) {
                    console.log(config.method);
                    console.log(config.url);
                    if(config.method=='GET'){
                        var separator = config.url.indexOf('?') === -1 ? '?' : '&';
                        config.url = config.url+separator+'noCache=' + new Date().getTime();
                    }
                    console.log(config.method);
                    console.log(config.url);
                    return config;
               }
           };
    });

you should remove console.log lines after verifying.

How to create a fixed-size array of objects

For now, semantically closest one would be a tuple with fixed number of elements.

typealias buffer = (
    SKSpriteNode, SKSpriteNode, SKSpriteNode, SKSpriteNode,
    SKSpriteNode, SKSpriteNode, SKSpriteNode, SKSpriteNode,
    SKSpriteNode, SKSpriteNode, SKSpriteNode, SKSpriteNode,
    SKSpriteNode, SKSpriteNode, SKSpriteNode, SKSpriteNode,
    SKSpriteNode, SKSpriteNode, SKSpriteNode, SKSpriteNode,
    SKSpriteNode, SKSpriteNode, SKSpriteNode, SKSpriteNode,
    SKSpriteNode, SKSpriteNode, SKSpriteNode, SKSpriteNode,
    SKSpriteNode, SKSpriteNode, SKSpriteNode, SKSpriteNode,
    SKSpriteNode, SKSpriteNode, SKSpriteNode, SKSpriteNode,
    SKSpriteNode, SKSpriteNode, SKSpriteNode, SKSpriteNode,
    SKSpriteNode, SKSpriteNode, SKSpriteNode, SKSpriteNode,
    SKSpriteNode, SKSpriteNode, SKSpriteNode, SKSpriteNode,
    SKSpriteNode, SKSpriteNode, SKSpriteNode, SKSpriteNode,
    SKSpriteNode, SKSpriteNode, SKSpriteNode, SKSpriteNode,
    SKSpriteNode, SKSpriteNode, SKSpriteNode, SKSpriteNode,
    SKSpriteNode, SKSpriteNode, SKSpriteNode, SKSpriteNode)

But this is (1) very uncomfortable to use and (2) memory layout is undefined. (at least unknown to me)

Recommended way to get hostname in Java

The most portable way to get the hostname of the current computer in Java is as follows:

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

public class getHostName {

    public static void main(String[] args) throws UnknownHostException {
        InetAddress iAddress = InetAddress.getLocalHost();
        String hostName = iAddress.getHostName();
        //To get  the Canonical host name
        String canonicalHostName = iAddress.getCanonicalHostName();

        System.out.println("HostName:" + hostName);
        System.out.println("Canonical Host Name:" + canonicalHostName);
    }
}

jQuery DataTable overflow and text-wrapping issues

You can just use render and wrap your own div or span around it. TD`s are hard to style when it comes to max-width, max-height, etc. Div and span is easy..

See: https://datatables.net/examples/advanced_init/column_render.html

I think a nicer solution then working with CSS hacks which are not supported cross browser.

R - Markdown avoiding package loading messages

My best solution on R Markdown was to create a code chunk only to load libraries and exclude everything in the chunk.

{r results='asis', echo=FALSE, include=FALSE,}
knitr::opts_chunk$set(echo = TRUE, warning=FALSE)
#formating tables
library(xtable)

#data wrangling
library(dplyr)

#text processing
library(stringi)

Angular-Material DateTime Picker Component?

For as long as there is no official date and time picker from angular itself, I would advise to make a combination of the default angular date picker and this Angular Material Timepicker. I've chosen that one because all the other ones I found at this time lack support for issues, are outdated or are not functioning well in the most recent angular versions. This guy seems to be very responsive.

I've wrapped them both in one component so that it looks like it is one unit. You just have to make sure to do a few things:

When no input has been given yet, I would advise:

  • On-click of the component, the datepicker should always be triggered first.
  • After the datepicker closes, have the timepicker automatically popup.
  • Use touchUi = true on the datepicker, so that both the datepicker and the timepicker come as a dialog after each other.
  • Make sure the datepicker also shows up when clicking on the form (instead of only on the icon which is the default).
  • Use this solution to use the timepicker also in a material form, when placing them behind each other, it looks like it is one form.

After a value has been given, it is clear that one part contains the time and the other part contains the date. At that moment it is clear that the user has to click on the time to change the time, and on the date to change the date. But before that, so when both fields are empty (and 'attached' to each other as one field) you should make sure the user cannot be confused by doing above recommendations.

My component is not complete yet, I will try to remember myself to share the code later. Shoot a comment if this question is more then a month old or so.

Edit: Result

enter image description here

<div fxLayout="row">
  <div *ngIf="!dateOnly" [formGroup]="timeFormGroup">
    <mat-form-field>
      <input matInput [ngxTimepicker]="endTime" [format]="24"  placeholder="{{placeholderTime}}" formControlName="endTime" />
    </mat-form-field>
    <ngx-material-timepicker #endTime (timeSet)="timeChange($event)" [minutesGap]="10"></ngx-material-timepicker>
  </div>
  <div>
    <mat-form-field>
      <input id="pickerId" matInput [matDatepicker]="datepicker" placeholder="{{placeholderDate}}" [formControl]="dateForm"
             [min]="config.minDate" [max]="config.maxDate" (dateChange)="dateChange($event)">
      <mat-datepicker-toggle matSuffix [for]="datepicker"></mat-datepicker-toggle>
      <mat-datepicker #datepicker [disabled]="disabled" [touchUi]="config.touchUi" startView="{{config.startView}}"></mat-datepicker>
    </mat-form-field>
  </div>
</div>
import { Component, OnInit, Input, EventEmitter, Output } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';
import { DateAdapter, MatDatepickerInputEvent } from '@angular/material';

import * as moment_ from 'moment';

const moment = moment_;

import { MAT_MOMENT_DATE_ADAPTER_OPTIONS } from '@angular/material-moment-adapter';

class DateConfig {
  startView: 'month' | 'year' | 'multi-year';
  touchUi: boolean;
  minDate: moment_.Moment;
  maxDate: moment_.Moment;
}

@Component({
  selector: 'cb-datetimepicker',
  templateUrl: './cb-datetimepicker.component.html',
  styleUrls: ['./cb-datetimepicker.component.scss'],
})
export class DatetimepickerComponent implements OnInit {

  @Input() disabled: boolean;
  @Input() placeholderDate: string;
  @Input() placeholderTime: string;
  @Input() model: Date;
  @Input() purpose: string;
  @Input() dateOnly: boolean;

  @Output() dateUpdate = new EventEmitter<Date>();

  public pickerId: string = "_" + Math.random().toString(36).substr(2, 9);

  public dateForm: FormControl;
  public timeFormGroup: FormGroup;
  public endTime: FormControl;

  public momentDate: moment_.Moment;
  public config: DateConfig;

  //myGroup: FormGroup;


  constructor(private adapter : DateAdapter<any>) { }

  ngOnInit() {

    this.adapter.setLocale("nl-NL");//todo: configurable
    this.config = new DateConfig();
    if (this.purpose === "birthday") {
      this.config.startView = 'multi-year';
      this.config.maxDate = moment().add('year', -15);
      this.config.minDate = moment().add('year', -90);
      this.dateOnly = true;
    } //add more configurations
    else {
      this.config.startView = 'month';
      this.config.maxDate = moment().add('year', 100);
      this.config.minDate = moment().add('year', -100);
    }


    if (window.screen.width < 767) {
      this.config.touchUi = true;
    }



    if (this.model) {
      var mom = moment(this.model);
      if (mom.isBefore(moment('1900-01-01'))) {
        this.momentDate = moment();
      } else {
        this.momentDate = mom;
      }
    } else {
      this.momentDate = moment();
    }

    this.dateForm = new FormControl(this.momentDate);
    if (this.disabled) {
      this.dateForm.disable();
    }
    this.endTime = new FormControl(this.momentDate.format("HH:mm"));

    this.timeFormGroup = new FormGroup({
      endTime: this.endTime
    });


  }


  public dateChange(date: MatDatepickerInputEvent<any>) {

    if (moment.isMoment(date.value)) {
      this.momentDate = moment(date.value);
      if (this.dateOnly) {
        this.momentDate = this.momentDate.utc(true);
      } 
      var newDate = this.momentDate.toDate();
      this.model = newDate;
      this.dateUpdate.emit(newDate);
    }

    console.log("datechange",date);
  }

  public timeChange(time: string) {

    var splitted = time.split(':');
    var hour = splitted[0];
    var minute = splitted[1];

    console.log("time change", time);
   this.momentDate = this.momentDate.set('hour', parseInt(hour));
    this.momentDate = this.momentDate.set('minute', parseInt(minute));

    var newDate = this.momentDate.toDate();
    this.model = newDate;
    this.dateUpdate.emit(newDate);
  }
}

One important source: https://github.com/Agranom/ngx-material-timepicker/issues/126

I think it still deserves some tweaks, as I think it can work a bit better when I would have more time creating this. Most importantly I tried to solve the UTC issue as well, so all dates should be shown in local time but should be sent to the server in UTC format (or at least saved with the correct timezone added to it).

Compiling/Executing a C# Source File in Command Prompt

Once you write the c# code and save it. You can use the command prompt to execute it just like the other code.

In command prompt you enter the directory your file is in and type

To Compile:

mcs yourfilename.cs

To Execute:

mono yourfilename.exe 

if you want your .exe file to be different with a different name, type

To Compile:

mcs yourfilename.cs -out:anyname.exe 

To Execute:

mono anyname.exe 

This should help!

How do I get cURL to not show the progress bar?

Since curl 7.67.0 (2019-11-06) there is --no-progress-meter, which does exactly this, and nothing else. From the man page:

   --no-progress-meter
         Option to switch off the progress meter output without muting or
         otherwise affecting warning and informational messages like  -s,
         --silent does.

         Note  that  this  is the negated option name documented. You can
         thus use --progress-meter to enable the progress meter again.

         See also -v, --verbose and -s, --silent. Added in 7.67.0.

It's available in Ubuntu =20.04 and Debian =11 (Bullseye).

For a bit of history on curl's verbosity options, you can read Daniel Stenberg's blog post.

Page scroll up or down in Selenium WebDriver (Selenium 2) using java

I did not want to use JavaScript, or any external libraries, so this was my solution (C#):

IWebElement body = Driver.FindElement(By.TagName("body"));

IAction scrollDown = new Actions(Driver)
    .MoveToElement(body, body.Size.Width - 10, 15) // position mouse over scrollbar
    .ClickAndHold()
    .MoveByOffset(0, 50) // scroll down
    .Release()
    .Build();

scrollDown.Perform();

You can also easily make this an extension method for scrolling up or down on any element.

Countdown timer in React

Countdown of user input

Interface Screenshot screenshot

import React, { Component } from 'react';
import './App.css';

class App extends Component {
  constructor() {
    super();
    this.state = {
      hours: 0,
      minutes: 0,
      seconds:0
    }
    this.hoursInput = React.createRef();
    this.minutesInput= React.createRef();
    this.secondsInput = React.createRef();
  }

  inputHandler = (e) => {
    this.setState({[e.target.name]: e.target.value});
  }

  convertToSeconds = ( hours, minutes,seconds) => {
    return seconds + minutes * 60 + hours * 60 * 60;
  }

  startTimer = () => {
    this.timer = setInterval(this.countDown, 1000);
  }

  countDown = () => {
    const  { hours, minutes, seconds } = this.state;
    let c_seconds = this.convertToSeconds(hours, minutes, seconds);

    if(c_seconds) {

      // seconds change
      seconds ? this.setState({seconds: seconds-1}) : this.setState({seconds: 59});

      // minutes change
      if(c_seconds % 60 === 0 && minutes) {
        this.setState({minutes: minutes -1});
      }

      // when only hours entered
      if(!minutes && hours) {
        this.setState({minutes: 59});
      }

      // hours change
      if(c_seconds % 3600 === 0 && hours) {
        this.setState({hours: hours-1});
      }

    } else {
      clearInterval(this.timer);
    }
  }


  stopTimer = () => {
    clearInterval(this.timer);
  }

  resetTimer = () => {
    this.setState({
      hours: 0,
      minutes: 0,
      seconds: 0
    });
    this.hoursInput.current.value = 0;
    this.minutesInput.current.value = 0;
    this.secondsInput.current.value = 0;
  }


  render() {
    const { hours, minutes, seconds } = this.state;

    return (
      <div className="App">
         <h1 className="title"> (( React Countdown )) </h1>
         <div className="inputGroup">
            <h3>Hrs</h3>
            <input ref={this.hoursInput} type="number" placeholder={0}  name="hours"  onChange={this.inputHandler} />
            <h3>Min</h3>
            <input  ref={this.minutesInput} type="number"  placeholder={0}   name="minutes"  onChange={this.inputHandler} />
            <h3>Sec</h3>
            <input   ref={this.secondsInput} type="number"  placeholder={0}  name="seconds"  onChange={this.inputHandler} />
         </div>
         <div>
            <button onClick={this.startTimer} className="start">start</button>
            <button onClick={this.stopTimer}  className="stop">stop</button>
            <button onClick={this.resetTimer}  className="reset">reset</button>
         </div>
         <h1> Timer {hours}: {minutes} : {seconds} </h1>
      </div>

    );
  }
}

export default App;

PHP Warning: POST Content-Length of 8978294 bytes exceeds the limit of 8388608 bytes in Unknown on line 0

From the XAMPP panel, click on the ADMIN button on the Apache site. Then choose to edit php.ini And add the missing post_max_size to a value you are comfortable with.

post_max_size = 100M

How to jquery alert confirm box "yes" & "no"

See following snippet :

_x000D_
_x000D_
$(document).on("click", "a.deleteText", function() {_x000D_
    if (confirm('Are you sure ?')) {_x000D_
        $(this).prev('span.text').remove();_x000D_
    }_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<div class="container">_x000D_
    <span class="text">some text</span>_x000D_
    <a href="#" class="deleteText"><span class="delete-icon"> x Delete </span></a>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How can I disable HREF if onclick is executed?

Try using javascript:void(0) as follows-

<a href="javascript:void(0)" onclick="...">Text</a>

Test class with a new() call in it with Mockito

Not that I know of, but what about doing something like this when you create an instance of TestedClass that you want to test:

TestedClass toTest = new TestedClass() {
    public LoginContext login(String user, String password) {
        //return mocked LoginContext
    }
};

Another option would be to use Mockito to create an instance of TestedClass and let the mocked instance return a LoginContext.

Convert tuple to list and back

List to Tuple and back can be done as below

import ast, sys
input_str = sys.stdin.read()
input_tuple = ast.literal_eval(input_str)

l = list(input_tuple)
l.append('Python')
#print(l)
tuple_2 = tuple(l)

# Make sure to name the final tuple 'tuple_2'
print(tuple_2)

In C#, what is the difference between public, private, protected, and having no access modifier?

public - can be access by anyone anywhere.
private - can only be accessed from with in the class it is a part of.
protected - can only be accessed from with in the class or any object that inherits off of the class.

Nothing is like null but in VB.
Static means you have one instance of that object, method for every instance of that class.

How do I check for null values in JavaScript?

I found a another way to test if the value is null:

if(variable >= 0 && typeof variable === "object")

null acts as a number and object at the same time. Comparing null >= 0 or null <= 0 results in true. Comparing null === 0 or null > 0 or null < 0 will result in false. But as null is also an object we can detect it as a null.

I made a more complex function natureof witch will do better than typeof and can be told what types to include or keep grouped

_x000D_
_x000D_
/* function natureof(variable, [included types])_x000D_
included types are _x000D_
    null - null will result in "undefined" or if included, will result in "null"_x000D_
    NaN - NaN will result in "undefined" or if included, will result in "NaN"_x000D_
    -infinity - will separate negative -Inifity from "Infinity"_x000D_
    number - will split number into "int" or "double"_x000D_
    array - will separate "array" from "object"_x000D_
    empty - empty "string" will result in "empty" or_x000D_
    empty=undefined - empty "string" will result in "undefined"_x000D_
*/_x000D_
function natureof(v, ...types){_x000D_
/*null*/            if(v === null) return types.includes('null') ? "null" : "undefined";_x000D_
/*NaN*/             if(typeof v == "number") return (isNaN(v)) ? types.includes('NaN') ? "NaN" : "undefined" : _x000D_
/*-infinity*/       (v+1 === v) ? (types.includes('-infinity') && v === Number.NEGATIVE_INFINITY) ? "-infinity" : "infinity" : _x000D_
/*number*/          (types.includes('number')) ? (Number.isInteger(v)) ? "int" : "double" : "number";_x000D_
/*array*/           if(typeof v == "object") return (types.includes('array') && Array.isArray(v)) ? "array" : "object";_x000D_
/*empty*/           if(typeof v == "string") return (v == "") ? types.includes('empty') ? "empty" : _x000D_
/*empty=undefined*/ types.includes('empty=undefined') ? "undefined" : "string" : "string";_x000D_
                    else return typeof v_x000D_
}_x000D_
_x000D_
// DEMO_x000D_
let types = [null, "", "string", undefined, NaN, Infinity, -Infinity, false, "false", true, "true", 0, 1, -1, 0.1, "test", {var:1}, [1,2], {0: 1, 1: 2, length: 2}]_x000D_
_x000D_
for(i in types){_x000D_
console.log("natureof ", types[i], " = ", natureof(types[i], "null", "NaN", "-infinity", "number", "array", "empty=undefined")) _x000D_
}
_x000D_
_x000D_
_x000D_

Java String encoding (UTF-8)

This could be complicated way of doing

String newString = new String(oldString);

This shortens the String is the underlying char[] used is much longer.

However more specifically it will be checking that every character can be UTF-8 encoded.

There are some "characters" you can have in a String which cannot be encoded and these would be turned into ?

Any character between \uD800 and \uDFFF cannot be encoded and will be turned into '?'

String oldString = "\uD800";
String newString = new String(oldString.getBytes("UTF-8"), "UTF-8");
System.out.println(newString.equals(oldString));

prints

false

Delete specified file from document directory

Swift 2.0:

func removeOldFileIfExist() {
    let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
    if paths.count > 0 {
        let dirPath = paths[0]
        let fileName = "someFileName"
        let filePath = NSString(format:"%@/%@.png", dirPath, fileName) as String
        if NSFileManager.defaultManager().fileExistsAtPath(filePath) {
            do {
                try NSFileManager.defaultManager().removeItemAtPath(filePath)
                print("old image has been removed")
            } catch {
                print("an error during a removing")
            }
        }
    }
}

How to unnest a nested list

the first case can also be easily done as:

A=A[0]

Version of Apache installed on a Debian machine

You can also use the package manager directly:

dpkg -l | grep apache

This isn't focused on just version number, but it will make a broader search, which will give you other useful information, like module versions.

Read the package name of an Android APK

As I don't was able to find the package name in the .apk file with editor (like suggested above), I have checked the functions in the App "ES Datei Explorer" / "ES File Explorer" (free version) that I had installed already. In this tool, the package name is showed properly.
As I think a good file explorer should not be missing on a phone, I suggest to use this tool (if you already have installed the apk on an mobile and have to know the package name).

No process is on the other end of the pipe (SQL Server 2012)

To solve this, connect to SQL Management Studio using Windows Authentication, then right-click on server node Properties->Security and enable SQL Server and Windows Authentication mode. If you're using 'sa' make sure the account is enabled. To do this open 'sa' under Logins and view Status.

enable sa admin

If this didn't work, you may need to reinstall SQL Server

How can I unstage my files again after making a local commit?

Lets say you want to unstage changes upto n commits,

Where commit hashes are as follows:

  • h1
  • h2 ...
  • hn
  • hn+1

Then run the following command:
git reset hn

Now the HEAD will be at hn+1. Changes from h1 to hn will be unstaged.

How to get a variable from a file to another file in Node.js

File FileOne.js:

module.exports = { ClientIDUnsplash : 'SuperSecretKey' };

File FileTwo.js:

var { ClientIDUnsplash } = require('./FileOne');

This example works best for React.

Apache won't follow symlinks (403 Forbidden)

Yet another subtle pitfall, in case you need AllowOverride All:

Somewhere deep in the fs tree, an old .htaccess having

    Options Indexes

instead of

    Options +Indexes

was all it took to nonchalantly disable the FollowSymLinks set in the server config, and cause a mysterious 403 here.

div inside php echo

You can do the following:

echo '<div class="my_class">';
echo ($cart->count_product > 0) ? $cart->count_product : '';
echo '</div>';

If you want to have it inside your statement, do this:

if($cart->count_product > 0) 
{
    echo '<div class="my_class">'.$cart->count_product.'</div>';
}

You don't need the else statement, since you're only going to output the above when it's truthy anyway.

HTTPS connection Python

If using httplib.HTTPSConnection:

Please take a look at:

Changed in version 2.7.9:

This class now performs all the necessary certificate and hostname checks by default. To revert to the previous, unverified, behavior ssl._create_unverified_context() can be passed to the context parameter. You can use:

if hasattr(ssl, '_create_unverified_context'):
  ssl._create_default_https_context = ssl._create_unverified_context

cannot redeclare block scoped variable (typescript)

I got the same problem, and my solution looks like this:

// *./module1/module1.ts*
export module Module1 {
    export class Module1{
        greating(){ return 'hey from Module1'}
    }
}


// *./module2/module2.ts*
import {Module1} from './../module1/module1';

export module Module2{
    export class Module2{
        greating(){
            let m1 = new Module1.Module1()
            return 'hey from Module2 + and from loaded Model1: '+ m1.greating();
        }
    }
}

Now we can use it on the server side:

// *./server.ts*
/// <reference path="./typings/node/node.d.ts"/>
import {Module2} from './module2/module2';

export module Server {
    export class Server{
        greating(){
            let m2 = new Module2.Module2();
            return "hello from server & loaded modules: " + m2.greating();
        }
    }
}

exports.Server = Server;

// ./app.js
var Server = require('./server').Server.Server;
var server = new Server();
console.log(server.greating());

And on the client side too:

// *./public/javscripts/index/index.ts*

import {Module2} from './../../../module2/module2';

document.body.onload = function(){
    let m2 = new Module2.Module2();
    alert(m2.greating());
}

// ./views/index.jade
extends layout

block content
  h1= title
  p Welcome to #{title}
  script(src='main.js')
  //
    the main.js-file created by gulp-task 'browserify' below in the gulpfile.js

And, of course, a gulp-file for all of this:

// *./gulpfile.js*
var gulp = require('gulp'),
    ts = require('gulp-typescript'),
    runSequence = require('run-sequence'),
    browserify = require('gulp-browserify'),
    rename = require('gulp-rename');

gulp.task('default', function(callback) {

    gulp.task('ts1', function() {
        return gulp.src(['./module1/module1.ts'])
            .pipe(ts())
            .pipe(gulp.dest('./module1'))
    });

    gulp.task('ts2', function() {
        return gulp.src(['./module2/module2.ts'])
            .pipe(ts())
            .pipe(gulp.dest('./module2'))
    });

    gulp.task('ts3', function() {
        return gulp.src(['./public/javascripts/index/index.ts'])
            .pipe(ts())
            .pipe(gulp.dest('./public/javascripts/index'))
    });

    gulp.task('browserify', function() {
        return gulp.src('./public/javascripts/index/index.js', { read: false })
            .pipe(browserify({
                insertGlobals: true
            }))
            .pipe(rename('main.js'))
            .pipe(gulp.dest('./public/javascripts/'))
    });

    runSequence('ts1', 'ts2', 'ts3', 'browserify', callback);
})

Updated. Of course, it's not neccessary to compile typescript files separatly. runSequence(['ts1', 'ts2', 'ts3'], 'browserify', callback) works perfect.

Change a column type from Date to DateTime during ROR migration

Also, if you're using Rails 3 or newer you don't have to use the up and down methods. You can just use change:

class ChangeFormatInMyTable < ActiveRecord::Migration
  def change
    change_column :my_table, :my_column, :my_new_type
  end
end

Java File - Open A File And Write To It

Please Search Google given to the world by Larry Page and Sergey Brin.

BufferedWriter out = null;

try {
    FileWriter fstream = new FileWriter("out.txt", true); //true tells to append data.
    out = new BufferedWriter(fstream);
    out.write("\nsue");
}

catch (IOException e) {
    System.err.println("Error: " + e.getMessage());
}

finally {
    if(out != null) {
        out.close();
    }
}

How to present popover properly in iOS 8

my two cents for xcode 9.1 / swift 4.

class ViewController: UIViewController, UIPopoverPresentationControllerDelegate {

    override func viewDidLoad(){
        super.viewDidLoad()

        let when = DispatchTime.now() + 0.5

        DispatchQueue.main.asyncAfter(deadline: when, execute: { () -> Void in
            // to test after 05.secs... :)
            self.showPopover(base: self.view)

        })

}


func showPopover(base: UIView) {
    if let viewController = self.storyboard?.instantiateViewController(withIdentifier: "popover") as? PopOverViewController {

        let navController = UINavigationController(rootViewController: viewController)
        navController.modalPresentationStyle = .popover

        if let pctrl = navController.popoverPresentationController {
            pctrl.delegate = self

            pctrl.sourceView = base
            pctrl.sourceRect = base.bounds

            self.present(navController, animated: true, completion: nil)
        }
    }
}


@IBAction func onShow(sender: UIButton){
    self.showPopover(base: sender)
}

func adaptivePresentationStyle(for controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle{
    return .none
}

and experiment in:

func adaptivePresentationStyle...

    return .popover

or: return .pageSheet.... and so on..

How to make Python speak

Combining the following sources, the following code works on Windows, Linux and macOS using just the platform and os modules:

tx = input("Text to say >>> ")
tx = repr(tx)

import os
import platform

syst = platform.system()
if syst == 'Linux' and platform.linux_distribution()[0] == "Ubuntu":
    os.system('spd-say %s' % tx)
elif syst == 'Windows':
    os.system('PowerShell -Command "Add-Type –AssemblyName System.Speech; (New-Object System.Speech.Synthesis.SpeechSynthesizer).Speak(%s);"' % tx)
elif syst == 'Darwin':
    os.system('say %s' % tx)
else:
    raise RuntimeError("Operating System '%s' is not supported" % syst)

Note: This method is not secure and could be exploited by malicious text.

How to create a file in Ruby

You can also use constants instead of strings to specify the mode you want. The benefit is if you make a typo in a constant name, your program will raise an runtime exception.

The constants are File::RDONLY or File::WRONLY or File::CREAT. You can also combine them if you like.

Full description of file open modes on ruby-doc.org

How to use zIndex in react-native

Use elevation instead of zIndex for android devices

elevatedElement: {
  zIndex: 3, // works on ios
  elevation: 3, // works on android
}

This worked fine for me!

ASP.NET Custom Validator Client side & Server Side validation not firing

Server-side validation won't fire if client-side validation is invalid, the postback is not send.

Don't you have some other validation that doesn't pass?

The client-side validation is not executed because you specified ClientValidationFunction="TextBoxDTownCityClient" and this will look for a function named TextBoxDTownCityClient as validation function, but the function name should be TextBoxDAddress1Client

(as you wrote)

How do you access a website running on localhost from iPhone browser

If you go the route of going into your Network Settings and getting Wi-Fi IP address such as xxx.xxx.x.xxx:9000 (:9000 or whichever port is open), make sure your mobile device is also on that same Wi-Fi/signal IP address. I spent a day trying to get this to work and it didn't work until i switched my phone off the cellular network to the same Wi-Fi connection/IP address. Opened right up once I made this update.

Difference between PACKETS and FRAMES

Packets and Frames are the names given to Protocol data units (PDUs) at different network layers

  • Segments/Datagrams are units of data in the Transport Layer.

    In the case of the internet, the term Segment typically refers to TCP, while Datagram typically refers to UDP. However Datagram can also be used in a more general sense and refer to other layers (link):

    Datagram

    A self-contained, independent entity of data carrying sufficient information to be routed from the source to the destination computer without reliance on earlier exchanges between this source and destination computer andthe transporting network.

  • Packets are units of data in the Network Layer (IP in case of the Internet)

  • Frames are units of data in the Link Layer (e.g. Wifi, Bluetooth, Ethernet, etc).

enter image description here

How to add icons to React Native app

If you're using expo just place an 1024 x 1024 png file in your project and add an icon property to your app.json i.e. "icon": "./src/assets/icon.png"

https://docs.expo.io/versions/latest/guides/app-icons

what's the easiest way to put space between 2 side-by-side buttons in asp.net

If you want the style to apply globally you could use the adjacent sibling combinator from css.

.my-button-style + .my-button-style {
  margin-left: 40px;
}

/* general button style */
.my-button-style {
  height: 100px;
  width: 150px;
}

Here is a fiddle: https://jsfiddle.net/caeLosby/10/

It is similar to some of the existing answers but it does not set the margin on the first button. For example in the case

<button id="btn1" class="my-button-style"/>
<button id="btn2" class="my-button-style"/>

only btn2 will get the margin.

For further information see https://developer.mozilla.org/en-US/docs/Web/CSS/Adjacent_sibling_combinator

How can I put an icon inside a TextInput in React Native?

This is working for me in ReactNative 0.60.4

View

<View style={styles.SectionStyle}>
    <Image
        source={require('../assets/images/ico-email.png')} //Change your icon image here
        style={styles.ImageStyle}
    />

    <TextInput
        style={{ flex: 1 }}
        placeholder="Enter Your Name Here"
        underlineColorAndroid="transparent"
    />
</View>

Styles

SectionStyle: {
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#fff',
    borderWidth: 0.5,
    borderColor: '#000',
    height: 40,
    borderRadius: 5,
    margin: 10,
},
ImageStyle: {
    padding: 10,
    margin: 5,
    height: 25,
    width: 25,
    resizeMode: 'stretch',
    alignItems: 'center',
}

Design Documents (High Level and Low Level Design Documents)

High-Level Design (HLD) involves decomposing a system into modules, and representing the interfaces & invocation relationships among modules. An HLD is referred to as software architecture.

LLD, also known as a detailed design, is used to design internals of the individual modules identified during HLD i.e. data structures and algorithms of the modules are designed and documented.

Now, HLD and LLD are actually used in traditional Approach (Function-Oriented Software Design) whereas, in OOAD, the system is seen as a set of objects interacting with each other.

As per the above definitions, a high-level design document will usually include a high-level architecture diagram depicting the components, interfaces, and networks that need to be further specified or developed. The document may also depict or otherwise refer to work flows and/or data flows between component systems.

Class diagrams with all the methods and relations between classes come under LLD. Program specs are covered under LLD. LLD describes each and every module in an elaborate manner so that the programmer can directly code the program based on it. There will be at least 1 document for each module. The LLD will contain - a detailed functional logic of the module in pseudo code - database tables with all elements including their type and size - all interface details with complete API references(both requests and responses) - all dependency issues - error message listings - complete inputs and outputs for a module.

How do I sort a Set to a List in Java?

The answer provided by the OP is not the best. It is inefficient, as it creates a new List and an unnecessary new array. Also, it raises "unchecked" warnings because of the type safety issues around generic arrays.

Instead, use something like this:

public static
<T extends Comparable<? super T>> List<T> asSortedList(Collection<T> c) {
  List<T> list = new ArrayList<T>(c);
  java.util.Collections.sort(list);
  return list;
}

Here's a usage example:

Map<Integer, String> map = new HashMap<Integer, String>();
/* Add entries to the map. */
...
/* Now get a sorted list of the *values* in the map. */
Collection<String> unsorted = map.values();
List<String> sorted = Util.asSortedList(unsorted);

Escape quote in web.config connection string

connectionString="Server=dbsrv;User ID=myDbUser;Password=somepass&quot;word"

Since the web.config is XML, you need to escape the five special characters:

&amp; -> & ampersand, U+0026
&lt; -> < left angle bracket, less-than sign, U+003C
&gt; -> > right angle bracket, greater-than sign, U+003E
&quot; -> " quotation mark, U+0022
&apos; -> ' apostrophe, U+0027

+ is not a problem, I suppose.


Duc Filan adds: You should also wrap your password with single quote ':

connectionString="Server=dbsrv;User ID=myDbUser;Password='somepass&quot;word'"

How to change the font and font size of an HTML input tag?

In your 'head' section, add this code:

<style>
input[type='text'] { font-size: 24px; }
</style>

Or you can only add the:

input[type='text'] { font-size: 24px; }

to a CSS file which can later be included.

You can also change the font face by using the CSS property: font-family

font-family: monospace;

So you can have a CSS code like this:

input[type='text'] { font-size: 24px; font-family: monospace; }

You can find further help at the W3Schools website.

I suggest you to have a look at the CSS3 specification. With CSS3 you can also load a font from the web instead of having the limitation to use only the most common fonts or tell the user to download the font you're using.

Unlink of file Failed. Should I try again?

I ran into this issue in Windows, you might want to run the git bash as an administrator and then perform the desire commands, that solved the issue for me.

python location on mac osx

I checked a few similar discussions and found out the best way to locate all python2/python3 builds is:

which -a python python3

How to enable external request in IIS Express?

A good resource is Working with SSL at Development Time is easier with IISExpress by Scott Hanselman.

What you're after is the section Getting IIS Express to serve externally over Port 80

Convert System.Drawing.Color to RGB and Hex Value

You could keep it simple and use the native color translator:

Color red = ColorTranslator.FromHtml("#FF0000");
string redHex = ColorTranslator.ToHtml(red);

Then break the three color pairs into integer form:

int value = int.Parse(hexValue, System.Globalization.NumberStyles.HexNumber);

Convert Python ElementTree to string

Element objects have no .getroot() method. Drop that call, and the .tostring() call works:

xmlstr = ElementTree.tostring(et, encoding='utf8', method='xml')

You only need to use .getroot() if you have an ElementTree instance.

Other notes:

  • This produces a bytestring, which in Python 3 is the bytes type.
    If you must have a str object, you have two options:

    1. Decode the resulting bytes value, from UTF-8: xmlstr.decode("utf8")

    2. Use encoding='unicode'; this avoids an encode / decode cycle:

      xmlstr = ElementTree.tostring(et, encoding='unicode', method='xml')
      
  • If you wanted the UTF-8 encoded bytestring value or are using Python 2, take into account that ElementTree doesn't properly detect utf8 as the standard XML encoding, so it'll add a <?xml version='1.0' encoding='utf8'?> declaration. Use utf-8 or UTF-8 (with a dash) if you want to prevent this. When using encoding="unicode" no declaration header is added.

How to get the HTML for a DOM element in javascript

var x = $('#container').get(0).outerHTML;

Closing a Userform with Unload Me doesn't work

It should also be noted that if you have buttons grouped together on your user form that it can link it to a different button in the group despite the one you intended being clicked.

Laravel Eloquent - Get one Row

Simply use this:

$user = User::whereEmail($email)->first();

Select mySQL based only on month and year

The logic will be:

SELECT * FROM objects WHERE Date LIKE '$_POST[period]-%';

The LIKE operator will select all rows that start with $_POST['period'] followed by dash and the day of the mont

http://dev.mysql.com/doc/refman/5.0/en/pattern-matching.html - Some additional information

What exactly does big ? notation represent?

I hope this is what you may want to find in the classical CLRS(page 66): enter image description here

Replace all double quotes within String

String info = "Hello \"world\"!";
info = info.replace("\"", "\\\"");

String info1 = "Hello "world!";
info1 = info1.replace('"', '\"').replace("\"", "\\\"");

For the 2nd field info1, 1st replace double quotes with an escape character.

Is there a way to cast float as a decimal without rounding and preserving its precision?

Have you tried:

SELECT Cast( 2.555 as decimal(53,8))

This would return 2.55500000. Is that what you want?

UPDATE:

Apparently you can also use SQL_VARIANT_PROPERTY to find the precision and scale of a value. Example:

SELECT SQL_VARIANT_PROPERTY(Cast( 2.555 as decimal(8,7)),'Precision'),
SQL_VARIANT_PROPERTY(Cast( 2.555 as decimal(8,7)),'Scale')

returns 8|7

You may be able to use this in your conversion process...

How to convert date to string and to date again?

For converting date to string check this thread

Convert java.util.Date to String

And for converting string to date try this,

import java.text.ParseException;
import java.text.SimpleDateFormat;

public class StringToDate
{
    public static void main(String[] args) throws ParseException
    {
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
        String strDate = "14/03/2003 08:05:10";     
        System.out.println("Date - " + sdf.parse(strDate));
    }
}

Reading file using relative path in python project

My Python version is Python 3.5.2 and the solution proposed in the accepted answer didn't work for me. I've still were given an error

FileNotFoundError: [Errno 2] No such file or directory

when I was running my_script.py from the terminal. Although it worked fine when I run it through Run/Debug Configurations from PyCharm IDE (PyCharm 2018.3.2 (Community Edition)).

Solution:

instead of using:

my_path = os.path.abspath(os.path.dirname(__file__)) + some_rel_dir_path 

as suggested in the accepted answer, I used:

my_path = os.path.abspath(os.path.dirname(os.path.abspath(__file__))) + some_rel_dir_path

Explanation: Changing os.path.dirname(__file__) to os.path.dirname(os.path.abspath(__file__)) solves the following problem:

When we run our script like that: python3 my_script.py the __file__ variable has a just a string value of "my_script.py" without path leading to that particular script. That is why method dirname(__file__) returns an empty string "". That is also the reson why my_path = os.path.abspath(os.path.dirname(__file__)) + some_rel_dir_path is actually the same thing as my_path = some_rel_dir_path. Consequently FileNotFoundError: [Errno 2] No such file or directory is given when trying to use open method because there is no directory like "some_rel_dir_path".

Running script from PyCharm IDE Running/Debug Configurations worked because it runs a command python3 /full/path/to/my_script.py (where "/full/path/to" is specified by us in "Working directory" variable in Run/Debug Configurations) instead of justpython3 my_script.py like it is done when we run it from the terminal.

Hope that will be useful.

How do I use reflection to invoke a private method?

I think you can pass it BindingFlags.NonPublic where it is the GetMethod method.

Regex pattern for numeric values

"[1-9][0-9]*|0"

I'd just use "[0-9]+" to represent positive whole numbers.

Can I remove the URL from my print css, so the web address doesn't print?

This is a browser issue. But you can handle this problem by these line of codes:

<style type="text/css" media="print">
@media print
{
    @page {
        margin-top: 0;
        margin-bottom: 0;
    }
    body  {
        padding-top: 72px;
        padding-bottom: 72px ;
    }
}
</style>

A simple scenario using wait() and notify() in java

The wait() and notify() methods are designed to provide a mechanism to allow a thread to block until a specific condition is met. For this I assume you're wanting to write a blocking queue implementation, where you have some fixed size backing-store of elements.

The first thing you have to do is to identify the conditions that you want the methods to wait for. In this case, you will want the put() method to block until there is free space in the store, and you will want the take() method to block until there is some element to return.

public class BlockingQueue<T> {

    private Queue<T> queue = new LinkedList<T>();
    private int capacity;

    public BlockingQueue(int capacity) {
        this.capacity = capacity;
    }

    public synchronized void put(T element) throws InterruptedException {
        while(queue.size() == capacity) {
            wait();
        }

        queue.add(element);
        notify(); // notifyAll() for multiple producer/consumer threads
    }

    public synchronized T take() throws InterruptedException {
        while(queue.isEmpty()) {
            wait();
        }

        T item = queue.remove();
        notify(); // notifyAll() for multiple producer/consumer threads
        return item;
    }
}

There are a few things to note about the way in which you must use the wait and notify mechanisms.

Firstly, you need to ensure that any calls to wait() or notify() are within a synchronized region of code (with the wait() and notify() calls being synchronized on the same object). The reason for this (other than the standard thread safety concerns) is due to something known as a missed signal.

An example of this, is that a thread may call put() when the queue happens to be full, it then checks the condition, sees that the queue is full, however before it can block another thread is scheduled. This second thread then take()'s an element from the queue, and notifies the waiting threads that the queue is no longer full. Because the first thread has already checked the condition however, it will simply call wait() after being re-scheduled, even though it could make progress.

By synchronizing on a shared object, you can ensure that this problem does not occur, as the second thread's take() call will not be able to make progress until the first thread has actually blocked.

Secondly, you need to put the condition you are checking in a while loop, rather than an if statement, due to a problem known as spurious wake-ups. This is where a waiting thread can sometimes be re-activated without notify() being called. Putting this check in a while loop will ensure that if a spurious wake-up occurs, the condition will be re-checked, and the thread will call wait() again.


As some of the other answers have mentioned, Java 1.5 introduced a new concurrency library (in the java.util.concurrent package) which was designed to provide a higher level abstraction over the wait/notify mechanism. Using these new features, you could rewrite the original example like so:

public class BlockingQueue<T> {

    private Queue<T> queue = new LinkedList<T>();
    private int capacity;
    private Lock lock = new ReentrantLock();
    private Condition notFull = lock.newCondition();
    private Condition notEmpty = lock.newCondition();

    public BlockingQueue(int capacity) {
        this.capacity = capacity;
    }

    public void put(T element) throws InterruptedException {
        lock.lock();
        try {
            while(queue.size() == capacity) {
                notFull.await();
            }

            queue.add(element);
            notEmpty.signal();
        } finally {
            lock.unlock();
        }
    }

    public T take() throws InterruptedException {
        lock.lock();
        try {
            while(queue.isEmpty()) {
                notEmpty.await();
            }

            T item = queue.remove();
            notFull.signal();
            return item;
        } finally {
            lock.unlock();
        }
    }
}

Of course if you actually need a blocking queue, then you should use an implementation of the BlockingQueue interface.

Also, for stuff like this I'd highly recommend Java Concurrency in Practice, as it covers everything you could want to know about concurrency related problems and solutions.

Convert INT to DATETIME (SQL)

Try this:

select CONVERT(datetime, convert(varchar(10), 20120103))

How do I change the text size in a label widget, python tkinter

Try passing width=200 as additional paramater when creating the Label.

This should work in creating label with specified width.

If you want to change it later, you can use:

label.config(width=200)

As you want to change the size of font itself you can try:

label.config(font=("Courier", 44))

What is the correct wget command syntax for HTTPS with username and password?

You could try the same address with HTTP instead of HTTPS. Be aware that this does use HTTP instead of HTTPS and only some sites might support this method.

Example address: https://cdimage.debian.org/debian-cd/current/amd64/iso-cd/debian-10.3.0-amd64-netinst.iso

wget http://cdimage.debian.org/debian-cd/current/amd64/iso-cd/debian-10.3.0-amd64-netinst.iso

*notice the http:// instead of https://.

This is probably not recommended though :)

If you can, try use curl.


EDIT:

FYI an example with username (and prompt for password) would be:

curl --user $USERNAME -O http://cdimage.debian.org/debian-cd/current/amd64/iso-cd/debian-10.3.0-amd64-netinst.iso

Where -O is

 -O, --remote-name
              Write output to a local file named like the remote file we get. (Only the file part of the remote file is used, the path is cut off.)

How to change time in DateTime?

Since DateTime is immutable, a new instance has to be created when a date component needs to be changed. Unfortunately, there is no built-in functionality to set individual components of a DateTime instance.

Using the following extension methods

public static DateTime SetPart(this DateTime dateTime, int? year, int? month, int? day, int? hour, int? minute, int? second)
{
    return new DateTime(
        year ?? dateTime.Year,
        month ?? dateTime.Month,
        day ?? dateTime.Day,
        hour ?? dateTime.Hour,
        minute ?? dateTime.Minute,
        second ?? dateTime.Second
    );
}

public static DateTime SetYear(this DateTime dateTime, int year)
{
    return dateTime.SetPart(year, null, null, null, null, null);
}

public static DateTime SetMonth(this DateTime dateTime, int month)
{
    return dateTime.SetPart(null, month, null, null, null, null);
}

public static DateTime SetDay(this DateTime dateTime, int day)
{
    return dateTime.SetPart(null, null, day, null, null, null);
}

public static DateTime SetHour(this DateTime dateTime, int hour)
{
    return dateTime.SetPart(null, null, null, hour, null, null);
}

public static DateTime SetMinute(this DateTime dateTime, int minute)
{
    return dateTime.SetPart(null, null, null, null, minute, null);
}

public static DateTime SetSecond(this DateTime dateTime, int second)
{
    return dateTime.SetPart(null, null, null, null, null, second);
}

you can set individual DateTime components like

var now = DateTime.Now;

now.SetSecond(0);

How to convert image file data in a byte array to a Bitmap?

Just try this:

Bitmap bitmap = BitmapFactory.decodeFile("/path/images/image.jpg");
ByteArrayOutputStream blob = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 0 /* Ignored for PNGs */, blob);
byte[] bitmapdata = blob.toByteArray();

If bitmapdata is the byte array then getting Bitmap is done like this:

Bitmap bitmap = BitmapFactory.decodeByteArray(bitmapdata, 0, bitmapdata.length);

Returns the decoded Bitmap, or null if the image could not be decoded.

How to rename array keys in PHP?

Recursive php rename keys function:

function replaceKeys($oldKey, $newKey, array $input){
    $return = array(); 
    foreach ($input as $key => $value) {
        if ($key===$oldKey)
            $key = $newKey;

        if (is_array($value))
            $value = replaceKeys( $oldKey, $newKey, $value);

        $return[$key] = $value;
    }
    return $return; 
}

php return 500 error but no error log

Copy and paste the following into a new .htaccess file and place it on your website's root folder :

php_flag  display_errors                  on
php_flag  display_startup_errors          on

Errors will be shown directly in your page.

That's the best way to debug quickly but don't use it for long time because it could be a security breach.

Reading serial data in realtime in Python

A very good solution to this can be found here:

Here's a class that serves as a wrapper to a pyserial object. It allows you to read lines without 100% CPU. It does not contain any timeout logic. If a timeout occurs, self.s.read(i) returns an empty string and you might want to throw an exception to indicate the timeout.

It is also supposed to be fast according to the author:

The code below gives me 790 kB/sec while replacing the code with pyserial's readline method gives me just 170kB/sec.

class ReadLine:
    def __init__(self, s):
        self.buf = bytearray()
        self.s = s

    def readline(self):
        i = self.buf.find(b"\n")
        if i >= 0:
            r = self.buf[:i+1]
            self.buf = self.buf[i+1:]
            return r
        while True:
            i = max(1, min(2048, self.s.in_waiting))
            data = self.s.read(i)
            i = data.find(b"\n")
            if i >= 0:
                r = self.buf + data[:i+1]
                self.buf[0:] = data[i+1:]
                return r
            else:
                self.buf.extend(data)

ser = serial.Serial('COM7', 9600)
rl = ReadLine(ser)

while True:

    print(rl.readline())

CSS3 gradient background set on body doesn't stretch but instead repeats?

instead of 100% i just add some pixxel got this now and it works for whole page without gap:

html {     
height: 1420px; } 
body {     
height: 1400px;     
margin: 0;     
background-repeat: no-repeat; }

How can I convert an HTML element to a canvas element?

the next code can be used in 2 modes, mode 1 save the html code to a image, mode 2 save the html code to a canvas.

this code work with the library: https://github.com/tsayen/dom-to-image

*the "id_div" is the id of the element html that you want to transform.

**the "canvas_out" is the id of the div that will contain the canvas so try this code. :

   function Guardardiv(id_div){

      var mode = 2 // default 1 (save to image), mode 2 = save to canvas
      console.log("Process start");
      var node = document.getElementById(id_div);
      // get the div that will contain the canvas
      var canvas_out = document.getElementById('canvas_out');
      var canvas = document.createElement('canvas');
      canvas.width = node.scrollWidth;
      canvas.height = node.scrollHeight;

      domtoimage.toPng(node).then(function (pngDataUrl) {
          var img = new Image();
          img.onload = function () {
          var context = canvas.getContext('2d');
          context.drawImage(img, 0, 0);
        };

        if (mode == 1){ // save to image
             downloadURI(pngDataUrl, "salida.png");
        }else if (mode == 2){ // save to canvas
          img.src = pngDataUrl;
          canvas_out.appendChild(img);

        }
      console.log("Process finish");
    });

    }

so, if you want to save to image just add this function:

    function downloadURI(uri, name) {
        var link = document.createElement("a");

        link.download = name;
        link.href = uri;
        document.body.appendChild(link);
        link.click();   
    }

Example of use:

 <html>
 <head>
 </script src="/dom-to-image.js"></script>
 </head> 
 <body>
 <div id="container">
   All content that want to transform
  </div>
  <button onclick="Guardardiv('container');">Convert<button> 

 <!-- if use mode 2 -->
 <div id="canvas_out"></div>
 </html>

Comment if that work. Comenten si les sirvio :)

Gradle failed to resolve library in Android Studio

i had the same problem, i added the following lines in build.gradle

allprojects {
    repositories {
        jcenter()
        maven { url "https://jitpack.io" }

        maven {
            url 'http://dl.bintray.com/dev-fingerlinks/maven'
        }
        mavenCentral()
    }
}

Only local connections are allowed Chrome and Selenium webdriver

Sorry for late post but still for info,I also facing same problem so I Used updated version of chromedriver ie.2.28 for updated chrome browser ie. 55 to 57 which resolved my problem.

C# HttpClient 4.5 multipart/form-data upload

public async Task<object> PassImageWithText(IFormFile files)
{
    byte[] data;
    string result = "";
    ByteArrayContent bytes;

    MultipartFormDataContent multiForm = new MultipartFormDataContent();

    try
    {
        using (var client = new HttpClient())
        {
            using (var br = new BinaryReader(files.OpenReadStream()))
            {
                data = br.ReadBytes((int)files.OpenReadStream().Length);
            }

            bytes = new ByteArrayContent(data);
            multiForm.Add(bytes, "files", files.FileName);
            multiForm.Add(new StringContent("value1"), "key1");
            multiForm.Add(new StringContent("value2"), "key2");

            var res = await client.PostAsync(_MEDIA_ADD_IMG_URL, multiForm);
        }
    }
    catch (Exception e)
    {
        throw new Exception(e.ToString());
    }

    return result;
}

How can I play sound in Java?

I'm surprised nobody suggested using Applet. Use Applet. You'll have to supply the beep audio file as a wav file, but it works. I tried this on Ubuntu:

package javaapplication2;

import java.applet.Applet;
import java.applet.AudioClip;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;

public class JavaApplication2 {

    public static void main(String[] args) throws MalformedURLException {
        File file = new File("/path/to/your/sounds/beep3.wav");
        URL url = null;
        if (file.canRead()) {url = file.toURI().toURL();}
        System.out.println(url);
        AudioClip clip = Applet.newAudioClip(url);
        clip.play();
        System.out.println("should've played by now");
    }
}
//beep3.wav was available from: http://www.pacdv.com/sounds/interface_sound_effects/beep-3.wav

Extracting columns from text file with different delimiters in Linux

If the command should work with both tabs and spaces as the delimiter I would use awk:

awk '{print $100,$101,$102,$103,$104,$105}' myfile > outfile

As long as you just need to specify 5 fields it is imo ok to just type them, for longer ranges you can use a for loop:

awk '{for(i=100;i<=105;i++)print $i}' myfile > outfile

If you want to use cut, you need to use the -f option:

cut -f100-105 myfile > outfile

If the field delimiter is different from TAB you need to specify it using -d:

cut -d' ' -f100-105 myfile > outfile

Check the man page for more info on the cut command.

Convert web page to image

Somebody wrote a blog post about this a few years back. There are examples in several languages, using both WebKit and Mozilla. There's also an example in Ruby.

It boils down to this: decide how wide you want your window to be; put a browser component in the window; wait until the page loads; capture the pixel buffer contents.

Best way to change the background color for an NSView

In Swift 3, you can create an extension to do it:

extension NSView {
    func setBackgroundColor(_ color: NSColor) {
        wantsLayer = true
        layer?.backgroundColor = color.cgColor
    }
}

// how to use
btn.setBackgroundColor(NSColor.gray)

Regular expression replace in C#

You can do it this with two replace's

//let stw be "John Smith $100,000.00 M"

sb_trim = Regex.Replace(stw, @"\s+\$|\s+(?=\w+$)", ",");
//sb_trim becomes "John Smith,100,000.00,M"

sb_trim = Regex.Replace(sb_trim, @"(?<=\d),(?=\d)|[.]0+(?=,)", "");
//sb_trim becomes "John Smith,100000,M"

sw.WriteLine(sb_trim);

Sibling package imports

I don't yet have the comprehension of Pythonology necessary to see the intended way of sharing code amongst unrelated projects without a sibling/relative import hack. Until that day, this is my solution. For examples or tests to import stuff from ..\api, it would look like:

import sys.path
import os.path
# Import from sibling directory ..\api
sys.path.append(os.path.dirname(os.path.abspath(__file__)) + "/..")
import api.api
import api.api_key

SQL Server Restore Error - Access is Denied

I was having the same problem. It turned out that my SQL Server and SQL Server Agent services logon as were running under the Network Services account which didn't have write access to perform the restore of the back up.

I changed both of these services to logon on as Local System Account and this fixed the problem.

How to convert an Array to a Set in Java

Set<T> b = new HashSet<>(Arrays.asList(requiredArray));

How to return a custom object from a Spring Data JPA GROUP BY query

define a custom pojo class say sureveyQueryAnalytics and store the query returned value in your custom pojo class

@Query(value = "select new com.xxx.xxx.class.SureveyQueryAnalytics(s.answer, count(sv)) from Survey s group by s.answer")
List<SureveyQueryAnalytics> calculateSurveyCount();

How can I count the rows with data in an Excel sheet?

You should use the sumif function in Excel:

=SUMIF(A5:C10;"Text_to_find";C5:C10)

This function takes a range like this square A5:C10 then you have some text to find this text can be in A or B then it will add the number from the C-row.

asp.net mvc3 return raw html to view

That looks fine, unless you want to pass it as Model string

public class HomeController : Controller
{
    public ActionResult Index()
    {
        string model = "<HTML></HTML>";
        return View(model);
    }
}

@model string
@{
    ViewBag.Title = "Index";
}

@Html.Raw(Model)

How do I round a double to two decimal places in Java?

Here is an easy way that guarantee to output the myFixedNumber rounded to two decimal places:

import java.text.DecimalFormat;

public class TwoDecimalPlaces {
    static double myFixedNumber = 98765.4321;
    public static void main(String[] args) {

        System.out.println(new DecimalFormat("0.00").format(myFixedNumber));
    }
}

The result is: 98765.43

Interfaces with static fields in java for sharing 'constants'

It's generally considered bad practice. The problem is that the constants are part of the public "interface" (for want of a better word) of the implementing class. This means that the implementing class is publishing all of these values to external classes even when they are only required internally. The constants proliferate throughout the code. An example is the SwingConstants interface in Swing, which is implemented by dozens of classes that all "re-export" all of its constants (even the ones that they don't use) as their own.

But don't just take my word for it, Josh Bloch also says it's bad:

The constant interface pattern is a poor use of interfaces. That a class uses some constants internally is an implementation detail. Implementing a constant interface causes this implementation detail to leak into the class's exported API. It is of no consequence to the users of a class that the class implements a constant interface. In fact, it may even confuse them. Worse, it represents a commitment: if in a future release the class is modified so that it no longer needs to use the constants, it still must implement the interface to ensure binary compatibility. If a nonfinal class implements a constant interface, all of its subclasses will have their namespaces polluted by the constants in the interface.

An enum may be a better approach. Or you could simply put the constants as public static fields in a class that cannot be instantiated. This allows another class to access them without polluting its own API.

How to filter data in dataview

Eg:

Datatable newTable =  new DataTable();

            foreach(string s1 in list)
            {
                if (s1 != string.Empty) {
                    dvProducts.RowFilter = "(CODE like '" + serachText + "*') AND (CODE <> '" + s1 + "')";
                    foreach(DataRow dr in dvProducts.ToTable().Rows)
                    {
                       newTable.ImportRow(dr);
                    }
                }
            }
ListView1.DataSource = newTable;
ListView1.DataBind();

Get raw POST body in Python Flask regardless of Content-Type header

request.data will be empty if request.headers["Content-Type"] is recognized as form data, which will be parsed into request.form. To get the raw data regardless of content type, use request.get_data().

request.data calls request.get_data(parse_form_data=True), which results in the different behavior for form data.

Error Message : Cannot find or open the PDB file

Working with VS 2013. Try the following Tools -> Options -> Debugging -> Output Window -> Module Load Messages -> Off It will disable the display of modules loaded.

Is it better in C++ to pass by value or pass by constant reference?

Simple difference :- In function we have input and output parameter , so if your passing input and out parameter is same then use call by reference else if input and output parameter are different then better to use call by value .

example void amount(int account , int deposit , int total )

input parameter : account , deposit output paramteter: total

input and out is different use call by vaule

  1. void amount(int total , int deposit )

input total deposit output total

Building executable jar with maven?

Actually, I think that the answer given in the question you mentioned is just wrong (UPDATE - 20101106: someone fixed it, this answer refers to the version preceding the edit) and this explains, at least partially, why you run into troubles.


It generates two jar files in logmanager/target: logmanager-0.1.0.jar, and logmanager-0.1.0-jar-with-dependencies.jar.

The first one is the JAR of the logmanager module generated during the package phase by jar:jar (because the module has a packaging of type jar). The second one is the assembly generated by assembly:assembly and should contain the classes from the current module and its dependencies (if you used the descriptor jar-with-dependencies).

I get an error when I double-click on the first jar:

Could not find the main class: com.gorkwobble.logmanager.LogManager. Program will exit.

If you applied the suggested configuration of the link posted as reference, you configured the jar plugin to produce an executable artifact, something like this:

  <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-jar-plugin</artifactId>
    <configuration>
      <archive>
        <manifest>
          <addClasspath>true</addClasspath>
          <mainClass>com.gorkwobble.logmanager.LogManager</mainClass>
        </manifest>
      </archive>
    </configuration>
  </plugin>

So logmanager-0.1.0.jar is indeed executable but 1. this is not what you want (because it doesn't have all dependencies) and 2. it doesn't contain com.gorkwobble.logmanager.LogManager (this is what the error is saying, check the content of the jar).

A slightly different error when I double-click the jar-with-dependencies.jar:

Failed to load Main-Class manifest attribute from: C:\EclipseProjects\logmanager\target\logmanager-0.1.0-jar-with-dependencies.jar

Again, if you configured the assembly plugin as suggested, you have something like this:

  <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-assembly-plugin</artifactId>
    <configuration>
      <descriptorRefs>
        <descriptorRef>jar-with-dependencies</descriptorRef>
      </descriptorRefs>
    </configuration>
  </plugin>

With this setup, logmanager-0.1.0-jar-with-dependencies.jar contains the classes from the current module and its dependencies but, according to the error, its META-INF/MANIFEST.MF doesn't contain a Main-Class entry (its likely not the same MANIFEST.MF as in logmanager-0.1.0.jar). The jar is actually not executable, which again is not what you want.


So, my suggestion would be to remove the configuration element from the maven-jar-plugin and to configure the maven-assembly-plugin like this:

  <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-jar-plugin</artifactId>
    <version>2.2</version>
    <!-- nothing here -->
  </plugin>
  <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-assembly-plugin</artifactId>
    <version>2.2-beta-4</version>
    <configuration>
      <descriptorRefs>
        <descriptorRef>jar-with-dependencies</descriptorRef>
      </descriptorRefs>
      <archive>
        <manifest>
          <mainClass>org.sample.App</mainClass>
        </manifest>
      </archive>
    </configuration>
    <executions>
      <execution>
        <phase>package</phase>
        <goals>
          <goal>single</goal>
        </goals>
      </execution>
    </executions>
  </plugin>

Of course, replace org.sample.App with the class you want to have executed. Little bonus, I've bound assembly:single to the package phase so you don't have to run assembly:assembly anymore. Just run mvn install and the assembly will be produced during the standard build.

So, please update your pom.xml with the configuration given above and run mvn clean install. Then, cd into the target directory and try again:

java -jar logmanager-0.1.0-jar-with-dependencies.jar

If you get an error, please update your question with it and post the content of the META-INF/MANIFEST.MF file and the relevant part of your pom.xml (the plugins configuration parts). Also please post the result of:

java -cp logmanager-0.1.0-jar-with-dependencies.jar com.gorkwobble.logmanager.LogManager

to demonstrate it's working fine on the command line (regardless of what eclipse is saying).

EDIT: For Java 6, you need to configure the maven-compiler-plugin. Add this to your pom.xml:

  <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <configuration>
      <source>1.6</source>
      <target>1.6</target>
    </configuration>
  </plugin>

How to create a shared library with cmake?

First, this is the directory layout that I am using:

.
+-- include
¦   +-- class1.hpp
¦   +-- ...
¦   +-- class2.hpp
+-- src
    +-- class1.cpp
    +-- ...
    +-- class2.cpp

After a couple of days taking a look into this, this is my favourite way of doing this thanks to modern CMake:

cmake_minimum_required(VERSION 3.5)
project(mylib VERSION 1.0.0 LANGUAGES CXX)

set(DEFAULT_BUILD_TYPE "Release")

if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES)
  message(STATUS "Setting build type to '${DEFAULT_BUILD_TYPE}' as none was specified.")
  set(CMAKE_BUILD_TYPE "${DEFAULT_BUILD_TYPE}" CACHE STRING "Choose the type of build." FORCE)
  # Set the possible values of build type for cmake-gui
  set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS "Debug" "Release" "MinSizeRel" "RelWithDebInfo")
endif()

include(GNUInstallDirs)

set(SOURCE_FILES src/class1.cpp src/class2.cpp)

add_library(${PROJECT_NAME} ...)

target_include_directories(${PROJECT_NAME} PUBLIC
    $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
    $<INSTALL_INTERFACE:include>
    PRIVATE src)

set_target_properties(${PROJECT_NAME} PROPERTIES
    VERSION ${PROJECT_VERSION}
    SOVERSION 1)

install(TARGETS ${PROJECT_NAME} EXPORT MyLibConfig
    ARCHIVE  DESTINATION ${CMAKE_INSTALL_LIBDIR}
    LIBRARY  DESTINATION ${CMAKE_INSTALL_LIBDIR}
    RUNTIME  DESTINATION ${CMAKE_INSTALL_BINDIR})
install(DIRECTORY include/ DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/${PROJECT_NAME})

install(EXPORT MyLibConfig DESTINATION share/MyLib/cmake)

export(TARGETS ${PROJECT_NAME} FILE MyLibConfig.cmake)

After running CMake and installing the library, there is no need to use Find***.cmake files, it can be used like this:

find_package(MyLib REQUIRED)

#No need to perform include_directories(...)
target_link_libraries(${TARGET} mylib)

That's it, if it has been installed in a standard directory it will be found and there is no need to do anything else. If it has been installed in a non-standard path, it is also easy, just tell CMake where to find MyLibConfig.cmake using:

cmake -DMyLib_DIR=/non/standard/install/path ..

I hope this helps everybody as much as it has helped me. Old ways of doing this were quite cumbersome.

ASP.NET MVC - Find Absolute Path to the App_Data folder from Controller

The most correct way is to use HttpContext.Current.Server.MapPath("~/App_Data");. This means you can only retrieve the path from a method where the HttpContext is available. It makes sense: the App_Data directory is a web project folder structure [1].

If you need the path to ~/App_Data from a class where you don't have access to the HttpContext you can always inject a provider interface using your IoC container:

public interface IAppDataPathProvider
{
    string GetAppDataPath();
}

Implement it using your HttpApplication:

public class AppDataPathProvider : IAppDataPathProvider
{
    public string GetAppDataPath()
    {
        return MyHttpApplication.GetAppDataPath();
    }
}

Where MyHttpApplication.GetAppDataPath looks like:

public class MyHttpApplication : HttpApplication
{
    // of course you can fetch&store the value at Application_Start
    public static string GetAppDataPath()
    {
        return HttpContext.Current.Server.MapPath("~/App_Data");
    }
}

[1] http://msdn.microsoft.com/en-us/library/ex526337%28v=vs.100%29.aspx

Passing multiple values for same variable in stored procedure

You will need to do a couple of things to get this going, since your parameter is getting multiple values you need to create a Table Type and make your store procedure accept a parameter of that type.

Split Function Works Great when you are getting One String containing multiple values but when you are passing Multiple values you need to do something like this....

TABLE TYPE

CREATE TYPE dbo.TYPENAME AS TABLE   (     arg int    )  GO 

Stored Procedure to Accept That Type Param

 CREATE PROCEDURE mainValues   @TableParam TYPENAME READONLY  AS     BEGIN     SET NOCOUNT ON;   --Temp table to store split values   declare @tmp_values table (   value nvarchar(255) not null);        --function splitting values     INSERT INTO @tmp_values (value)    SELECT arg FROM @TableParam      SELECT * FROM @tmp_values  --<-- For testing purpose END 

EXECUTE PROC

Declare a variable of that type and populate it with your values.

 DECLARE @Table TYPENAME     --<-- Variable of this TYPE   INSERT INTO @Table                --<-- Populating the variable   VALUES (331),(222),(876),(932)  EXECUTE mainValues @Table   --<-- Stored Procedure Executed  

Result

╔═══════╗ ║ value ║ ╠═══════╣ ║   331 ║ ║   222 ║ ║   876 ║ ║   932 ║ ╚═══════╝ 

Remove a child with a specific attribute, in SimpleXML for PHP

This work for me:

$data = '<data>
<seg id="A1"/>
<seg id="A5"/>
<seg id="A12"/>
<seg id="A29"/>
<seg id="A30"/></data>';

$doc = new SimpleXMLElement($data);

$segarr = $doc->seg;

$count = count($segarr);

$j = 0;

for ($i = 0; $i < $count; $i++) {

    if ($segarr[$j]['id'] == 'A12') {
        unset($segarr[$j]);
        $j = $j - 1;
    }
    $j = $j + 1;
}

echo $doc->asXml();

Best way to check if a drop down list contains a value?

//you can use the ? operator instead of if

ddlCustomerNumber.SelectedValue = ddlType.Items.FindByValue(GetCustomerNumberCookie().ToString()) != null ? GetCustomerNumberCookie().ToString() : "0";

Rounding up to next power of 2

Assuming you have a good compiler & it can do the bit twiddling before hand thats above me at this point, but anyway this works!!!

    // http://graphics.stanford.edu/~seander/bithacks.html#IntegerLogObvious
    #define SH1(v)  ((v-1) | ((v-1) >> 1))            // accidently came up w/ this...
    #define SH2(v)  ((v) | ((v) >> 2))
    #define SH4(v)  ((v) | ((v) >> 4))
    #define SH8(v)  ((v) | ((v) >> 8))
    #define SH16(v) ((v) | ((v) >> 16))
    #define OP(v) (SH16(SH8(SH4(SH2(SH1(v))))))         

    #define CB0(v)   ((v) - (((v) >> 1) & 0x55555555))
    #define CB1(v)   (((v) & 0x33333333) + (((v) >> 2) & 0x33333333))
    #define CB2(v)   ((((v) + ((v) >> 4) & 0xF0F0F0F) * 0x1010101) >> 24)
    #define CBSET(v) (CB2(CB1(CB0((v)))))
    #define FLOG2(v) (CBSET(OP(v)))

Test code below:

#include <iostream>

using namespace std;

// http://graphics.stanford.edu/~seander/bithacks.html#IntegerLogObvious
#define SH1(v)  ((v-1) | ((v-1) >> 1))  // accidently guess this...
#define SH2(v)  ((v) | ((v) >> 2))
#define SH4(v)  ((v) | ((v) >> 4))
#define SH8(v)  ((v) | ((v) >> 8))
#define SH16(v) ((v) | ((v) >> 16))
#define OP(v) (SH16(SH8(SH4(SH2(SH1(v))))))         

#define CB0(v)   ((v) - (((v) >> 1) & 0x55555555))
#define CB1(v)   (((v) & 0x33333333) + (((v) >> 2) & 0x33333333))
#define CB2(v)   ((((v) + ((v) >> 4) & 0xF0F0F0F) * 0x1010101) >> 24)
#define CBSET(v) (CB2(CB1(CB0((v)))))
#define FLOG2(v) (CBSET(OP(v))) 

#define SZ4         FLOG2(4)
#define SZ6         FLOG2(6)
#define SZ7         FLOG2(7)
#define SZ8         FLOG2(8) 
#define SZ9         FLOG2(9)
#define SZ16        FLOG2(16)
#define SZ17        FLOG2(17)
#define SZ127       FLOG2(127)
#define SZ1023      FLOG2(1023)
#define SZ1024      FLOG2(1024)
#define SZ2_17      FLOG2((1ul << 17))  // 
#define SZ_LOG2     FLOG2(SZ)

#define DBG_PRINT(x) do { std::printf("Line:%-4d" "  %10s = %-10d\n", __LINE__, #x, x); } while(0);

uint32_t arrTble[FLOG2(63)];

int main(){
    int8_t n;

    DBG_PRINT(SZ4);    
    DBG_PRINT(SZ6);    
    DBG_PRINT(SZ7);    
    DBG_PRINT(SZ8);    
    DBG_PRINT(SZ9); 
    DBG_PRINT(SZ16);
    DBG_PRINT(SZ17);
    DBG_PRINT(SZ127);
    DBG_PRINT(SZ1023);
    DBG_PRINT(SZ1024);
    DBG_PRINT(SZ2_17);

    return(0);
}

Outputs:

Line:39           SZ4 = 2
Line:40           SZ6 = 3
Line:41           SZ7 = 3
Line:42           SZ8 = 3
Line:43           SZ9 = 4
Line:44          SZ16 = 4
Line:45          SZ17 = 5
Line:46         SZ127 = 7
Line:47        SZ1023 = 10
Line:48        SZ1024 = 10
Line:49        SZ2_16 = 17

Visual Studio 64 bit?

No, but the 32-bit version runs just fine on 64-bit Windows.

Failed to load JavaHL Library

You may or may not need JavaHL depending on your OS. In addition to other suggestions just posting this here.

enter image description here

For other OS see this source: http://subclipse.tigris.org/wiki/JavaHL

how to kill hadoop jobs

Run list to show all the jobs, then use the jobID/applicationID in the appropriate command.

Kill mapred jobs:

mapred job -list
mapred job -kill <jobId>

Kill yarn jobs:

yarn application -list
yarn application -kill <ApplicationId>

How to spawn a process and capture its STDOUT in .NET?

It looks like two of your lines are out of order. You start the process before setting up an event handler to capture the output. It's possible the process is just finishing before the event handler is added.

Switch the lines like so.

p.OutputDataReceived += ...
p.Start();        

NULL vs nullptr (Why was it replaced?)

One reason: the literal 0 has a bad tendency to acquire the type int, e.g. in perfect argument forwarding or more in general as argument with templated type.

Another reason: readability and clarity of code.

What algorithm for a tic-tac-toe game can I use to determine the "best move" for the AI?

A typical algo for tic-tac-toe should look like this:

Board : A nine-element vector representing the board. We store 2 (indicating Blank), 3 (indicating X), or 5 (indicating O). Turn: An integer indicating which move of the game about to be played. The 1st move will be indicated by 1, last by 9.

The Algorithm

The main algorithm uses three functions.

Make2: returns 5 if the center square of the board is blank i.e. if board[5]=2. Otherwise, this function returns any non-corner square (2, 4, 6 or 8).

Posswin(p): Returns 0 if player p can’t win on his next move; otherwise, it returns the number of the square that constitutes a winning move. This function will enable the program both to win and to block opponents win. This function operates by checking each of the rows, columns, and diagonals. By multiplying the values of each square together for an entire row (or column or diagonal), the possibility of a win can be checked. If the product is 18 (3 x 3 x 2), then X can win. If the product is 50 (5 x 5 x 2), then O can win. If a winning row (column or diagonal) is found, the blank square in it can be determined and the number of that square is returned by this function.

Go (n): makes a move in square n. this procedure sets board [n] to 3 if Turn is odd, or 5 if Turn is even. It also increments turn by one.

The algorithm has a built-in strategy for each move. It makes the odd numbered move if it plays X, the even-numbered move if it plays O.

Turn = 1    Go(1)   (upper left corner).
Turn = 2    If Board[5] is blank, Go(5), else Go(1).
Turn = 3    If Board[9] is blank, Go(9), else Go(3).
Turn = 4    If Posswin(X) is not 0, then Go(Posswin(X)) i.e. [ block opponent’s win], else Go(Make2).
Turn = 5    if Posswin(X) is not 0 then Go(Posswin(X)) [i.e. win], else if Posswin(O) is not 0, then Go(Posswin(O)) [i.e. block win], else if Board[7] is blank, then Go(7), else Go(3). [to explore other possibility if there be any ].
Turn = 6    If Posswin(O) is not 0 then Go(Posswin(O)), else if Posswin(X) is not 0, then Go(Posswin(X)), else Go(Make2).
Turn = 7    If Posswin(X) is not 0 then Go(Posswin(X)), else if Posswin(X) is not 0, then Go(Posswin(O)) else go anywhere that is blank.
Turn = 8    if Posswin(O) is not 0 then Go(Posswin(O)), else if Posswin(X) is not 0, then Go(Posswin(X)), else go anywhere that is blank.
Turn = 9    Same as Turn=7.

I have used it. Let me know how you guys feel.

Entity Framework select distinct name

Try this:

var results = (from ta in context.TestAddresses
               select ta.Name).Distinct();

This will give you an IEnumerable<string> - you can call .ToList() on it to get a List<string>.

Plotting dates on the x-axis with Python's matplotlib

I have too low reputation to add comment to @bernie response, with response to @user1506145. I have run in to same issue.

1

The answer to it is a interval parameter which fixes things up

2

import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import numpy as np
import datetime as dt

np.random.seed(1)

N = 100
y = np.random.rand(N)

now = dt.datetime.now()
then = now + dt.timedelta(days=100)
days = mdates.drange(now,then,dt.timedelta(days=1))

plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
plt.gca().xaxis.set_major_locator(mdates.DayLocator(interval=5))
plt.plot(days,y)
plt.gcf().autofmt_xdate()
plt.show()

Postgresql - select something where date = "01/01/11"

With PostgreSQL there are a number of date/time functions available, see here.

In your example, you could use:

SELECT * FROM myTable WHERE date_trunc('day', dt) = 'YYYY-MM-DD';

If you are running this query regularly, it is possible to create an index using the date_trunc function as well:

CREATE INDEX date_trunc_dt_idx ON myTable ( date_trunc('day', dt) );

One advantage of this is there is some more flexibility with timezones if required, for example:

CREATE INDEX date_trunc_dt_idx ON myTable ( date_trunc('day', dt at time zone 'Australia/Sydney') );
SELECT * FROM myTable WHERE date_trunc('day', dt at time zone 'Australia/Sydney') = 'YYYY-MM-DD';

Error: [$injector:unpr] Unknown provider: $routeProvider

In angular 1.4 +, in addition to adding the dependency

angular.module('myApp', ['ngRoute'])

,we also need to reference the separate angular-route.js file

<script src="angular.js">
<script src="angular-route.js">

see https://docs.angularjs.org/api/ngRoute

How to get SLF4J "Hello World" working with log4j?

I had the same problem. I called my own custom logger in the log4j.properties file from code when using log4j api directly. If you are using the slf4j api calls, you are probably using the default root logger so you must configure that to be associated with an appender in the log4j.properties:


    # Set root logger level to DEBUG and its only appender to A1.
    log4j.rootLogger=DEBUG, A1

    # A1 is set to be a ConsoleAppender.
    log4j.appender.A1=org.apache.log4j.ConsoleAppender

How to install SimpleJson Package for Python

Really simple way is:

pip install simplejson

How to check if spark dataframe is empty?

If you do df.count > 0. It takes the counts of all partitions across all executors and add them up at Driver. This take a while when you are dealing with millions of rows.

The best way to do this is to perform df.take(1) and check if its null. This will return java.util.NoSuchElementException so better to put a try around df.take(1).

The dataframe return an error when take(1) is done instead of an empty row. I have highlighted the specific code lines where it throws the error.

enter image description here

How to execute a .sql script from bash

If you want to run a script to a database:

mysql -u user -p data_base_name_here < db.sql

How to Cast Objects in PHP

If the object you are trying to cast from or to has properties that are also user-defined classes, and you don't want to go through reflection, you can use this.

<?php
declare(strict_types=1);
namespace Your\Namespace\Here
{
  use Zend\Logger; // or your logging mechanism of choice
  final class OopFunctions
  {
    /**
     * @param object $from
     * @param object $to
     * @param Logger $logger
     *
     * @return object
     */
     static function Cast($from, $to, $logger)
    {
      $logger->debug($from);
      $fromSerialized = serialize($from);
      $fromName = get_class($from);
      $toName = get_class($to);
      $toSerialized = str_replace($fromName, $toName, $fromSerialized);
      $toSerialized = preg_replace("/O:\d*:\"([^\"]*)/", "O:" . strlen($toName) . ":\"$1", $toSerialized);
      $toSerialized = preg_replace_callback(
        "/s:\d*:\"[^\"]*\"/", 
        function ($matches)
        {
          $arr = explode(":", $matches[0]);
          $arr[1] = mb_strlen($arr[2]) - 2;
          return implode(":", $arr);
        }, 
        $toSerialized
      );
      $to = unserialize($toSerialized);
      $logger->debug($to);
      return $to;
    }
  }
}

Display Back Arrow on Toolbar

Simple and easy way to show back button on toolbar

Paste this code in onCreate method

 if (getSupportActionBar() != null){

            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setDisplayShowHomeEnabled(true);
        }

Paste this override method outside the onCreate method

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if(item.getItemId()== android.R.id.home) {

        finish();
    }
    return super.onOptionsItemSelected(item);
}

How do I stop Notepad++ from showing autocomplete for all words in the file

Notepad++ provides 2 types of features:

  • Auto-completion that read the open file and provide suggestion of words and/or functions within the file
  • Suggestion with the arguments of functions (specific to the language)

Based on what you write, it seems what you want is auto-completion on function only + suggestion on arguments.

To do that, you just need to change a setting.

  1. Go to Settings > Preferences... > Auto-completion
  2. Check Enable Auto-completion on each input
  3. Select Function completion and not Word completion
  4. Check Function parameter hint on input (if you have this option)

On version 6.5.5 of Notepad++, I have this setting settings

Some documentation about auto-completion is available in Notepad++ Wiki.

java.net.SocketException: Software caused connection abort: recv failed

This error occurs when a connection is closed abruptly (when a TCP connection is reset while there is still data in the send buffer). The condition is very similar to a much more common 'Connection reset by peer'. It can happen sporadically when connecting over the Internet, but also systematically if the timing is right (e.g. with keep-alive connections on localhost).

An HTTP client should just re-open the connection and retry the request. It is important to understand that when a connection is in this state, there is no way out of it other than to close it. Any attempt to send or receive will produce the same error.

Don't use URL.open(), use Apache-Commons HttpClient which has a retry mechanism, connection pooling, keep-alive and many other features.

Sample usage:

HttpClient httpClient = HttpClients.custom()
            .setConnectionTimeToLive(20, TimeUnit.SECONDS)
            .setMaxConnTotal(400).setMaxConnPerRoute(400)
            .setDefaultRequestConfig(RequestConfig.custom()
                    .setSocketTimeout(30000).setConnectTimeout(5000).build())
            .setRetryHandler(new DefaultHttpRequestRetryHandler(5, true))
            .build();
// the httpClient should be re-used because it is pooled and thread-safe.

HttpGet request = new HttpGet(uri);
HttpResponse response = httpClient.execute(request);
reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
// handle response ...

Eclipse Intellisense?

I've get closer to VisualStudio-like behaviour by setting the "Autocomplete Trigger for Java" to

.(abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ

and setting delay to 0.

Now I'd like to realize how to make it autocomplete method name when I press ( as VS's Intellisense does.

How can I invert color using CSS?

Here is a different approach using mix-blend-mode: difference, that will actually invert whatever the background is, not just a single colour:

_x000D_
_x000D_
div {_x000D_
  background-image: linear-gradient(to right, red, yellow, green, cyan, blue, violet);_x000D_
}_x000D_
p {_x000D_
  color: white;_x000D_
  mix-blend-mode: difference;_x000D_
}
_x000D_
<div>_x000D_
  <p>Lorem ipsum dolor sit amet, consectetur adipiscit elit, sed do</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Where does PostgreSQL store the database?

As suggested in "PostgreSQL database default location on Linux", under Linux you can find out using the following command:

ps aux | grep postgres | grep -- -D

Get int value from enum in C#

Since Enums can be any integral type (byte, int, short, etc.), a more robust way to get the underlying integral value of the enum would be to make use of the GetTypeCode method in conjunction with the Convert class:

enum Sides {
    Left, Right, Top, Bottom
}
Sides side = Sides.Bottom;

object val = Convert.ChangeType(side, side.GetTypeCode());
Console.WriteLine(val);

This should work regardless of the underlying integral type.

How to open a URL in a new Tab using JavaScript or jQuery?

Use window.open():

var win = window.open('http://stackoverflow.com/', '_blank');
if (win) {
    //Browser has allowed it to be opened
    win.focus();
} else {
    //Browser has blocked it
    alert('Please allow popups for this website');
}

Depending on the browsers implementation this will work

There is nothing you can do to make it open in a window rather than a tab.

How to check if an email address is real or valid using PHP

I have been searching for this same answer all morning and have pretty much found out that it's probably impossible to verify if every email address you ever need to check actually exists at the time you need to verify it. So as a work around, I kind of created a simple PHP script to verify that the email address is formatted correct and it also verifies that the domain name used is correct as well.

GitHub here https://github.com/DukeOfMarshall/PHP---JSON-Email-Verification/tree/master

<?php

# What to do if the class is being called directly and not being included in a script     via PHP
# This allows the class/script to be called via other methods like JavaScript

if(basename(__FILE__) == basename($_SERVER["SCRIPT_FILENAME"])){
$return_array = array();

if($_GET['address_to_verify'] == '' || !isset($_GET['address_to_verify'])){
    $return_array['error']              = 1;
    $return_array['message']            = 'No email address was submitted for verification';
    $return_array['domain_verified']    = 0;
    $return_array['format_verified']    = 0;
}else{
    $verify = new EmailVerify();

    if($verify->verify_formatting($_GET['address_to_verify'])){
        $return_array['format_verified']    = 1;

        if($verify->verify_domain($_GET['address_to_verify'])){
            $return_array['error']              = 0;
            $return_array['domain_verified']    = 1;
            $return_array['message']            = 'Formatting and domain have been verified';
        }else{
            $return_array['error']              = 1;
            $return_array['domain_verified']    = 0;
            $return_array['message']            = 'Formatting was verified, but verification of the domain has failed';
        }
    }else{
        $return_array['error']              = 1;
        $return_array['domain_verified']    = 0;
        $return_array['format_verified']    = 0;
        $return_array['message']            = 'Email was not formatted correctly';
    }
}

echo json_encode($return_array);

exit();
}

class EmailVerify {
public function __construct(){

}

public function verify_domain($address_to_verify){
    // an optional sender  
    $record = 'MX';
    list($user, $domain) = explode('@', $address_to_verify);
    return checkdnsrr($domain, $record);
}

public function verify_formatting($address_to_verify){
    if(strstr($address_to_verify, "@") == FALSE){
        return false;
    }else{
        list($user, $domain) = explode('@', $address_to_verify);

        if(strstr($domain, '.') == FALSE){
            return false;
        }else{
            return true;
        }
    }
    }
}
?>

How do I run Selenium in Xvfb?

You can use PyVirtualDisplay (a Python wrapper for Xvfb) to run headless WebDriver tests.

#!/usr/bin/env python

from pyvirtualdisplay import Display
from selenium import webdriver

display = Display(visible=0, size=(800, 600))
display.start()

# now Firefox will run in a virtual display. 
# you will not see the browser.
browser = webdriver.Firefox()
browser.get('http://www.google.com')
print browser.title
browser.quit()

display.stop()

more info


You can also use xvfbwrapper, which is a similar module (but has no external dependencies):

from xvfbwrapper import Xvfb

vdisplay = Xvfb()
vdisplay.start()

# launch stuff inside virtual display here

vdisplay.stop()

or better yet, use it as a context manager:

from xvfbwrapper import Xvfb

with Xvfb() as xvfb:
    # launch stuff inside virtual display here.
    # It starts/stops in this code block.

Removing elements from array Ruby

a = [1,1,1,2,2,3]
a.slice!(0) # remove first index
a.slice!(-1) # remove last index
# a = [1,1,2,2] as desired

Updating GUI (WPF) using a different thread

As akjoshi and Julio say this is about dispatching an Action to update the GUI on the same thread as the GUI item but from the method that is handling the background data. You can see this code in specific form in akjoshi's answer above. This is a general version.

myTextBlock.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
                                   new Action(delegate() 
                                      {
                                      myTextBlock.Text = Convert.ToString(myDataObject.getMeData());
                                      }));

The critical part is to call the dispatcher of your UI object - that ensures you have the correct thread.

From personal experience it seems much easier to create and use the Action inline like this. Declaring it at class level gave me lots of problems with static/non-static contexts.

Find the paths between two given nodes?

In Prolog (specifically, SWI-Prolog)

:- use_module(library(tabling)).

% path(+Graph,?Source,?Target,?Path)
:- table path/4.

path(_,N,N,[N]).
path(G,S,T,[S|Path]) :-
    dif(S,T),
    member(S-I, G), % directed graph
    path(G,I,T,Path).

test:

paths :- Graph =
    [ 1- 2  % node 1 and 2 are connected
    , 2- 3 
    , 2- 5 
    , 4- 2 
    , 5-11
    ,11-12
    , 6- 7 
    , 5- 6 
    , 3- 6 
    , 6- 8 
    , 8-10
    , 8- 9
    ],
    findall(Path, path(Graph,1,7,Path), Paths),
    maplist(writeln, Paths).

?- paths.
[1,2,3,6,7]
[1,2,5,6,7]
true.

C# convert int to string with padding zeros?

To pad int i to match the string length of int x, when both can be negative:

i.ToString().PadLeft((int)Math.Log10(Math.Abs(x < 0 ? x * 10 : x)) + 1, '0')

No output to console from a WPF application?

Right click on the project, "Properties", "Application" tab, change "Output Type" to "Console Application", and then it will also have a console.

How is Perl's @INC constructed? (aka What are all the ways of affecting where Perl modules are searched for?)

As it was said already @INC is an array and you're free to add anything you want.

My CGI REST script looks like:

#!/usr/bin/perl
use strict;
use warnings;
BEGIN {
    push @INC, 'fully_qualified_path_to_module_wiht_our_REST.pm';
}
use Modules::Rest;
gone(@_);

Subroutine gone is exported by Rest.pm.

set environment variable in python script

bash:

LD_LIBRARY_PATH=my_path
sqsub -np $1 /path/to/executable

Similar, in Python:

import os
import subprocess
import sys

os.environ['LD_LIBRARY_PATH'] = "my_path" # visible in this process + all children
subprocess.check_call(['sqsub', '-np', sys.argv[1], '/path/to/executable'],
                      env=dict(os.environ, SQSUB_VAR="visible in this subprocess"))

What are all the user accounts for IIS/ASP.NET and how do they differ?

This is a very good question and sadly many developers don't ask enough questions about IIS/ASP.NET security in the context of being a web developer and setting up IIS. So here goes....

To cover the identities listed:

IIS_IUSRS:

This is analogous to the old IIS6 IIS_WPG group. It's a built-in group with it's security configured such that any member of this group can act as an application pool identity.

IUSR:

This account is analogous to the old IUSR_<MACHINE_NAME> local account that was the default anonymous user for IIS5 and IIS6 websites (i.e. the one configured via the Directory Security tab of a site's properties).

For more information about IIS_IUSRS and IUSR see:

Understanding Built-In User and Group Accounts in IIS 7

DefaultAppPool:

If an application pool is configured to run using the Application Pool Identity feature then a "synthesised" account called IIS AppPool\<pool name> will be created on the fly to used as the pool identity. In this case there will be a synthesised account called IIS AppPool\DefaultAppPool created for the life time of the pool. If you delete the pool then this account will no longer exist. When applying permissions to files and folders these must be added using IIS AppPool\<pool name>. You also won't see these pool accounts in your computers User Manager. See the following for more information:

Application Pool Identities

ASP.NET v4.0: -

This will be the Application Pool Identity for the ASP.NET v4.0 Application Pool. See DefaultAppPool above.

NETWORK SERVICE: -

The NETWORK SERVICE account is a built-in identity introduced on Windows 2003. NETWORK SERVICE is a low privileged account under which you can run your application pools and websites. A website running in a Windows 2003 pool can still impersonate the site's anonymous account (IUSR_ or whatever you configured as the anonymous identity).

In ASP.NET prior to Windows 2008 you could have ASP.NET execute requests under the Application Pool account (usually NETWORK SERVICE). Alternatively you could configure ASP.NET to impersonate the site's anonymous account via the <identity impersonate="true" /> setting in web.config file locally (if that setting is locked then it would need to be done by an admin in the machine.config file).

Setting <identity impersonate="true"> is common in shared hosting environments where shared application pools are used (in conjunction with partial trust settings to prevent unwinding of the impersonated account).

In IIS7.x/ASP.NET impersonation control is now configured via the Authentication configuration feature of a site. So you can configure to run as the pool identity, IUSR or a specific custom anonymous account.

LOCAL SERVICE:

The LOCAL SERVICE account is a built-in account used by the service control manager. It has a minimum set of privileges on the local computer. It has a fairly limited scope of use:

LocalService Account

LOCAL SYSTEM:

You didn't ask about this one but I'm adding for completeness. This is a local built-in account. It has fairly extensive privileges and trust. You should never configure a website or application pool to run under this identity.

LocalSystem Account

In Practice:

In practice the preferred approach to securing a website (if the site gets its own application pool - which is the default for a new site in IIS7's MMC) is to run under Application Pool Identity. This means setting the site's Identity in its Application Pool's Advanced Settings to Application Pool Identity:

enter image description here

In the website you should then configure the Authentication feature:

enter image description here

Right click and edit the Anonymous Authentication entry:

enter image description here

Ensure that "Application pool identity" is selected:

enter image description here

When you come to apply file and folder permissions you grant the Application Pool identity whatever rights are required. For example if you are granting the application pool identity for the ASP.NET v4.0 pool permissions then you can either do this via Explorer:

enter image description here

Click the "Check Names" button:

enter image description here

Or you can do this using the ICACLS.EXE utility:

icacls c:\wwwroot\mysite /grant "IIS AppPool\ASP.NET v4.0":(CI)(OI)(M)

...or...if you site's application pool is called BobsCatPicBlogthen:

icacls c:\wwwroot\mysite /grant "IIS AppPool\BobsCatPicBlog":(CI)(OI)(M)

I hope this helps clear things up.

Update:

I just bumped into this excellent answer from 2009 which contains a bunch of useful information, well worth a read:

The difference between the 'Local System' account and the 'Network Service' account?

Click event doesn't work on dynamically generated elements

The Jquery .on works ok but I had some problems with the rendering implementing some of the solutions above. My problem using the .on is that somehow it was rendering the events differently than the .hover method.

Just fyi for anyone else that may also have the problem. I solved my problem by re-registering the hover event for the dynamically added item:

re-register the hover event because hover doesn't work for dynamically created items. so every time i create the new/dynamic item i add the hover code again. works perfectly

$('#someID div:last').hover(
    function() {
       //...
    },
    function() {
       //...
    }
);

Dynamically add data to a javascript map

Javascript now has a specific built in object called Map, you can call as follows :

   var myMap = new Map()

You can update it with .set :

   myMap.set("key0","value")

This has the advantage of methods you can use to handle look ups, like the boolean .has

  myMap.has("key1"); // evaluates to false 

You can use this before calling .get on your Map object to handle looking up non-existent keys

Python dictionary replace values

If you iterate over a dictionary you get the keys, so assuming your dictionary is in a variable called data and you have some function find_definition() which gets the definition, you can do something like the following:

for word in data:
    data[word] = find_definition(word)

dll missing in JDBC

Set java.library.path to a directory containing this DLL which Java uses to find native libraries. Specify -D switch on the command line

java -Djava.library.path=C:\Java\native\libs YourProgram

C:\Java\native\libs should contain sqljdbc_auth.dll

Look at this SO post if you are using Eclipse or at this blog if you want to set programatically.

AngularJS: how to implement a simple file upload with multipart form?

You can use the simple/lightweight ng-file-upload directive. It supports drag&drop, file progress and file upload for non-HTML5 browsers with FileAPI flash shim

<div ng-controller="MyCtrl">
  <input type="file" ngf-select="onFileSelect($files)" multiple>
</div>

JS:

//inject angular file upload directive.
angular.module('myApp', ['ngFileUpload']);

var MyCtrl = [ '$scope', 'Upload', function($scope, Upload) {
  $scope.onFileSelect = function($files) {
  Upload.upload({
    url: 'my/upload/url',
    file: $files,            
  }).progress(function(e) {
  }).then(function(data, status, headers, config) {
    // file is uploaded successfully
    console.log(data);
  }); 

}];

How do I center list items inside a UL element?

I have run into this issue before and found that sometimes padding is the issue.

By removing padding from the ul, any li's set to inline-block will be nicely centred:

_x000D_
_x000D_
* {_x000D_
 box-sizing: border-box;_x000D_
}_x000D_
_x000D_
ul {_x000D_
 width: 120px;_x000D_
 margin: auto;_x000D_
 text-align: center;_x000D_
 border: 1px solid black;_x000D_
}_x000D_
_x000D_
li {_x000D_
 display: inline-block;_x000D_
}_x000D_
_x000D_
ul.no_pad {_x000D_
 padding: 0;_x000D_
}_x000D_
_x000D_
p {_x000D_
 margin: auto;_x000D_
 text-align: center;_x000D_
}_x000D_
_x000D_
.break {_x000D_
 margin: 50px 10px;_x000D_
}
_x000D_
<div>  _x000D_
  <p>With Padding (Default Style)</p>_x000D_
            <ul class="with_pad">_x000D_
                <li>x</li>_x000D_
                <li>x</li>_x000D_
                <li>x</li>_x000D_
                <li>x</li>_x000D_
            </ul>_x000D_
  <div class="break"></div>_x000D_
  <p>No Padding (Padding: 0)</p>_x000D_
   <ul class="no_pad">_x000D_
                <li>x</li>_x000D_
                <li>x</li>_x000D_
                <li>x</li>_x000D_
                <li>x</li>_x000D_
            </ul>_x000D_
 <div>
_x000D_
_x000D_
_x000D_

Hope that helps anyone running into this same issue :)

Cheers,

Jake

C Program to find day of week given date

A one-liner is unlikely, but the strptime function can be used to parse your date format and the struct tm argument can be queried for its tm_wday member on systems that modify those fields automatically (e.g. some glibc implementations).

int get_weekday(char * str) {
  struct tm tm;
  memset((void *) &tm, 0, sizeof(tm));
  if (strptime(str, "%d-%m-%Y", &tm) != NULL) {
    time_t t = mktime(&tm);
    if (t >= 0) {
      return localtime(&t)->tm_wday; // Sunday=0, Monday=1, etc.
    }
  }
  return -1;
}

Or you could encode these rules to do some arithmetic in a really long single line:

  • 1 Jan 1900 was a Monday.
  • Thirty days has September, April, June and November; all the rest have thirty-one, saving February alone, which has twenty-eight, rain or shine, and on leap years, twenty-nine.
  • A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400.

EDIT: note that this solution only works for dates after the UNIX epoch (1970-01-01T00:00:00Z).

How to set root password to null

You can recover MySQL database server password with following five easy steps.

Step # 1: Stop the MySQL server process.

Step # 2: Start the MySQL (mysqld) server/daemon process with the --skip-grant-tables option so that it will not prompt for password.

Step # 3: Connect to mysql server as the root user.

Step # 4: Setup new mysql root account password i.e. reset mysql password.

Step # 5: Exit and restart the MySQL server.

Here are commands you need to type for each step (login as the root user):

Step # 1 : Stop mysql service

# /etc/init.d/mysql stop

Output:

Stopping MySQL database server: mysqld.

Step # 2: Start to MySQL server w/o password:

# mysqld_safe --skip-grant-tables &

Output:

[1] 5988
Starting mysqld daemon with databases from /var/lib/mysql
mysqld_safe[6025]: started

Step # 3: Connect to mysql server using mysql client:

# mysql -u root

Output:

Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 1 to server version: 4.1.15-Debian_1-log
Type 'help;' or '\h' for help. Type '\c' to clear the buffer.
mysql>

Step # 4: Setup new MySQL root user password

mysql> use mysql;
mysql> update user set password=PASSWORD("NEW-ROOT-PASSWORD") where User='root';
mysql> flush privileges;
mysql> quit

Step # 5: Stop MySQL Server:

# /etc/init.d/mysql stop

Output:

Stopping MySQL database server: mysqld
STOPPING server from pid file /var/run/mysqld/mysqld.pid
mysqld_safe[6186]: ended
[1]+  Done                    mysqld_safe --skip-grant-tables

Step # 6: Start MySQL server and test it

# /etc/init.d/mysql start
# mysql      
ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO) 
# mysql -u root -p

Source: http://www.cyberciti.biz/tips/recover-mysql-root-password.html

How to update/refresh specific item in RecyclerView

The problem is RecyclerView.Adatper does not provide any methods that return the index of element

public abstract static class Adapter<VH extends ViewHolder> {
  /**
   * returns index of the given element in adapter, return -1 if not exist
   */
  public int indexOf(Object elem);
}

My workaround is to create a map instance for (element, position)s

public class FriendAdapter extends RecyclerView.Adapter<MyViewHolder> {
  private Map<Friend, Integer> posMap ;
  private List<Friend> friends;

  public FriendAdapter(List<Friend> friends ) {
    this.friends = new ArrayList<>(friends);
    this.posMap = new HashMap<>();
    for(int i = 0; i < this.friends.size(); i++) {
      posMap.put(this.friends.get(i), i);
    }
  }

  public int indexOf(Friend friend) {
    Integer position = this.posMap.get(elem);
    return position == null ? -1 : position;
  }
  // skip other methods in class Adapter
}
  • the element type(here class Friend) should implements hashCode() and equals() because it is key in hashmap.

when an element changed,

  void someMethod() {
    Friend friend = ...;
    friend.setPhoneNumber('xxxxx');

    int position = friendAdapter.indexOf(friend);
    friendAdapter.notifyItemChanged(position);

  }

It is good to define an helper method

public class FriendAdapter extends extends RecyclerView.Adapter<MyViewHolder> {

  public void friendUpdated(Friend friend) {
    int position = this.indexOf(friend);
    this.notifyItemChanged(position);
  }
}

Map instance(Map<Friend, Integer> posMap) is not necessarily required. If map is not used, looping throughout list can find the position of an element.

How to disable Compatibility View in IE

If you're using ASP.NET MVC, I found Response.AddHeader("X-UA-Compatible", "IE=edge,chrome=1") in a code block in _Layout to work quite well:

@Code
    Response.AddHeader("X-UA-Compatible", "IE=edge,chrome=1")
End Code
<!DOCTYPE html>
everything else

How do I tell a Python script to use a particular version

I would use the shebang #!/usr/bin/python (first line of code) with the serial number of Python at the end ;)

Then run the Python file as a script, e.g., ./main.py from the command line, rather than python main.py.

It is the same when you want to run Python from a Linux command line.

'str' object does not support item assignment in Python

Python strings are immutable so what you are trying to do in C will be simply impossible in python. You will have to create a new string.

I would like to read some characters from a string and put it into other string.

Then use a string slice:

>>> s1 = 'Hello world!!'
>>> s2 = s1[6:12]
>>> print s2
world!

ASP.NET MVC: No parameterless constructor defined for this object

In my case, my class had the [Serializable] attribute.

You are required to have a constructor that takes no parameters if your class is [Serializable]

How can I sanitize user input with PHP?

PHP 5.2 introduced the filter_var function.

It supports a great deal of SANITIZE, VALIDATE filters.

http://php.net/manual/en/function.filter-var.php

UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block

I resolve the problem. It's very simple . if do you checking care the problem may be because the auxiliar variable has whitespace. Why ? I don't know but yus must use the trim() method and will resolve the problem

How do I divide in the Linux console?

Better way is to use "bc", an arbitrary precision calculator.

variable=$(echo "OPTIONS; OPERATIONS" | bc)

ex:

my_var=$(echo "scale=5; $temp_var/100 + $temp_var2" | bc)

where "scale=5" is accuracy.

man bc 

comes with several usage examples.

Random string generation with upper case letters and digits

you can now use a new library (python >= 3.6) chancepy here

from chancepy import Chance

random_string = Chance.string(length=10, pool="someLettersAndNumbers123")

CSS display: inline vs inline-block

Inline elements:

  1. respect left & right margins and padding, but not top & bottom
  2. cannot have a width and height set
  3. allow other elements to sit to their left and right.
  4. see very important side notes on this here.

Block elements:

  1. respect all of those
  2. force a line break after the block element
  3. acquires full-width if width not defined

Inline-block elements:

  1. allow other elements to sit to their left and right
  2. respect top & bottom margins and padding
  3. respect height and width

From W3Schools:

  • An inline element has no line break before or after it, and it tolerates HTML elements next to it.

  • A block element has some whitespace above and below it and does not tolerate any HTML elements next to it.

  • An inline-block element is placed as an inline element (on the same line as adjacent content), but it behaves as a block element.

When you visualize this, it looks like this:

CSS block vs inline vs inline-block

The image is taken from this page, which also talks some more about this subject.

How to test the `Mosquitto` server?

To test and see if you can access your MQTT server from outside world (outside of your VM or local machine), you can install one of the MQTT publishing and monitoring tools such as MQTT-Spy on your outside-world machine and then subscribe for '#" (meaning all the topics).

You can follow this by the method @hardillb mentioned in his answer above and test back and forth such as this:

On the machine with Mosquitto Server running, enter image description here

On the outside-word machine with mqtt-spy running, enter image description here

I have mainly mentioned mqtt-spy since it's multi-platform and easy to use. You can go with any other tool really. And also to my knowledge to run the mosquitto_sub and mosquitto_pub you need to have mosquitto-clients installed on your Linux machine running the test (in my case Ubuntu) which can be done easily by,

sudo apt-get install mosquitto-clients

How to sort Counter by value? - python

A rather nice addition to @MartijnPieters answer is to get back a dictionary sorted by occurrence since Collections.most_common only returns a tuple. I often couple this with a json output for handy log files:

from collections import Counter, OrderedDict

x = Counter({'a':5, 'b':3, 'c':7})
y = OrderedDict(x.most_common())

With the output:

OrderedDict([('c', 7), ('a', 5), ('b', 3)])
{
  "c": 7, 
  "a": 5, 
  "b": 3
}

DateTime's representation in milliseconds?

This other solution for covert datetime to unixtimestampmillis C#.

private static readonly DateTime UnixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

public static long GetCurrentUnixTimestampMillis()
{
    DateTime localDateTime, univDateTime;
    localDateTime = DateTime.Now;          
    univDateTime = localDateTime.ToUniversalTime();
    return (long)(univDateTime - UnixEpoch).TotalMilliseconds;
} 

Jenkins returned status code 128 with github

When I got a similar status code 128 error from Jenkins:

status code 128:
stdout: 
stderr: fatal: Couldn't find remote ref refs/heads/jenkins

    at org.jenkinsci.plugins.gitclient.CliGitAPIImpl.launchCommandIn(CliGitAPIImpl.java:2172)
    at org.jenkinsci.plugins.gitclient.CliGitAPIImpl.launchCommandWithCredentials(CliGitAPIImpl.java:1864)
    at org.jenkinsci.plugins.gitclient.CliGitAPIImpl.access$500(CliGitAPIImpl.java:78)
    at org.jenkinsci.plugins.gitclient.CliGitAPIImpl$1.execute(CliGitAPIImpl.java:545)
    at jenkins.plugins.git.GitSCMFileSystem$BuilderImpl.build(GitSCMFileSystem.java:358)
    at jenkins.scm.api.SCMFileSystem.of(SCMFileSystem.java:197)
    at jenkins.scm.api.SCMFileSystem.of(SCMFileSystem.java:173)
    at org.jenkinsci.plugins.workflow.cps.CpsScmFlowDefinition.create(CpsScmFlowDefinition.java:113)
    at org.jenkinsci.plugins.workflow.cps.CpsScmFlowDefinition.create(CpsScmFlowDefinition.java:67)
    at org.jenkinsci.plugins.workflow.job.WorkflowRun.run(WorkflowRun.java:299)
    at hudson.model.ResourceController.execute(ResourceController.java:97)
    at hudson.model.Executor.run(Executor.java:429)
Finished: FAILURE

It was because I hadn't pushed my new branch "jenkins" that had my Jenkinsfile. So the solution was to just push my changes

Calling Javascript function from server side

ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "scr", "javascript:test();", true);

Function return value in PowerShell

I pass around a simple Hashtable object with a single result member to avoid the return craziness as I also want to output to the console. It acts through pass by reference.

function sample-loop($returnObj) {
  for($i = 0; $i -lt 10; $i++) {
    Write-Host "loop counter: $i"
    $returnObj.result++
  }
}

function main-sample() {
  $countObj = @{ result = 0 }
  sample-loop -returnObj $countObj
  Write-Host "_____________"
  Write-Host "Total = " ($countObj.result)
}

main-sample

You can see real example usage at my GitHub project unpackTunes.

java.security.AccessControlException: Access denied (java.io.FilePermission

Just document it here on Windows you need to escape the \ character:

"e:\\directory\\-"

Comment out HTML and PHP together

You can also use this as a comment:

<?php
    /* get_sidebar(); */

?>

How to add List<> to a List<> in asp.net

  1. Use Concat or Union extension methods. You have to make sure that you have this direction using System.Linq; in order to use LINQ extensions methods.

  2. Use the AddRange method.

How to update Pandas from Anaconda and is it possible to use eclipse with this last

The answer above did not work for me (python 3.6, Anaconda, pandas 0.20.3). It worked with

conda install -c anaconda pandas 

Unfortunately I do not know how to help with Eclipse.

matplotlib: Group boxplots

Mock data:

df = pd.DataFrame({'Group':['A','A','A','B','C','B','B','C','A','C'],\
                  'Apple':np.random.rand(10),'Orange':np.random.rand(10)})
df = df[['Group','Apple','Orange']]

        Group    Apple     Orange
    0      A  0.465636  0.537723
    1      A  0.560537  0.727238
    2      A  0.268154  0.648927
    3      B  0.722644  0.115550
    4      C  0.586346  0.042896
    5      B  0.562881  0.369686
    6      B  0.395236  0.672477
    7      C  0.577949  0.358801
    8      A  0.764069  0.642724
    9      C  0.731076  0.302369

You can use the Seaborn library for these plots. First melt the dataframe to format data and then create the boxplot of your choice.

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
dd=pd.melt(df,id_vars=['Group'],value_vars=['Apple','Orange'],var_name='fruits')
sns.boxplot(x='Group',y='value',data=dd,hue='fruits')

enter image description here

Magento: Set LIMIT on collection

The way to do was looking at the code in code/core/Mage/Catalog/Model/Resource/Category/Flat/Collection.php at line 380 in Magento 1.7.2 on the function setPage($pageNum, $pageSize)

 $collection = Mage::getModel('model')
     ->getCollection()
     ->setCurPage(2) // 2nd page
     ->setPageSize(10); // 10 elements per pages

I hope this will help someone.

How do I change the hover over color for a hover over table in Bootstrap?

This was the most simple way to do it imo and it worked for me.

.table-hover tbody tr:hover td {
    background: aqua;
}

Not sure why you would want to change the heading color to the same hover color as the rows but if you do then you can use the above solutions. If you just want t

What's the difference between import java.util.*; and import java.util.Date; ?

The toString() implementation of java.util.Date does not depend on the way the class is imported. It always returns a nice formatted date.

The toString() you see comes from another class.

Specific import have precedence over wildcard imports.

in this case

import other.Date
import java.util.*

new Date();

refers to other.Date and not java.util.Date.

The odd thing is that

import other.*
import java.util.*

Should give you a compiler error stating that the reference to Date is ambiguous because both other.Date and java.util.Date matches.

gdb: "No symbol table is loaded"

I met this issue this morning because I used the same executable in DIFFERENT OSes: after compiling my program with gcc -ggdb -Wall test.c -o test in my Mac(10.15.2), I ran gdb with the executable in Ubuntu(16.04) in my VirtualBox.

Fix: recompile with the same command under Ubuntu, then you should be good.

How to make sure you don't get WCF Faulted state exception?

This error can also be caused by having zero methods tagged with the OperationContract attribute. This was my problem when building a new service and testing it a long the way.

javascript setTimeout() not working

Please change your code as follows:

<script>
    var button = document.getElementById("reactionTester");
    var start = document.getElementById("start");
    function init() {
        var startInterval/*in milliseconds*/ = Math.floor(Math.random()*30)*1000;
        setTimeout(startTimer,startInterval); 
    }
    function startTimer(){
        document.write("hey");
    }
</script>

See if that helps. Basically, the difference is references the 'startTimer' function instead of executing it.

How do I import/include MATLAB functions?

Solution for Windows

Go to File --> Set Path and add the folder containing the functions as Matlab files. (At least for Matlab 2007b on Vista)

json and empty array

null is a legal value (and reserved word) in JSON, but some environments do not have a "NULL" object (as opposed to a NULL value) and hence cannot accurately represent the JSON null. So they will sometimes represent it as an empty array.

Whether null is a legal value in that particular element of that particular API is entirely up to the API designer.

How to free memory in Java?

System.gc(); 

Runs the garbage collector.

Calling the gc method suggests that the Java Virtual Machine expend effort toward recycling unused objects in order to make the memory they currently occupy available for quick reuse. When control returns from the method call, the Java Virtual Machine has made a best effort to reclaim space from all discarded objects.

Not recommended.

Edit: I wrote the original response in 2009. It's now 2015.

Garbage collectors have gotten steadily better in the ~20 years Java's been around. At this point, if you're manually calling the garbage collector, you may want to consider other approaches:

  • If you're forcing GC on a limited number of machines, it may be worth having a load balancer point away from the current machine, waiting for it to finish serving to connected clients, timeout after some period for hanging connections, and then just hard-restart the JVM. This is a terrible solution, but if you're looking at System.gc(), forced-restarts may be a possible stopgap.
  • Consider using a different garbage collector. For example, the (new in the last six years) G1 collector is a low-pause model; it uses more CPU overall, but does it's best to never force a hard-stop on execution. Since server CPUs now almost all have multiple cores, this is A Really Good Tradeoff to have available.
  • Look at your flags tuning memory use. Especially in newer versions of Java, if you don't have that many long-term running objects, consider bumping up the size of newgen in the heap. newgen (young) is where new objects are allocated. For a webserver, everything created for a request is put here, and if this space is too small, Java will spend extra time upgrading the objects to longer-lived memory, where they're more expensive to kill. (If newgen is slightly too small, you're going to pay for it.) For example, in G1:
    • XX:G1NewSizePercent (defaults to 5; probably doesn't matter.)
    • XX:G1MaxNewSizePercent (defaults to 60; probably raise this.)
  • Consider telling the garbage collector you're not okay with a longer pause. This will cause more-frequent GC runs, to allow the system to keep the rest of it's constraints. In G1:
    • XX:MaxGCPauseMillis (defaults to 200.)

docker mounting volumes on host

Basically VOLUME and -v option are almost equal. These mean 'mount specific directory on your container'. For example, VOLUME /data and -v /data is exactly same meaning. If you run the image that have VOLUME /data or with -v /data option, /data directory is mounted your container. This directory doesn't belong to your container.

Imagine that You add some files to /data on the container, then commit the container into new image. There isn't any files on data directory because mounted /data directory is belong to original container.

$ docker run -it -v /data --name volume ubuntu:14.04 bash
root@2b5e0f2d37cd:/# cd /data
root@2b5e0f2d37cd:/data# touch 1 2 3 4 5 6 7 8 9
root@2b5e0f2d37cd:/data# cd /tmp
root@2b5e0f2d37cd:/tmp# touch 1 2 3 4 5 6 7 8 9
root@2b5e0f2d37cd:/tmp# exit
exit

$ docker commit volume nacyot/volume  
835cfe3d8d159622507ba3256bb1c0b0d6e7c1419ae32751ad0f925c40378945
nacyot $ docker run -it nacyot/volume
root@dbe335c7e64d:/# cd /data
root@dbe335c7e64d:/data# ls
root@dbe335c7e64d:/data# cd /tmp
root@dbe335c7e64d:/tmp# ls
1  2  3  4  5  6  7  8  9
root@dbe335c7e64d:/tmp# 
root@dbe335c7e64d:/tmp# 

This mounted directory like /data is used to store data that is not belong to your application. And you can predefine the data directory that is not belong to the container by using VOLUME.

A difference between Volume and -v option is that you can use -v option dynamically on starting container. It mean you can mount some directory dynamically. And another difference is that you can mount your host directory on your container by using -v

HTTP could not register URL http://+:8000/HelloWCF/. Your process does not have access rights to this namespace

You need some Administrator privilege to your account if your machine in local area network then you apply some administrator privilege to your User else you should start ide as Administrator...

Sql connection-string for localhost server

use this connection string :

Server=HARIHARAN-PC\SQLEXPRESS;Intial Catalog=persons;Integrated Security=True;

rename person with your database name

Get all validation errors from Angular 2 FormGroup

Or you can just use this library to get all errors, even from deep and dynamic forms.

npm i @naologic/forms

If you want to use the static function on your own forms

import {NaoFormStatic} from '@naologic/forms';
...
const errorsFlat = NaoFormStatic.getAllErrorsFlat(fg); 
console.log(errorsFlat);

If you want to use NaoFromGroup you can import and use it

import {NaoFormGroup, NaoFormControl, NaoValidators} from '@naologic/forms';
...
    this.naoFormGroup = new NaoFormGroup({
      firstName: new NaoFormControl('John'),
      lastName: new NaoFormControl('Doe'),
      ssn: new NaoFormControl('000 00 0000', NaoValidators.isSSN()),
    });

   const getFormErrors = this.naoFormGroup.getAllErrors();
   console.log(getFormErrors);
   // --> {first: {ok: false, isSSN: false, actualValue: "000 00 0000"}}

Read the full documentation

Attempted to read or write protected memory

For VS 2013, .NET Framework 4.5.1 also has a AccessViolationException bug (KB2915689) when dealing with SQL Server / TCP Sockets. Upgrading to .NET Framework 4.5.2 corrects this problem.

Reported VS.NET AccessViolationException

Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

Test if element is present using Selenium WebDriver?

To find a particular Element is present or not, we have to use findElements() method instead of findElement()..

int i=driver.findElements(By.xpath(".......")).size();
if(i=0)
System.out.println("Element is not present");
else
System.out.println("Element is present");

this is worked for me.. suggest me if i am wrong..

Oracle: SQL select date with timestamp

You can specify the whole day by doing a range, like so:

WHERE bk_date >= TO_DATE('2012-03-18', 'YYYY-MM-DD')
AND bk_date <  TO_DATE('2012-03-19', 'YYYY-MM-DD')

More simply you can use TRUNC:

WHERE TRUNC(bk_date) = TO_DATE('2012-03-18', 'YYYY-MM-DD')

TRUNC without parameter removes hours, minutes and seconds from a DATE.

Foreach Control in form, how can I do something to all the TextBoxes in my Form?

You can do the following:

foreach (Control X in this.Controls)
{
    TextBox tb = X as TextBox;
    if (tb != null)
    {
        string text = tb.Text;
        // Do something to text...
        tb.Text = string.Empty; // Clears it out...
    }
}

get the value of input type file , and alert if empty

HTML Code

<input type="file" name="image" id="uploadImage" size="30" />
<input type="submit" name="upload"  class="send_upload" value="upload" />

jQuery Code using bind method

$(document).ready(function() {
    $('#upload').bind("click",function() 
    { if(!$('#uploadImage').val()){
                alert("empty");
                return false;} });  });

Cannot serve WCF services in IIS on Windows 8

For Windows Server 2012, the solution is very similar to faester's (see above). From the Server Manager, click on Add roles and features, select the appropriate server, then select Features. Under .NET Framework 4.5 Features, you'll see WCF Services, and under that, you'll find HTTP Activation.

ASP.NET Web API - PUT & DELETE Verbs Not Allowed - IIS 8

Remove the WebDAV works perfectly for my case:

<modules>
  <remove name="WebDAVModule"/>
</modules>
<handlers>
  <remove name="WebDAV" />
  <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
  <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" 
       type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>

it always better to solve the problem through the web.config instead of going to fix it through the iis or machine.config to grantee it wouldn't happen if the app hosted at another machine

Java Runtime.getRuntime(): getting output from executing a command line program

@Senthil and @Arend answer (https://stackoverflow.com/a/5711150/2268559) mentioned ProcessBuilder. Here is the example using ProcessBuilder with specifying environment variables and working folder for the command:

    ProcessBuilder pb = new ProcessBuilder("ls", "-a", "-l");

    Map<String, String> env = pb.environment();
    // If you want clean environment, call env.clear() first
    //env.clear();
    env.put("VAR1", "myValue");
    env.remove("OTHERVAR");
    env.put("VAR2", env.get("VAR1") + "suffix");

    File workingFolder = new File("/home/user");
    pb.directory(workingFolder);

    Process proc = pb.start();

    BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));

    BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));

    // Read the output from the command:
    System.out.println("Here is the standard output of the command:\n");
    String s = null;
    while ((s = stdInput.readLine()) != null)
        System.out.println(s);

    // Read any errors from the attempted command:
    System.out.println("Here is the standard error of the command (if any):\n");
    while ((s = stdError.readLine()) != null)
        System.out.println(s);

rsync: how can I configure it to create target directory on server?

The -R, --relative option will do this.

For example: if you want to backup /var/named/chroot and create the same directory structure on the remote server then -R will do just that.

CentOS: Copy directory to another directory

To copy all files, including hidden files use:

cp -r /home/server/folder/test/. /home/server/

How to make Sonar ignore some classes for codeCoverage metric?

I am able to achieve the necessary code coverage exclusions by updating jacoco-maven-plugin configuration in pom.xml

<plugin>
                <groupId>org.jacoco</groupId>
                <artifactId>jacoco-maven-plugin</artifactId>
                <version>0.8.6</version>
                <executions>
                    <execution>
                        <id>pre-test</id>
                        <goals>
                            <goal>prepare-agent</goal>
                        </goals>
                        <configuration>
                            <propertyName>jacocoArgLine</propertyName>
                            <destFile>${project.test.result.directory}/jacoco/jacoco.exec</destFile>
                        </configuration>
                    </execution>
                    <execution>
                        <id>post-test</id>
                        <phase>test</phase>
                        <goals>
                            <goal>report</goal>
                        </goals>
                        <configuration>
                            <dataFile>${project.test.result.directory}/jacoco/jacoco.exec</dataFile>
                            <outputDirectory>${project.test.result.directory}/jacoco</outputDirectory>
                        </configuration>
                    </execution>
                </executions>
                <configuration>
                    <excludes>
                        <exclude>**/GlobalExceptionHandler*.*</exclude>
                        <exclude>**/ErrorResponse*.*</exclude>
                    </excludes>
                </configuration>
            </plugin>

this configuration excludes the GlobalExceptionHandler.java and ErrorResponse.java in the jacoco coverage.

And the following two lines does the same for sonar coverage .

    <sonar.exclusions> **/*GlobalExceptionHandler*.*, **/*ErrorResponse*.</sonar.exclusions>
        <sonar.coverage.exclusions> **/*GlobalExceptionHandler*.*, **/*ErrorResponse*.* </sonar.coverage.exclusions>

Create HTTP post request and receive response using C# console application

HttpWebRequest request =(HttpWebRequest)WebRequest.Create("some url");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 7.1; Trident/5.0)";
request.Accept = "/";
request.UseDefaultCredentials = true;
request.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
doc.Save(request.GetRequestStream());
HttpWebResponse resp = request.GetResponse() as HttpWebResponse;

Hope it helps

Revert a jQuery draggable object back to its original container on out event of droppable

In case anyone's interested, here's my solution to the problem. It works completely independently of the Draggable objects, by using events on the Droppable object instead. It works quite well:

$(function() {
    $(".draggable").draggable({
        opacity: .4,
        create: function(){$(this).data('position',$(this).position())},
        cursor:'move',
        start:function(){$(this).stop(true,true)}
    });

    $('.active').droppable({
        over: function(event, ui) {
            $(ui.helper).unbind("mouseup");
        },
        drop:function(event, ui){
            snapToMiddle(ui.draggable,$(this));
        },
        out:function(event, ui){
            $(ui.helper).mouseup(function() {
                snapToStart(ui.draggable,$(this)); 
            });
        }
    });
}); 

function snapToMiddle(dragger, target){
    var topMove = target.position().top - dragger.data('position').top + (target.outerHeight(true) - dragger.outerHeight(true)) / 2;
    var leftMove= target.position().left - dragger.data('position').left + (target.outerWidth(true) - dragger.outerWidth(true)) / 2;
    dragger.animate({top:topMove,left:leftMove},{duration:600,easing:'easeOutBack'});
}
function snapToStart(dragger, target){
    dragger.animate({top:0,left:0},{duration:600,easing:'easeOutBack'});
}