Programs & Examples On #Rawbytestring

How can I test an AngularJS service from the console?

TLDR: In one line the command you are looking for:

angular.element(document.body).injector().get('serviceName')

Deep dive

AngularJS uses Dependency Injection (DI) to inject services/factories into your components,directives and other services. So what you need to do to get a service is to get the injector of AngularJS first (the injector is responsible for wiring up all the dependencies and providing them to components).

To get the injector of your app you need to grab it from an element that angular is handling. For example if your app is registered on the body element you call injector = angular.element(document.body).injector()

From the retrieved injector you can then get whatever service you like with injector.get('ServiceName')

More information on that in this answer: Can't retrieve the injector from angular
And even more here: Call AngularJS from legacy code


Another useful trick to get the $scope of a particular element. Select the element with the DOM inspection tool of your developer tools and then run the following line ($0 is always the selected element):
angular.element($0).scope()

PHP: How to get referrer URL?

$_SERVER['HTTP_REFERER'];

But if you run a file (that contains the above code) by directly hitting the URL in the browser then you get the following error.

Notice: Undefined index: HTTP_REFERER

boto3 client NoRegionError: You must specify a region error only sometimes

Alternatively you can run the following (aws cli)

aws configure --profile $PROFILE_NAME

it'll prompt you for the region.

notice in ~/.aws/config it's:

[default]
region = ap-southeast-1
output = json

[profile prod]
region = ap-southeast-1
output = json

[profile profile name] in the square brackets

What's the name for hyphen-separated case?

My ECMAScript proposal for String.prototype.toKebabCase.

String.prototype.toKebabCase = function () {
  return this.valueOf().replace(/-/g, ' ').split('')
    .reduce((str, char) => char.toUpperCase() === char ?
      `${str} ${char}` :
      `${str}${char}`, ''
    ).replace(/ * /g, ' ').trim().replace(/ /g, '-').toLowerCase();
}

Getting "method not valid without suitable object" error when trying to make a HTTP request in VBA?

You probably haven't added a reference to Microsoft XML (any version) for Dim objHTTP As New MSXML2.XMLHTTP in the VBA window's Tools/References... dialog.

Also, it's a good idea to avoid using late binding (CreateObject...); better to use early binding (Dim objHTTP As New MSXML2.XMLHTTP), as early binding allows you to use Intellisense to list the members and do all sorts of design-time validation.

How can I invert color using CSS?

Add the same color of the background to the paragraph and then invert with CSS:

_x000D_
_x000D_
div {_x000D_
    background-color: #f00;_x000D_
}_x000D_
_x000D_
p { _x000D_
    color: #f00;_x000D_
    -webkit-filter: invert(100%);_x000D_
    filter: invert(100%);_x000D_
}
_x000D_
<div>_x000D_
    <p>inverted color</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Console app arguments, how arguments are passed to Main method

The runtime splits the arguments given at the console at each space.

If you call

myApp.exe arg1 arg2 arg3

The Main Method gets an array of

var args = new string[] {"arg1","arg2","arg3"}

error LNK2005, already defined?

If you want both to reference the same variable, one of them should have int k;, and the other should have extern int k;

For this situation, you typically put the definition (int k;) in one .cpp file, and put the declaration (extern int k;) in a header, to be included wherever you need access to that variable.

If you want each k to be a separate variable that just happen to have the same name, you can either mark them as static, like: static int k; (in all files, or at least all but one file). Alternatively, you can us an anonymous namespace:

namespace { 
   int k;
};

Again, in all but at most one of the files.

In C, the compiler generally isn't quite so picky about this. Specifically, C has a concept of a "tentative definition", so if you have something like int k; twice (in either the same or separate source files) each will be treated as a tentative definition, and there won't be a conflict between them. This can be a bit confusing, however, because you still can't have two definitions that both include initializers--a definition with an initializer is always a full definition, not a tentative definition. In other words, int k = 1; appearing twice would be an error, but int k; in one place and int k = 1; in another would not. In this case, the int k; would be treated as a tentative definition and the int k = 1; as a definition (and both refer to the same variable).

How to convert dataframe into time series?

R has multiple ways of represeting time series. Since you're working with daily prices of stocks, you may wish to consider that financial markets are closed on weekends and business holidays so that trading days and calendar days are not the same. However, you may need to work with your times series in terms of both trading days and calendar days. For example, daily returns are calculated from sequential daily closing prices regardless of whether a weekend intervenes. But you may also want to do calendar-based reporting such as weekly price summaries. For these reasons the xts package, an extension of zoo, is commonly used with financial data in R. An example of how it could be used with your data follows.

Assuming the data shown in your example is in the dataframe df

  library(xts)
  stocks <- xts(df[,-1], order.by=as.Date(df[,1], "%m/%d/%Y"))
#
#  daily returns
#
   returns <- diff(stocks, arithmetic=FALSE ) - 1
#
#  weekly open, high, low, close reports
#
   to.weekly(stocks$Hero_close, name="Hero")

which gives the output

           Hero.Open Hero.High Hero.Low Hero.Close
2013-03-15    1669.1   1684.45   1669.1    1684.45
2013-03-22    1690.5   1690.50   1623.3    1659.60
2013-03-28    1617.7   1617.70   1542.0    1542.00

How to calculate number of days between two dates

I made a quick re-usable function in ES6 using Moment.js.

_x000D_
_x000D_
const getDaysDiff = (start_date, end_date, date_format = 'YYYY-MM-DD') => {_x000D_
  const getDateAsArray = (date) => {_x000D_
    return moment(date.split(/\D+/), date_format);_x000D_
  }_x000D_
  return getDateAsArray(end_date).diff(getDateAsArray(start_date), 'days') + 1;_x000D_
}_x000D_
_x000D_
console.log(getDaysDiff('2019-10-01', '2019-10-30'));_x000D_
console.log(getDaysDiff('2019/10/01', '2019/10/30'));_x000D_
console.log(getDaysDiff('2019.10-01', '2019.10 30'));_x000D_
console.log(getDaysDiff('2019 10 01', '2019 10 30'));_x000D_
console.log(getDaysDiff('+++++2019!!/###10/$$01', '2019-10-30'));_x000D_
console.log(getDaysDiff('2019-10-01-2019', '2019-10-30'));_x000D_
console.log(getDaysDiff('10-01-2019', '10-30-2019', 'MM-DD-YYYY'));_x000D_
_x000D_
console.log(getDaysDiff('10-01-2019', '10-30-2019'));_x000D_
console.log(getDaysDiff('10-01-2019', '2019-10-30', 'MM-DD-YYYY'));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.js"></script>
_x000D_
_x000D_
_x000D_

How to fix getImageData() error The canvas has been tainted by cross-origin data?

I found that I had to use .setAttribute('crossOrigin', '') and had to append a timestamp to the URL's query string to avoid a 304 response lacking the Access-Control-Allow-Origin header.

This gives me

var url = 'http://lorempixel.com/g/400/200/';
var imgObj = new Image();
imgObj.src = url + '?' + new Date().getTime();
imgObj.setAttribute('crossOrigin', '');

How do I convert an enum to a list in C#?

public class NameValue
{
    public string Name { get; set; }
    public object Value { get; set; }
}

public class NameValue
{
    public string Name { get; set; }
    public object Value { get; set; }
}

public static List<NameValue> EnumToList<T>()
{
    var array = (T[])(Enum.GetValues(typeof(T)).Cast<T>()); 
    var array2 = Enum.GetNames(typeof(T)).ToArray<string>(); 
    List<NameValue> lst = null;
    for (int i = 0; i < array.Length; i++)
    {
        if (lst == null)
            lst = new List<NameValue>();
        string name = array2[i];
        T value = array[i];
        lst.Add(new NameValue { Name = name, Value = value });
    }
    return lst;
}

Convert Enum To a list more information available here.

What is the full path to the Packages folder for Sublime text 2 on Mac OS Lion

A useful shortcut from inside Sublime Text:

cmd-shift-P --> Browse Packages Now open user folder.

What version of Java is running in Eclipse?

Under the help menu, there should be a menu item labeled "About Eclipse" I can't say with absolute precision because I'm using STS which is the same thing but my label is different.

In the dialog box that opens after you click the relevant about menu item there should be an installation details button in the lower left hand corner.

The version of Java that you're running Eclipse against ought to be in "System properties:" under the "Configuration" tab.

What is HTTP "Host" header?

I would always recommend going to the authoritative source when trying to understand the meaning and purpose of HTTP headers.

The "Host" header field in a request provides the host and port
information from the target URI, enabling the origin server to
distinguish among resources while servicing requests for multiple
host names on a single IP address.

https://tools.ietf.org/html/rfc7230#section-5.4

powershell 2.0 try catch how to access the exception

Try something like this:

try {
    $w = New-Object net.WebClient
    $d = $w.downloadString('http://foo')
}
catch [Net.WebException] {
    Write-Host $_.Exception.ToString()
}

The exception is in the $_ variable. You might explore $_ like this:

try {
    $w = New-Object net.WebClient
    $d = $w.downloadString('http://foo')
}
catch [Net.WebException] {
    $_ | fl * -Force
}

I think it will give you all the info you need.

My rule: if there is some data that is not displayed, try to use -force.

Android emulator doesn't take keyboard input - SDK tools rev 20

Restarting the emulator helps sometimes when typing is unavailable - despite keyboard input being enabled for your Android Virtual Device.

how to show only even or odd rows in sql server 2008?

Try following

SELECT * FROM Worker WHERE MOD (WORKER_ID, 2) <> 0;

What is Gradle in Android Studio?

Search Results Featured snippet from the web Android | build. gradle. Gradle is a build system (open source) which is used to automate building, testing, deployment etc. ... For example, the simple task to copy some files from one directory to another can be performed by Gradle build script before the actual build process happens.

PHP replacing special characters like à->a, è->e

The string $chain is in the same character encoding as the characters in the array - it's possible, even likely, that the $first_name string is in a different encoding, and so those characters don't match. You might want to try using the multibyte string functions instead.

Try mb_convert_encoding. You might also want to try using HTML_ENTITIES as the to_encoding parameter, then you don't need to worry about how the characters will get converted - it will be very predictable.

Assuming your input to this script is in UTF-8, probably not a bad place to start...

$first_name = mb_convert_encoding($first_name, "HTML-ENTITIES", "UTF-8"); 

Getting list of items inside div using Selenium Webdriver

Follow the code below exactly matched with your case.

  1. Create an interface of the web element for the div under div with class as facetContainerDiv

ie for

<div class="facetContainerDiv">
    <div>

    </div>
</div>

2. Create an IList with all the elements inside the second div i.e for,

<label class="facetLabel">
   <input class="facetCheck" type="checkbox" />
</label>
<label class="facetLabel">
   <input class="facetCheck" type="checkbox" />
</label>
<label class="facetLabel">
   <input class="facetCheck" type="checkbox" />
</label>
<label class="facetLabel">
   <input class="facetCheck" type="checkbox" />
</label>
<label class="facetLabel">
   <input class="facetCheck" type="checkbox" />
</label>

3. Access each check boxes using the index

Please find the code below

using System;
using System.Collections.Generic;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Support.UI;

namespace SeleniumTests
{
  class ChechBoxClickWthIndex
    {
        static void Main(string[] args)
        {

            IWebDriver driver = new FirefoxDriver();

            driver.Navigate().GoToUrl("file:///C:/Users/chery/Desktop/CheckBox.html");

            // Create an interface WebElement of the div under div with **class as facetContainerDiv**
            IWebElement WebElement =    driver.FindElement(By.XPath("//div[@class='facetContainerDiv']/div"));
            // Create an IList and intialize it with all the elements of div under div with **class as facetContainerDiv**
            IList<IWebElement> AllCheckBoxes = WebElement.FindElements(By.XPath("//label/input"));
            int RowCount = AllCheckBoxes.Count;
            for (int i = 0; i < RowCount; i++)
            {
            // Check the check boxes based on index
               AllCheckBoxes[i].Click();

            }
            Console.WriteLine(RowCount);
            Console.ReadLine(); 

        }
    }
}

SQL Server table creation date query

For SQL Server 2000:

SELECT   su.name,so.name,so.crdate,* 
FROM     sysobjects so JOIN sysusers su
ON       so.uid = su.uid
WHERE    xtype='U'
ORDER BY so.name

Converting a string to JSON object

convert the string to HashMap using Object Mapper ...

new ObjectMapper().readValue(string, Map.class);

Internally Map will behave as JSON Object

JavaScript: filter() for Objects

As patrick already stated this is a bad idea, as it will almost certainly break any 3rd party code you could ever wish to use.

All libraries like jquery or prototype will break if you extend Object.prototype, the reason being that lazy iteration over objects (without hasOwnProperty checks) will break since the functions you add will be part of the iteration.

How to copy to clipboard using Access/VBA?

VB 6 provides a Clipboard object that makes all of this extremely simple and convenient, but unfortunately that's not available from VBA.

If it were me, I'd go the API route. There's no reason to be scared of calling native APIs; the language provides you with the ability to do that for a reason.

However, a simpler alternative is to use the DataObject class, which is part of the Forms library. I would only recommend going this route if you are already using functionality from the Forms library in your app. Adding a reference to this library only to use the clipboard seems a bit silly.

For example, to place some text on the clipboard, you could use the following code:

Dim clipboard As MSForms.DataObject
Set clipboard = New MSForms.DataObject
clipboard.SetText "A string value"
clipboard.PutInClipboard

Or, to copy text from the clipboard into a string variable:

Dim clipboard As MSForms.DataObject
Dim strContents As String

Set clipboard = New MSForms.DataObject
clipboard.GetFromClipboard
strContents = clipboard.GetText

How to get URL of current page in PHP

if you want just the parts of url after http://domain.com, try this:

<?php echo $_SERVER['REQUEST_URI']; ?>

if the current url was http://domain.com/some-slug/some-id, echo will return only '/some-slug/some-id'.

if you want the full url, try this:

<?php echo 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; ?>

What is the difference between screenX/Y, clientX/Y and pageX/Y?

What helped me was to add an event directly to this page and click around for myself! Open up your console in developer tools/Firebug etc and paste this:

_x000D_
_x000D_
document.addEventListener('click', function(e) {_x000D_
  console.log(_x000D_
    'page: ' + e.pageX + ',' + e.pageY,_x000D_
    'client: ' + e.clientX + ',' + e.clientY,_x000D_
    'screen: ' + e.screenX + ',' + e.screenY)_x000D_
}, false);
_x000D_
Click anywhere
_x000D_
_x000D_
_x000D_

With this snippet, you can track your click position as you scroll, move the browser window, etc.

Notice that pageX/Y and clientX/Y are the same when you're scrolled all the way to the top!

How to install SQL Server Management Studio 2012 (SSMS) Express?

You can download the 32bit or 64bit version of "Express With Tools" or "SQL Server Management Studio Express" (SSMSE tools only) from:

https://web.archive.org/web/20170507040411/https://www.microsoft.com/betaexperience/pd/SQLEXPNOCTAV2/enus/default.aspx

This link is for SQL Server 2012 Express Service Pack 1 released 11/09/2012 (11.0.3000.00) The original RTM release was 11.0.2100.60 from March or May of 2012.

enter image description here

Succeeded installing but could not start apache 2.4 on my windows 7 system

if you are using windows os and believe that skype is not the suspect, then you might want to check the task manager and check the "Show processes from all users" and make sure that there is NO entry for httpd.exe. Otherwise, end its process. That solves my problem.

Check if year is leap year in javascript

You can try using JavaScript's Date Object

new Date(year,month).getFullYear()%4==0

This will return true or false.

Invalid default value for 'create_date' timestamp field

Default values should start from the year 1000.

For example,

ALTER TABLE mytable last_active DATETIME DEFAULT '1000-01-01 00:00:00'

Hope this helps someone.

Guid is all 0's (zeros)?

Lessons to learn from this:

1) Guid is a value type, not a reference type.

2) Calling the default constructor new S() on any value type always gives you back the all-zero form of that value type, whatever it is. It is logically the same as default(S).

Send JSON data via POST (ajax) and receive json response from Controller (MVC)

var SendInfo= { SendInfo: [... your elements ...]};

        $.ajax({
            type: 'post',
            url: 'Your-URI',
            data: JSON.stringify(SendInfo),
            contentType: "application/json; charset=utf-8",
            traditional: true,
            success: function (data) {
                ...
            }
        });

and in action

public ActionResult AddDomain(IEnumerable<PersonSheets> SendInfo){
...

you can bind your array like this

var SendInfo = [];

$(this).parents('table').find('input:checked').each(function () {
    var domain = {
        name: $("#id-manuf-name").val(),
        address: $("#id-manuf-address").val(),
        phone: $("#id-manuf-phone").val(),
    }

    SendInfo.push(domain);
});

hope this can help you.

Bring element to front using CSS

In my case i had to move the html code of the element i wanted at the front at the end of the html file, because if one element has z-index and the other doesn't have z index it doesn't work.

SQL Server : export query as a .txt file

Another way is from command line, using the osql:

OSQL -S SERVERNAME -E -i thequeryfile.sql -o youroutputfile.txt

This can be used from a BAT file and shceduled by a windows user to authenticated.

Is there a way to rollback my last push to Git?

First you need to determine the revision ID of the last known commit. You can use HEAD^ or HEAD~{1} if you know you need to reverse exactly one commit.

git reset --hard <revision_id_of_last_known_good_commit>
git push --force

updating table rows in postgres using subquery

update json_source_tabcol as d
set isnullable = a.is_Nullable
from information_schema.columns as a 
where a.table_name =d.table_name 
and a.table_schema = d.table_schema 
and a.column_name = d.column_name;

How to update Xcode from command line

I was facing the same problem, resolved it by using the following command.

sudo xcode-select -s /Library/Developer/CommandLineTools

After running the above command then xcode-select -p command showed the following.

/Library/Developer/CommandLineTools

Comparing date part only without comparing time in JavaScript

Make sure you construct userDate with a 4 digit year as setFullYear(10, ...) !== setFullYear(2010, ...).

Easy way to make a confirmation dialog in Angular?

Method 1

One simple way to confirm is to use the native browser confirm alert. The template can have a button or link.

<button type=button class="btn btn-primary"  (click)="clickMethod('name')">Delete me</button>

And the component method can be something like below.

clickMethod(name: string) {
  if(confirm("Are you sure to delete "+name)) {
    console.log("Implement delete functionality here");
  }
}

Method 2

Another way to get a simple confirmation dialog is to use the angular bootstrap components like ng-bootstrap or ngx-bootstrap. You can simply install the component and use the modal component.

  1. Examples of modals using ng-bootstrap
  2. Examples of modals using ngx-bootstrap.

Method 3

Provided below is another way to implement a simple confirmation popup using angular2/material that I implemented in my project.

app.module.ts

import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { ConfirmationDialog } from './confirm-dialog/confirmation-dialog';

@NgModule({
  imports: [
    ...
    FormsModule,
    ReactiveFormsModule
  ],
  declarations: [
    ...
    ConfirmationDialog
  ],
  providers: [ ... ],
  bootstrap: [ AppComponent ],
  entryComponents: [ConfirmationDialog]
})
export class AppModule { }

confirmation-dialog.ts

import { Component, Input } from '@angular/core';
import { MdDialog, MdDialogRef } from '@angular/material';

@Component({
  selector: 'confirm-dialog',
  templateUrl: '/app/confirm-dialog/confirmation-dialog.html',
})
export class ConfirmationDialog {
  constructor(public dialogRef: MdDialogRef<ConfirmationDialog>) {}

  public confirmMessage:string;
}

confirmation-dialog.html

<h1 md-dialog-title>Confirm</h1>
<div md-dialog-content>{{confirmMessage}}</div>
<div md-dialog-actions>
  <button md-button style="color: #fff;background-color: #153961;" (click)="dialogRef.close(true)">Confirm</button>
  <button md-button (click)="dialogRef.close(false)">Cancel</button>
</div>

app.component.html

<button (click)="openConfirmationDialog()">Delete me</button>

app.component.ts

import { MdDialog, MdDialogRef } from '@angular/material';
import { ConfirmationDialog } from './confirm-dialog/confirmation-dialog';

@Component({
  moduleId: module.id,
  templateUrl: '/app/app.component.html',
  styleUrls: ['/app/main.css']
})

export class AppComponent implements AfterViewInit {
  dialogRef: MdDialogRef<ConfirmationDialog>;

  constructor(public dialog: MdDialog) {}

  openConfirmationDialog() {
    this.dialogRef = this.dialog.open(ConfirmationDialog, {
      disableClose: false
    });
    this.dialogRef.componentInstance.confirmMessage = "Are you sure you want to delete?"

    this.dialogRef.afterClosed().subscribe(result => {
      if(result) {
        // do confirmation actions
      }
      this.dialogRef = null;
    });
  }
}

index.html => added following stylesheet

<link rel="stylesheet" href="node_modules/@angular/material/core/theming/prebuilt/indigo-pink.css">

Viewing all `git diffs` with vimdiff

Git accepts kdiff3, tkdiff, meld, xxdiff, emerge, vimdiff, gvimdiff, ecmerge,
and opendiff as valid diff tools. You can also set up a custom tool. 

git config --global diff.tool vimdiff
git config --global diff.tool kdiff3
git config --global diff.tool meld
git config --global diff.tool xxdiff
git config --global diff.tool emerge
git config --global diff.tool gvimdiff
git config --global diff.tool ecmerge

Module not found: Error: Can't resolve 'core-js/es6'

Change all "es6" and "es7" to "es" in your polyfills.ts and polyfills.ts (Optional).

  • From: import 'core-js/es6/symbol';
  • To: import 'core-js/es/symbol';

Keep a line of text as a single line - wrap the whole line or none at all

You can use white-space: nowrap; to define this behaviour:

// HTML:

_x000D_
_x000D_
.nowrap {_x000D_
  white-space: nowrap ;_x000D_
}
_x000D_
<p>_x000D_
      <span class="nowrap">How do I wrap this line of text</span>_x000D_
      <span class="nowrap">- asked by Peter 2 days ago</span>_x000D_
    </p>
_x000D_
_x000D_
_x000D_

// CSS:
.nowrap {
  white-space: nowrap ;
}

Permission denied (publickey) when SSH Access to Amazon EC2 instance

This is how I solved the problem

ssh -i <key> ec2-user@<ec2 ip>

PHP simple foreach loop with HTML

This will work although when embedding PHP in HTML it is better practice to use the following form:

<table>
    <?php foreach($array as $key=>$value): ?>
    <tr>
        <td><?= $key; ?></td>
    </tr>
    <?php endforeach; ?>
</table>

You can find the doc for the alternative syntax on PHP.net

sed with literal string--not input file

You have a single quotes conflict, so use:

 echo "A,B,C" | sed "s/,/','/g"

If using , you can do too (<<< is a here-string):

sed "s/,/','/g" <<< "A,B,C"

but not

sed "s/,/','/g"  "A,B,C"

because sed expect file(s) as argument(s)

EDIT:

if you use or any other ones :

echo string | sed ...

Where do I put my php files to have Xampp parse them?

The default location to put all the web projects in ubuntu with LAMPP is :

 /var/www/

You may make symbolic link to public_html directory from this directory.Refered. Hope this is helpful.

How to include JavaScript file or library in Chrome console?

In the modern browsers you can use the fetch to download resource (Mozilla docs) and then eval to execute it.

For example to download Angular1 you need to type:

fetch('https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js')
    .then(response => response.text())
    .then(text => eval(text))
    .then(() => { /* now you can use your library */ })

Change Name of Import in Java, or import two classes with the same name

Java doesn't allow you to do that. You'll need to refer to one of the classes by its fully qualified name and only import the other one.

How can I use Timer (formerly NSTimer) in Swift?

Swift 3, pre iOS 10

func schedule() {
    DispatchQueue.main.async {
      self.timer = Timer.scheduledTimer(timeInterval: 20, target: self,
                                   selector: #selector(self.timerDidFire(timer:)), userInfo: nil, repeats: false)
    }
  }

  @objc private func timerDidFire(timer: Timer) {
    print(timer)
  }

Swift 3, iOS 10+

DispatchQueue.main.async {
      self.timer = Timer.scheduledTimer(withTimeInterval: 20, repeats: false) { timer in
        print(timer)
      }
    }

Notes

  • It needs to be on the main queue
  • Callback function can be public, private, ...
  • Callback function needs to be @objc

How to set a variable inside a loop for /F

I know this isn't what's asked but I benefited from this method, when trying to set a variable within a "loop". Uses an array. Alternative implementation option.

SETLOCAL ENABLEDELAYEDEXPANSION

...

set Services[0]=SERVICE1
set Services[1]=SERVICE2
set Services[2]=SERVICE3

set "i=0"

:ServicesLoop
if defined Services[%i%] (
    set SERVICE=!Services[%i%]!

    echo CurrentService: !SERVICE!

    set /a "i+=1"
    GOTO :ServicesLoop
)

How do I post button value to PHP?

    $restore = $this->createElement('submit', 'restore', array(
        'label' => 'FILE_RESTORE',
        'class' => 'restore btn btn-small btn-primary',
        'attribs' => array(
            'onClick' => 'restoreCheck();return false;'
        )
    ));

HTTP POST Returns Error: 417 "Expectation Failed."

System.Net.HttpWebRequest adds the header 'HTTP header "Expect: 100-Continue"' to every request unless you explicitly ask it not to by setting this static property to false:

System.Net.ServicePointManager.Expect100Continue = false;

Some servers choke on that header and send back the 417 error you're seeing.

Give that a shot.

Sending simple message body + file attachment using Linux Mailx

Johnsyweb's answer didn't work for me, but it works for me with Mutt:

echo "Message body" | mutt -s "Message subject" -a myfile.txt [email protected]

On a CSS hover event, can I change another div's styling?

Yes, you can do that, but only if #b is after #a in the HTML.

If #b comes immediately after #a: http://jsfiddle.net/u7tYE/

#a:hover + #b {
    background: #ccc
}

<div id="a">Div A</div>
<div id="b">Div B</div>

That's using the adjacent sibling combinator (+).

If there are other elements between #a and #b, you can use this: http://jsfiddle.net/u7tYE/1/

#a:hover ~ #b {
    background: #ccc
}

<div id="a">Div A</div>
<div>random other elements</div>
<div>random other elements</div>
<div>random other elements</div>
<div id="b">Div B</div>

That's using the general sibling combinator (~).

Both + and ~ work in all modern browsers and IE7+

If #b is a descendant of #a, you can simply use #a:hover #b.

ALTERNATIVE: You can use pure CSS to do this by positioning the second element before the first. The first div is first in markup, but positioned to the right or below the second. It will work as if it were a previous sibling.

mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given

You are single quoting your SQL statement which is making the variables text instead of variables.

$sql = "SELECT * 
    FROM $usertable 
    WHERE PartNumber = $partid";

MySQL query to select events between start/end date

You need the events that start and end within the scope. But that's not all: you also want the events that start within the scope and the events that end within the scope. But then you're still not there because you also want the events that start before the scope and end after the scope.

Simplified:

  1. events with a start date in the scope
  2. events with an end date in the scope
  3. events with the scope startdate between the startdate and enddate

Because point 2 results in records that also meet the query in point 3 we will only need points 1 and 3

So the SQL becomes:

SELECT * FROM events 
WHERE start BETWEEN '2014-09-01' AND '2014-10-13' 
OR '2014-09-01' BETWEEN start AND end

Required maven dependencies for Apache POI to work

No, you don't have to include all of POI's dependencies. Maven's transitive dependency mechanism will take care of that. As noted you just have to express a dependency on the appropriate POI artifact. For example:

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>3.8-beta4</version>
</dependency>

Edit(UPDATE): I don't know about previous versions but to resolve imports to XSSFWorkbook and other classes in org.apache.poi package you need to add dependency for poi-ooxml too. The dependencies will be:

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>4.1.2</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>4.1.2</version>
</dependency>

How to change webservice url endpoint?

IMO, the provider is telling you to change the service endpoint (i.e. where to reach the web service), not the client endpoint (I don't understand what this could be). To change the service endpoint, you basically have two options.

Use the Binding Provider to set the endpoint URL

The first option is to change the BindingProvider.ENDPOINT_ADDRESS_PROPERTY property value of the BindingProvider (every proxy implements javax.xml.ws.BindingProvider interface):

...
EchoService service = new EchoService();
Echo port = service.getEchoPort();

/* Set NEW Endpoint Location */
String endpointURL = "http://NEW_ENDPOINT_URL";
BindingProvider bp = (BindingProvider)port;
bp.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, endpointURL);

System.out.println("Server said: " + echo.echo(args[0]));
...

The drawback is that this only works when the original WSDL is still accessible. Not recommended.

Use the WSDL to get the endpoint URL

The second option is to get the endpoint URL from the WSDL.

...
URL newEndpoint = new URL("NEW_ENDPOINT_URL");
QName qname = new QName("http://ws.mycompany.tld","EchoService"); 

EchoService service = new EchoService(newEndpoint, qname);
Echo port = service.getEchoPort();

System.out.println("Server said: " + echo.echo(args[0]));
...

Python Library Path

You can also make additions to this path with the PYTHONPATH environment variable at runtime, in addition to:

import sys
sys.path.append('/home/user/python-libs')

How to add text at the end of each line in Vim?

I have <M-DOWN>(alt down arrow) mapped to <DOWN>. so that I can repeat the last command on a series of lines very quickly. with this mapping I can:

A,<ESC>

And then hold alt while pressing down repeatedly to append the comma to the end of each line.
This works well for me because it allows very good control over what lines do and do not get the change.
(I also have the other arrows mapped similarly to allow for easy repeating of .)

Here's the mapping line to paste into your vimrc:

map <M-DOWN> <DOWN>.

Convert HTML string to image

Try the following:

using System;
using System.Drawing;
using System.Threading;
using System.Windows.Forms;

class Program
{
    static void Main(string[] args)
    {
        var source =  @"
        <!DOCTYPE html>
        <html>
            <body>
                <p>An image from W3Schools:</p>
                <img 
                    src=""http://www.w3schools.com/images/w3schools_green.jpg"" 
                    alt=""W3Schools.com"" 
                    width=""104"" 
                    height=""142"">
            </body>
        </html>";
        StartBrowser(source);
        Console.ReadLine();
    }

    private static void StartBrowser(string source)
    {
        var th = new Thread(() =>
        {
            var webBrowser = new WebBrowser();
            webBrowser.ScrollBarsEnabled = false;
            webBrowser.DocumentCompleted +=
                webBrowser_DocumentCompleted;
            webBrowser.DocumentText = source;
            Application.Run();
        });
        th.SetApartmentState(ApartmentState.STA);
        th.Start();
    }

    static void 
        webBrowser_DocumentCompleted(
        object sender, 
        WebBrowserDocumentCompletedEventArgs e)
    {
        var webBrowser = (WebBrowser)sender;
        using (Bitmap bitmap = 
            new Bitmap(
                webBrowser.Width, 
                webBrowser.Height))
        {
            webBrowser
                .DrawToBitmap(
                bitmap, 
                new System.Drawing
                    .Rectangle(0, 0, bitmap.Width, bitmap.Height));
            bitmap.Save(@"filename.jpg", 
                System.Drawing.Imaging.ImageFormat.Jpeg);
        }
    }
}

Note: Credits should go to Hans Passant for his excellent answer on the question WebBrowser Control in a new thread which inspired this solution.

Link to "pin it" on pinterest without generating a button

The standard Pinterest button code (which you can generate here), is an <a> tag wrapping an <img> of the Pinterest button.

If you don't include the pinit.js script on your page, this <a> tag will work "as-is". You could improve the experience by registering your own click handler on these tags that opens a new window with appropriate dimensions, or at least adding target="_blank" to the tag to make it open clicks in a new window.

The tag syntax would look like:

<a href="http://pinterest.com/pin/create/button/?url={URI-encoded URL of the page to pin}&media={URI-encoded URL of the image to pin}&description={optional URI-encoded description}" class="pin-it-button" count-layout="horizontal">
    <img border="0" src="//assets.pinterest.com/images/PinExt.png" title="Pin It" />
</a>

If using the JavaScript versions of sharing buttons are ruining your page load times, you can improve your site by using asynchronous loading methods. For an example of doing this with the Pinterest button, check out my GitHub Pinterest button project with an improved HTML5 syntax.

How to use ImageBackground to set background image for screen in react-native

You have to import background component first to use backgroundimage on your code

Can a main() method of class be invoked from another class in java

If you want to call the main method of another class you can do it this way assuming I understand the question.

public class MyClass {

    public static void main(String[] args) {

        System.out.println("main() method of MyClass");
        OtherClass obj = new OtherClass();
    }
}

class OtherClass {

    public OtherClass() {

        // Call the main() method of MyClass
        String[] arguments = new String[] {"123"};
        MyClass.main(arguments);
    }
}

How to extract text from a PDF file?

Camelot seems a fairly powerful solution to extract tables from PDFs in Python.

At first sight it seems to achieve almost as accurate extraction as the tabula-py package suggested by CreekGeek, which is already waaaaay above any other posted solution as of today in terms of reliability, but it is supposedly much more configurable. Furthermore it has its own accuracy indicator (results.parsing_report), and great debugging features.

Both Camelot and Tabula provide the results as Pandas’ DataFrames, so it is easy to adjust tables afterwards.

pip install camelot-py

(Not to be confused with the camelot package.)

import camelot

df_list = []
results = camelot.read_pdf("file.pdf", ...)
for table in results:
    print(table.parsing_report)
    df_list.append(results[0].df)

It can also output results as CSV, JSON, HTML or Excel.

Camelot comes at the expense of a number of dependencies.

NB : Since my input is pretty complex with many different tables I ended up using both Camelot and Tabula, depending on the table, to achieve the best results.

How do I escape a single quote ( ' ) in JavaScript?

The answer here is very simple:

You're already containing it in double quotes, so there's no need to escape it with \.

If you want to escape single quotes in a single quote string:

var string = 'this isn\'t a double quoted string';
var string = "this isn\"t a single quoted string";
//           ^         ^ same types, hence we need to escape it with a backslash

or if you want to escape \', you can escape the bashslash to \\ and the quote to \' like so:

var string = 'this isn\\\'t a double quoted string';
//                    vvvv
//                     \ ' (the escaped characters)

However, if you contain the string with a different quote type, you don't need to escape:

var string = 'this isn"t a double quoted string';
var string = "this isn't a single quoted string";
//           ^        ^ different types, hence we don't need escaping

I need to round a float to two decimal places in Java

1.2975118E7 is scientific notation.

1.2975118E7 = 1.2975118 * 10^7 = 12975118

Also, Math.round(f) returns an integer. You can't use it to get your desired format x.xx.

You could use String.format.

String s = String.format("%.2f", 1.2975118);
// 1.30

How do I check if string contains substring?

Like this:

if (str.indexOf("Yes") >= 0)

...or you can use the tilde operator:

if (~str.indexOf("Yes"))

This works because indexOf() returns -1 if the string wasn't found at all.

Note that this is case-sensitive.
If you want a case-insensitive search, you can write

if (str.toLowerCase().indexOf("yes") >= 0)

Or:

if (/yes/i.test(str))

PHP Warning: Division by zero

You can try with this. You have this error because we can not divide by 'zero' (0) value. So we want to validate before when we do calculations.

if ($itemCost != 0 && $itemCost != NULL && $itemQty != 0 && $itemQty != NULL) 
{
    $diffPricePercent = (($actual * 100) / $itemCost) / $itemQty;
}

And also we can validate POST data. Refer following

$itemQty = isset($_POST['num1']) ? $_POST['num1'] : 0;

$itemCost = isset($_POST['num2']) ? $_POST['num2'] : 0;

$itemSale = isset($_POST['num3']) ? $_POST['num3'] : 0;

$shipMat = isset($_POST['num4']) ? $_POST['num4'] : 0;

Cannot use mkdir in home directory: permission denied (Linux Lubuntu)

As @kirbyfan64sos notes in a comment, /home is NOT your home directory (a.k.a. home folder):

The fact that /home is an absolute, literal path that has no user-specific component provides a clue.

While /home happens to be the parent directory of all user-specific home directories on Linux-based systems, you shouldn't even rely on that, given that this differs across platforms: for instance, the equivalent directory on macOS is /Users.

What all Unix platforms DO have in common are the following ways to navigate to / refer to your home directory:

  • Using cd with NO argument changes to your home dir., i.e., makes your home dir. the working directory.
    • e.g.: cd # changes to home dir; e.g., '/home/jdoe'
  • Unquoted ~ by itself / unquoted ~/ at the start of a path string represents your home dir. / a path starting at your home dir.; this is referred to as tilde expansion (see man bash)
    • e.g.: echo ~ # outputs, e.g., '/home/jdoe'
  • $HOME - as part of either unquoted or preferably a double-quoted string - refers to your home dir. HOME is a predefined, user-specific environment variable:
    • e.g.: cd "$HOME/tmp" # changes to your personal folder for temp. files

Thus, to create the desired folder, you could use:

mkdir "$HOME/bin"  # same as: mkdir ~/bin

Note that most locations outside your home dir. require superuser (root user) privileges in order to create files or directories - that's why you ran into the Permission denied error.

How to convert a string or integer to binary in Ruby?

You would naturally use Integer#to_s(2), String#to_i(2) or "%b" in a real program, but, if you're interested in how the translation works, this method calculates the binary representation of a given integer using basic operators:

def int_to_binary(x)
  p = 0
  two_p = 0
  output = ""

  while two_p * 2 <= x do
    two_p = 2 ** p
    output << ((two_p & x == two_p) ? "1" : "0")
    p += 1
  end

  #Reverse output to match the endianness of %b
  output.reverse
end

To check it works:

1.upto(1000) do |n|
  built_in, custom = ("%b" % n), int_to_binary(n)
  if built_in != custom
    puts "I expected #{built_in} but got #{custom}!"
    exit 1
  end
  puts custom
end

How do implement a breadth first traversal?

Breadth first is a queue, depth first is a stack.

For breadth first, add all children to the queue, then pull the head and do a breadth first search on it, using the same queue.

For depth first, add all children to the stack, then pop and do a depth first on that node, using the same stack.

Access to build environment variables from a groovy script in a Jenkins build step (Windows)

You might be able to get them like this:

def thr = Thread.currentThread()
def build = thr?.executable
def envVarsMap = build.parent.builds[0].properties.get("envVars")

Delete a row in Excel VBA

Chris Nielsen's solution is simple and will work well. A slightly shorter option would be...

ws.Rows(Rand).Delete

...note there is no need to specify a Shift when deleting a row as, by definition, it's not possible to shift left

Incidentally, my preferred method for deleting rows is to use...

ws.Rows(Rand) = ""

...in the initial loop. I then use a Sort function to push these rows to the bottom of the data. The main reason for this is because deleting single rows can be a very slow procedure (if you are deleting >100). It also ensures nothing gets missed as per Robert Ilbrink's comment

You can learn the code for sorting by recording a macro and reducing the code as demonstrated in this expert Excel video. I have a suspicion that the neatest method (Range("A1:Z10").Sort Key1:=Range("A1"), Order1:=xlSortAscending/Descending, Header:=xlYes/No) can only be discovered on pre-2007 versions of Excel...but you can always reduce the 2007/2010 equivalent code

Couple more points...if your list is not already sorted by a column and you wish to retain the order, you can stick the row number 'Rand' in a spare column to the right of each row as you loop through. You would then sort by that comment and eliminate it

If your data rows contain formatting, you may wish to find the end of the new data range and delete the rows that you cleared earlier. That's to keep the file size down. Note that a single large delete at the end of the procedure will not impair your code's performance in the same way that deleting single rows does

Set value for particular cell in pandas DataFrame with iloc

If you know the position, why not just get the index from that?

Then use .loc:

df.loc[index, 'COL_NAME'] = x

How to use mongoose findOne

In my case same error is there , I am using Asyanc / Await functions , for this needs to add AWAIT for findOne

Ex:const foundUser = User.findOne ({ "email" : req.body.email });

above , foundUser always contains Object value in both cases either user found or not because it's returning values before finishing findOne .

const foundUser = await User.findOne ({ "email" : req.body.email });

above , foundUser returns null if user is not there in collection with provided condition . If user found returns user document.

Reading a cell value in Excel vba and write in another Cell

surely you can do this with worksheet formulas, avoiding VBA entirely:

so for this value in say, column AV S:1 P:0 K:1 Q:1

you put this formula in column BC:

=MID(AV:AV,FIND("S",AV:AV)+2,1)

then these formulas in columns BD, BE...

=MID(AV:AV,FIND("P",AV:AV)+2,1)
=MID(AV:AV,FIND("K",AV:AV)+2,1)
=MID(AV:AV,FIND("Q",AV:AV)+2,1)

so these formulas look for the values S:1, P:1 etc in column AV. If the FIND function returns an error, then 0 is returned by the formula, else 1 (like an IF, THEN, ELSE

Then you would just copy down the formulas for all the rows in column AV.

HTH Philip

Angular2 router (@angular/router), how to set default route?

Suppose you want to load RegistrationComponent on load and then ConfirmationComponent on some event click on RegistrationComponent.

So in appModule.ts, you can write like this.

RouterModule.forRoot([
      { 
        path: '', 
        redirectTo: 'registration', 
        pathMatch: 'full'
       },
       { 
        path: 'registration', 
        component: RegistrationComponent
       },
      {
        path : 'confirmation',
        component: ConfirmationComponent
      }
    ]) 

OR

RouterModule.forRoot([
       { 
        path: '', 
        component: RegistrationComponent
       },
      {
        path : 'confirmation',
        component: ConfirmationComponent
      }
    ]) 

is also fine. Choose whatever you like.

What is the SQL command to return the field names of a table?

MySQL 3 and 4 (and 5):

desc tablename

which is an alias for

show fields from tablename

SQL Server (from 2000) and MySQL 5:

select COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS 
where TABLE_NAME = 'tablename'

Completing the answer: like people below have said, in SQL Server you can also use the stored procedure sp_help

exec sp_help 'tablename'

How to map a composite key with JPA and Hibernate?

Another option is to map is as a Map of composite elements in the ConfPath table.

This mapping would benefit from an index on (ConfPathID,levelStation) though.

public class ConfPath {
    private Map<Long,Time> timeForLevelStation = new HashMap<Long,Time>();

    public Time getTime(long levelStation) {
        return timeForLevelStation.get(levelStation);
    }

    public void putTime(long levelStation, Time newValue) {
        timeForLevelStation.put(levelStation, newValue);
    }
}

public class Time {
    String src;
    String dst;
    long distance;
    long price;

    public long getDistance() {
        return distance;
    }

    public void setDistance(long distance) {
        this.distance = distance;
    }

    public String getDst() {
        return dst;
    }

    public void setDst(String dst) {
        this.dst = dst;
    }

    public long getPrice() {
        return price;
    }

    public void setPrice(long price) {
        this.price = price;
    }

    public String getSrc() {
        return src;
    }

    public void setSrc(String src) {
        this.src = src;
    }
}

Mapping:

<class name="ConfPath" table="ConfPath">
    <id column="ID" name="id">
        <generator class="native"/>
    </id>
    <map cascade="all-delete-orphan" name="values" table="example"
            lazy="extra">
        <key column="ConfPathID"/>
        <map-key type="long" column="levelStation"/>
        <composite-element class="Time">
            <property name="src" column="src" type="string" length="100"/>
            <property name="dst" column="dst" type="string" length="100"/>
            <property name="distance" column="distance"/>
            <property name="price" column="price"/>
        </composite-element>
    </map>
</class>

How to merge specific files from Git branches

The simplest solution is:

git checkout the name of the source branch and the paths to the specific files that we want to add to our current branch

git checkout sourceBranchName pathToFile

How to print a list in Python "nicely"

Simply by "unpacking" the list in the print function argument and using a newline (\n) as separator.

print(*lst, sep='\n')

lst = ['foo', 'bar', 'spam', 'egg']
print(*lst, sep='\n')

foo
bar
spam
egg

How can I apply styles to multiple classes at once?

You can have multiple CSS declarations for the same properties by separating them with commas:

.abc, .xyz {
   margin-left: 20px;
}

JQuery, Spring MVC @RequestBody and JSON - making it work together

In case you are willing to use Curl for the calls with JSON 2 and Spring 3.2.0 in hand checkout the FAQ here. As AnnotationMethodHandlerAdapter is deprecated and replaced by RequestMappingHandlerAdapter.

How to install Android SDK Build Tools on the command line?

Build tools could not be downloaded automatically by default as Nate said in https://stackoverflow.com/a/19416222/1104031 post.

But I wrote small tool that make everything for you

I used "expect" tool as danb in https://stackoverflow.com/a/17863931/1104031 post. You only need android-sdk and python27, expect.

This script will install all build tools, all sdks and everything you need for automated build:

import subprocess,re,sys

w = subprocess.check_output(["android", "list", "sdk", "--all"])
lines = w.split("\n")
tools = filter(lambda x: "Build-tools" in x, lines)
filters = []
for tool in tools:
  m = re.search("^\s+([0-9]+)-", tool)
  tool_no = m.group(1)
  filters.append(tool_no)

if len(filters) == 0:
  raise Exception("Not found build tools")


filters.extend(['extra', 'platform', 'platform-tool', 'tool'])

filter = ",".join(filters)

expect= '''set timeout -1;
spawn android update sdk --no-ui --all --filter %s;
expect {
  "Do you accept the license" { exp_send "y\\r" ; exp_continue }
  eof
}''' % (filter)

print expect

ret = subprocess.call(["expect", "-c", expect])
sys.exit(ret)

Which terminal command to get just IP address and nothing else?

On latest Ubuntu versions (14.04 - 16.04), this command did the trick for me.

hostname -I | awk '{print $1}'

How can we convert an integer to string in AngularJs

.toString() is available, or just add "" to the end of the int

var x = 3,
    toString = x.toString(),
    toConcat = x + "";

Angular is simply JavaScript at the core.

ORA-01652 Unable to extend temp segment by in tablespace

I found the solution to this. There is a temporary tablespace called TEMP which is used internally by database for operations like distinct, joins,etc. Since my query(which has 4 joins) fetches almost 50 million records the TEMP tablespace does not have that much space to occupy all data. Hence the query fails even though my tablespace has free space.So, after increasing the size of TEMP tablespace the issue was resolved. Hope this helps someone with the same issue. Thanks :)

Rename a dictionary key

In Python 3.6 (onwards?) I would go for the following one-liner

test = {'a': 1, 'old': 2, 'c': 3}
old_k = 'old'
new_k = 'new'
new_v = 4  # optional

print(dict((new_k, new_v) if k == old_k else (k, v) for k, v in test.items()))

which produces

{'a': 1, 'new': 4, 'c': 3}

May be worth noting that without the print statement the ipython console/jupyter notebook present the dictionary in an order of their choosing...

How to pause a YouTube player when hiding the iframe?

A more concise, elegant, and secure answer: add “?enablejsapi=1” to the end of the video URL, then construct and stringify an ordinary object representing the pause command:

const YouTube_pause_video_command_JSON = JSON.stringify(Object.create(null, {
    "event": {
        "value": "command",
        "enumerable": true
    },
    "func": {
        "value": "pauseVideo",
        "enumerable": true
    }
}));

Use the Window.postMessage method to send the resulting JSON string to the embedded video document:

// |iframe_element| is defined elsewhere.
const video_URL = iframe_element.getAttributeNS(null, "src");
iframe_element.contentWindow.postMessage(YouTube_pause_video_command_JSON, video_URL);

Make sure you specify the video URL for the Window.postMessage method’s targetOrigin argument to ensure that your messages won’t be sent to any unintended recipient.

React Error: Target Container is not a DOM Element

For those that implemented react js in some part of the website and encounter this issue. Just add a condition to check if the element exist on that page before you render the react component.

<div id="element"></div>

...

const someElement = document.getElementById("element")
    
if(someElement) {
  ReactDOM.render(<Yourcomponent />, someElement)
}

MongoDB - admin user not authorized

I had this problem because of the hostname in my MongoDB Compass was pointing to admin instead for my project. Fixed by adding the /projectname after the hostname :) Try this:

  1. Choose your project in the MongoDB atlas website
  2. Connect/Connect with MongoDB Compass
  3. Download Compass/Choose your OS
  4. I used Compass 1.12 or later
  5. Copy the connection string under the Compass 1.12 or later.
  6. Open MongoDB Compass/Connect(top left)/Connect To
  7. Connection String detected/Yes/
  8. Append your project name after the hostname: cluster9-foodie.mongodb.net/projectname
  9. Connect & Tested the API with POSTMAN.
  10. Succeed.

Use the same connection string in your code too:

  1. Before:
    • mongodb+srv://projectname:password@cluster9-foodie.mongodb.net/admin
  2. After:
    • mongodb+srv://projectname:password@cluster9-foodie.mongodb.net/projectname

Good luck.

Controlling Maven final name of jar artifact

At the package stage, the plugin allows configuration of the imported file names via file mapping:

maven-ear-plugin

http://maven.apache.org/plugins/maven-ear-plugin/examples/customize-file-name-mapping.html

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-ear-plugin</artifactId>
    <version>2.7</version>
    <configuration>
       [...]
        <fileNameMapping>full</fileNameMapping>
    </configuration>
</plugin>

http://maven.apache.org/plugins/maven-war-plugin/war-mojo.html#outputFileNameMapping

If you have configured your version to be 'testing' via a profile or something, this would work for a war package:

maven-war-plugin

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-war-plugin</artifactId>
    <version>2.2</version>
    <configuration>
        <encoding>UTF-8</encoding>                        
        <outputFileNameMapping>@{groupId}@-@{artifactId}@-@{baseVersion}@@{dashClassifier?}@.@{extension}@</outputFileNameMapping>
    </configuration>
</plugin>

JS: Uncaught TypeError: object is not a function (onclick)

Please change only the name of the function; no other change is required

<script>
    function totalbandwidthresult() {
        alert("fdf");
        var fps = Number(document.calculator.fps.value);
        var bitrate = Number(document.calculator.bitrate.value);
        var numberofcameras = Number(document.calculator.numberofcameras.value);
        var encoding = document.calculator.encoding.value;
        if (encoding = "mjpeg") {
            storage = bitrate * fps;
        } else {
            storage = bitrate;
        }

        totalbandwidth = (numberofcameras * storage) / 1000;
        alert(totalbandwidth);
        document.calculator.totalbandwidthresult.value = totalbandwidth;
    }
</script>

<form name="calculator" class="formtable">
    <div class="formrow">
        <label for="rcname">RC Name</label>
        <input type="text" name="rcname">
    </div>
    <div class="formrow">
        <label for="fps">FPS</label>
        <input type="text" name="fps">
    </div>
    <div class="formrow">
        <label for="bitrate">Bitrate</label>
        <input type="text" name="bitrate">
    </div>
    <div class="formrow">
        <label for="numberofcameras">Number of Cameras</label>
        <input type="text" name="numberofcameras">
    </div>
    <div class="formrow">
        <label for="encoding">Encoding</label>
        <select name="encoding" id="encodingoptions">
            <option value="h264">H.264</option>
            <option value="mjpeg">MJPEG</option>
            <option value="mpeg4">MPEG4</option>
        </select>
    </div>Total Storage:
    <input type="text" name="totalstorage">Total Bandwidth:
    <input type="text" name="totalbandwidth">
    <input type="button" value="totalbandwidthresult" onclick="totalbandwidthresult();">
</form>

List vs tuple, when to use each?

But if I am the one who designs the API and gets to choose the data types, then what are the guidelines?

For input parameters it's best to accept the most generic interface that does what you need. It is seldom just a tuple or list - more often it's sequence, sliceable or even iterable. Python's duck typing usually gets it for free, unless you explicitly check input types. Don't do that unless absolutely unavoidable.

For the data that you produce (output parameters) just return what's most convenient for you, e.g. return whatever datatype you keep or whatever your helper function returns.

One thing to keep in mind is to avoid returning a list (or any other mutable) that's part of your state, e.g.

class ThingsKeeper
    def __init__(self):
        self.__things = []

    def things(self):
        return self.__things  #outside objects can now modify your state

    def safer(self):
        return self.__things[:]  #it's copy-on-write, shouldn't hurt performance

How to split a string with angularJS

You could try this:

$scope.testdata = [{ 'name': 'name,id' }, {'name':'someName,someId'}]
$scope.array= [];
angular.forEach($scope.testdata, function (value, key) {
    $scope.array.push({ 'name': value.name.split(',')[0], 'id': value.name.split(',')[1] });
});
console.log($scope.array)

This way you can save the data for later use and acces it by using an ng-repeat like this:

<div ng-repeat="item in array">{{item.name}}{{item.id}}</div>


I hope this helped someone,
Plunker link: here
All credits go to @jwpfox and @Mohideen ibn Mohammed from the answer above.

SQLSTATE[28000] [1045] Access denied for user 'root'@'localhost' (using password: YES) Symfony2

Try to login via the terminal using the following command:

mysql -u root -p

It will then prompt for your password. If this fails, then definitely the username or password is incorrect. If this works, then your database's password needs to be enclosed in quotes:

database_password: "0000"

object==null or null==object?

It is Yoda condition writing in different manner

In java

String myString = null;
if (myString.equals("foobar")) { /* ... */ } //Will give u null pointer

yoda condition

String myString = null;
if ("foobar".equals(myString)) { /* ... */ } // will be false 

PowerShell script to return members of multiple security groups

If you don't care what groups the users were in, and just want a big ol' list of users - this does the job:

$Groups = Get-ADGroup -Filter {Name -like "AB*"}

$rtn = @(); ForEach ($Group in $Groups) {
    $rtn += (Get-ADGroupMember -Identity "$($Group.Name)" -Recursive)
}

Then the results:

$rtn | ft -autosize

Error : java.lang.NoSuchMethodError: org.objectweb.asm.ClassWriter.<init>(I)V

There is a lot of incompatibility between different versions of cglib and lots of poor advice that can be googled on this subject (use ancient versions of cglib-nodeb, etc). After wrestling with this nonsense for 3 days with an ancient version of Spring (2.5.6)I have discovered:

  • if Spring is throwing exceptions about NoSuchMethodError based on Enhancer from cglib missing setInterceptDuringConstruction(boolean), check your dependencies in maven (Dependency Hierarchy tab should list all the versions of cglib your project is polluted by). You probably have a dependency that is bringing in a pre-2.2 version of cglib, which Spring Cglib2AopProxy will grab Enhancer from to do the proxying. Add 2.2+ version to your dependencies but make sure to put in exclusions for these other versions. If you don't it will just keep blowing up.
  • Make sure you have a high enough version of cglib in the current project's maven dependencies but beware of picking too high a version because then you'll get IncompatibleClassChangeError(s) instead.
  • Verify that your pom changes have made it into the project correctly by doing a maven update on the project in question and then looking at Project > preferences > Java Build Path > Libraries > Maven Dependencies. If you see the wrong cglib versions in there, time to edit the pom again.

Getting the last element of a list

You can also do:

alist.pop()

It depends on what you want to do with your list because the pop() method will delete the last element.

javax.servlet.ServletException cannot be resolved to a type in spring web app

It seems to me that eclipse doesn't recognize the java ee web api (servlets, el, and so on). If you're using maven and don't want to configure eclipse with a specified server runtime, put the dependecy below in your web project pom:

<dependency>  
    <groupId>javax</groupId>    
    <artifactId>javaee-web-api</artifactId>    
    <version>7.0</version> <!-- Put here the version of your Java EE app, in my case 7.0 -->
    <scope>provided</scope>
</dependency>

Login failed for user 'DOMAIN\MACHINENAME$'

NETWORK SERVICE and LocalSystem will authenticate themselves always as the correpsonding account locally (builtin\network service and builtin\system) but both will authenticate as the machine account remotely.

If you see a failure like Login failed for user 'DOMAIN\MACHINENAME$' it means that a process running as NETWORK SERVICE or as LocalSystem has accessed a remote resource, has authenticated itself as the machine account and was denied authorization.

Typical example would be an ASP application running in an app pool set to use NETWORK SERVICE credential and connecting to a remote SQL Server: the app pool will authenticate as the machine running the app pool, and is this machine account that needs to be granted access.

When access is denied to a machine account, then access must be granted to the machine account. If the server refuses to login 'DOMAIN\MACHINE$', then you must grant login rights to 'DOMAIN\MACHINE$' not to NETWORK SERVICE. Granting access to NETWORK SERVICE would allow a local process running as NETWORK SERVICE to connect, not a remote one, since the remote one will authenticate as, you guessed, DOMAIN\MACHINE$.

If you expect the asp application to connect to the remote SQL Server as a SQL login and you get exceptions about DOMAIN\MACHINE$ it means you use Integrated Security in the connection string. If this is unexpected, it means you screwed up the connection strings you use.

Javascript date.getYear() returns 111 in 2011?

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/getYear

getYear is no longer used and has been replaced by the getFullYear method.

The getYear method returns the year minus 1900; thus:

  • For years greater than or equal to 2000, the value returned by getYear is 100 or greater. For example, if the year is 2026, getYear returns 126.
  • For years between and including 1900 and 1999, the value returned by getYear is between 0 and 99. For example, if the year is 1976, getYear returns 76.
  • For years less than 1900, the value returned by getYear is less than 0. For example, if the year is 1800, getYear returns -100.
  • To take into account years before and after 2000, you should use getFullYear instead of getYear so that the year is specified in full.

mysql after insert trigger which updates another table's column

Maybe remove the semi-colon after set because now the where statement doesn't belong to the update statement. Also the idRequest could be a problem, better write BookingRequest.idRequest

how to implement Pagination in reactJs

Give you a pagination component, which is maybe a little difficult to understand for newbie to react:

https://www.npmjs.com/package/pagination

Returning a value even if no result

Do search with LEFT OUTER JOIN. I don't know if MySQL allows inline VALUES in join clauses but you can have predefined table for this purposes.

A reference to the dll could not be added

I used dependency walker to check out the internal references the dll was having. Turns out it was in need of the VB runtime msvbvm60.dll and since my dev box doesnt have that installed I was unable to register it using regsvr32

That seems to be the answer to my original question for now.

How to get Time from DateTime format in SQL?

Try this, it will work:

CONVERT(VARCHAR(8),DATETIME,114)

For your reference.

How to generate a HTML page dynamically using PHP?

As per your requirement you dont have to generate a html page dynamicaly. It can be done by .htaccess file .

Still this is sample code to generate HTML Page

<?php

 $filename = 'test.html';
 header("Cache-Control: public");
 header("Content-Description: File Transfer");
 header("Content-Disposition: attachment; filename=$filename");
 header("Content-Type: application/octet-stream; ");
 header("Content-Transfer-Encoding: binary");
?>

you can create any .html , .php file just change extention in file name

Tar a directory, but don't store full absolute paths in the archive

One minor detail:

tar -cjf site1.tar.bz2 -C /var/www/site1 .

adds the files as

tar -tf site1.tar.bz2
./style.css
./index.html
./page2.html
./page3.html
./images/img1.png
./images/img2.png
./subdir/index.html

If you really want

tar -tf site1.tar.bz2
style.css
index.html
page2.html
page3.html
images/img1.png
images/img2.png
subdir/index.html

You should either cd into the directory first or run

tar -cjf site1.tar.bz2 -C /var/www/site1 $(ls /var/www/site1)

What is the correct syntax of ng-include?

This worked for me:

ng-include src="'views/templates/drivingskills.html'"

complete div:

<div id="drivivgskills" ng-controller="DrivingSkillsCtrl" ng-view ng-include src="'views/templates/drivingskills.html'" ></div>

How do I bind Twitter Bootstrap tooltips to dynamically created elements?

Try this one:

$('body').tooltip({
    selector: '[rel=tooltip]'
});

#ifdef replacement in the Swift language

This builds on Jon Willis's answer that relies upon assert, which only gets executed in Debug compilations:

func Log(_ str: String) { 
    assert(DebugLog(str)) 
}
func DebugLog(_ str: String) -> Bool { 
    print(str) 
    return true
}

My use case is for logging print statements. Here is a benchmark for Release version on iPhone X:

let iterations = 100_000_000
let time1 = CFAbsoluteTimeGetCurrent()
for i in 0 ..< iterations {
    Log ("? unarchiveArray:\(fileName) memoryTime:\(memoryTime) count:\(array.count)")
}
var time2 = CFAbsoluteTimeGetCurrent()
print ("Log: \(time2-time1)" )

prints:

Log: 0.0

Looks like Swift 4 completely eliminates the function call.

How to run a C# application at Windows startup?

Try this code:

private void RegisterInStartup(bool isChecked)
{
    RegistryKey registryKey = Registry.CurrentUser.OpenSubKey
            ("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
    if (isChecked)
    {
        registryKey.SetValue("ApplicationName", Application.ExecutablePath);
    }
    else
    {
        registryKey.DeleteValue("ApplicationName");
    }
}

Source (dead): http://www.dotnetthoughts.net/2010/09/26/run-the-application-at-windows-startup/

Archived link: https://web.archive.org/web/20110104113608/http://www.dotnetthoughts.net/2010/09/26/run-the-application-at-windows-startup/

static const vs #define

Pros and cons between #defines, consts and (what you have forgot) enums, depending on usage:

  1. enums:

    • only possible for integer values
    • properly scoped / identifier clash issues handled nicely, particularly in C++11 enum classes where the enumerations for enum class X are disambiguated by the scope X::
    • strongly typed, but to a big-enough signed-or-unsigned int size over which you have no control in C++03 (though you can specify a bit field into which they should be packed if the enum is a member of struct/class/union), while C++11 defaults to int but can be explicitly set by the programmer
    • can't take the address - there isn't one as the enumeration values are effectively substituted inline at the points of usage
    • stronger usage restraints (e.g. incrementing - template <typename T> void f(T t) { cout << ++t; } won't compile, though you can wrap an enum into a class with implicit constructor, casting operator and user-defined operators)
    • each constant's type taken from the enclosing enum, so template <typename T> void f(T) get a distinct instantiation when passed the same numeric value from different enums, all of which are distinct from any actual f(int) instantiation. Each function's object code could be identical (ignoring address offsets), but I wouldn't expect a compiler/linker to eliminate the unnecessary copies, though you could check your compiler/linker if you care.
    • even with typeof/decltype, can't expect numeric_limits to provide useful insight into the set of meaningful values and combinations (indeed, "legal" combinations aren't even notated in the source code, consider enum { A = 1, B = 2 } - is A|B "legal" from a program logic perspective?)
    • the enum's typename may appear in various places in RTTI, compiler messages etc. - possibly useful, possibly obfuscation
    • you can't use an enumeration without the translation unit actually seeing the value, which means enums in library APIs need the values exposed in the header, and make and other timestamp-based recompilation tools will trigger client recompilation when they're changed (bad!)

  1. consts:

    • properly scoped / identifier clash issues handled nicely
    • strong, single, user-specified type
      • you might try to "type" a #define ala #define S std::string("abc"), but the constant avoids repeated construction of distinct temporaries at each point of use
    • One Definition Rule complications
    • can take address, create const references to them etc.
    • most similar to a non-const value, which minimises work and impact if switching between the two
    • value can be placed inside the implementation file, allowing a localised recompile and just client links to pick up the change

  1. #defines:

    • "global" scope / more prone to conflicting usages, which can produce hard-to-resolve compilation issues and unexpected run-time results rather than sane error messages; mitigating this requires:
      • long, obscure and/or centrally coordinated identifiers, and access to them can't benefit from implicitly matching used/current/Koenig-looked-up namespace, namespace aliases etc.
      • while the trumping best-practice allows template parameter identifiers to be single-character uppercase letters (possibly followed by a number), other use of identifiers without lowercase letters is conventionally reserved for and expected of preprocessor defines (outside the OS and C/C++ library headers). This is important for enterprise scale preprocessor usage to remain manageable. 3rd party libraries can be expected to comply. Observing this implies migration of existing consts or enums to/from defines involves a change in capitalisation, and hence requires edits to client source code rather than a "simple" recompile. (Personally, I capitalise the first letter of enumerations but not consts, so I'd be hit migrating between those two too - maybe time to rethink that.)
    • more compile-time operations possible: string literal concatenation, stringification (taking size thereof), concatenation into identifiers
      • downside is that given #define X "x" and some client usage ala "pre" X "post", if you want or need to make X a runtime-changeable variable rather than a constant you force edits to client code (rather than just recompilation), whereas that transition is easier from a const char* or const std::string given they already force the user to incorporate concatenation operations (e.g. "pre" + X + "post" for string)
    • can't use sizeof directly on a defined numeric literal
    • untyped (GCC doesn't warn if compared to unsigned)
    • some compiler/linker/debugger chains may not present the identifier, so you'll be reduced to looking at "magic numbers" (strings, whatever...)
    • can't take the address
    • the substituted value need not be legal (or discrete) in the context where the #define is created, as it's evaluated at each point of use, so you can reference not-yet-declared objects, depend on "implementation" that needn't be pre-included, create "constants" such as { 1, 2 } that can be used to initialise arrays, or #define MICROSECONDS *1E-6 etc. (definitely not recommending this!)
    • some special things like __FILE__ and __LINE__ can be incorporated into the macro substitution
    • you can test for existence and value in #if statements for conditionally including code (more powerful than a post-preprocessing "if" as the code need not be compilable if not selected by the preprocessor), use #undef-ine, redefine etc.
    • substituted text has to be exposed:
      • in the translation unit it's used by, which means macros in libraries for client use must be in the header, so make and other timestamp-based recompilation tools will trigger client recompilation when they're changed (bad!)
      • or on the command line, where even more care is needed to make sure client code is recompiled (e.g. the Makefile or script supplying the definition should be listed as a dependency)

My personal opinion:

As a general rule, I use consts and consider them the most professional option for general usage (though the others have a simplicity appealing to this old lazy programmer).

Bootstrap table striped: How do I change the stripe background colour?

.table-striped>tbody>tr:nth-child(odd)>td,
.table-striped>tbody>tr:nth-child(odd)>th {
  background-color: #e08283;
  color: white;
}
.table-striped>tbody>tr:nth-child(even)>td,
.table-striped>tbody>tr:nth-child(even)>th {
  background-color: #ECEFF1;
  color: white;
}

Use 'even' for change colour of even rows and use 'odd' for change colour of odd rows.

Excel - Shading entire row based on change of value

What you can do is create a new column over on the right side of your spreadsheet that you'll use to compute a value you can base your shading on.

Let's say your new column is column D, and the value you want to look at is in column A starting in row 2.

In cell D2 put: =MOD(IF(ROW()=2,0,IF(A2=A1,D1, D1+1)), 2)

Fill that down as far as you need, (then hide the column if you want).

Now highlight your entire data set - this selection of cells will be the ones that get shaded in the next step.

From the Home tab, click Conditional Formatting, then New Rule.

Select Use a formula to determine which cells to format.

In "Format values where this formula is true" put =$D2=1

Click the Format button, click the Fill tab, then choose the color you want to shade with.

Examples here:

Interface naming in Java

Is there really a difference between:

class User implements IUser

and

class UserImpl implements User

if all we're talking about is naming conventions?

Personally I prefer NOT preceding the interface with I as I want to be coding to the interface and I consider that to be more important in terms of the naming convention. If you call the interface IUser then every consumer of that class needs to know its an IUser. If you call the class UserImpl then only the class and your DI container know about the Impl part and the consumers just know they're working with a User.

Then again, the times I've been forced to use Impl because a better name doesn't present itself have been few and far between because the implementation gets named according to the implementation because that's where it's important, e.g.

class DbBasedAccountDAO implements AccountDAO
class InMemoryAccountDAO implements AccountDAO

exit application when click button - iOS

exit(X), where X is a number (according to the doc) should work. But it is not recommended by Apple and won't be accepted by the AppStore. Why? Because of these guidelines (one of my app got rejected):

We found that your app includes a UI control for quitting the app. This is not in compliance with the iOS Human Interface Guidelines, as required by the App Store Review Guidelines.

Please refer to the attached screenshot/s for reference.

The iOS Human Interface Guidelines specify,

"Always Be Prepared to Stop iOS applications stop when people press the Home button to open a different application or use a device feature, such as the phone. In particular, people don’t tap an application close button or select Quit from a menu. To provide a good stopping experience, an iOS application should:

Save user data as soon as possible and as often as reasonable because an exit or terminate notification can arrive at any time.

Save the current state when stopping, at the finest level of detail possible so that people don’t lose their context when they start the application again. For example, if your app displays scrolling data, save the current scroll position."

> It would be appropriate to remove any mechanisms for quitting your app.

Plus, if you try to hide that function, it would be understood by the user as a crash.

Python main call within class

Well, first, you need to actually define a function before you can run it (and it doesn't need to be called main). For instance:

class Example(object):
    def run(self):
        print "Hello, world!"

if __name__ == '__main__':
    Example().run()

You don't need to use a class, though - if all you want to do is run some code, just put it inside a function and call the function, or just put it in the if block:

def main():
    print "Hello, world!"

if __name__ == '__main__':
    main()

or

if __name__ == '__main__':
    print "Hello, world!"

Single line sftp from terminal

To UPLOAD a single file, you will need to create a bash script. Something like the following should work on OS X if you have sshpass installed.

Usage:

sftpx <password> <user@hostname> <localfile> <remotefile>

Put this script somewhere in your path and call it sftpx:

#!/bin/bash

export RND=`cat /dev/urandom | env LC_CTYPE=C tr -cd 'a-f0-9' | head -c 32`
export TMPDIR=/tmp/$RND
export FILENAME=$(basename "$4")
export DSTDIR=$(dirname "$4")

mkdir $TMPDIR
cp "$3" $TMPDIR/$FILENAME

export SSHPASS=$1
sshpass -e sftp -oBatchMode=no -b - $2 << !
   lcd $TMPDIR
   cd $DSTDIR
   put $FILENAME
   bye
!

rm $TMPDIR/$FILENAME
rmdir $TMPDIR

Taskkill /f doesn't kill a process

I am going to suggest something here because I recently faced the same issue and I tried every possible thing in the answers but nothing worked. I was getting errors like

ERROR: The process with PID 23908 could not be terminated. Reason: There is no running instance of the task.

using command prompt. Power shell wasn't helpful either. it would simply execute the commands and no response with process still running.

Until I decided to delete the associated '.exe' file. Since the file was active, windows would not allow the deletion, but in that warning window it gave me the name of the process which was holding up the task I wanted to kill. I was able to kill the original task and thus the buggy process.

It is definitely worth a try if none of the solutions works out.

Drawing Isometric game worlds

Either way gets the job done. I assume that by zigzag you mean something like this: (numbers are order of rendering)

..  ..  01  ..  ..
  ..  06  02  ..
..  11  07  03  ..
  16  12  08  04
21  17  13  09  05
  22  18  14  10
..  23  19  15  ..
  ..  24  20  ..
..  ..  25  ..  ..

And by diamond you mean:

..  ..  ..  ..  ..
  01  02  03  04
..  05  06  07  ..
  08  09  10  11
..  12  13  14  ..
  15  16  17  18
..  19  20  21  ..
  22  23  24  25
..  ..  ..  ..  ..

The first method needs more tiles rendered so that the full screen is drawn, but you can easily make a boundary check and skip any tiles fully off-screen. Both methods will require some number crunching to find out what is the location of tile 01. In the end, both methods are roughly equal in terms of math required for a certain level of efficiency.

Open a link in browser with java button?

A solution without the Desktop environment is BrowserLauncher2. This solution is more general as on Linux, Desktop is not always available.

The lenghty answer is posted at https://stackoverflow.com/a/21676290/873282

How can I split this comma-delimited string in Python?

You don't want regular expressions here.

s = "144,1231693144,26959535291011309493156476344723991336010898738574164086137773096960,26959535291011309493156476344723991336010898738574164086137773096960,1.00,4295032833,1563,2747941 288,1231823695,26959535291011309493156476344723991336010898738574164086137773096960,26959535291011309493156476344723991336010898738574164086137773096960,1.00,4295032833,909,4725008"

print s.split(',')

Gives you:

['144', '1231693144', '26959535291011309493156476344723991336010898738574164086137773096960', '26959535291011309493156476344723991336010898738574164086137773096960', '1.00
', '4295032833', '1563', '2747941 288', '1231823695', '26959535291011309493156476344723991336010898738574164086137773096960', '26959535291011309493156476344723991336010898
738574164086137773096960', '1.00', '4295032833', '909', '4725008']

How to calculate UILabel height dynamically?

This is the extension I use for calculating multiline UILabel heights, it's an adjusted snippet from a previous stack overflow post:

extension UILabel {
    func estimatedHeight(forWidth: CGFloat, text: String, ofSize: CGFloat) -> CGFloat {

        let size = CGSize(width: forWidth, height: CGFloat(MAXFLOAT))

        let options = NSStringDrawingOptions.usesFontLeading.union(.usesLineFragmentOrigin)

        let attributes = [NSFontAttributeName: UIFont.systemFont(ofSize: ofSize)]

        let rectangleHeight = String(text).boundingRect(with: size, options: options, attributes: attributes, context: nil).height

        return ceil(rectangleHeight)
    }
}

How to fix "unable to open stdio.h in Turbo C" error?

Check if you have anything like those stdio.h file and other header files under INCLUDE folder and LIB folder. LIB contains some files. In my case, I had the same issue but both of these folder were blank.. good to know. Steps:

  1. Press: ALT + O + D (i.e. press ATL (keep pressed) and then O english character) and then D).
  2. You'll see a popup window.
  3. This window will have values for INCLUDE and LIB directories. The by default value for these two boxes in the popup window are: Drive leter where you installed TC... i.e. C:\ or D:\ or whatever followed by the path for INCLUDE and LIB folder. So, in my case,

    INCLUDE box was set to: "C:\TC\INCLUDE" and LIB directory value box was set to: "C:\TC\LIB" (without quotes). Steps to resolve:

  4. Press ALT + C.

  5. Set your current directory as C:\TC\BGI
  6. Press ALT + O + D, and put ../INCLUDE and ../LIB in Include/Lib directory values.
  7. and now... when you'll run your progress, you'll say thanks to me. I like the archduchess C fractal graphics that I'm running on DOS Turbo C right now. Lol.

Capture keyboardinterrupt in Python without try-except

I know this is an old question but I came here first and then discovered the atexit module. I do not know about its cross-platform track record or a full list of caveats yet, but so far it is exactly what I was looking for in trying to handle post-KeyboardInterrupt cleanup on Linux. Just wanted to throw in another way of approaching the problem.

I want to do post-exit clean-up in the context of Fabric operations, so wrapping everything in try/except wasn't an option for me either. I feel like atexit may be a good fit in such a situation, where your code is not at the top level of control flow.

atexit is very capable and readable out of the box, for example:

import atexit

def goodbye():
    print "You are now leaving the Python sector."

atexit.register(goodbye)

You can also use it as a decorator (as of 2.6; this example is from the docs):

import atexit

@atexit.register
def goodbye():
    print "You are now leaving the Python sector."

If you wanted to make it specific to KeyboardInterrupt only, another person's answer to this question is probably better.

But note that the atexit module is only ~70 lines of code and it would not be hard to create a similar version that treats exceptions differently, for example passing the exceptions as arguments to the callback functions. (The limitation of atexit that would warrant a modified version: currently I can't conceive of a way for the exit-callback-functions to know about the exceptions; the atexit handler catches the exception, calls your callback(s), then re-raises that exception. But you could do this differently.)

For more info see:

Attach the Java Source Code

The option provided by"praveenak" can also be applied to any other jar files with source file provided. For example, for JavaFx, we right click jfxrt.jar, select "Properties" and enter jdk1.8.0_05/javafx-src.zip for "Path" under External location.

using scp in terminal

Simple :::

scp remoteusername@remoteIP:/path/of/file /Local/path/to/copy

scp -r remoteusername@remoteIP:/path/of/folder /Local/path/to/copy

Finding a substring within a list in Python

I'd just use a simple regex, you can do something like this

import re
old_list = ['abc123', 'def456', 'ghi789']
new_list = [x for x in old_list if re.search('abc', x)]
for item in new_list:
    print item

How to take column-slices of dataframe in pandas

You can slice along the columns of a DataFrame by referring to the names of each column in a list, like so:

data = pandas.DataFrame(np.random.rand(10,5), columns = list('abcde'))
data_ab = data[list('ab')]
data_cde = data[list('cde')]

what's the default value of char?

'\u0000' stands for null . So if you print an uninitialized char variable , you'll get nothing.

Exporting results of a Mysql query to excel?

This is an old question, but it's still one of the first results on Google. The fastest way to do this is to link MySQL directly to Excel using ODBC queries or MySQL For Excel. The latter was mentioned in a comment to the OP, but I felt it really deserved its own answer because exporting to CSV is not the most efficient way to achieve this.

ODBC Queries - This is a little bit more complicated to setup, but it's a lot more flexible. For example, the MySQL For Excel add-in doesn't allow you to use WHERE clauses in the query expressions. The flexibility of this method also allows you to use the data in more complex ways.

MySQL For Excel - Use this add-in if you don't need to do anything complex with the query or if you need to get something accomplished quickly and easily. You can make views in your database to workaround some of the query limitations.

How to subtract a day from a date?

Also just another nice function i like to use when i want to compute i.e. first/last day of the last month or other relative timedeltas etc. ...

The relativedelta function from dateutil function (a powerful extension to the datetime lib)

import datetime as dt
from dateutil.relativedelta import relativedelta
#get first and last day of this and last month)
today = dt.date.today()
first_day_this_month = dt.date(day=1, month=today.month, year=today.year)
last_day_last_month = first_day_this_month - relativedelta(days=1)
print (first_day_this_month, last_day_last_month)

>2015-03-01 2015-02-28

Transform only one axis to log10 scale with ggplot2

I had a similar problem and this scale worked for me like a charm:

breaks = 10**(1:10)
scale_y_log10(breaks = breaks, labels = comma(breaks))

as you want the intermediate levels, too (10^3.5), you need to tweak the formatting:

breaks = 10**(1:10 * 0.5)
m <- ggplot(diamonds, aes(y = price, x = color)) + geom_boxplot()
m + scale_y_log10(breaks = breaks, labels = comma(breaks, digits = 1))

After executing::

enter image description here

Move SQL data from one table to another

Use this single sql statement which is safe no need of commit/rollback with multiple statements.

INSERT Table2 (
      username,password
) SELECT username,password
      FROM    (
           DELETE Table1
           OUTPUT
                   DELETED.username,
                   DELETED.password
           WHERE username = 'X' and password = 'X'
      ) AS RowsToMove ;

Works on SQL server make appropriate changes for MySql

Why do we need the "finally" clause in Python?

They are not equivalent. Finally code is run no matter what else happens. It is useful for cleanup code that has to run.

C# int to byte[]

If you want more general information about various methods of representing numbers including Two's Complement have a look at:

Two's Complement and Signed Number Representation on Wikipedia

How do you query for "is not null" in Mongo?

An alternative that has not been mentioned, but that may be a more efficient option for some (won't work with NULL entries) is to use a sparse index (entries in the index only exist when there is something in the field). Here is a sample data set:

db.foo.find()
{ "_id" : ObjectId("544540b31b5cf91c4893eb94"), "imageUrl" : "http://example.com/foo.jpg" }
{ "_id" : ObjectId("544540ba1b5cf91c4893eb95"), "imageUrl" : "http://example.com/bar.jpg" }
{ "_id" : ObjectId("544540c51b5cf91c4893eb96"), "imageUrl" : "http://example.com/foo.png" }
{ "_id" : ObjectId("544540c91b5cf91c4893eb97"), "imageUrl" : "http://example.com/bar.png" }
{ "_id" : ObjectId("544540ed1b5cf91c4893eb98"), "otherField" : 1 }
{ "_id" : ObjectId("544540f11b5cf91c4893eb99"), "otherField" : 2 }

Now, create the sparse index on imageUrl field:

db.foo.ensureIndex( { "imageUrl": 1 }, { sparse: true } )
{
    "createdCollectionAutomatically" : false,
    "numIndexesBefore" : 1,
    "numIndexesAfter" : 2,
    "ok" : 1
}

Now, there is always a chance (and in particular with a small data set like my sample) that rather than using an index, MongoDB will use a table scan, even for a potential covered index query. As it turns out that gives me an easy way to illustrate the difference here:

db.foo.find({}, {_id : 0, imageUrl : 1})
{ "imageUrl" : "http://example.com/foo.jpg" }
{ "imageUrl" : "http://example.com/bar.jpg" }
{ "imageUrl" : "http://example.com/foo.png" }
{ "imageUrl" : "http://example.com/bar.png" }
{  }
{  }

OK, so the extra documents with no imageUrl are being returned, just empty, not what we wanted. Just to confirm why, do an explain:

db.foo.find({}, {_id : 0, imageUrl : 1}).explain()
{
    "cursor" : "BasicCursor",
    "isMultiKey" : false,
    "n" : 6,
    "nscannedObjects" : 6,
    "nscanned" : 6,
    "nscannedObjectsAllPlans" : 6,
    "nscannedAllPlans" : 6,
    "scanAndOrder" : false,
    "indexOnly" : false,
    "nYields" : 0,
    "nChunkSkips" : 0,
    "millis" : 0,
    "server" : "localhost:31100",
    "filterSet" : false
}

So, yes, a BasicCursor equals a table scan, it did not use the index. Let's force the query to use our sparse index with a hint():

db.foo.find({}, {_id : 0, imageUrl : 1}).hint({imageUrl : 1})
{ "imageUrl" : "http://example.com/bar.jpg" }
{ "imageUrl" : "http://example.com/bar.png" }
{ "imageUrl" : "http://example.com/foo.jpg" }
{ "imageUrl" : "http://example.com/foo.png" }

And there is the result we were looking for - only documents with the field populated are returned. This also only uses the index (i.e. it is a covered index query), so only the index needs to be in memory to return the results.

This is a specialized use case and can't be used generally (see other answers for those options). In particular it should be noted that as things stand you cannot use count() in this way (for my example it will return 6 not 4), so please only use when appropriate.

How to do a regular expression replace in MySQL?

UPDATE 2: A useful set of regex functions including REGEXP_REPLACE have now been provided in MySQL 8.0. This renders reading on unnecessary unless you're constrained to using an earlier version.


UPDATE 1: Have now made this into a blog post: http://stevettt.blogspot.co.uk/2018/02/a-mysql-regular-expression-replace.html


The following expands upon the function provided by Rasika Godawatte but trawls through all necessary substrings rather than just testing single characters:

-- ------------------------------------------------------------------------------------
-- USAGE
-- ------------------------------------------------------------------------------------
-- SELECT reg_replace(<subject>,
--                    <pattern>,
--                    <replacement>,
--                    <greedy>,
--                    <minMatchLen>,
--                    <maxMatchLen>);
-- where:
-- <subject> is the string to look in for doing the replacements
-- <pattern> is the regular expression to match against
-- <replacement> is the replacement string
-- <greedy> is TRUE for greedy matching or FALSE for non-greedy matching
-- <minMatchLen> specifies the minimum match length
-- <maxMatchLen> specifies the maximum match length
-- (minMatchLen and maxMatchLen are used to improve efficiency but are
--  optional and can be set to 0 or NULL if not known/required)
-- Example:
-- SELECT reg_replace(txt, '^[Tt][^ ]* ', 'a', TRUE, 2, 0) FROM tbl;
DROP FUNCTION IF EXISTS reg_replace;
DELIMITER //
CREATE FUNCTION reg_replace(subject VARCHAR(21845), pattern VARCHAR(21845),
  replacement VARCHAR(21845), greedy BOOLEAN, minMatchLen INT, maxMatchLen INT)
RETURNS VARCHAR(21845) DETERMINISTIC BEGIN 
  DECLARE result, subStr, usePattern VARCHAR(21845); 
  DECLARE startPos, prevStartPos, startInc, len, lenInc INT;
  IF subject REGEXP pattern THEN
    SET result = '';
    -- Sanitize input parameter values
    SET minMatchLen = IF(minMatchLen < 1, 1, minMatchLen);
    SET maxMatchLen = IF(maxMatchLen < 1 OR maxMatchLen > CHAR_LENGTH(subject),
                         CHAR_LENGTH(subject), maxMatchLen);
    -- Set the pattern to use to match an entire string rather than part of a string
    SET usePattern = IF (LEFT(pattern, 1) = '^', pattern, CONCAT('^', pattern));
    SET usePattern = IF (RIGHT(pattern, 1) = '$', usePattern, CONCAT(usePattern, '$'));
    -- Set start position to 1 if pattern starts with ^ or doesn't end with $.
    IF LEFT(pattern, 1) = '^' OR RIGHT(pattern, 1) <> '$' THEN
      SET startPos = 1, startInc = 1;
    -- Otherwise (i.e. pattern ends with $ but doesn't start with ^): Set start pos
    -- to the min or max match length from the end (depending on "greedy" flag).
    ELSEIF greedy THEN
      SET startPos = CHAR_LENGTH(subject) - maxMatchLen + 1, startInc = 1;
    ELSE
      SET startPos = CHAR_LENGTH(subject) - minMatchLen + 1, startInc = -1;
    END IF;
    WHILE startPos >= 1 AND startPos <= CHAR_LENGTH(subject)
      AND startPos + minMatchLen - 1 <= CHAR_LENGTH(subject)
      AND !(LEFT(pattern, 1) = '^' AND startPos <> 1)
      AND !(RIGHT(pattern, 1) = '$'
            AND startPos + maxMatchLen - 1 < CHAR_LENGTH(subject)) DO
      -- Set start length to maximum if matching greedily or pattern ends with $.
      -- Otherwise set starting length to the minimum match length.
      IF greedy OR RIGHT(pattern, 1) = '$' THEN
        SET len = LEAST(CHAR_LENGTH(subject) - startPos + 1, maxMatchLen), lenInc = -1;
      ELSE
        SET len = minMatchLen, lenInc = 1;
      END IF;
      SET prevStartPos = startPos;
      lenLoop: WHILE len >= 1 AND len <= maxMatchLen
                 AND startPos + len - 1 <= CHAR_LENGTH(subject)
                 AND !(RIGHT(pattern, 1) = '$' 
                       AND startPos + len - 1 <> CHAR_LENGTH(subject)) DO
        SET subStr = SUBSTRING(subject, startPos, len);
        IF subStr REGEXP usePattern THEN
          SET result = IF(startInc = 1,
                          CONCAT(result, replacement), CONCAT(replacement, result));
          SET startPos = startPos + startInc * len;
          LEAVE lenLoop;
        END IF;
        SET len = len + lenInc;
      END WHILE;
      IF (startPos = prevStartPos) THEN
        SET result = IF(startInc = 1, CONCAT(result, SUBSTRING(subject, startPos, 1)),
                        CONCAT(SUBSTRING(subject, startPos, 1), result));
        SET startPos = startPos + startInc;
      END IF;
    END WHILE;
    IF startInc = 1 AND startPos <= CHAR_LENGTH(subject) THEN
      SET result = CONCAT(result, RIGHT(subject, CHAR_LENGTH(subject) + 1 - startPos));
    ELSEIF startInc = -1 AND startPos >= 1 THEN
      SET result = CONCAT(LEFT(subject, startPos), result);
    END IF;
  ELSE
    SET result = subject;
  END IF;
  RETURN result;
END//
DELIMITER ;

Demo

Rextester Demo

Limitations

  1. This method is of course going to take a while when the subject string is large. Update: Have now added minimum and maximum match length parameters for improved efficiency when these are known (zero = unknown/unlimited).
  2. It won't allow substitution of backreferences (e.g. \1, \2 etc.) to replace capturing groups. If this functionality is needed, please see this answer which attempts to provide a workaround by updating the function to allow a secondary find and replace within each found match (at the expense of increased complexity).
  3. If ^and/or $ is used in the pattern, they must be at the very start and very end respectively - e.g. patterns such as (^start|end$) are not supported.
  4. There is a "greedy" flag to specify whether the overall matching should be greedy or non-greedy. Combining greedy and lazy matching within a single regular expression (e.g. a.*?b.*) is not supported.

Usage Examples

The function has been used to answer the following StackOverflow questions:

Disabled form inputs do not appear in the request

To post values from disabled inputs in addition to enabled inputs, you can simply re-enable all of the form's inputs as it is being submitted.

<form onsubmit="this.querySelectorAll('input').forEach(i => i.disabled = false)">
    <!-- Re-enable all input elements on submit so they are all posted, 
         even if currently disabled. -->

    <!-- form content with input elements -->
</form>

If you prefer jQuery:

<form onsubmit="$(this).find('input').prop('disabled', false)">
    <!-- Re-enable all input elements on submit so they are all posted, 
         even if currently disabled. -->

    <!-- form content with input elements -->
</form>

For ASP.NET MVC C# Razor, you add the submit handler like this:

using (Html.BeginForm("ActionName", "ControllerName", FormMethod.Post,
    // Re-enable all input elements on submit so they are all posted, even if currently disabled.
    new { onsubmit = "this.querySelectorAll('input').forEach(i => i.disabled = false)" } ))
{
    <!-- form content with input elements -->
}

Can you hide the controls of a YouTube embed without enabling autoplay?

Autoplay works only with /v/ instead of /embed/, so change the src to:

src="//www.youtube.com/v/qUJYqhKZrwA?autoplay=1&showinfo=0&controls=0"

The view didn't return an HttpResponse object. It returned None instead

Python is very sensitive to indentation, with the code below I got the same error:

    except IntegrityError as e:
        if 'unique constraint' in e.args:
            return render(request, "calender.html")

The correct indentation is:

    except IntegrityError as e:
        if 'unique constraint' in e.args:
        return render(request, "calender.html")

What's the difference between .so, .la and .a library files?

.so files are dynamic libraries. The suffix stands for "shared object", because all the applications that are linked with the library use the same file, rather than making a copy in the resulting executable.

.a files are static libraries. The suffix stands for "archive", because they're actually just an archive (made with the ar command -- a predecessor of tar that's now just used for making libraries) of the original .o object files.

.la files are text files used by the GNU "libtools" package to describe the files that make up the corresponding library. You can find more information about them in this question: What are libtool's .la file for?

Static and dynamic libraries each have pros and cons.

Static pro: The user always uses the version of the library that you've tested with your application, so there shouldn't be any surprising compatibility problems.

Static con: If a problem is fixed in a library, you need to redistribute your application to take advantage of it. However, unless it's a library that users are likely to update on their own, you'd might need to do this anyway.

Dynamic pro: Your process's memory footprint is smaller, because the memory used for the library is amortized among all the processes using the library.

Dynamic pro: Libraries can be loaded on demand at run time; this is good for plugins, so you don't have to choose the plugins to be used when compiling and installing the software. New plugins can be added on the fly.

Dynamic con: The library might not exist on the system where someone is trying to install the application, or they might have a version that's not compatible with the application. To mitigate this, the application package might need to include a copy of the library, so it can install it if necessary. This is also often mitigated by package managers, which can download and install any necessary dependencies.

Dynamic con: Link-Time Optimization is generally not possible, so there could possibly be efficiency implications in high-performance applications. See the Wikipedia discussion of WPO and LTO.

Dynamic libraries are especially useful for system libraries, like libc. These libraries often need to include code that's dependent on the specific OS and version, because kernel interfaces have changed. If you link a program with a static system library, it will only run on the version of the OS that this library version was written for. But if you use a dynamic library, it will automatically pick up the library that's installed on the system you run on.

NPM stuck giving the same error EISDIR: Illegal operation on a directory, read at error (native)

Make sure to check your version of npm and whether or not there are issues with it. I was having the same issue at the time of this post and I discovered that my npm version (6.5) was having issues. I had to uninstall and reinstall npm version 6.4.1 and then everything started to work great again.

Determine if Python is running inside virtualenv

In windows OS you see something like this:

C:\Users\yourusername\virtualEnvName\Scripts>activate
(virtualEnvName) C:\Users\yourusername\virtualEnvName\Scripts>

Parentheses mean that you are actually in the virtual environment called "virtualEnvName".

Removing viewcontrollers from navigation stack

Using setViewControllers function from UINavigationController is the best way. There is also animated parameter to enable animation.

func setViewControllers(_ viewControllers: [UIViewController], animated: Bool)

Example in swift for question

func goToFifthVC() {

    var currentVCStack = self.navigationController?.viewControllers
    currentVCStack?.removeSubrange(2...3)

    let fifthVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "fifthVC")
    currentVCStack?.append(fifthVC)

    self.navigationController?.setViewControllers(currentVCStack!, animated: true)
}

I tried other ways like [tempVC removeFromParentViewController];. It make weird behaviour, removed ViewController navigation still showing when pop back like reported by @robin-ellerkmann

How to wait 5 seconds with jQuery?

I realize that this is an old question, but here's a plugin to address this issue that someone might find useful.

https://github.com/madbook/jquery.wait

lets you do this:

$('#myElement').addClass('load').wait(5000).addClass('done');

The reason why you should use .wait instead of .delay is because not all jquery functions are supported by .delay and that .delay only works with animation functions. For example delay does not support .addClass and .removeClass

Or you can use this function instead.

function sleep(milliseconds) {
  var start = new Date().getTime();
  for (var i = 0; i < 1e7; i++) {
    if ((new Date().getTime() - start) > milliseconds){
      break;
    }
  }
}

sleep(5000);

How would I create a UIAlertView in Swift?

SwiftUI on Swift 5.x and Xcode 11.x

import SwiftUI

struct ContentView: View {

    @State private var isShowingAlert = false

    var body: some View {
        VStack {
            Button("A Button") {

                self.isShowingAlert.toggle()
            }
            .alert(isPresented: $isShowingAlert) { () -> Alert in
                Alert(
                    title: Text("Alert"),
                    message: Text("This is an alert"),
                    dismissButton:
                        .default(
                            Text("OK"),
                            action: {
                                print("Dismissing alert")
                            }
                        )
                )
            }

        }
        .padding()
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

How to change progress bar's progress color in Android

You can try to change your Styles, Themes, or using android:indeterminateTint="@color/yourColor" anywhere you want, but there's just one way o doing that will work on any Android SKD version:

If you progress bar is not indeterminate, please use:

progressBar.getProgressDrawable().setColorFilter(ContextCompat.getColor(context, R.color.yourColor), PorterDuff.Mode.SRC_IN );

If you progress bar is indeterminate, please use:

progressBar.getIndeterminateDrawable().setColorFilter(ContextCompat.getColor(getContext(), R.color.yourColor), PorterDuff.Mode.SRC_IN );

It's sad that Android is such a mess!

Sum all the elements java arraylist

I haven't tested it but it should work.

public double incassoMargherita()
{
    double sum = 0;
    for(int i = 0; i < m.size(); i++)
    {
        sum = sum + m.get(i);
    }
    return sum;
}

Test if a string contains a word in PHP?

<?php
//  Use this function and Pass Mixed string and what you want to search in mixed string.
//  For Example :
    $mixedStr = "hello world. This is john duvey";
    $searchStr= "john";

    if(strpos($mixedStr,$searchStr)) {
      echo "Your string here";
    }else {
      echo "String not here";
    }

Get method arguments using Spring AOP?

If you have to log all args or your method have one argument, you can simply use getArgs like described in previous answers.

If you have to log a specific arg, you can annoted it and then recover its value like this :

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
public @interface Data {
 String methodName() default "";
}

@Aspect
public class YourAspect {

 @Around("...")
 public Object around(ProceedingJoinPoint point) throws Throwable {
  Method method = MethodSignature.class.cast(point.getSignature()).getMethod();
  Object[] args = point.getArgs();
  StringBuilder data = new StringBuilder();
    Annotation[][] parameterAnnotations = method.getParameterAnnotations();
    for (int argIndex = 0; argIndex < args.length; argIndex++) {
        for (Annotation paramAnnotation : parameterAnnotations[argIndex]) {
            if (!(paramAnnotation instanceof Data)) {
                continue;
            }
            Data dataAnnotation = (Data) paramAnnotation;
            if (dataAnnotation.methodName().length() > 0) {
                Object obj = args[argIndex];
                Method dataMethod = obj.getClass().getMethod(dataAnnotation.methodName());
                data.append(dataMethod.invoke(obj));
                continue;
            }
            data.append(args[argIndex]);
        }
    }
 }
}

Examples of use :

public void doSomething(String someValue, @Data String someData, String otherValue) {
    // Apsect will log value of someData param
}

public void doSomething(String someValue, @Data(methodName = "id") SomeObject someData, String otherValue) {
    // Apsect will log returned value of someData.id() method
}

What does "control reaches end of non-void function" mean?

Compiler by itself would not know that the conditions you have given are optimum .. meaning of this is you have covered all cases .. So therefore it always wants a return statement ... So either you can change last else if with else or just write return 0 after last else if ;`int binary(int val, int sorted[], int low, int high) { int mid = (low+high)/2;

if(high < low)
    return -1;

if(val < sorted[mid])
    return binary(val, sorted, low, mid-1);

else if(val > sorted[mid])
    return binary(val, sorted, mid+1, high);

else if(val == sorted[mid])
    return mid;
return 0; }`

Are there constants in JavaScript?

You can easily equip your script with a mechanism for constants that can be set but not altered. An attempt to alter them will generate an error.

/* author Keith Evetts 2009 License: LGPL  
anonymous function sets up:  
global function SETCONST (String name, mixed value)  
global function CONST (String name)  
constants once set may not be altered - console error is generated  
they are retrieved as CONST(name)  
the object holding the constants is private and cannot be accessed from the outer script directly, only through the setter and getter provided  
*/

(function(){  
  var constants = {};  
  self.SETCONST = function(name,value) {  
      if (typeof name !== 'string') { throw new Error('constant name is not a string'); }  
      if (!value) { throw new Error(' no value supplied for constant ' + name); }  
      else if ((name in constants) ) { throw new Error('constant ' + name + ' is already defined'); }   
      else {   
          constants[name] = value;   
          return true;  
    }    
  };  
  self.CONST = function(name) {  
      if (typeof name !== 'string') { throw new Error('constant name is not a string'); }  
      if ( name in constants ) { return constants[name]; }    
      else { throw new Error('constant ' + name + ' has not been defined'); }  
  };  
}())  


// -------------  demo ----------------------------  
SETCONST( 'VAT', 0.175 );  
alert( CONST('VAT') );


//try to alter the value of VAT  
try{  
  SETCONST( 'VAT', 0.22 );  
} catch ( exc )  {  
   alert (exc.message);  
}  
//check old value of VAT remains  
alert( CONST('VAT') );  


// try to get at constants object directly  
constants['DODO'] = "dead bird";  // error  

JUnit test for System.out.println()

You can set the System.out print stream via setOut() (and for in and err). Can you redirect this to a print stream that records to a string, and then inspect that ? That would appear to be the simplest mechanism.

(I would advocate, at some stage, convert the app to some logging framework - but I suspect you already are aware of this!)

Auto-center map with multiple markers in Google Maps API v3

i had a situation where i can't change old code, so added this javascript function to calculate center point and zoom level:

_x000D_
_x000D_
//input_x000D_
var tempdata = ["18.9400|72.8200-19.1717|72.9560-28.6139|77.2090"];_x000D_
_x000D_
function getCenterPosition(tempdata){_x000D_
 var tempLat = tempdata[0].split("-");_x000D_
 var latitudearray = [];_x000D_
 var longitudearray = [];_x000D_
 var i;_x000D_
 for(i=0; i<tempLat.length;i++){_x000D_
  var coordinates = tempLat[i].split("|");_x000D_
  latitudearray.push(coordinates[0]);_x000D_
  longitudearray.push(coordinates[1]);_x000D_
 }_x000D_
 latitudearray.sort(function (a, b) { return a-b; });_x000D_
 longitudearray.sort(function (a, b) { return a-b; });_x000D_
 var latdifferenece = latitudearray[latitudearray.length-1] - latitudearray[0];_x000D_
 var temp = (latdifferenece / 2).toFixed(4) ;_x000D_
 var latitudeMid = parseFloat(latitudearray[0]) + parseFloat(temp);_x000D_
 var longidifferenece = longitudearray[longitudearray.length-1] - longitudearray[0];_x000D_
 temp = (longidifferenece / 2).toFixed(4) ;_x000D_
 var longitudeMid = parseFloat(longitudearray[0]) + parseFloat(temp);_x000D_
 var maxdifference = (latdifferenece > longidifferenece)? latdifferenece : longidifferenece;_x000D_
 var zoomvalue; _x000D_
 if(maxdifference >= 0 && maxdifference <= 0.0037)  //zoom 17_x000D_
  zoomvalue='17';_x000D_
 else if(maxdifference > 0.0037 && maxdifference <= 0.0070)  //zoom 16_x000D_
  zoomvalue='16';_x000D_
 else if(maxdifference > 0.0070 && maxdifference <= 0.0130)  //zoom 15_x000D_
  zoomvalue='15';_x000D_
 else if(maxdifference > 0.0130 && maxdifference <= 0.0290)  //zoom 14_x000D_
  zoomvalue='14';_x000D_
 else if(maxdifference > 0.0290 && maxdifference <= 0.0550)  //zoom 13_x000D_
  zoomvalue='13';_x000D_
 else if(maxdifference > 0.0550 && maxdifference <= 0.1200)  //zoom 12_x000D_
  zoomvalue='12';_x000D_
 else if(maxdifference > 0.1200 && maxdifference <= 0.4640)  //zoom 10_x000D_
  zoomvalue='10';_x000D_
 else if(maxdifference > 0.4640 && maxdifference <= 1.8580)  //zoom 8_x000D_
  zoomvalue='8';_x000D_
 else if(maxdifference > 1.8580 && maxdifference <= 3.5310)  //zoom 7_x000D_
  zoomvalue='7';_x000D_
 else if(maxdifference > 3.5310 && maxdifference <= 7.3367)  //zoom 6_x000D_
  zoomvalue='6';_x000D_
 else if(maxdifference > 7.3367 && maxdifference <= 14.222)  //zoom 5_x000D_
  zoomvalue='5';_x000D_
 else if(maxdifference > 14.222 && maxdifference <= 28.000)  //zoom 4_x000D_
  zoomvalue='4';_x000D_
 else if(maxdifference > 28.000 && maxdifference <= 58.000)  //zoom 3_x000D_
  zoomvalue='3';_x000D_
 else_x000D_
  zoomvalue='1';_x000D_
 return latitudeMid+'|'+longitudeMid+'|'+zoomvalue;_x000D_
}
_x000D_
_x000D_
_x000D_

Get statistics for each group (such as count, mean, etc) using pandas GroupBy?

We can easily do it by using groupby and count. But, we should remember to use reset_index().

df[['col1','col2','col3','col4']].groupby(['col1','col2']).count().\
reset_index()

Angular2 - TypeScript : Increment a number after timeout in AppComponent

This is not valid TypeScript code. You can not have method invocations in the body of a class.

// INVALID CODE
export class AppComponent {
  public n: number = 1;
  setTimeout(function() {
    n = n + 10;
  }, 1000);
}

Instead move the setTimeout call to the constructor of the class. Additionally, use the arrow function => to gain access to this.

export class AppComponent {
  public n: number = 1;

  constructor() {
    setTimeout(() => {
      this.n = this.n + 10;
    }, 1000);
  }

}

In TypeScript, you can only refer to class properties or methods via this. That's why the arrow function => is important.

AJAX Mailchimp signup form integration

In the other hand, there is some packages in AngularJS which are helpful (in AJAX WEB):

https://github.com/cgarnier/angular-mailchimp-subscribe

Is it possible to set async:false to $.getJSON call

I don't think you can set that option there. You will have to use jQuery.ajax() with the appropriate parameters (basically getJSON just wraps that call into an easier API, as well).

Playing m3u8 Files with HTML Video Tag

Use Flowplayer:

<link rel="stylesheet" href="//releases.flowplayer.org/7.0.4/commercial/skin/skin.css">
    <style>

   </style>
   <script src="//code.jquery.com/jquery-1.12.4.min.js"></script>
  <script src="//releases.flowplayer.org/7.0.4/commercial/flowplayer.min.js"></script>
  <script src="//releases.flowplayer.org/hlsjs/flowplayer.hlsjs.min.js"></script> 
  <script>
  flowplayer(function (api) {
    api.on("load", function (e, api, video) {
      $("#vinfo").text(api.engine.engineName + " engine playing " + video.type);
    }); });
  </script>

<div class="flowplayer fixed-controls no-toggle no-time play-button obj"
      style="    width: 85.5%;
    height: 80%;
    margin-left: 7.2%;
    margin-top: 6%;
    z-index: 1000;" data-key="$812975748999788" data-live="true" data-share="false" data-ratio="0.5625"  data-logo="">
      <video autoplay="true" stretch="true">

         <source type="application/x-mpegurl" src="http://live.wmncdn.net/safaritv2/live2.stream/index.m3u8">
      </video>   
   </div>

Different methods are available in flowplayer.org website.

React Native absolute positioning horizontal centre

You can center absolute items by providing the left property with the width of the device divided by two and subtracting out half of the element you'd like to center's width.

For example, your style might look something like this.

bottom: {
    position: 'absolute',
    left: (Dimensions.get('window').width / 2) - 25,
    top: height*0.93,
}

subtract time from date - moment js

There is a simple function subtract which moment library gives us to subtract time from some time. Using it is also very simple.

moment(Date.now()).subtract(7, 'days'); // This will subtract 7 days from current time
moment(Date.now()).subtract(3, 'd'); // This will subtract 3 days from current time

//You can do this for days, years, months, hours, minutes, seconds
//You can also subtract multiple things simulatneously

//You can chain it like this.
moment(Date.now()).subtract(3, 'd').subtract(5. 'h'); // This will subtract 3 days and 5 hours from current time

//You can also use it as object literal
moment(Date.now()).subtract({days:3, hours:5}); // This will subtract 3 days and 5 hours from current time

Hope this helps!

Android Studio Google JAR file causing GC overhead limit exceeded error

Add this to build.gradle file

dexOptions {
   javaMaxHeapSize "2g"
}

PHP - include a php file and also send query parameters

You could do something like this to achieve the effect you are after:

$_GET['id']=$somevar;
include('myFile.php');

However, it sounds like you are using this include like some kind of function call (you mention calling it repeatedly with different arguments).

In this case, why not turn it into a regular function, included once and called multiple times?

Android view pager with page indicator

Here are a few things you need to do:

1-Download the library if you haven't already done that.

2- Import into Eclipse.

3- Set you project to use the library: Project-> Properties -> Android -> Scroll down to Library section, click Add... and select viewpagerindicator.

4- Now you should be able to import com.viewpagerindicator.TitlePageIndicator.

Now about implementing this without using fragments:

In the sample that comes with viewpagerindicatior, you can see that the library is being used with a ViewPager which has a FragmentPagerAdapter.

But in fact the library itself is Fragment independant. It just needs a ViewPager. So just use a PagerAdapter instead of a FragmentPagerAdapter and you're good to go.

What is the most efficient way to concatenate N arrays?

Here is a function by which you can concatenate multiple number of arrays

function concatNarrays(args) {
    args = Array.prototype.slice.call(arguments);
    var newArr = args.reduce( function(prev, next) {
       return prev.concat(next) ;
    });

    return newArr;
}

Example -

console.log(concatNarrays([1, 2, 3], [5, 2, 1, 4], [2,8,9]));

will output

[1,2,3,5,2,1,4,2,8,9]

PostgreSQL database default location on Linux

The "directory where postgresql will keep all databases" (and configuration) is called "data directory" and corresponds to what PostgreSQL calls (a little confusingly) a "database cluster", which is not related to distributed computing, it just means a group of databases and related objects managed by a PostgreSQL server.

The location of the data directory depends on the distribution. If you install from source, the default is /usr/local/pgsql/data:

In file system terms, a database cluster will be a single directory under which all data will be stored. We call this the data directory or data area. It is completely up to you where you choose to store your data. There is no default, although locations such as /usr/local/pgsql/data or /var/lib/pgsql/data are popular. (ref)

Besides, an instance of a running PostgreSQL server is associated to one cluster; the location of its data directory can be passed to the server daemon ("postmaster" or "postgres") in the -D command line option, or by the PGDATA environment variable (usually in the scope of the running user, typically postgres). You can usually see the running server with something like this:

[root@server1 ~]# ps auxw |  grep postgres | grep -- -D
postgres  1535  0.0  0.1  39768  1584 ?        S    May17   0:23 /usr/local/pgsql/bin/postgres -D /usr/local/pgsql/data

Note that it is possible, though not very frequent, to run two instances of the same PostgreSQL server (same binaries, different processes) that serve different "clusters" (data directories). Of course, each instance would listen on its own TCP/IP port.

What are the aspect ratios for all Android phone and tablet devices?

In case anyone wanted more of a visual reference:

aspect_ratio_visual_reference

Decimal approximations reference table:

+----------------------------------------------------------------------------+
¦       aspect ratio       ¦     decimal approx.    ¦     decimal approx.    ¦
¦ [long edge x short edge] ¦ [short edge/long edge] ¦ [long edge/short edge] ¦
¦--------------------------+------------------------+------------------------¦
¦         19.5 x 9         ¦        0.462...        ¦        2.167...        ¦
¦--------------------------+------------------------+------------------------¦
¦          19 x 9          ¦        0.474...        ¦         2.11...        ¦
¦--------------------------+------------------------+------------------------¦
¦        ~18.7 x 9         ¦        0.482...        ¦        2.074...        ¦
¦--------------------------+------------------------+------------------------¦    
¦         18.5 x 9         ¦        0.486...        ¦        2.056...        ¦
¦--------------------------+------------------------+------------------------¦
¦          18 x 9          ¦           0.5          ¦            2           ¦
¦--------------------------+------------------------+------------------------¦
¦          19 x 10         ¦        0.526...        ¦           1.9          ¦
¦--------------------------+------------------------+------------------------¦
¦          16 x 9          ¦         0.5625         ¦        1.778...        ¦
¦--------------------------+------------------------+------------------------¦
¦           5 x 3          ¦           0.6          ¦        1.667...        ¦
¦--------------------------+------------------------+------------------------¦
¦          16 x 10         ¦          0.625         ¦           1.6          ¦
¦--------------------------+------------------------+------------------------¦
¦           3 x 2          ¦        0.667...        ¦           1.5          ¦
¦--------------------------+------------------------+------------------------¦
¦           4 x 3          ¦          0.75          ¦        1.333...        ¦
+----------------------------------------------------------------------------+

Changelog:

  • May 2018: Added 56x27 === ~18.7x9 (Huawei P20), 19x9 (Nokia X6 2018) and 19.5x9 (LG G7 ThinQ)
  • May 2017: Added 19x10 (Essential Phone)
  • March 2017: Added 18.5x9 (Samsung Galaxy S8) and 18x9 (LG G6)

HTML5 Video not working in IE 11

I used MP4Box to decode the atom tags in the mp4. (MP4Box -v myfile.mp4) I also used ffmpeg to convert the mp41 to mp42. After comparing the differences and experimenting, I found that IE11 did not like that my original mp4 had two avC1 atoms inside stsd.

After deleting the duplicate avC1 in my original mp41 mp4, IE11 would play the mp4.

MongoDB running but can't connect using shell

Not so much an answer but more of an FYI:I've just hit this and found this question as a result of searching. Here is the details of my experience:

Shell error

markdsievers@ip-xx-xx-xx-xx:~$ mongo
MongoDB shell version: 2.0.1
connecting to: test
Wed Dec 21 03:36:13 Socket recv() errno:104 Connection reset by peer 127.0.0.1:27017
Wed Dec 21 03:36:13 SocketException: remote: 127.0.0.1:27017 error: 9001 socket exception [1] server [127.0.0.1:27017] 
Wed Dec 21 03:36:13 DBClientCursor::init call() failed
Wed Dec 21 03:36:13 Error: Error during mongo startup. :: caused by :: DBClientBase::findN: transport error: 127.0.0.1 query: { whatsmyuri: 1 } shell/mongo.js:84
exception: connect failed

Mongo logs reveal

Wed Dec 21 03:35:04 [initandlisten] connection accepted from 127.0.0.1:50273 #6612
Wed Dec 21 03:35:04 [initandlisten] connection refused because too many open connections: 819

This perhaps indicates the other answer (JaKi) was experiencing the same thing, where some connections were purged and access made possible again for the shell (other clients)

Best solution to protect PHP code without encryption

Obfuscating things can only inconvenience your legitimate, law-abiding customers, while the people who would would rip you off are not your target paying customers anyway. (edited out other thoughts about obfuscation)

Another suggestion for protecting your software: create a business model in which the code is an incomplete part of the value of your offering. For example, sell product licenses along with access to some data you manage on your site, or license the product on a subscription model or with customer support.

Designing a EULA is a legal matter, not a coding matter. You can start by reading some EULA text for products and websites you use. You might find some interesting details!

Creating a proprietary license is is highly flexible, and probably a subject beyond the intended scope of StackOverflow, since it's not strictly about coding.

Some parts of a EULA that come to mind:

  • Limiting your liability if the product has bugs or causes damage.
  • Spelling out how the customer can use their licensed software, for how long, on how many machines, with or without redistribution rights, etc.
  • Giving you rights to audit their site, so you can enforce the licenses.
  • What happens if they violate the EULA, e.g. they lose their privilege to use your software.

You should consult a legal professional to prepare a commercial EULA.

edit: If this project can't justify the expense of a lawyer, check out these resources:

PersistenceContext EntityManager injection NullPointerException

If the component is an EJB, then, there shouldn't be a problem injecting an EM.

But....In JBoss 5, the JAX-RS integration isn't great. If you have an EJB, you cannot use scanning and you must manually list in the context-param resteasy.jndi.resource. If you still have scanning on, Resteasy will scan for the resource class and register it as a vanilla JAX-RS service and handle the lifecycle.

This is probably the problem.

Stretch image to fit full container width bootstrap

Here's what worked for me. Note: Adding the image within a row introduces some space so I've intentionally used only a div to encapsulate the image.

<div class="container-fluid w-100 h-auto m-0 p-0">  

    <img src="someimg.jpg" class="img-fluid w-100 h-auto p-0 m-0" alt="Patience">           

</div>

What version of MongoDB is installed on Ubuntu

ANSWER: Read the instructions #dua

Ok the magic was in this line that I apparently missed when installing was:

$ sudo apt-get install mongodb-10gen=2.4.6

And the full process as described here http://docs.mongodb.org/manual/tutorial/install-mongodb-on-ubuntu/ is

$ sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10
$ echo 'deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen' | sudo tee /etc/apt/sources.list.d/mongodb.list
$ sudo apt-get update
$ sudo apt-get install mongodb-10gen
$ sudo apt-get install mongodb-10gen=2.2.3
$ echo "mongodb-10gen hold" | sudo dpkg --set-selections
$ sudo service mongodb start

$ mongod --version
db version v2.4.6
Wed Oct 16 12:21:39.938 git version: b9925db5eac369d77a3a5f5d98a145eaaacd9673

IMPORTANT: Make sure you change 2.4.6 to the latest version (or whatever you want to install). Find the latest version number here http://www.mongodb.org/downloads

Basic Python client socket example

It looks like your client is trying to connect to a non-existent server. In a shell window, run:

$ nc -l 5000

before running your Python code. It will act as a server listening on port 5000 for you to connect to. Then you can play with typing into your Python window and seeing it appear in the other terminal and vice versa.

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use

There are two different types of quotation marks in MySQL. You need to use ` for column names and ' for strings. Since you have used ' for the filename column the query parser got confused. Either remove the quotation marks around all column names, or change 'filename' to `filename`. Then it should work.

How to kill a process in MacOS?

If you're trying to kill -9 it, you have the correct PID, and nothing happens, then you don't have permissions to kill the process.

Solution:

$ sudo kill -9 PID

Okay, sure enough Mac OS/X does give an error message for this case:

$ kill -9 196
-bash: kill: (196) - Operation not permitted

So, if you're not getting an error message, you somehow aren't getting the right PID.

How can I order a List<string>?

You can use Sort

List<string> ListaServizi = new List<string>() { };
ListaServizi.Sort();

How do I profile memory usage in Python?

If you only want to look at the memory usage of an object, (answer to other question)

There is a module called Pympler which contains the asizeof module.

Use as follows:

from pympler import asizeof
asizeof.asizeof(my_object)

Unlike sys.getsizeof, it works for your self-created objects.

>>> asizeof.asizeof(tuple('bcd'))
200
>>> asizeof.asizeof({'foo': 'bar', 'baz': 'bar'})
400
>>> asizeof.asizeof({})
280
>>> asizeof.asizeof({'foo':'bar'})
360
>>> asizeof.asizeof('foo')
40
>>> asizeof.asizeof(Bar())
352
>>> asizeof.asizeof(Bar().__dict__)
280
>>> help(asizeof.asizeof)
Help on function asizeof in module pympler.asizeof:

asizeof(*objs, **opts)
    Return the combined size in bytes of all objects passed as positional arguments.

How to return HTTP 500 from ASP.NET Core RC2 Web Api?

When you want to return a JSON response in MVC .Net Core You can also use:

Response.StatusCode = (int)HttpStatusCode.InternalServerError;//Equals to HTTPResponse 500
return Json(new { responseText = "my error" });

This will return both JSON result and HTTPStatus. I use it for returning results to jQuery.ajax().

How to remove all callbacks from a Handler?

If you don't have the Runnable references, on the first callback, get the obj of the message, and use removeCallbacksAndMessages() to remove all related callbacks.

Textarea Auto height

I see that this is answered already, but I believe I have a simple jQuery solution ( jQuery is not even really needed; I just enjoy using it ):

I suggest counting the line breaks in the textarea text and setting the rows attribute of the textarea accordingly.

var text = jQuery('#your_textarea').val(),
    // look for any "\n" occurences
    matches = text.match(/\n/g),
    breaks = matches ? matches.length : 2;

jQuery('#your_textarea').attr('rows',breaks + 2);

Enter key press behaves like a Tab in Javascript

Here is an angular.js directive to make enter go to the next field using the other answers as inspiration. There is some, perhaps, odd looking code here because I only use the jQlite packaged with angular. I believe most of the features here work in all browsers > IE8.

angular.module('myapp', [])
.directive('pdkNextInputOnEnter', function() {
    var includeTags = ['INPUT', 'SELECT'];

    function link(scope, element, attrs) {
        element.on('keydown', function (e) {
            // Go to next form element on enter and only for included tags
            if (e.keyCode == 13 && includeTags.indexOf(e.target.tagName) != -1) {
                // Find all form elements that can receive focus
                var focusable = element[0].querySelectorAll('input,select,button,textarea');

                // Get the index of the currently focused element
                var currentIndex = Array.prototype.indexOf.call(focusable, e.target)

                // Find the next items in the list
                var nextIndex = currentIndex == focusable.length - 1 ? 0 : currentIndex + 1;

                // Focus the next element
                if(nextIndex >= 0 && nextIndex < focusable.length)
                    focusable[nextIndex].focus();

                return false;
            }
        });
    }

    return {
        restrict: 'A',
        link: link
    };
});

Here's how I use it in the app I'm working on, by just adding the pdk-next-input-on-enter directive on an element. I am using a barcode scanner to enter data into fields, the default function of the scanner is to emulate a keayboard, injecting an enter key after typing the data of the scanned barcode.

There is one side-effect to this code (a positive one for my use-case), if it moves focus onto a button, the enter keyup event will cause the button's action to be activated. This worked really well for my flow as the last form element in my markup is a button that I want activated once all the fields have been "tabbed" through by scanning barcodes.

<!DOCTYPE html>
<html ng-app=myapp>
  <head>
      <script src="angular.min.js"></script>
      <script src="controller.js"></script>
  </head>
  <body ng-controller="LabelPrintingController">
      <div class='.container' pdk-next-input-on-enter>
          <select ng-options="p for p in partNumbers" ng-model="selectedPart" ng-change="selectedPartChanged()"></select>
          <h2>{{labelDocument.SerialNumber}}</h2>
          <div ng-show="labelDocument.ComponentSerials">
              <b>Component Serials</b>
              <ul>
                  <li ng-repeat="serial in labelDocument.ComponentSerials">
                      {{serial.name}}<br/>
                      <input type="text" ng-model="serial.value" />
                  </li>
              </ul>
          </div>
          <button ng-click="printLabel()">Print</button>
      </div>
  </body>
</html>

JQuery Ajax - How to Detect Network Connection error when making Ajax call

Since I can't duplicate the issue I can only suggest to try with a timeout on the ajax call. In jQuery you can set it with the $.ajaxSetup (and it will be global for all your $.ajax calls) or you can set it specifically for your call like this:

$.ajax({
    type: 'GET',
    url: 'http://www.mywebapp.com/keepAlive',
    timeout: 15000,
    success: function(data) {},
    error: function(XMLHttpRequest, textStatus, errorThrown) {}
})

JQuery will register a 15 seconds timeout on your call; after that without an http response code from the server jQuery will execute the error callback with the textStatus value set to "timeout". With this you can at least stop the ajax call but you won't be able to differentiate the real network issues from the loss of connections.

#pragma pack effect

Why one want to use it ?

To reduce the memory of the structure

Why one should not use it ?

  1. This may lead to performance penalty, because some system works better on aligned data
  2. Some machine will fail to read unaligned data
  3. Code is not portable

LINQ Group By and select collection

you may also like this

var Grp = Model.GroupBy(item => item.Order.Customer)
      .Select(group => new 
        { 
             Customer = Model.First().Customer, 
             CustomerId= group.Key,  
             Orders= group.ToList() 
       })
      .ToList();

How to run python script on terminal (ubuntu)?

First create the file you want, with any editor like vi r gedit. And save with. Py extension.In that the first line should be

!/usr/bin/env python

How to write both h1 and h2 in the same line?

<h1 style="text-align: left; float: left;">Text 1</h1>
<h2 style="text-align: right; float: right; display: inline;">Text 2</h2>
<hr style="clear: both;" />

Hope this helps!

What is the meaning of "$" sign in JavaScript

From another answer:

A little history

Remember, there is nothing inherently special about $. It is a variable name just like any other. In earlier days, people used to write code using document.getElementById. Because JavaScript is case-sensitive, it was normal to make a mistake while writing document.getElementById. Should I capital 'b' of 'by'? Should I capital 'i' of Id? You get the drift. Because functions are first-class citizens in JavaScript, you can always do this:

var $ = document.getElementById; //freedom from document.getElementById!

When Prototype library arrived, they named their function, which gets the DOM elements, as '$'. Almost all the JavaScript libraries copied this idea. Prototype also introduced a $$ function to select elements using CSS selector.

jQuery also adapted $ function but expanded to make it accept all kinds of 'selectors' to get the elements you want. Now, if you are already using Prototype in your project and wanted to include jQuery, you will be in problem as '$' could either refer to Prototype's implementation OR jQuery's implementation. That's why jQuery has the option of noConflict so that you can include jQuery in your project which uses Prototype and slowly migrate your code. I think this was a brilliant move on John's part! :)

How can I delete all Git branches which have been merged?

If you wish to delete local branches that have been merged as well as delete their remotes here's the one-liner I prefer:

git branch --merged | xargs -I_br -- sh -c 'git branch -d _br; git push origin --delete _br'

Single Form Hide on Startup

I'm coming at this from C#, but should be very similar in vb.net.

In your main program file, in the Main method, you will have something like:

Application.Run(new MainForm());

This creates a new main form and limits the lifetime of the application to the lifetime of the main form.

However, if you remove the parameter to Application.Run(), then the application will be started with no form shown and you will be free to show and hide forms as much as you like.

Rather than hiding the form in the Load method, initialize the form before calling Application.Run(). I'm assuming the form will have a NotifyIcon on it to display an icon in the task bar - this can be displayed even if the form itself is not yet visible. Calling Form.Show() or Form.Hide() from handlers of NotifyIcon events will show and hide the form respectively.