Programs & Examples On #Waveoutwrite

How do I change Bootstrap 3 column order on mobile layout?

You cannot change the order of columns in smaller screens but you can do that in large screens.

So change the order of your columns.

<!--Main Content-->
<div class="col-lg-9 col-lg-push-3">
</div>

<!--Sidebar-->
<div class="col-lg-3 col-lg-pull-9">
</div>

By default this displays the main content first.

So in mobile main content is displayed first.

By using col-lg-push and col-lg-pull we can reorder the columns in large screens and display sidebar on the left and main content on the right.

Working fiddle here.

Output (echo/print) everything from a PHP Array

You can use print_r to get human-readable output. But to display it as text we add "echo '';"

echo ''; print_r($row);

Create, read, and erase cookies with jQuery

Use JavaScript Cookie plugin

Set a cookie

Cookies.set("example", "foo"); // Sample 1
Cookies.set("example", "foo", { expires: 7 }); // Sample 2
Cookies.set("example", "foo", { path: '/admin', expires: 7 }); // Sample 3

Get a cookie

alert( Cookies.get("example") );

Delete the cookie

Cookies.remove("example");
Cookies.remove('example', { path: '/admin' }) // Must specify path if used when setting.

Android Get Application's 'Home' Data Directory

Of course, never fails. Found the solution about a minute after posting the above question... solution for those that may have had the same issue:

ContextWrapper.getFilesDir()

Found here.

Removing rounded corners from a <select> element in Chrome/Webkit

Eliminating the arrows should be avoided. A solution that preserves the dropdown arrows is to first remove styles from the dropdown:

.myDropdown {
  background-color: #yourbg;
  border-style: none;
}

Then create div directly before the dropdown in your HTML:

<div class="myDiv"></div>
<select class="myDropdown...">...</select>

And style the div like this:

.myDiv {
  background-color: #yourbg;
  border-style: none;
  position: absolute;
  display: inline;
  border: 1px solid #acolor;
}

Display inline will keep the div from going to a new line, position absolute removes it from the flow of the page. The end result is a nice clean underline you can style as you'd like, and your dropdown still behaves as the user would expect.

How to specify multiple return types using type-hints

The statement def foo(client_id: str) -> list or bool: when evaluated is equivalent to def foo(client_id: str) -> list: and will therefore not do what you want.

The native way to describe a "either A or B" type hint is Union (thanks to Bhargav Rao):

def foo(client_id: str) -> Union[list, bool]:

I do not want to be the "Why do you want to do this anyway" guy, but maybe having 2 return types isn't what you want:

If you want to return a bool to indicate some type of special error-case, consider using Exceptions instead. If you want to return a bool as some special value, maybe an empty list would be a good representation. You can also indicate that None could be returned with Optional[list]

In Perl, how to remove ^M from a file?

^M is carriage return. You can do this:

$str =~ s/\r//g

Gradle - Could not find or load main class

Struggled with the same problem for some time. But after creating the directory structure src/main/java and putting the source(from the top of the package), it worked as expected.

The tutorial I tried with. After you execute gradle build, you will have to be able to find classes under build directory.

docker: Error response from daemon: Get https://registry-1.docker.io/v2/: Service Unavailable. IN DOCKER , MAC

In my case, stopping Proxifier fixed it. I added a rule to route any connections from vpnkit.exe as Direct and it now works.

What is [Serializable] and when should I use it?

Since the original question was about the SerializableAttribute, it should be noted that this attribute only applies when using the BinaryFormatter or SoapFormatter.

It is a bit confusing, unless you really pay attention to the details, as to when to use it and what its actual purpose is.

It has NOTHING to do with XML or JSON serialization.

Used with the SerializableAttribute are the ISerializable Interface and SerializationInfo Class. These are also only used with the BinaryFormatter or SoapFormatter.

Unless you intend to serialize your class using Binary or Soap, do not bother marking your class as [Serializable]. XML and JSON serializers are not even aware of its existence.

multiple where condition codeigniter

you can try this function for multi-purpose

function ManageData($table_name='',$condition=array(),$udata=array(),$is_insert=false){
$resultArr = array();
$ci = & get_instance();
if($condition && count($condition))
    $ci->db->where($condition);
if($is_insert)
{
    $ci->db->insert($table_name,$udata);
    return 0;
}
else
{
    $ci->db->update($table_name,$udata);
    return 1;
}

}

Adding an HTTP Header to the request in a servlet filter

You'll have to use an HttpServletRequestWrapper:

public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException {
    final HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletRequestWrapper wrapper = new HttpServletRequestWrapper(httpRequest) {
        @Override
        public String getHeader(String name) {
            final String value = request.getParameter(name);
            if (value != null) {
                return value;
            }
            return super.getHeader(name);
        }
    };
    chain.doFilter(wrapper, response);
}

Depending on what you want to do you may need to implement other methods of the wrapper like getHeaderNames for instance. Just be aware that this is trusting the client and allowing them to manipulate any HTTP header. You may want to sandbox it and only allow certain header values to be modified this way.

Select data between a date/time range

You must search date defend on how you insert that game_date data on your database.. for example if you inserted date value on long date or short.

SELECT * FROM hockey_stats WHERE game_date >= "6/11/2018" AND game_date <= "6/17/2018"

You can also use BETWEEN:

SELECT * FROM hockey_stats WHERE game_date BETWEEN "6/11/2018" AND "6/17/2018"

simple as that.

How to disable HTML button using JavaScript?

The official way to set the disabled attribute on an HTMLInputElement is this:

var input = document.querySelector('[name="myButton"]');
// Without querySelector API
// var input = document.getElementsByName('myButton').item(0);

// disable
input.setAttribute('disabled', true);
// enable
input.removeAttribute('disabled');

While @kaushar's answer is sufficient for enabling and disabling an HTMLInputElement, and is probably preferable for cross-browser compatibility due to IE's historically buggy setAttribute, it only works because Element properties shadow Element attributes. If a property is set, then the DOM uses the value of the property by default rather than the value of the equivalent attribute.

There is a very important difference between properties and attributes. An example of a true HTMLInputElement property is input.value, and below demonstrates how shadowing works:

_x000D_
_x000D_
var input = document.querySelector('#test');_x000D_
_x000D_
// the attribute works as expected_x000D_
console.log('old attribute:', input.getAttribute('value'));_x000D_
// the property is equal to the attribute when the property is not explicitly set_x000D_
console.log('old property:', input.value);_x000D_
_x000D_
// change the input's value property_x000D_
input.value = "My New Value";_x000D_
_x000D_
// the attribute remains there because it still exists in the DOM markup_x000D_
console.log('new attribute:', input.getAttribute('value'));_x000D_
// but the property is equal to the set value due to the shadowing effect_x000D_
console.log('new property:', input.value);
_x000D_
<input id="test" type="text" value="Hello World" />
_x000D_
_x000D_
_x000D_

That is what it means to say that properties shadow attributes. This concept also applies to inherited properties on the prototype chain:

_x000D_
_x000D_
function Parent() {_x000D_
  this.property = 'ParentInstance';_x000D_
}_x000D_
_x000D_
Parent.prototype.property = 'ParentPrototype';_x000D_
_x000D_
// ES5 inheritance_x000D_
Child.prototype = Object.create(Parent.prototype);_x000D_
Child.prototype.constructor = Child;_x000D_
_x000D_
function Child() {_x000D_
  // ES5 super()_x000D_
  Parent.call(this);_x000D_
_x000D_
  this.property = 'ChildInstance';_x000D_
}_x000D_
_x000D_
Child.prototype.property = 'ChildPrototype';_x000D_
_x000D_
logChain('new Parent()');_x000D_
_x000D_
log('-------------------------------');_x000D_
logChain('Object.create(Parent.prototype)');_x000D_
_x000D_
log('-----------');_x000D_
logChain('new Child()');_x000D_
_x000D_
log('------------------------------');_x000D_
logChain('Object.create(Child.prototype)');_x000D_
_x000D_
// below is for demonstration purposes_x000D_
// don't ever actually use document.write(), eval(), or access __proto___x000D_
function log(value) {_x000D_
  document.write(`<pre>${value}</pre>`);_x000D_
}_x000D_
_x000D_
function logChain(code) {_x000D_
  log(code);_x000D_
_x000D_
  var object = eval(code);_x000D_
_x000D_
  do {_x000D_
    log(`${object.constructor.name} ${object instanceof object.constructor ? 'instance' : 'prototype'} property: ${JSON.stringify(object.property)}`);_x000D_
    _x000D_
    object = object.__proto__;_x000D_
  } while (object !== null);_x000D_
}
_x000D_
_x000D_
_x000D_

I hope this clarifies any confusion about the difference between properties and attributes.

How can I change the default width of a Twitter Bootstrap modal box?

Below is the code for set the modal pop-up width and left position from the screen through javascript.

$('#openModalPopupId').css({ "width": "80%", "left": "30%"});

How to detect the physical connected state of a network cable/connector?

on arch linux. (im not sure on other distros) you can view the operstate. which shows up if connected or down if not the operstate lives on

/sys/class/net/(interface name here)/operstate
#you can also put watch 
watch -d -n -1 /sys/class/net/(interface name here)/operstate

Javascript callback when IFRAME is finished loading?

First up, going by the function name xssRequest it sounds like you're trying cross site request - which if that's right, you're not going to be able to read the contents of the iframe.

On the other hand, if the iframe's URL is on your domain you can access the body, but I've found that if I use a timeout to remove the iframe the callback works fine:

// possibly excessive use of jQuery - but I've got a live working example in production
$('#myUniqueID').load(function () {
  if (typeof callback == 'function') {
    callback($('body', this.contentWindow.document).html());
  }
  setTimeout(function () {$('#frameId').remove();}, 50);
});

Multiple inheritance for an anonymous class

// The interface
interface Blah {
    void something();
}

...

// Something that expects an object implementing that interface
void chewOnIt(Blah b) {
    b.something();
}

...

// Let's provide an object of an anonymous class
chewOnIt(
    new Blah() {
        @Override
        void something() { System.out.println("Anonymous something!"); }
    }
);

how to install tensorflow on anaconda python 3.6

UPDATE: TensorFlow supports Python 3.6 on Windows since version 1.2.0 (see the release notes)


TensorFlow only supports Python 3.5 64-bit as of now. Support for Python 3.6 is a work in progress and you can track it here as well as chime in the discussion.

The only alternative to use Python 3.6 with TensorFlow on Windows currently is building TF from source.

If you don't want to uninstall your Anaconda distribution for Python 3.6 and install a previous release you can create a conda environment for Python=3.5 as in: conda create --name tensorflow python=3.5 activate tensorflow pip install tensorflow-gpu

Removing legend on charts with chart.js v2

You can change default options by using Chart.defaults.global in your javascript file. So you want to change legend and tooltip options.

Remove legend

Chart.defaults.global.legend.display = false;

Remove Tooltip

Chart.defaults.global.tooltips.enabled = false;

Here is a working fiddler.

How to restart ADB manually from Android Studio

Open task manager and kill adb.exe, now adb will start normally

Set SSH connection timeout

The problem may be that ssh is trying to connect to all the different IPs that www.google.com resolves to. For example on my machine:

# ssh -v -o ConnectTimeout=1 -o ConnectionAttempts=1 www.google.com
OpenSSH_5.9p1, OpenSSL 0.9.8t 18 Jan 2012
debug1: Connecting to www.google.com [173.194.43.20] port 22.
debug1: connect to address 173.194.43.20 port 22: Connection timed out
debug1: Connecting to www.google.com [173.194.43.19] port 22.
debug1: connect to address 173.194.43.19 port 22: Connection timed out
debug1: Connecting to www.google.com [173.194.43.18] port 22.
debug1: connect to address 173.194.43.18 port 22: Connection timed out
debug1: Connecting to www.google.com [173.194.43.17] port 22.
debug1: connect to address 173.194.43.17 port 22: Connection timed out
debug1: Connecting to www.google.com [173.194.43.16] port 22.
debug1: connect to address 173.194.43.16 port 22: Connection timed out
ssh: connect to host www.google.com port 22: Connection timed out

If I run it with a specific IP, it returns much faster.

EDIT: I've timed it (with time) and the results are:

  • www.google.com - 5.086 seconds
  • 173.94.43.16 - 1.054 seconds

Android get Current UTC time

see my answer here:

How can I get the current date and time in UTC or GMT in Java?

I've fully tested it by changing the timezones on the emulator

How to get week number in Python?

There are many systems for week numbering. The following are the most common systems simply put with code examples:

  • ISO: First week starts with Monday and must contain the January 4th. The ISO calendar is already implemented in Python:

    >>> from datetime import date
    >>> date(2014, 12, 29).isocalendar()[:2]
    (2015, 1)
    
  • North American: First week starts with Sunday and must contain the January 1st. The following code is my modified version of Python's ISO calendar implementation for the North American system:

    from datetime import date
    
    def week_from_date(date_object):
        date_ordinal = date_object.toordinal()
        year = date_object.year
        week = ((date_ordinal - _week1_start_ordinal(year)) // 7) + 1
        if week >= 52:
            if date_ordinal >= _week1_start_ordinal(year + 1):
                year += 1
                week = 1
        return year, week
    
    def _week1_start_ordinal(year):
        jan1 = date(year, 1, 1)
        jan1_ordinal = jan1.toordinal()
        jan1_weekday = jan1.weekday()
        week1_start_ordinal = jan1_ordinal - ((jan1_weekday + 1) % 7)
        return week1_start_ordinal
    
    >>> from datetime import date
    >>> week_from_date(date(2014, 12, 29))
    (2015, 1)
    
  • MMWR (CDC): First week starts with Sunday and must contain the January 4th. I created the epiweeks package specifically for this numbering system (also has support for the ISO system). Here is an example:
    >>> from datetime import date
    >>> from epiweeks import Week
    >>> Week.fromdate(date(2014, 12, 29))
    (2014, 53)
    

Wait until page is loaded with Selenium WebDriver for Python

The webdriver will wait for a page to load by default via .get() method.

As you may be looking for some specific element as @user227215 said, you should use WebDriverWait to wait for an element located in your page:

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.common.exceptions import TimeoutException

browser = webdriver.Firefox()
browser.get("url")
delay = 3 # seconds
try:
    myElem = WebDriverWait(browser, delay).until(EC.presence_of_element_located((By.ID, 'IdOfMyElement')))
    print "Page is ready!"
except TimeoutException:
    print "Loading took too much time!"

I have used it for checking alerts. You can use any other type methods to find the locator.

EDIT 1:

I should mention that the webdriver will wait for a page to load by default. It does not wait for loading inside frames or for ajax requests. It means when you use .get('url'), your browser will wait until the page is completely loaded and then go to the next command in the code. But when you are posting an ajax request, webdriver does not wait and it's your responsibility to wait an appropriate amount of time for the page or a part of page to load; so there is a module named expected_conditions.

How to get the squared symbol (²) to display in a string

I create equations with random numbers in VBA and for x squared put in x^2.

I read each square (or textbox) text into a string.

I then read each character in the string in turn and note the location of the ^ ("hats")'s in each.

Say the hats were at positions 4, 8 and 12.

I then "chop out" the first hat - the position of the character to be superscripted is now 4, the position of the other hats is now 7 and 11. I chop out the second hat, the character to superscript is now at 7 and the hat has moved to 10. I chop out the last hat .. the superscript character is now position 10.

I now select each character in turn and change the font to superscript.

Thus I can fill a whole spreadsheet with algebra using ^ and then call a routine to tidy it up.

For big powers like x to the 23 I build x^2^3 and the above routine does it.

Run a command shell in jenkins

As far as I know, Windows will not support shell scripts out of the box. You can install Cygwin or Git for Windows, go to Manage Jenkins > Configure System Shell and point it to the location of sh.exe file found in their installation. For example:

C:\Program Files\Git\bin\sh.exe

There is another option I've discovered. This one is better because it allowed me to use shell in pipeline scripts with simple sh "something".

Add the folder to system PATH. Right click on Computer, click properties > advanced system settings > environmental variables, add C:\Program Files\Git\bin\ to your system Path property.

IMPORTANT note: for some reason I had to add it to the system wide Path, adding to user Path didn't work, even though Jenkins was running on this user.

An important note (thanks bugfixr!):

This works. It should be noted that you will need to restart Jenkins in order for it to pick up the new PATH variable. I just went to my services and restated it from there.

Disclaimer: the names may differ slightly as I'm not using English Windows.

How to check model string property for null in a razor view

Try this first, you may be passing a Null Model:

@if (Model != null && !String.IsNullOrEmpty(Model.ImageName))
{
    <label for="Image">Change picture</label>
}
else
{ 
    <label for="Image">Add picture</label>
}

Otherise, you can make it even neater with some ternary fun! - but that will still error if your model is Null.

<label for="Image">@(String.IsNullOrEmpty(Model.ImageName) ? "Add" : "Change") picture</label>

Changing cell color using apache poi

Short version: Create styles only once, use them everywhere.

Long version: use a method to create the styles you need (beware of the limit on the amount of styles).

private static Map<String, CellStyle> styles;

private static Map<String, CellStyle> createStyles(Workbook wb){
        Map<String, CellStyle> styles = new HashMap<String, CellStyle>();
        DataFormat df = wb.createDataFormat();

        CellStyle style;
        Font headerFont = wb.createFont();
        headerFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
        headerFont.setFontHeightInPoints((short) 12);
        style = createBorderedStyle(wb);
        style.setAlignment(CellStyle.ALIGN_CENTER);
        style.setFont(headerFont);
        styles.put("style1", style);

        style = createBorderedStyle(wb);
        style.setAlignment(CellStyle.ALIGN_CENTER);
        style.setFillForegroundColor(IndexedColors.LIGHT_CORNFLOWER_BLUE.getIndex());
        style.setFillPattern(CellStyle.SOLID_FOREGROUND);
        style.setFont(headerFont);
        style.setDataFormat(df.getFormat("d-mmm"));
        styles.put("date_style", style);
        ...
        return styles;
    }

you can also use methods to do repetitive tasks while creating styles hashmap

private static CellStyle createBorderedStyle(Workbook wb) {
        CellStyle style = wb.createCellStyle();
        style.setBorderRight(CellStyle.BORDER_THIN);
        style.setRightBorderColor(IndexedColors.BLACK.getIndex());
        style.setBorderBottom(CellStyle.BORDER_THIN);
        style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
        style.setBorderLeft(CellStyle.BORDER_THIN);
        style.setLeftBorderColor(IndexedColors.BLACK.getIndex());
        style.setBorderTop(CellStyle.BORDER_THIN);
        style.setTopBorderColor(IndexedColors.BLACK.getIndex());
        return style;
    }

then, in your "main" code, set the style from the styles map you have.

Cell cell = xssfCurrentRow.createCell( intCellPosition );       
cell.setCellValue( blah );
cell.setCellStyle( (CellStyle) styles.get("style1") );

Pass props to parent component in React.js

Basically you use props to send information to and from Child and Parent.

Adding to all the wonderful answers, let me give a simple example that explains passing values from child to parent component in React

App.js

class App extends React.Component {
      constructor(){
            super();
            this.handleFilterUpdate = this.handleFilterUpdate.bind(this);
            this.state={name:'igi'}
      }
      handleFilterUpdate(filterValue) {
            this.setState({
                  name: filterValue
            });
      }
   render() {
      return (
        <div>
            <Header change={this.handleFilterUpdate} name={this.state.name} />
            <p>{this.state.name}</p>
        </div>
      );
   }
}

Header.js

class Header extends React.Component {
      constructor(){
            super();
            this.state={
                  names: 'jessy'
            }
      }
      Change(event) {

      // this.props.change(this.state.names);
      this.props.change('jessy');
  }

   render() {
      return (
       <button onClick={this.Change.bind(this)}>click</button>

      );
   }
}

Main.js

import React from 'react';
import ReactDOM from 'react-dom';

import App from './App.jsx';

ReactDOM.render(<App />, document.getElementById('app'));

Thats it , now you can pass values from your client to the server.

Take a look at the Change function in the Header.js

Change(event) {
      // this.props.change(this.state.names);
      this.props.change('jessy');
  }

This is how you push values into the props from client to the server

Java Timestamp - How can I create a Timestamp with the date 23/09/2007?

What about this?

java.sql.Timestamp timestamp = java.sql.Timestamp.valueOf("2007-09-23 10:10:10.0");

How to Apply Mask to Image in OpenCV?

While @perrejba s answer is correct, it uses the legacy C-style functions. As the question is tagged C++, you may want to use a method instead:

inputMat.copyTo(outputMat, maskMat);

All objects are of type cv::Mat.

Please be aware that the masking is binary. Any non-zero value in the mask is interpreted as 'do copy'. Even if the mask is a greyscale image.

Also be aware that the .copyTo() function does not clear the output before copying.

If you want to permanently alter the original Image, you have to do an additional copy/clone/assignment. The copyTo() function is not defined for overlapping input/output images. So you can't use the same image as both input and output.

Binding a Button's visibility to a bool value in ViewModel

2 way conversion in c# from boolean to visibility

using System;
using System.Windows;
using System.Windows.Data;

namespace FaceTheWall.converters
{
    class BooleanToVisibilityConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value is Boolean && (bool)value)
            {
                return Visibility.Visible;
            }
            return Visibility.Collapsed;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value is Visibility && (Visibility)value == Visibility.Visible)
            {
                return true;
            }
            return false;
        }
    }
}

CSS grid wrapping

Here's my attempt. Excuse the fluff, I was feeling extra creative.

My method is a parent div with fixed dimensions. The rest is just fitting the content inside that div accordingly.

This will rescale the images regardless of the aspect ratio. There will be no hard cropping either.

_x000D_
_x000D_
body {_x000D_
    background: #131418;_x000D_
    text-align: center;_x000D_
    margin: 0 auto;_x000D_
}_x000D_
_x000D_
.my-image-parent {_x000D_
    display: inline-block;_x000D_
    width: 300px;_x000D_
    height: 300px;_x000D_
    line-height: 300px; /* Should match your div height */_x000D_
    text-align: center;_x000D_
    font-size: 0;_x000D_
}_x000D_
_x000D_
/* Start demonstration background fluff */_x000D_
    .bg1 {background: url(https://unsplash.it/801/799);}_x000D_
    .bg2 {background: url(https://unsplash.it/799/800);}_x000D_
    .bg3 {background: url(https://unsplash.it/800/799);}_x000D_
    .bg4 {background: url(https://unsplash.it/801/801);}_x000D_
    .bg5 {background: url(https://unsplash.it/802/800);}_x000D_
    .bg6 {background: url(https://unsplash.it/800/802);}_x000D_
    .bg7 {background: url(https://unsplash.it/802/802);}_x000D_
    .bg8 {background: url(https://unsplash.it/803/800);}_x000D_
    .bg9 {background: url(https://unsplash.it/800/803);}_x000D_
    .bg10 {background: url(https://unsplash.it/803/803);}_x000D_
    .bg11 {background: url(https://unsplash.it/803/799);}_x000D_
    .bg12 {background: url(https://unsplash.it/799/803);}_x000D_
    .bg13 {background: url(https://unsplash.it/806/799);}_x000D_
    .bg14 {background: url(https://unsplash.it/805/799);}_x000D_
    .bg15 {background: url(https://unsplash.it/798/804);}_x000D_
    .bg16 {background: url(https://unsplash.it/804/799);}_x000D_
    .bg17 {background: url(https://unsplash.it/804/804);}_x000D_
    .bg18 {background: url(https://unsplash.it/799/804);}_x000D_
    .bg19 {background: url(https://unsplash.it/798/803);}_x000D_
    .bg20 {background: url(https://unsplash.it/803/797);}_x000D_
/* end demonstration background fluff */_x000D_
_x000D_
.my-image {_x000D_
    width: auto;_x000D_
    height: 100%;_x000D_
    vertical-align: middle;_x000D_
    background-size: contain;_x000D_
    background-position: center;_x000D_
    background-repeat: no-repeat;_x000D_
}
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg1"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg2"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg3"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg4"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg5"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg6"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg7"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg8"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg9"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg10"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg11"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg12"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg13"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg14"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg15"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg16"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg17"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg18"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg19"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg20"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

RecyclerView onClick

I have developed a light weighted library for android, you can visit https://github.com/ChathuraHettiarachchi/RecycleClick

and follow for following sample

RecycleClick.addTo(YOUR_RECYCLEVIEW).setOnItemClickListener(new RecycleClick.OnItemClickListener() {
            @Override
            public void onItemClicked(RecyclerView recyclerView, int position, View v) {
                // YOUR CODE
            }
        });

What are the differences between Visual Studio Code and Visual Studio?

For Unity3D users ...

  • VSCode is incredibly faster than VS. Files open instantly from Unity. VS is very slow. VSCode launches instantly. VS takes forever to launch.

  • VS can literally compile code, build apps and so on, it's a huge IDE like Unity itself or XCode. VSCode is indeed "just" a full-featured text editor. VSCode is NOT a compiler (far less a huge, build-everything system that can literally create apps and software of all types): VSCode is literally "just a text editor".

  • With VSCode, you DO need to install the "Visual Studio Code" package. (Not to be confused with the "Visual Studio" package.) (It seems to me that VS works fine without the VS package, but, with VS Code, you must install Unity's VSCode package.)

enter image description here

  • When you first download and install VSCode, simply open any C# file on your machine. It will instantly prompt you to install the needed C# package. This is harmless and easy.

  • Unfortunately VSCode generally has only one window! You cannot, really, easily drag files to separate windows. If this is important to you, you may need to go with VS.

  • The biggest problem with VS is that the overall concept of settings and preferences are absolutely horrible. In VS, it is all-but impossible to change the font, etc. In contrast, VSCode has FANTASTIC preferences - dead simple, never a problem.

  • As far as I can see, every single feature in VS which you use in Unity is present in VSCode. (So, code coloring, jump to definitions, it understands/autocompletes every single thing in Unity, it opens from Unity, double clicking something in the Unity console opens the file to that line, etc etc)

  • If you are used to VS. And you want to change to VSCode. It's always hard changing editors, they are so intimate, but it's pretty similar; you won't have a big heartache.

In short if you're a VS for Unity3D user,

and you're going to try VSCode...

  1. VSCode is on the order of 19 trillion times faster in every way. It will blow your mind.

  2. It does seem to have every feature.

  3. Basically VS is the world's biggest IDE and application building system: VSCode is just an editor. (Indeed, that's exactly what you want with Unity, since Unity itself is the IDE.)

  4. Don't forget to just click to install the relevant Unity package.

If I'm not mistaken, there is no reason whatsoever to use VS with Unity.

Unity is an IDE so you just need a text editor, and that is what VSCode is. VSCode is hugely better in both speed and preferences. The only possible problem - multiple-windows are a bit clunky in VSCode!

That horrible "double copy" problem in VS ... solved!

If you are using VS with Unity. There is an infuriating problem where often VS will try to open twice, that is you will end up with two or more copies of VS running. Nobody has ever been able to fix this or figure out what the hell causes it. Fortunately, this problem never happens with VSCode.

Installing VSCode on a Mac - unbelievably easy.

There are no installers, etc etc etc. On the download page, you download a zipped Mac app. Put it in the Applications folder and you're done.

Folding! (Mac/Windows keystrokes are different)

Bizarrely there's no menu entry / docu whatsoever for folding, but here are the keys:

https://stackoverflow.com/a/30077543/294884

Setting colors and so on in VSCode - the critical tips

Particularly for Mac users who may find the colors strange:

Priceless post #1:

https://stackoverflow.com/a/45640244/294884

Priceless post #2:

https://stackoverflow.com/a/63303503/294884

Meta files ...

To keep the "Explorer" list of files on the left tidy, in the Unity case:

enter image description here

AngularJS $watch window resize inside directive

// Following is angular 2.0 directive for window re size that adjust scroll bar for give element as per your tag

---- angular 2.0 window resize directive.
import { Directive, ElementRef} from 'angular2/core';

@Directive({
       selector: '[resize]',
       host: { '(window:resize)': 'onResize()' } // Window resize listener
})

export class AutoResize {

element: ElementRef; // Element that associated to attribute.
$window: any;
       constructor(_element: ElementRef) {

         this.element = _element;
         // Get instance of DOM window.
         this.$window = angular.element(window);

         this.onResize();

    }

    // Adjust height of element.
    onResize() {
         $(this.element.nativeElement).css('height', (this.$window.height() - 163) + 'px');
   }
}

Bootstrap - dropdown menu not working?

put following code in your page

  Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequest);
    function EndRequest(sender, args) {
        if (args.get_error() == undefined) {
        $('.dropdown-toggle').dropdown();
        }
    }

How can I remove an entry in global configuration with git config?

You can check all the config settings using

git config --global --list

You can remove the setting for example username

git config --global --unset user.name

You can edit the configuration or remove the config setting manually by hand using:

git config --global --edit 

Why does 'git commit' not save my changes?

I had an issue where I was doing commit --amend even after issuing a git add . and it still wasn't working. Turns out I made some .vimrc customizations and my editor wasn't working correctly. Fixing these errors so that vim returns the correct code resolved the issue.

Does Enter key trigger a click event?

Here is the correct SOLUTION! Since the button doesn't have a defined attribute type, angular maybe attempting to issue the keyup event as a submit request and triggers the click event on the button.

<button type="button" ...></button>

Big thanks to DeborahK!

Angular2 - Enter Key executes first (click) function present on the form

Starting iPhone app development in Linux?

You can use Tersus (open source), and it lets you export the app as an Xcode project.

How do I remove leading whitespace in Python?

If you want to cut the whitespaces before and behind the word, but keep the middle ones.
You could use:

word = '  Hello World  '
stripped = word.strip()
print(stripped)

Android device does not show up in adb list

I have an Android LG G4 and the only thing that worked for me was to install the Software Update and Repair tool from my device. Steps:

  • Plug device into usb
  • Make sure developer options are enabled and usb debugging is checked (see elsewhere in thread or google for instructions)
  • Select usb connection type "Software installation":

enter image description here

  • An installation wizard should come up on the computer.
  • At some point during the installation you will see on your phone a prompt that asks "Trust this computer?" with an RSA token/fingerprint. After you say yes the device should be recognized by ADB and you can finish the wizard.

How can I deserialize JSON to a simple Dictionary<string,string> in ASP.NET?

I did discover .NET has a built in way to cast the JSON string into a Dictionary<String, Object> via the System.Web.Script.Serialization.JavaScriptSerializer type in the 3.5 System.Web.Extensions assembly. Use the method DeserializeObject(String).

I stumbled upon this when doing an ajax post (via jquery) of content type 'application/json' to a static .net Page Method and saw that the method (which had a single parameter of type Object) magically received this Dictionary.

How can I make git accept a self signed certificate?

My answer may be late but it worked for me. It may help somebody.

I tried above mentioned steps and that didn't solved the issue.

try thisgit config --global http.sslVerify false

Can I add a UNIQUE constraint to a PostgreSQL table, after it's already created?

If you had a table that already had a existing constraints based on lets say: name and lastname and you wanted to add one more unique constraint, you had to drop the entire constrain by:

ALTER TABLE your_table DROP CONSTRAINT constraint_name;

Make sure tha the new constraint you wanted to add is unique/ not null ( if its Microsoft Sql, it can contain only one null value) across all data on that table, and then you could re-create it.

ALTER TABLE table_name
ADD CONSTRAINT constraint_name UNIQUE (column1, column2, ... column_n);

Code for a simple JavaScript countdown timer?

I wrote this script some time ago:

Usage:

var myCounter = new Countdown({  
    seconds:5,  // number of seconds to count down
    onUpdateStatus: function(sec){console.log(sec);}, // callback for each second
    onCounterEnd: function(){ alert('counter ended!');} // final action
});

myCounter.start();

function Countdown(options) {
  var timer,
  instance = this,
  seconds = options.seconds || 10,
  updateStatus = options.onUpdateStatus || function () {},
  counterEnd = options.onCounterEnd || function () {};

  function decrementCounter() {
    updateStatus(seconds);
    if (seconds === 0) {
      counterEnd();
      instance.stop();
    }
    seconds--;
  }

  this.start = function () {
    clearInterval(timer);
    timer = 0;
    seconds = options.seconds;
    timer = setInterval(decrementCounter, 1000);
  };

  this.stop = function () {
    clearInterval(timer);
  };
}

NameError: global name 'unicode' is not defined - in Python 3

Hope you are using Python 3 , Str are unicode by default, so please Replace Unicode function with String Str function.

if isinstance(unicode_or_str, str):    ##Replaces with str
    text = unicode_or_str
    decoded = False

What does "select count(1) from table_name" on any database tables mean?

There is no difference.

COUNT(1) is basically just counting a constant value 1 column for each row. As other users here have said, it's the same as COUNT(0) or COUNT(42). Any non-NULL value will suffice.

http://asktom.oracle.com/pls/asktom/f?p=100:11:2603224624843292::::P11_QUESTION_ID:1156151916789

The Oracle optimizer did apparently use to have bugs in it, which caused the count to be affected by which column you picked and whether it was in an index, so the COUNT(1) convention came into being.

Resize command prompt through commands

Modify cmd.exe properties using the command prompt Pretty much has what you're asking for. More on the topic, mode con: cols=160 lines=78 should achieve what you want. Change 160 and 78 to your values.

How can I test that a variable is more than eight characters in PowerShell?

Use the length property of the [String] type:

if ($dbUserName.length -gt 8) {
    Write-Output "Please enter more than 8 characters."
    $dbUserName = Read-Host "Re-enter database username"
}

Please note that you have to use -gt instead of > in your if condition. PowerShell uses the following comparison operators to compare values and test conditions:

  • -eq = equals
  • -ne = not equals
  • -lt = less than
  • -gt = greater than
  • -le = less than or equals
  • -ge = greater than or equals

RegEx to extract all matches from string using RegExp.exec

Here's a one line solution without a while loop.

The order is preserved in the resulting list.

The potential downsides are

  1. It clones the regex for every match.
  2. The result is in a different form than expected solutions. You'll need to process them one more time.
let re = /\s*([^[:]+):\"([^"]+)"/g
let str = '[description:"aoeu" uuid:"123sth"]'

(str.match(re) || []).map(e => RegExp(re.source, re.flags).exec(e))

[ [ 'description:"aoeu"',
    'description',
    'aoeu',
    index: 0,
    input: 'description:"aoeu"',
    groups: undefined ],
  [ ' uuid:"123sth"',
    'uuid',
    '123sth',
    index: 0,
    input: ' uuid:"123sth"',
    groups: undefined ] ]

Remove a file from the list that will be committed

Answer:

git reset HEAD path/to/file

Getting vertical gridlines to appear in line plot in matplotlib

maybe this can solve the problem: matplotlib, define size of a grid on a plot

ax.grid(True, which='both')

The truth is that the grid is working, but there's only one v-grid in 00:00 and no grid in others. I meet the same problem that there's only one grid in Nov 1 among many days.

Reading in double values with scanf in c

Using %lf will help you in solving this problem.

Use :

scanf("%lf",&doub)

When should I use git pull --rebase?

One practice case is when you are working with Bitbucket PR. There is PR open.

Then you decide to rebase the PR remote branch on the latest Master branch. This will change the commit's ids of your PR.

Then you want to add a new commit to the PR branch.

Since you have rebased the remote branch using GUI first you to sync the local branch on PC with the remote branch.

In this case git pull --rebase works like magic.

After git pull --rebase your remote branch and local branch has same history with same commit ids.

Now you can nicely push a new commit without using force or anything.

How to exclude records with certain values in sql select

You can use EXCEPT syntax, for example:

SELECT var FROM table1
EXCEPT
SELECT var FROM table2

How do I execute a program using Maven?

In order to execute multiple programs, I also needed a profiles section:

<profiles>
  <profile>
    <id>traverse</id>
    <activation>
      <property>
        <name>traverse</name>
      </property>
    </activation>
    <build>
      <plugins>
        <plugin>
          <groupId>org.codehaus.mojo</groupId>
          <artifactId>exec-maven-plugin</artifactId>
          <configuration>
            <executable>java</executable>
            <arguments>
              <argument>-classpath</argument>
              <argument>org.dhappy.test.NeoTraverse</argument>
            </arguments>
          </configuration>
        </plugin>
      </plugins>
    </build>
  </profile>
</profiles>

This is then executable as:

mvn exec:exec -Ptraverse

Concatenate chars to form String in java

You can use StringBuilder:

    StringBuilder sb = new StringBuilder();
    sb.append('a');
    sb.append('b');
    sb.append('c');
    String str = sb.toString()

Or if you already have the characters, you can pass a character array to the String constructor:

String str = new String(new char[]{'a', 'b', 'c'});

Nginx sites-enabled, sites-available: Cannot create soft-link between config files in Ubuntu 12.04

My site configuration file is example.conf in sites-available folder So you can create a symbolic link as

ln -s /etc/nginx/sites-available/example.conf /etc/nginx/sites-enabled/

Java - creating a new thread

If you want more Thread to be created, in above case you have to repeat the code inside run method or at least repeat calling some method inside.

Try this, which will help you to call as many times you needed. It will be helpful when you need to execute your run more then once and from many place.

class A extends Thread {
    public void run() {
             //Code you want to get executed seperately then main thread.       
    }
     }

Main class

A obj1 = new A();
obj1.start();

A obj2 = new A();
obj2.start();

How to write a simple Html.DropDownListFor()?

Avoid of lot of fat fingering by starting with a Dictionary in the Model

namespace EzPL8.Models
{
    public class MyEggs
    {
        public Dictionary<int, string> Egg { get; set; }

        public MyEggs()
        {
            Egg = new Dictionary<int, string>()
            {
                { 0, "No Preference"},
                { 1, "I hate eggs"},
                { 2, "Over Easy"},
                { 3, "Sunny Side Up"},
                { 4, "Scrambled"},
                { 5, "Hard Boiled"},
                { 6, "Eggs Benedict"}
            };

    }


    }

In the View convert it to a list for display

@Html.DropDownListFor(m => m.Egg.Keys,
                         new SelectList(
                             Model.Egg, 
                             "Key", 
                             "Value"))

MySQL Select Query - Get only first 10 characters of a value

Using the below line

SELECT LEFT(subject , 10) FROM tbl 

MySQL Doc.

When I catch an exception, how do I get the type, file, and line number?

import sys, os

try:
    raise NotImplementedError("No error")
except Exception as e:
    exc_type, exc_obj, exc_tb = sys.exc_info()
    fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
    print(exc_type, fname, exc_tb.tb_lineno)

In SQL Server, how do I generate a CREATE TABLE statement for a given table?

If the application you are generating the scripts from is a .NET application, you may want to look into using SMO (Sql Management Objects). Reference this SQL Team link on how to use SMO to script objects.

glm rotate usage in Opengl

You need to multiply your Model matrix. Because that is where model position, scaling and rotation should be (that's why it's called the model matrix).

All you need to do is (see here)

Model = glm::rotate(Model, angle_in_radians, glm::vec3(x, y, z)); // where x, y, z is axis of rotation (e.g. 0 1 0)

Note that to convert from degrees to radians, use glm::radians(degrees)

That takes the Model matrix and applies rotation on top of all the operations that are already in there. The other functions translate and scale do the same. That way it's possible to combine many transformations in a single matrix.

note: earlier versions accepted angles in degrees. This is deprecated since 0.9.6

Model = glm::rotate(Model, angle_in_degrees, glm::vec3(x, y, z)); // where x, y, z is axis of rotation (e.g. 0 1 0)

How to put the legend out of the plot

Here is an example from the matplotlib tutorial found here. This is one of the more simpler examples but I added transparency to the legend and added plt.show() so you can paste this into the interactive shell and get a result:

import matplotlib.pyplot as plt
p1, = plt.plot([1, 2, 3])
p2, = plt.plot([3, 2, 1])
p3, = plt.plot([2, 3, 1])
plt.legend([p2, p1, p3], ["line 1", "line 2", "line 3"]).get_frame().set_alpha(0.5)
plt.show()

How do I make WRAP_CONTENT work on a RecyclerView

I had used some of the above solutions but it was working for width but height.

  1. If your specified compileSdkVersion greater than 23, you can directly use RecyclerView provided in their respective support libraries of recycler view, like for 23 it will be 'com.android.support:recyclerview-v7:23.2.1'. These support libraries support attributes of wrap_content for both width and height.

You have to add it to your dependencies

compile 'com.android.support:recyclerview-v7:23.2.1'
  1. If your compileSdkVersion less than 23, you can use below-mentioned solution.

I found this Google thread regarding this issue. In this thread, there is one contribution which leads to the implementation of LinearLayoutManager.

I have tested it for both height and width and it worked fine for me in both cases.

/*
 * Copyright 2015 serso aka se.solovyev
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 *
 * Contact details
 *
 * Email: [email protected]
 * Site:  http://se.solovyev.org
 */

package org.solovyev.android.views.llm;

import android.content.Context;
import android.graphics.Rect;
import android.support.v4.view.ViewCompat;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;

import java.lang.reflect.Field;

/**
 * {@link android.support.v7.widget.LinearLayoutManager} which wraps its content. Note that this class will always
 * wrap the content regardless of {@link android.support.v7.widget.RecyclerView} layout parameters.
 * <p/>
 * Now it's impossible to run add/remove animations with child views which have arbitrary dimensions (height for
 * VERTICAL orientation and width for HORIZONTAL). However if child views have fixed dimensions
 * {@link #setChildSize(int)} method might be used to let the layout manager know how big they are going to be.
 * If animations are not used at all then a normal measuring procedure will run and child views will be measured during
 * the measure pass.
 */
public class LinearLayoutManager extends android.support.v7.widget.LinearLayoutManager {

    private static boolean canMakeInsetsDirty = true;
    private static Field insetsDirtyField = null;

    private static final int CHILD_WIDTH = 0;
    private static final int CHILD_HEIGHT = 1;
    private static final int DEFAULT_CHILD_SIZE = 100;

    private final int[] childDimensions = new int[2];
    private final RecyclerView view;

    private int childSize = DEFAULT_CHILD_SIZE;
    private boolean hasChildSize;
    private int overScrollMode = ViewCompat.OVER_SCROLL_ALWAYS;
    private final Rect tmpRect = new Rect();

    @SuppressWarnings("UnusedDeclaration")
    public LinearLayoutManager(Context context) {
        super(context);
        this.view = null;
    }

    @SuppressWarnings("UnusedDeclaration")
    public LinearLayoutManager(Context context, int orientation, boolean reverseLayout) {
        super(context, orientation, reverseLayout);
        this.view = null;
    }

    @SuppressWarnings("UnusedDeclaration")
    public LinearLayoutManager(RecyclerView view) {
        super(view.getContext());
        this.view = view;
        this.overScrollMode = ViewCompat.getOverScrollMode(view);
    }

    @SuppressWarnings("UnusedDeclaration")
    public LinearLayoutManager(RecyclerView view, int orientation, boolean reverseLayout) {
        super(view.getContext(), orientation, reverseLayout);
        this.view = view;
        this.overScrollMode = ViewCompat.getOverScrollMode(view);
    }

    public void setOverScrollMode(int overScrollMode) {
        if (overScrollMode < ViewCompat.OVER_SCROLL_ALWAYS || overScrollMode > ViewCompat.OVER_SCROLL_NEVER)
            throw new IllegalArgumentException("Unknown overscroll mode: " + overScrollMode);
        if (this.view == null) throw new IllegalStateException("view == null");
        this.overScrollMode = overScrollMode;
        ViewCompat.setOverScrollMode(view, overScrollMode);
    }

    public static int makeUnspecifiedSpec() {
        return View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
    }

    @Override
    public void onMeasure(RecyclerView.Recycler recycler, RecyclerView.State state, int widthSpec, int heightSpec) {
        final int widthMode = View.MeasureSpec.getMode(widthSpec);
        final int heightMode = View.MeasureSpec.getMode(heightSpec);

        final int widthSize = View.MeasureSpec.getSize(widthSpec);
        final int heightSize = View.MeasureSpec.getSize(heightSpec);

        final boolean hasWidthSize = widthMode != View.MeasureSpec.UNSPECIFIED;
        final boolean hasHeightSize = heightMode != View.MeasureSpec.UNSPECIFIED;

        final boolean exactWidth = widthMode == View.MeasureSpec.EXACTLY;
        final boolean exactHeight = heightMode == View.MeasureSpec.EXACTLY;

        final int unspecified = makeUnspecifiedSpec();

        if (exactWidth && exactHeight) {
            // in case of exact calculations for both dimensions let's use default "onMeasure" implementation
            super.onMeasure(recycler, state, widthSpec, heightSpec);
            return;
        }

        final boolean vertical = getOrientation() == VERTICAL;

        initChildDimensions(widthSize, heightSize, vertical);

        int width = 0;
        int height = 0;

        // it's possible to get scrap views in recycler which are bound to old (invalid) adapter entities. This
        // happens because their invalidation happens after "onMeasure" method. As a workaround let's clear the
        // recycler now (it should not cause any performance issues while scrolling as "onMeasure" is never
        // called whiles scrolling)
        recycler.clear();

        final int stateItemCount = state.getItemCount();
        final int adapterItemCount = getItemCount();
        // adapter always contains actual data while state might contain old data (f.e. data before the animation is
        // done). As we want to measure the view with actual data we must use data from the adapter and not from  the
        // state
        for (int i = 0; i < adapterItemCount; i++) {
            if (vertical) {
                if (!hasChildSize) {
                    if (i < stateItemCount) {
                        // we should not exceed state count, otherwise we'll get IndexOutOfBoundsException. For such items
                        // we will use previously calculated dimensions
                        measureChild(recycler, i, widthSize, unspecified, childDimensions);
                    } else {
                        logMeasureWarning(i);
                    }
                }
                height += childDimensions[CHILD_HEIGHT];
                if (i == 0) {
                    width = childDimensions[CHILD_WIDTH];
                }
                if (hasHeightSize && height >= heightSize) {
                    break;
                }
            } else {
                if (!hasChildSize) {
                    if (i < stateItemCount) {
                        // we should not exceed state count, otherwise we'll get IndexOutOfBoundsException. For such items
                        // we will use previously calculated dimensions
                        measureChild(recycler, i, unspecified, heightSize, childDimensions);
                    } else {
                        logMeasureWarning(i);
                    }
                }
                width += childDimensions[CHILD_WIDTH];
                if (i == 0) {
                    height = childDimensions[CHILD_HEIGHT];
                }
                if (hasWidthSize && width >= widthSize) {
                    break;
                }
            }
        }

        if (exactWidth) {
            width = widthSize;
        } else {
            width += getPaddingLeft() + getPaddingRight();
            if (hasWidthSize) {
                width = Math.min(width, widthSize);
            }
        }

        if (exactHeight) {
            height = heightSize;
        } else {
            height += getPaddingTop() + getPaddingBottom();
            if (hasHeightSize) {
                height = Math.min(height, heightSize);
            }
        }

        setMeasuredDimension(width, height);

        if (view != null && overScrollMode == ViewCompat.OVER_SCROLL_IF_CONTENT_SCROLLS) {
            final boolean fit = (vertical && (!hasHeightSize || height < heightSize))
                    || (!vertical && (!hasWidthSize || width < widthSize));

            ViewCompat.setOverScrollMode(view, fit ? ViewCompat.OVER_SCROLL_NEVER : ViewCompat.OVER_SCROLL_ALWAYS);
        }
    }

    private void logMeasureWarning(int child) {
        if (BuildConfig.DEBUG) {
            Log.w("LinearLayoutManager", "Can't measure child #" + child + ", previously used dimensions will be reused." +
                    "To remove this message either use #setChildSize() method or don't run RecyclerView animations");
        }
    }

    private void initChildDimensions(int width, int height, boolean vertical) {
        if (childDimensions[CHILD_WIDTH] != 0 || childDimensions[CHILD_HEIGHT] != 0) {
            // already initialized, skipping
            return;
        }
        if (vertical) {
            childDimensions[CHILD_WIDTH] = width;
            childDimensions[CHILD_HEIGHT] = childSize;
        } else {
            childDimensions[CHILD_WIDTH] = childSize;
            childDimensions[CHILD_HEIGHT] = height;
        }
    }

    @Override
    public void setOrientation(int orientation) {
        // might be called before the constructor of this class is called
        //noinspection ConstantConditions
        if (childDimensions != null) {
            if (getOrientation() != orientation) {
                childDimensions[CHILD_WIDTH] = 0;
                childDimensions[CHILD_HEIGHT] = 0;
            }
        }
        super.setOrientation(orientation);
    }

    public void clearChildSize() {
        hasChildSize = false;
        setChildSize(DEFAULT_CHILD_SIZE);
    }

    public void setChildSize(int childSize) {
        hasChildSize = true;
        if (this.childSize != childSize) {
            this.childSize = childSize;
            requestLayout();
        }
    }

    private void measureChild(RecyclerView.Recycler recycler, int position, int widthSize, int heightSize, int[] dimensions) {
        final View child;
        try {
            child = recycler.getViewForPosition(position);
        } catch (IndexOutOfBoundsException e) {
            if (BuildConfig.DEBUG) {
                Log.w("LinearLayoutManager", "LinearLayoutManager doesn't work well with animations. Consider switching them off", e);
            }
            return;
        }

        final RecyclerView.LayoutParams p = (RecyclerView.LayoutParams) child.getLayoutParams();

        final int hPadding = getPaddingLeft() + getPaddingRight();
        final int vPadding = getPaddingTop() + getPaddingBottom();

        final int hMargin = p.leftMargin + p.rightMargin;
        final int vMargin = p.topMargin + p.bottomMargin;

        // we must make insets dirty in order calculateItemDecorationsForChild to work
        makeInsetsDirty(p);
        // this method should be called before any getXxxDecorationXxx() methods
        calculateItemDecorationsForChild(child, tmpRect);

        final int hDecoration = getRightDecorationWidth(child) + getLeftDecorationWidth(child);
        final int vDecoration = getTopDecorationHeight(child) + getBottomDecorationHeight(child);

        final int childWidthSpec = getChildMeasureSpec(widthSize, hPadding + hMargin + hDecoration, p.width, canScrollHorizontally());
        final int childHeightSpec = getChildMeasureSpec(heightSize, vPadding + vMargin + vDecoration, p.height, canScrollVertically());

        child.measure(childWidthSpec, childHeightSpec);

        dimensions[CHILD_WIDTH] = getDecoratedMeasuredWidth(child) + p.leftMargin + p.rightMargin;
        dimensions[CHILD_HEIGHT] = getDecoratedMeasuredHeight(child) + p.bottomMargin + p.topMargin;

        // as view is recycled let's not keep old measured values
        makeInsetsDirty(p);
        recycler.recycleView(child);
    }

    private static void makeInsetsDirty(RecyclerView.LayoutParams p) {
        if (!canMakeInsetsDirty) {
            return;
        }
        try {
            if (insetsDirtyField == null) {
                insetsDirtyField = RecyclerView.LayoutParams.class.getDeclaredField("mInsetsDirty");
                insetsDirtyField.setAccessible(true);
            }
            insetsDirtyField.set(p, true);
        } catch (NoSuchFieldException e) {
            onMakeInsertDirtyFailed();
        } catch (IllegalAccessException e) {
            onMakeInsertDirtyFailed();
        }
    }

    private static void onMakeInsertDirtyFailed() {
        canMakeInsetsDirty = false;
        if (BuildConfig.DEBUG) {
            Log.w("LinearLayoutManager", "Can't make LayoutParams insets dirty, decorations measurements might be incorrect");
        }
    }
}

How to write multiple line string using Bash with variables?

Below mechanism helps in redirecting multiple lines to file. Keep complete string under " so that we can redirect values of the variable.

#!/bin/bash
kernel="2.6.39"
echo "line 1, ${kernel}
line 2," > a.txt
echo 'line 2, ${kernel}
line 2,' > b.txt

Content of a.txt is

line 1, 2.6.39
line 2,

Content of b.txt is

line 2, ${kernel}
line 2,

Ignore invalid self-signed ssl certificate in node.js with https.request?

Add the following environment variable:

NODE_TLS_REJECT_UNAUTHORIZED=0

e.g. with export:

export NODE_TLS_REJECT_UNAUTHORIZED=0

(with great thanks to Juanra)

Is it possible to insert HTML content in XML document?

so long as your html content doesn't need to contain a CDATA element, you can contain the HTML in a CDATA element, otherwise you'll have to escape the XML entities.

<element><![CDATA[<p>your html here</p>]]></element>

VS

<element>&lt;p&gt;your html here&lt;/p&gt;</element>

pow (x,y) in Java

In Java x ^ y is an XOR operation.

How do I call an Angular.js filter with multiple arguments?

If you want to call your filter inside ng-options the code will be as follows:

ng-options="productSize as ( productSize | sizeWithPrice: product )  for productSize in productSizes track by productSize.id"

where the filter is sizeWithPriceFilter and it has two parameters product and productSize

Sqlite primary key on multiple columns

In another way, you can also make the two column primary key unique and the auto-increment key primary. Just like this: https://stackoverflow.com/a/6157337

SSL: error:0B080074:x509 certificate routines:X509_check_private_key:key values mismatch

If this happens and you are using Let's Encrypt / certbot, the reason is most likely that you used chain.pem instead of fullchain.pem.

It should be something like this:

ssl_certificate /etc/certbot/live/example.com/fullchain.pem;
ssl_certificate_key /etc/certbot/live/example.com/privkey.pem;

See certbot docs “Where are my certificates?”

SQLite table constraint - unique on multiple columns

Well, your syntax doesn't match the link you included, which specifies:

 CREATE TABLE name (column defs) 
    CONSTRAINT constraint_name    -- This is new
    UNIQUE (col_name1, col_name2) ON CONFLICT REPLACE

Uncaught ReferenceError: $ is not defined

Root problem is a ReferenceError. MDN indicates that a try/catch block is the proper tool for the job. In my case, I was getting uncaught reference error for a payment sdk/library. The below works for me.

try {
  var stripe = Stripe('pk_test_---------');
} catch (e) {
    stripe = null;
}

if(stripe){
  //we are good to go now
}

Obviously the fix is to load whatever SDK/library, e.g. jQuery, prior to calling its methods but the try/catch does keep your shared JavaScript from barfing up errors in case you run that shared script on a page that doesn't load whatever library you use on a subset of pages.

What are the date formats available in SimpleDateFormat class?

Date and time formats are well described below

SimpleDateFormat (Java Platform SE 7) - Date and Time Patterns

There could be n Number of formats you can possibly make. ex - dd/MM/yyyy or YYYY-'W'ww-u or you can mix and match the letters to achieve your required pattern. Pattern letters are as follow.

  • G - Era designator (AD)
  • y - Year (1996; 96)
  • Y - Week Year (2009; 09)
  • M - Month in year (July; Jul; 07)
  • w - Week in year (27)
  • W - Week in month (2)
  • D - Day in year (189)
  • d - Day in month (10)
  • F - Day of week in month (2)
  • E - Day name in week (Tuesday; Tue)
  • u - Day number of week (1 = Monday, ..., 7 = Sunday)
  • a - AM/PM marker
  • H - Hour in day (0-23)
  • k - Hour in day (1-24)
  • K - Hour in am/pm (0-11)
  • h - Hour in am/pm (1-12)
  • m - Minute in hour (30)
  • s - Second in minute (55)
  • S - Millisecond (978)
  • z - General time zone (Pacific Standard Time; PST; GMT-08:00)
  • Z - RFC 822 time zone (-0800)
  • X - ISO 8601 time zone (-08; -0800; -08:00)

To parse:

2000-01-23T04:56:07.000+0000

Use: new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");

How do I execute a stored procedure in a SQL Agent job?

As Marc says, you run it exactly like you would from the command line. See Creating SQL Server Agent Jobs on MSDN.

SecurityException during executing jnlp file (Missing required Permissions manifest attribute in main jar)

JAR File Manifest Attributes for Security

The JAR file manifest contains information about the contents of the JAR file, including security and configuration information.

Add the attributes to the manifest before the JAR file is signed.
See Modifying a Manifest File in the Java Tutorial for information on adding attributes to the JAR manifest file.

Permissions Attribute

The Permissions attribute is used to verify that the permissions level requested by the RIA when it runs matches the permissions level that was set when the JAR file was created.

Use this attribute to help prevent someone from re-deploying an application that is signed with your certificate and running it at a different privilege level. Set this attribute to one of the following values:

  • sandbox - runs in the security sandbox and does not require additional permissions.

  • all-permissions - requires access to the user's system resources.

Changes to Security Slider:

The following changes to Security Slider were included in this release(7u51):

  • Block Self-Signed and Unsigned applets on High Security Setting
  • Require Permissions Attribute for High Security Setting
  • Warn users of missing Permissions Attributes for Medium Security Setting

For more information, see Java Control Panel documentation.

enter image description here

sample MANIFEST.MF

Manifest-Version: 1.0
Ant-Version: Apache Ant 1.8.3
Created-By: 1.7.0_51-b13 (Oracle Corporation)
Trusted-Only: true
Class-Path: lib/plugin.jar
Permissions: sandbox
Codebase: http://myweb.de http://www.myweb.de
Application-Name: summary-applet

Angular: Cannot Get /

I had the same error caused by build errors. I ran ng build in the directory of my application which helped me correct my errors

Using Server.MapPath() inside a static field in ASP.NET MVC

Try HostingEnvironment.MapPath, which is static.

See this SO question for confirmation that HostingEnvironment.MapPath returns the same value as Server.MapPath: What is the difference between Server.MapPath and HostingEnvironment.MapPath?

Remove blank attributes from an Object in Javascript

a reduce helper can do the trick (without type checking) -

const cleanObj = Object.entries(objToClean).reduce((acc, [key, value]) => {
      if (value) {
        acc[key] = value;
      }
      return acc;
    }, {});

AndroidStudio: Failed to sync Install build tools

enter image description here

Start the project structure( file>structure) You can see: on the left, modules list;

on the right, Properties>Build Tools Version there maybe are more than one modules.

change "Build Tools Version" for every Module.

it works.

how to convert string to numerical values in mongodb

If you can edit all documents in aggregate :

"TimeStamp": {$toDecimal: {$toDate: "$Your Date"}}

And for the client, you set the query :

Date.parse("Your date".toISOString())

That's what makes you whole work with ISODate.

Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.2:java (default-cli)

I had a similar problem with 'org.codehaus.mojo'-'jaxws-maven-plugin': could not resolve dependencies. Fortunately, I was able to do a Project > Clean in Eclipse, which resolved the issue.

Loop through an array of strings in Bash?

None of those answers include a counter...

#!/bin/bash
## declare an array variable
declare -a array=("one" "two" "three")

# get length of an array
arraylength=${#array[@]}

# use for loop to read all values and indexes
for (( i=1; i<${arraylength}+1; i++ ));
do
  echo $i " / " ${arraylength} " : " ${array[$i-1]}
done

Output:

1  /  3  :  one
2  /  3  :  two
3  /  3  :  three

Creating Roles in Asp.net Identity MVC 5

As an improvement on Peters code above you can use this:

   var roleManager = new RoleManager<Microsoft.AspNet.Identity.EntityFramework.IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));

   if (!roleManager.RoleExists("Member"))
            roleManager.Create(new IdentityRole("Member"));

jQuery: get data attribute

This is what I came up with:

_x000D_
_x000D_
  $(document).ready(function(){_x000D_
  _x000D_
  $(".fc-event").each(function(){_x000D_
  _x000D_
   console.log(this.attributes['data'].nodeValue) _x000D_
  });_x000D_
    _x000D_
    });
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>_x000D_
<div id='external-events'>_x000D_
   <h4>Booking</h4>_x000D_
   <div class='fc-event' data='00:30:00' >30 Mins</div>_x000D_
   <div class='fc-event' data='00:45:00' >45 Mins</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Memcache Vs. Memcached

(PartlyStolen from ServerFault)

I think that both are functionally the same, but they simply have different authors, and the one is simply named more appropriately than the other.


Here is a quick backgrounder in naming conventions (for those unfamiliar), which explains the frustration by the question asker: For many *nix applications, the piece that does the backend work is called a "daemon" (think "service" in Windows-land), while the interface or client application is what you use to control or access the daemon. The daemon is most often named the same as the client, with the letter "d" appended to it. For example "imap" would be a client that connects to the "imapd" daemon.

This naming convention is clearly being adhered to by memcache when you read the introduction to the memcache module (notice the distinction between memcache and memcached in this excerpt):

Memcache module provides handy procedural and object oriented interface to memcached, highly effective caching daemon, which was especially designed to decrease database load in dynamic web applications.

The Memcache module also provides a session handler (memcache).

More information about memcached can be found at » http://www.danga.com/memcached/.

The frustration here is caused by the author of the PHP extension which was badly named memcached, since it shares the same name as the actual daemon called memcached. Notice also that in the introduction to memcached (the php module), it makes mention of libmemcached, which is the shared library (or API) that is used by the module to access the memcached daemon:

memcached is a high-performance, distributed memory object caching system, generic in nature, but intended for use in speeding up dynamic web applications by alleviating database load.

This extension uses libmemcached library to provide API for communicating with memcached servers. It also provides a session handler (memcached).

Information about libmemcached can be found at » http://tangent.org/552/libmemcached.html.

How do I share a global variable between c files?

file 1:

int x = 50;

file 2:

extern int x;

printf("%d", x);

How to filter a dictionary according to an arbitrary condition function?

points_small = dict(filter(lambda (a,(b,c)): b<5 and c < 5, points.items()))

How to add additional fields to form before submit?

You can add a hidden input with whatever value you need to send:

$('#form').submit(function(eventObj) {
    $(this).append('<input type="hidden" name="someName" value="someValue">');
    return true;
});

How to connect android wifi to adhoc wifi?

I did notice something of interest here: In my 2.3.4 phone I can't see AP/AdHoc SSIDs in the Settings > Wireless & Networks menu. On an Acer A500 running 4.0.3 I do see them, prefixed by (*)

However in the following bit of code that I adapted from (can't remember source, sorry!) I do see the Ad Hoc show up in the Wifi Scan on my 2.3.4 phone. I am still looking to actually connect and create a socket + input/outputStream. But, here ya go:

    public class MainActivity extends Activity {

private static final String CHIPKIT_BSSID = "E2:14:9F:18:40:1C";
private static final int CHIPKIT_WIFI_PRIORITY = 1;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    final Button btnDoSomething = (Button) findViewById(R.id.btnDoSomething);
    final Button btnNewScan = (Button) findViewById(R.id.btnNewScan);
    final TextView textWifiManager = (TextView) findViewById(R.id.WifiManager);
    final TextView textWifiInfo = (TextView) findViewById(R.id.WifiInfo);
    final TextView textIp = (TextView) findViewById(R.id.Ip);

    final WifiManager myWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    final WifiInfo myWifiInfo = myWifiManager.getConnectionInfo();

    WifiConfiguration wifiConfiguration = new WifiConfiguration();
    wifiConfiguration.BSSID = CHIPKIT_BSSID;
    wifiConfiguration.priority = CHIPKIT_WIFI_PRIORITY;
    wifiConfiguration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
    wifiConfiguration.allowedKeyManagement.set(KeyMgmt.NONE);
    wifiConfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
    wifiConfiguration.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
    wifiConfiguration.status = WifiConfiguration.Status.ENABLED;

    myWifiManager.setWifiEnabled(true);

    int netID = myWifiManager.addNetwork(wifiConfiguration);

    myWifiManager.enableNetwork(netID, true);

    textWifiInfo.setText("SSID: " + myWifiInfo.getSSID() + '\n' 
            + myWifiManager.getWifiState() + "\n\n");

    btnDoSomething.setOnClickListener(new View.OnClickListener() {          
        public void onClick(View v) {
            clearTextViews(textWifiManager, textIp);                
        }           
    });

    btnNewScan.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            getNewScan(myWifiManager, textWifiManager, textIp);
        }
    });     
}

private void clearTextViews(TextView...tv) {
    for(int i = 0; i<tv.length; i++){
        tv[i].setText("");
    }       
}

public void getNewScan(WifiManager wm, TextView...textViews) {
    wm.startScan();

    List<ScanResult> scanResult = wm.getScanResults();

    String scan = "";

    for (int i = 0; i < scanResult.size(); i++) {
        scan += (scanResult.get(i).toString() + "\n\n");
    }

    textViews[0].setText(scan);
    textViews[1].setText(wm.toString());
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

Don't forget that in Eclipse you can use Ctrl+Shift+[letter O] to fill in the missing imports...

and my manifest:

    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.digilent.simpleclient"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="15" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>

<application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".MainActivity"
        android:label="@string/title_activity_main" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

Hope that helps!

Does WhatsApp offer an open API?

1) It looks possible. This info on Github describes how to create a java program to send a message using the whatsapp encryption protocol from WhisperSystems.

2) No. See the whatsapp security white paper.

3) See #1.

Make absolute positioned div expand parent div height

There's a very simple hack that fixes this issue

Here's a codesandbox that illustrates the solution: https://codesandbox.io/s/00w06z1n5l

HTML

<div id="parent">
  <div class="hack">
   <div class="child">
   </div>
  </div>
</div>

CSS

.parent { position: relative; width: 100%; }
.hack { position: absolute; left:0; right:0; top:0;}
.child { position: absolute; left: 0; right: 0; bottom:0; }

you can play with the positioning of the hack div to affect where the child positions itself.

Here's a snippet:

_x000D_
_x000D_
html {_x000D_
  font-family: sans-serif;_x000D_
  text-align: center;_x000D_
}_x000D_
_x000D_
.container {_x000D_
  border: 2px solid gray;_x000D_
  height: 400px;_x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
}_x000D_
_x000D_
.stuff-the-middle {_x000D_
  background: papayawhip_x000D_
    url("https://camo.githubusercontent.com/6609e7239d46222bbcbd846155351a8ce06eb11f/687474703a2f2f692e696d6775722e636f6d2f4e577a764a6d6d2e706e67");_x000D_
  flex: 1;_x000D_
}_x000D_
_x000D_
.parent {_x000D_
  background: palevioletred;_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
.hack {_x000D_
  position: absolute;_x000D_
  left: 0;_x000D_
  top:0;_x000D_
  right: 0;_x000D_
}_x000D_
.child {_x000D_
  height: 40px;_x000D_
  background: rgba(0, 0, 0, 0.5);_x000D_
  position: absolute;_x000D_
  bottom: 0;_x000D_
  left: 0;_x000D_
  right: 0;_x000D_
}
_x000D_
    <div class="container">_x000D_
      <div class="stuff-the-middle">_x000D_
        I have stuff annoyingly in th emiddle_x000D_
      </div>_x000D_
      <div class="parent">_x000D_
        <div class="hack">_x000D_
          <div class="child">_x000D_
            I'm inside of my parent but absolutely on top_x000D_
          </div>_x000D_
        </div>_x000D_
        I'm the parent_x000D_
        <br /> You can modify my height_x000D_
        <br /> and my child is always on top_x000D_
        <br /> absolutely on top_x000D_
        <br /> try removing this text_x000D_
      </div>_x000D_
    </div>
_x000D_
_x000D_
_x000D_

base64 encoded images in email signatures

The image should be embedded in the message as an attachment like this:

--boundary
Content-Type: image/png; name="sig.png"
Content-Disposition: inline; filename="sig.png"
Content-Transfer-Encoding: base64
Content-ID: <0123456789>
Content-Location: sig.png

base64 data

--boundary

And, the HTML part would reference the image like this:

<img src="cid:0123456789">

In some clients, src="sig.png" will work too.

You'd basically have a multipart/mixed, multipart/alternative, multipart/related message where the image attachment is in the related part.

Clients shouldn't block this image either as it isn't remote.

Or, here's a multipart/alternative, multipart/related example as an mbox file (save as windows newline format and put a blank line at the end. And, use no extension or the .mbs extension):

From 
From: [email protected]
To: [email protected]
Subject: HTML Messages with Embedded Pic in Signature
MIME-Version: 1.0
Content-Type: multipart/alternative; boundary="alternative_boundary"

This is a message with multiple parts in MIME format.

--alternative_boundary
Content-Type: text/plain; charset="utf-8"
Content-Transfer-Encoding: 8bit

test

-- 
[Picture of a Christmas Tree]

--alternative_boundary
Content-Type: multipart/related; boundary="related_boundary"

--related_boundary
Content-Type: text/html; charset="utf-8"
Content-Transfer-Encoding: 8bit

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
    </head>
    <body>
        <p>test</p>
        <p class="sig">-- <br><img src="cid:0123456789"></p>
    </body>
</html>

--related_boundary
Content-Type: image/png; name="sig.png"
Content-Disposition: inline; filename="sig.png"
Content-Location: sig.png
Content-ID: <0123456789>
Content-Transfer-Encoding: base64

R0lGODlhKAA8AIMLAAD//wAhAABKAABrAACUAAC1AADeAAD/AGsAAP8zM///AP//
///M//////+ZAMwAACH/C05FVFNDQVBFMi4wAwGgDwAh+QQJFAALACwAAAAAKAA8
AAME+3DJSWt1Nuu9Mf+g5IzK6IXopaxn6orlKy/jMc6vQRy4GySABK+HAiaIoQdg
uUSCBAKAYTBwbgyGA2AgsGqo0wMh7K0YEuj0sUxRoAfqB1vycBN21Ki8vOofBndR
c1AKgH8ETE1lBgo7O2JaU2UFAgRoDGoAXV4PD2qYagl7Vp0JDKenfwado0QCAQOQ
DIcDBgIFVgYBAlOxswR5r1VIUbCHwH8HlQWFRLYABVOWamACCkiJAAehaX0rPZ1B
oQSg3Z04AuFqB2IMd+atLwUBtpAHqKdUtbwGM1BTOgA5YhBr374ZAxhAqRVLzA53
OwTEAjhDIZYs09aBASYq+94HfAq3cRt57sWDct2EvEsTpBMVF6sYeEpDQIFDdo62
BHwZApjEhjW94RyQTWK/FPx+Ahpg09GdOzoJ/ESx0JaOQ42e2tsiEYpCEFwAGi04
8g6gSgNOovD0gBeVjCPR2BIAkgOrmSNxPo3rbhgHZiMFPnLkBg2BAuQ2XdmlwK1Z
ooZu1sRz6xWlxd4U9GIHwOmdzFgCFKCERYNoeo2BZsPp0KY+A/OAfZDYWKJZLZBo
1mQXdlojvxNYiXrD8I+2uEvTdFJQksID0XjXiUwjJm6CzBVeBQgwBop1ZPpC8RKt
YN5RCpS6XiyMht093o8KcFFf/vKE0dCmaLeWYhQMwbeQaHLRfNk9o5Q13lQGklFQ
aMLFRLcwcN5qSWmGxS2jKQQFL9nEAgxsDEiwlAHaPPJWIfroo6FVEun0VkL4UABA
CAjUiIAFM2YQogzcoLCjC3HNsYB1aSBB5JFrZBABACH5BAkUAAsALAAAAAAoADwA
AwT7cMlJa3U2670x/6DkjKQXnleJrqnJruMxvq8xHDQbJEyC5yheAnh6MI5HYkgg
YNgGSo7BcGAMBNHNYGA7ELpZiyFBLg/DFvLArEBPHoAEgXDYChQP90IAoNYJCoGB
aACFhX8HBwoGegYAdHReijZoBXxmPWRYYQ8PZmSZZHmcnqBITp2jSgIBN5BVBFwC
BVkGAQJPiVV2rFCrCq1/sXUHAgQFAL45BncFNgSfW8wASoKBB59lhoVAnQqfDNCf
AJ05At5msHPiCeSqLwUBzF6nVnXSuIwvTDYGsXPhiMmSRUOWAC436HmZU+yGDQYF
81FhV+aevzUM3oHoZBD7W7Zs9VaUIhOn4pwE38p0srLCQCqSciBFUuBFGgEryj7E
Ojhg2yOG1hQMIMCEy4p8PB8llKmAIReiW040keUvmUygiexcwbWJwxUrzBDW+Thn
qLEB5UDUe0LxYwJmAhKk+pAqVLZE69qWGZpTQwG7ZISuw7uwzDFAXTXYYoJraKym
Q/HSASDpiiUFljbYitfYRtCF635yMRBUn4UA8aYclCw0shefW7gUgPxBKGPHA5pK
MpwsKy5AcmNZSIVHjdjI2eLwVZlK44IHQT8lkq7XTDznrAIEWMTErZwbsT/hQj1L
noXLV6YwS5eIJqIDf4tyLZB5Av1ZNrLzQSplrXVkOgxItBU1E+DCwC2xFZUME5dZ
c5AB9aw2jXkSQLhFIrj4xAx9szGWzwABdkGATwuAeEokW4wY24oK8MMViAjxxcc8
E0CUAYETIKAjAifgWGMI2ehBgVtCeleGEkYmeUYGEQAAIfkECRQACwAsAAAAACgA
PAADBPtwyUlrdTbrvTH/oOSMpBeeV4muqcmu4zG+r6EcNBskSoLnJ4VQCAw9ErzE
oxgSCBSGwYDJMRgOhIGAupFGsVEG12JAmpHicaU3QDPe6fHjoSAQDlIBY6leDIUD
dnp9C04DdXh3eAaEUTeKdwJRagUCBGdnW3JHmJh8XHNmWAeLDwCfRQIBA6MMiQMG
AgBcBgGSUgeuWQMAvb1MAgWruXAMrJYAUkU2wVGXDGZeAIxMCgVfaJhOVkB/PWeX
nXM5AnScSKR2dmZzqCwFUAKjo1l4XpLULNuwWXYHAHgWCYD15AXBgV+wEACg7sDA
A45oaLFy5ZKvXvYMEPCGYvvOwQOYAHRCQufFuU7/wp2Zo2AKCgPtwN3xR8/LLpcg
kg1khaVlQyw8GRAwlC8nvp2HeM5UR8CYxp05L8ay8YcplmLGtmniwCtKLFhJR9oR
amnAuBAiH9wK9G1kAgaxBCg5u6HdSUzp1LlNCqJAgZGBaC41Q6DAUAUfajm5ZUdK
v7z08ATjmKGWAltecaVTqE5oFisB/EIpSiH06IcKpQTa3JSVagPCWm7wZsgOwJkg
3xaTrJFkFgvtFHDywmt1J2iB2pC0C9x0yItnsLx1K8xdoQDYCcQ9I5KwaynaalUS
RnpBpYH4YiXoTipgIlIFtLSUFKwSBb/NtGCnb2Zl51fHo8hnhRZbSfCEKkgZkkcw
TgBgyVdxeQNRMNNMoMBOpBxFUSx+ObgYPgS1BBRss/jxxzwAqsbLRfwh1VJyF5WI
2AkIAIAAAiiUKMGMICDRXQIn6IiCW4Qs4NYZTByppBkbRAAAIf4ZQm95J3MgSGFw
cHkgSG9saWRheXMgUGFnZQA7

--related_boundary--

--alternative_boundary--

You can import that into Sylpheed or Thunderbird (with the Import/Export tools extension) or Opera's built-in mail client. Then, in Opera for example, you can toggle "prefer plain text" to see the difference between the HTML and text version. Anyway, you'll see the HTML version makes use of the embedded pic in the sig.

Are 'Arrow Functions' and 'Functions' equivalent / interchangeable?

tl;dr: No! Arrow functions and function declarations / expressions are not equivalent and cannot be replaced blindly.
If the function you want to replace does not use this, arguments and is not called with new, then yes.


As so often: it depends. Arrow functions have different behavior than function declarations / expressions, so let's have a look at the differences first:

1. Lexical this and arguments

Arrow functions don't have their own this or arguments binding. Instead, those identifiers are resolved in the lexical scope like any other variable. That means that inside an arrow function, this and arguments refer to the values of this and arguments in the environment the arrow function is defined in (i.e. "outside" the arrow function):

_x000D_
_x000D_
// Example using a function expression
function createObject() {
  console.log('Inside `createObject`:', this.foo);
  return {
    foo: 42,
    bar: function() {
      console.log('Inside `bar`:', this.foo);
    },
  };
}

createObject.call({foo: 21}).bar(); // override `this` inside createObject
_x000D_
_x000D_
_x000D_

_x000D_
_x000D_
// Example using a arrow function
function createObject() {
  console.log('Inside `createObject`:', this.foo);
  return {
    foo: 42,
    bar: () => console.log('Inside `bar`:', this.foo),
  };
}

createObject.call({foo: 21}).bar(); // override `this` inside createObject
_x000D_
_x000D_
_x000D_

In the function expression case, this refers to the object that was created inside the createObject. In the arrow function case, this refers to this of createObject itself.

This makes arrow functions useful if you need to access the this of the current environment:

// currently common pattern
var that = this;
getData(function(data) {
  that.data = data;
});

// better alternative with arrow functions
getData(data => {
  this.data = data;
});

Note that this also means that is not possible to set an arrow function's this with .bind or .call.

If you are not very familiar with this, consider reading

2. Arrow functions cannot be called with new

ES2015 distinguishes between functions that are callable and functions that are constructable. If a function is constructable, it can be called with new, i.e. new User(). If a function is callable, it can be called without new (i.e. normal function call).

Functions created through function declarations / expressions are both constructable and callable.
Arrow functions (and methods) are only callable. class constructors are only constructable.

If you are trying to call a non-callable function or to construct a non-constructable function, you will get a runtime error.


Knowing this, we can state the following.

Replaceable:

  • Functions that don't use this or arguments.
  • Functions that are used with .bind(this)

Not replaceable:

  • Constructor functions
  • Function / methods added to a prototype (because they usually use this)
  • Variadic functions (if they use arguments (see below))

Lets have a closer look at this using your examples:

Constructor function

This won't work because arrow functions cannot be called with new. Keep using a function declaration / expression or use class.

Prototype methods

Most likely not, because prototype methods usually use this to access the instance. If they don't use this, then you can replace it. However, if you primarily care for concise syntax, use class with its concise method syntax:

class User {
  constructor(name) {
    this.name = name;
  }
  
  getName() {
    return this.name;
  }
}

Object methods

Similarly for methods in an object literal. If the method wants to reference the object itself via this, keep using function expressions, or use the new method syntax:

const obj = {
  getName() {
    // ...
  },
};

Callbacks

It depends. You should definitely replace it if you are aliasing the outer this or are using .bind(this):

// old
setTimeout(function() {
  // ...
}.bind(this), 500);

// new
setTimeout(() => {
  // ...
}, 500);

But: If the code which calls the callback explicitly sets this to a specific value, as is often the case with event handlers, especially with jQuery, and the callback uses this (or arguments), you cannot use an arrow function!

Variadic functions

Since arrow functions don't have their own arguments, you cannot simply replace them with an arrow function. However, ES2015 introduces an alternative to using arguments: the rest parameter.

// old
function sum() {
  let args = [].slice.call(arguments);
  // ...
}

// new
const sum = (...args) => {
  // ...
};

Related question:

Further resources:

Capturing count from an SQL query

You'll get converting errors with:

cmd.CommandText = "SELECT COUNT(*) FROM table_name";
Int32 count = (Int32) cmd.ExecuteScalar();

Use instead:

string stm = "SELECT COUNT(*) FROM table_name WHERE id="+id+";";
MySqlCommand cmd = new MySqlCommand(stm, conn);
Int32 count = Convert.ToInt32(cmd.ExecuteScalar());
if(count > 0){
    found = true; 
} else {
    found = false; 
}

How to get a Fragment to remove itself, i.e. its equivalent of finish()?

See if your needs are met by a DialogFragment. DialogFragment has a dismiss() method. Much cleaner in my opinion.

jQuery: How can I create a simple overlay?

If you're already using jquery, I don't see why you wouldn't also be able to use a lightweight overlay plugin. Other people have already written some nice ones in jquery, so why re-invent the wheel?

How can I ping a server port with PHP?

In case the OP really wanted an ICMP-Ping, there are some proposals within the User Contributed Notes to socket_create() [link], which use raw sockets. Be aware that on UNIX like systems root access is required.

Update: note that the usec argument has no function on windows. Minimum timeout is 1 second.

In any case, this is the code of the top voted ping function:

function ping($host, $timeout = 1) {
    /* ICMP ping packet with a pre-calculated checksum */
    $package = "\x08\x00\x7d\x4b\x00\x00\x00\x00PingHost";
    $socket  = socket_create(AF_INET, SOCK_RAW, 1);
    socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, array('sec' => $timeout, 'usec' => 0));
    socket_connect($socket, $host, null);
    $ts = microtime(true);
    socket_send($socket, $package, strLen($package), 0);
    if (socket_read($socket, 255)) {
        $result = microtime(true) - $ts;
    } else {
        $result = false;
    }
    socket_close($socket);
    return $result;
}

WCF on IIS8; *.svc handler mapping doesn't work

Windows 8 with IIS8

  • Hit Windows+X
  • Select Programs and Features (first item on list)
  • Select Turn Windows Features on or off on the left
  • Expand .NET Framework 4.5 Advanced Services
  • Expand WCF Services
  • Enable HTTP Activation

How to implement debounce in Vue2?

Very simple without lodash

  handleScroll: function() {
    if (this.timeout) 
      clearTimeout(this.timeout); 

    this.timeout = setTimeout(() => {
      // your action
    }, 200); // delay
  }

How can I close a window with Javascript on Mozilla Firefox 3?

From a user experience stand-point, you don't want a major action to be done passively.

Something major like a window close should be the result of an action by the user.

What's the difference between a temp table and table variable in SQL Server?

For all of you who believe the myth that temp variables are in memory only

First, the table variable is NOT necessarily memory resident. Under memory pressure, the pages belonging to a table variable can be pushed out to tempdb.

Read the article here: TempDB:: Table variable vs local temporary table

Validate that a string is a positive integer

Solution 1

If we consider a JavaScript integer to be a value of maximum 4294967295 (i.e. Math.pow(2,32)-1), then the following short solution will perfectly work:

function isPositiveInteger(n) {
    return n >>> 0 === parseFloat(n);
}

DESCRIPTION:

  1. Zero-fill right shift operator does three important things:
    • truncates decimal part
      • 123.45 >>> 0 === 123
    • does the shift for negative numbers
      • -1 >>> 0 === 4294967295
    • "works" in range of MAX_INT
      • 1e10 >>> 0 === 1410065408
      • 1e7 >>> 0 === 10000000
  2. parseFloat does correct parsing of string numbers (setting NaN for non numeric strings)

TESTS:

"0"                     : true
"23"                    : true
"-10"                   : false
"10.30"                 : false
"-40.1"                 : false
"string"                : false
"1234567890"            : true
"129000098131766699.1"  : false
"-1e7"                  : false
"1e7"                   : true
"1e10"                  : false
"1edf"                  : false
" "                     : false
""                      : false

DEMO: http://jsfiddle.net/5UCy4/37/


Solution 2

Another way is good for all numeric values which are valid up to Number.MAX_VALUE, i.e. to about 1.7976931348623157e+308:

function isPositiveInteger(n) {
    return 0 === n % (!isNaN(parseFloat(n)) && 0 <= ~~n);
}

DESCRIPTION:

  1. !isNaN(parseFloat(n)) is used to filter pure string values, e.g. "", " ", "string";
  2. 0 <= ~~n filters negative and large non-integer values, e.g. "-40.1", "129000098131766699";
  3. (!isNaN(parseFloat(n)) && 0 <= ~~n) returns true if value is both numeric and positive;
  4. 0 === n % (...) checks if value is non-float -- here (...) (see 3) is evaluated as 0 in case of false, and as 1 in case of true.

TESTS:

"0"                     : true
"23"                    : true
"-10"                   : false
"10.30"                 : false
"-40.1"                 : false
"string"                : false
"1234567890"            : true
"129000098131766699.1"  : false
"-1e10"                 : false
"1e10"                  : true
"1edf"                  : false
" "                     : false
""                      : false

DEMO: http://jsfiddle.net/5UCy4/14/


The previous version:

function isPositiveInteger(n) {
    return n == "0" || ((n | 0) > 0 && n % 1 == 0);
}

DEMO: http://jsfiddle.net/5UCy4/2/

Repeat-until or equivalent loop in Python

REPEAT
    ...
UNTIL cond

Is equivalent to

while True:
    ...
    if cond:
        break

Oracle Installer:[INS-13001] Environment does not meet minimum requirements

To make @Raghavendra's answer more specific:

Once you've downloaded 2 zip files,

copy ALL the contents of "win64_11gR2_database_2of2.zip -> Database -> Stage -> Components" folder to "win64_11gR2_database_1of2.zip -> Database -> Stage -> Components" folder.

You'll still get the same warning, however, the installation will run completely without generating any errors.

Sorting std::map using value

If you want to present the values in a map in sorted order, then copy the values from the map to vector and sort the vector.

Can I get Unix's pthread.h to compile in Windows?

Just pick up the TDM-GCC 64x package. (It constains both the 32 and 64 bit versions of the MinGW toolchain and comes within a neat installer.) More importantly, it contains something called the "winpthread" library.

It comprises of the pthread.h header, libwinpthread.a, libwinpthread.dll.a static libraries for both 32-bit and 64-bit and the required .dlls libwinpthread-1.dll and libwinpthread_64-1.dll(this, as of 01-06-2016).

You'll need to link to the libwinpthread.a library during build. Other than that, your code can be the same as for native Pthread code on Linux. I've so far successfully used it to compile a few basic Pthread programs in 64-bit on windows.

Alternatively, you can use the following library which wraps the windows threading API into the pthreads API: pthreads-win32.

The above two seem to be the most well known ways for this.

Hope this helps.

Saving an Excel sheet in a current directory with VBA

I am not clear exactly what your situation requires but the following may get you started. The key here is using ThisWorkbook.Path to get a relative file path:

Sub SaveToRelativePath()
    Dim relativePath As String
    relativePath = ThisWorkbook.Path & Application.PathSeparator & ActiveWorkbook.Name
    ActiveWorkbook.SaveAs Filename:=relativePath
End Sub

How do I compile a .c file on my Mac?

Ondrasej is the "most right" here, IMO.
There are also gui-er ways to do it, without resorting to Xcode. I like TryC.

Mac OS X includes Developer Tools, a developing environment for making Macintosh applications. However, if someone wants to study programming using C, Xcode is too big and too complicated for beginners, to write a small sample program. TryC is very suitable for beginners.

enter image description here

You don't need to launch a huge Xcode application, or type unfamiliar commands in Terminal. Using TryC, you can write, compile and run a C, C++ and Ruby program just like TextEdit. It's only available to compile one source code file but it's enough for trying sample programs.

What does <![CDATA[]]> in XML mean?

The Cdata is a data which you may want to pass to an xml parser and still not interpreted as an xml.

Say for eg :- You have an xml which has encapsulates question/answer object . Such open fields can have any data which does not strictly fall under basic data type or xml defined custom data types. Like --Is this a correct tag for xml comment ? .-- You may have a requirement to pass it as it is without being interpreted by the xml parser as another child element. Here Cdata comes to your rescue . By declaring as Cdata you are telling the parser don't treat the data wrapped as an xml (though it may look like one )

jQuery's jquery-1.10.2.min.map is triggering a 404 (Not Found)

jQuery 1.11.0/2.1.0 the // sourceMappingURL comment is not included in the compressed file.

Node.js https pem error: routines:PEM_read_bio:no start line

If you are using windows, you should make sure that the certificate file csr.pem and key.pem don't have unix-style line endings. Openssl will generate the key files with unix style line endings. You can convert these files to dos format using a utility like unix2dos or a text editor like notepad++

C# with MySQL INSERT parameters

I was facing very similar problem while trying to insert data using mysql-connector-net-5.1.7-noinstall and Visual Studio(2015) in Windows Form Application. I am not a C# guru. So, it takes around 2 hours to resolve everything.

The following code works lately:

string connetionString = null;
connetionString = "server=localhost;database=device_db;uid=root;pwd=123;";

using (MySqlConnection cn = new MySqlConnection(connetionString))
{
    try
    {
        string query = "INSERT INTO test_table(user_id, user_name) VALUES (?user_id,?user_name);";
        cn.Open();
        using (MySqlCommand cmd = new MySqlCommand(query, cn))
        {
            cmd.Parameters.Add("?user_id", MySqlDbType.Int32).Value = 123;
            cmd.Parameters.Add("?user_name", MySqlDbType.VarChar).Value = "Test username";
            cmd.ExecuteNonQuery();
        }
    }
    catch (MySqlException ex)
    {
        MessageBox.Show("Error in adding mysql row. Error: "+ex.Message);
    }
}

Why .NET String is immutable?

Strings are not really immutable. They are just publicly immutable. It means you cannot modify them from their public interface. But in the inside the are actually mutable.

If you don't believe me look at the String.Concat definition using reflector. The last lines are...

int length = str0.Length;
string dest = FastAllocateString(length + str1.Length);
FillStringChecked(dest, 0, str0);
FillStringChecked(dest, length, str1);
return dest;

As you can see the FastAllocateString returns an empty but allocated string and then it is modified by FillStringChecked

Actually the FastAllocateString is an extern method and the FillStringChecked is unsafe so it uses pointers to copy the bytes.

Maybe there are better examples but this is the one I have found so far.

How can I keep a container running on Kubernetes?

In order to keep a POD running it should to be performing certain task, otherwise Kubernetes will find it unnecessary, therefore it stops. There are many ways to keep a POD running.

I have faced similar problems when I needed a POD just to run continuously without doing any useful operation. The following are the two ways those worked for me:

  1. Firing up a sleep command while running the container.
  2. Running an infinite loop inside the container.

Although the first option is easier than the second one and may suffice the requirement, it is not the best option. As, there is a limit as far as the number of seconds you are going to assign in the sleep command. But a container with infinite loop running inside it never exits.

However, I will describe both the ways(Considering you are running busybox container):

1. Sleep Command

apiVersion: v1
kind: Pod
metadata:
  name: busybox
  labels:
    app: busybox
spec:
  containers:
  - name: busybox
    image: busybox
    ports:
    - containerPort: 80
    command: ["/bin/sh", "-ec", "sleep 1000"]
  nodeSelector:
    beta.kubernetes.io/os: linux

2. Infinite Loop

apiVersion: v1
kind: Pod
metadata:
  name: busybox
  labels:
    app: busybox
spec:
  containers:
  - name: busybox
    image: busybox
    ports:
    - containerPort: 80
    command: ["/bin/sh", "-ec", "while :; do echo '.'; sleep 5 ; done"]
  nodeSelector:
    beta.kubernetes.io/os: linux

Run the following command to run the pod:

kubectl apply -f <pod-yaml-file-name>.yaml

Hope it helps!

SyntaxError: Non-ASCII character '\xa3' in file when function returns '£'

Adding the following two lines in the script solved the issue for me.

# !/usr/bin/python
# coding=utf-8

Hope it helps !

Running CMD command in PowerShell

You must use the Invoke-Command cmdlet to launch this external program. Normally it works without an effort.

If you need more than one command you should use the Invoke-Expression cmdlet with the -scriptblock option.

Copy a file in a sane, safe and efficient way

I'm not quite sure what a "good way" of copying a file is, but assuming "good" means "fast", I could broaden the subject a little.

Current operating systems have long been optimized to deal with run of the mill file copy. No clever bit of code will beat that. It is possible that some variant of your copy techniques will prove faster in some test scenario, but they most likely would fare worse in other cases.

Typically, the sendfile function probably returns before the write has been committed, thus giving the impression of being faster than the rest. I haven't read the code, but it is most certainly because it allocates its own dedicated buffer, trading memory for time. And the reason why it won't work for files bigger than 2Gb.

As long as you're dealing with a small number of files, everything occurs inside various buffers (the C++ runtime's first if you use iostream, the OS internal ones, apparently a file-sized extra buffer in the case of sendfile). Actual storage media is only accessed once enough data has been moved around to be worth the trouble of spinning a hard disk.

I suppose you could slightly improve performances in specific cases. Off the top of my head:

  • If you're copying a huge file on the same disk, using a buffer bigger than the OS's might improve things a bit (but we're probably talking about gigabytes here).
  • If you want to copy the same file on two different physical destinations you will probably be faster opening the three files at once than calling two copy_file sequentially (though you'll hardly notice the difference as long as the file fits in the OS cache)
  • If you're dealing with lots of tiny files on an HDD you might want to read them in batches to minimize seeking time (though the OS already caches directory entries to avoid seeking like crazy and tiny files will likely reduce disk bandwidth dramatically anyway).

But all that is outside the scope of a general purpose file copy function.

So in my arguably seasoned programmer's opinion, a C++ file copy should just use the C++17 file_copy dedicated function, unless more is known about the context where the file copy occurs and some clever strategies can be devised to outsmart the OS.

How to align footer (div) to the bottom of the page?

This will make the div fixed at the bottom of the page but in case the page is long it will only be visible when you scroll down.

<style type="text/css">
  #footer {
    position : absolute;
    bottom : 0;
    height : 40px;
    margin-top : 40px;
  }
</style>
<div id="footer">I am footer</div>

The height and margin-top should be the same so that the footer doesnt show over the content.

How to add not null constraint to existing column in MySQL

Would like to add:

After update, such as

ALTER TABLE table_name modify column_name tinyint(4) NOT NULL;

If you get

ERROR 1138 (22004): Invalid use of NULL value

Make sure you update the table first to have values in the related column (so it's not null)

127 Return code from $?

If the IBM mainframe JCL has some extra characters or numbers at the end of the name of unix script being called then it can throw such error.

Where are the recorded macros stored in Notepad++?

On Vista with virtualization on, the file is here. Note that the AppData folder is hidden. Either show hidden folders, or go straight to it by typing %AppData% in the address bar of Windows Explorer.

C:\Users\[user]\AppData\Roaming\Notepad++\shortcuts.xml

INSERT INTO ... SELECT FROM ... ON DUPLICATE KEY UPDATE

MySQL will assume the part before the equals references the columns named in the INSERT INTO clause, and the second part references the SELECT columns.

INSERT INTO lee(exp_id, created_by, location, animal, starttime, endtime, entct, 
                inact, inadur, inadist, 
                smlct, smldur, smldist, 
                larct, lardur, lardist, 
                emptyct, emptydur)
SELECT id, uid, t.location, t.animal, t.starttime, t.endtime, t.entct, 
       t.inact, t.inadur, t.inadist, 
       t.smlct, t.smldur, t.smldist, 
       t.larct, t.lardur, t.lardist, 
       t.emptyct, t.emptydur 
FROM tmp t WHERE uid=x
ON DUPLICATE KEY UPDATE entct=t.entct, inact=t.inact, ...

How to catch a unique constraint error in a PL/SQL block?

I'm sure you have your reasons, but just in case... you should also consider using a "merge" query instead:

begin
    merge into some_table st
    using (select 'some' name, 'values' value from dual) v
    on (st.name=v.name)
    when matched then update set st.value=v.value
    when not matched then insert (name, value) values (v.name, v.value);
end;

(modified the above to be in the begin/end block; obviously you can run it independantly of the procedure too).

Conversion failed when converting the varchar value 'simple, ' to data type int

In order to avoid such error you could use CASE + ISNUMERIC to handle scenarios when you cannot convert to int.
Change

CONVERT(INT, CONVERT(VARCHAR(12), a.value))

To

CONVERT(INT,
        CASE
        WHEN IsNumeric(CONVERT(VARCHAR(12), a.value)) = 1 THEN CONVERT(VARCHAR(12),a.value)
        ELSE 0 END) 

Basically this is saying if you cannot convert me to int assign value of 0 (in my example)

Alternatively you can look at this article about creating a custom function that will check if a.value is number: http://www.tek-tips.com/faqs.cfm?fid=6423

What are the benefits of using C# vs F# or F# vs C#?

  • F# Has Better Performance than C# in Math
  • You could use F# projects in the same solution with C# (and call from one to another)
  • F# is really good for complex algorithmic programming, financial and scientific applications
  • F# logically is really good for the parallel execution (it is easier to make F# code execute on parallel cores, than C#)

How to read a string one letter at a time in python

For the actual processing I'd keep a string of finished product, and loop through each letter in the string they have entered. I'd call a function to convert a letter to morse code, then add it to the string of existing morse code.

finishedProduct = []
userInput = input("Enter text")
for letter in userInput:
    finishedProduct.append( letterToMorseCode(letter) )
theString = ''.join(finishedProduct)
print(theString)

You could either check for space in the loop, or in the function that is called.

How to fire a change event on a HTMLSelectElement if the new value is the same as the old?

It's not firing because the value hasn't "changed". It's the same value. Unfortunately, you can't achieve the desired behaviour using the change event.

You can handle the blur event and do whatever processing you need when the user leaves the select box. That way you can run the code you need even if the user selects the same value.

Detect backspace and del on "input" event?

Use .onkeydown and cancel the removing with return false;. Like this:

var input = document.getElementById('myInput');

input.onkeydown = function() {
    var key = event.keyCode || event.charCode;

    if( key == 8 || key == 46 )
        return false;
};

Or with jQuery, because you added a jQuery tag to your question:

jQuery(function($) {
  var input = $('#myInput');
  input.on('keydown', function() {
    var key = event.keyCode || event.charCode;

    if( key == 8 || key == 46 )
        return false;
  });
});

?

Is it good practice to use the xor operator for boolean checks?

!= is OK to compare two variables. It doesn't work, though, with multiple comparisons.

Why is the time complexity of both DFS and BFS O( V + E )

Time complexity is O(E+V) instead of O(2E+V) because if the time complexity is n^2+2n+7 then it is written as O(n^2).

Hence, O(2E+V) is written as O(E+V)

because difference between n^2 and n matters but not between n and 2n.

Get local href value from anchor (a) tag

In my case I had a href with a # and target.href was returning me the complete url. Target.hash did the work for me.

$(".test a").on('click', function(e) {
    console.log(e.target.href); // logs https://www.test.com/#test
    console.log(e.target.hash); // logs #test
  });

How many significant digits do floats and doubles have in java?

A normal math answer.

Understanding that a floating point number is implemented as some bits representing the exponent and the rest, most for the digits (in the binary system), one has the following situation:

With a high exponent, say 10²³ if the least significant bit is changed, a large difference between two adjacent distinghuishable numbers appear. Furthermore the base 2 decimal point makes that many base 10 numbers can only be approximated; 1/5, 1/10 being endless numbers.

So in general: floating point numbers should not be used if you care about significant digits. For monetary amounts with calculation, e,a, best use BigDecimal.

For physics floating point doubles are adequate, floats almost never. Furthermore the floating point part of processors, the FPU, can even use a bit more precission internally.

JAXB Exception: Class not known to this context

Fixed it by setting the class name to the property "classesToBeBound" of the JAXB marshaller:

<bean id="jaxbMarshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
        <property name="classesToBeBound">
          <list>
                <value>myclass</value>
          </list>
        </property>
</bean>

A beginner's guide to SQL database design

I started with this book: Relational Database Design Clearly Explained (The Morgan Kaufmann Series in Data Management Systems) (Paperback) by Jan L. Harrington and found it very clear and helpful

and as you get up to speed this one was good too Database Systems: A Practical Approach to Design, Implementation and Management (International Computer Science Series) (Paperback)

I think SQL and database design are different (but complementary) skills.

How to detect scroll direction

var mousewheelevt = (/Firefox/i.test(navigator.userAgent)) ? "DOMMouseScroll" : "mousewheel" //FF doesn't recognize mousewheel as of FF3.x
$(document).bind(mousewheelevt, 
function(e)
    {
        var evt = window.event || e //equalize event object     
        evt = evt.originalEvent ? evt.originalEvent : evt; //convert to originalEvent if possible               
        var delta = evt.detail ? evt.detail*(-40) : evt.wheelDelta //check for detail first, because it is used by Opera and FF
        if(delta > 0) 
            {
            scrollup();
            }
        else
            {
            scrolldown();
            }   
    }
);

Passing arguments to angularjs filters

Actually you can pass a parameter ( http://docs.angularjs.org/api/ng.filter:filter ) and don't need a custom function just for this. If you rewrite your HTML as below it'll work:

<div ng:app>
 <div ng-controller="HelloCntl">
 <ul>
    <li ng-repeat="friend in friends | filter:{name:'!Adam'}">
        <span>{{friend.name}}</span>
        <span>{{friend.phone}}</span>
    </li>
 </ul>
 </div>
</div>

http://jsfiddle.net/ZfGx4/59/

Reset textbox value in javascript

Try using this:

$('#searchField').val('');

How to allow users to check for the latest app version from inside the app?

I know the OP was very old, at that time in-app-update was not available. But from API 21, you can use in-app-update checking. You may need to keep your eyes on some points which are nicely written up here:

Difference Between ViewResult() and ActionResult()

ActionResult is an abstract class that can have several subtypes.

ActionResult Subtypes

  • ViewResult - Renders a specifed view to the response stream

  • PartialViewResult - Renders a specifed partial view to the response stream

  • EmptyResult - An empty response is returned

  • RedirectResult - Performs an HTTP redirection to a specifed URL

  • RedirectToRouteResult - Performs an HTTP redirection to a URL that is determined by the routing engine, based on given route data

  • JsonResult - Serializes a given ViewData object to JSON format

  • JavaScriptResult - Returns a piece of JavaScript code that can be executed on the client

  • ContentResult - Writes content to the response stream without requiring a view

  • FileContentResult - Returns a file to the client

  • FileStreamResult - Returns a file to the client, which is provided by a Stream

  • FilePathResult - Returns a file to the client

Resources

Clear screen in shell

Here's how to make your very own cls or clear command that will work without explicitly calling any function!

We'll take advantage of the fact that the python console calls repr() to display objects on screen. This is especially useful if you have your own customized python shell (with the -i option for example) and you have a pre-loading script for it. This is what you need:

import os
class ScreenCleaner:
    def __repr__(self):
        os.system('cls')  # This actually clears the screen
        return ''  # Because that's what repr() likes

cls = ScreenCleaner()

Use clear instead of cls if you're on linux (in both the os command and the variable name)!

Now if you just write cls or clear in the console - it will clear it! Not even cls() or clear() - just the raw variable. This is because python will call repr(cls) to print it out, which will in turn trigger our __repr__ function.

Let's test it out:

>>> df;sag
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'df' is not defined
>>> sglknas
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'sglknas' is not defined
>>> lksnldn
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'lksnldn' is not defined
>>> cls

And the screen is clear!

To clarify - the code above needs to either be imported in the console like this

from somefile import cls

Or pre load directly with something like:

python -i my_pre_loaded_classes.py

Angular window resize event

<div (window:resize)="onResize($event)"
onResize(event) {
  event.target.innerWidth;
}

or using the HostListener decorator:

@HostListener('window:resize', ['$event'])
onResize(event) {
  event.target.innerWidth;
}

Supported global targets are window, document, and body.

Until https://github.com/angular/angular/issues/13248 is implemented in Angular it is better for performance to subscribe to DOM events imperatively and use RXJS to reduce the amount of events as shown in some of the other answers.

Accessing elements of Python dictionary by index

You can use mydict['Apple'].keys()[0] in order to get the first key in the Apple dictionary, but there's no guarantee that it will be American. The order of keys in a dictionary can change depending on the contents of the dictionary and the order the keys were added.

How to open the terminal in Atom?

First, you should install "platformio-ide-terminal": Open "Preferences ?," >> Click "+ Install" >> In "Search packages" type "platformio-ide-terminal" >> Click "Install".

And answering exactly the question. If you have previously installed, just use:

  • Shortcut: ctrl-` or Option+Command+T (??T)
  • by Menu: Go to Packages > platformio-ide-terminal [or other] > New terminal

How is malloc() implemented internally?

It's also important to realize that simply moving the program break pointer around with brk and sbrk doesn't actually allocate the memory, it just sets up the address space. On Linux, for example, the memory will be "backed" by actual physical pages when that address range is accessed, which will result in a page fault, and will eventually lead to the kernel calling into the page allocator to get a backing page.

Postgres could not connect to server

If you shut down your system without quitting psql, postgres would not have removed some files.

I didn't find the file postmaster.pid in the location usr/local/var/postgres

So I did the below:

brew services start postgresql

The above command should let you start postgres

How to change Maven local repository in eclipse

In Eclipse Photon navigate to Windows > Preferences > Maven > User Settings > User Setting

For "User settings" Browse to the settings.xml of the maven. ex. in my case maven it is located on the path C:\Program Files\Apache Software Distribution\apache-maven-3.5.4\conf\Settings.xml

Depending on the Settings.xml the Local Repository gets automatically configured to the specified location. Click here for screenshot

Unlink of file Failed. Should I try again?

In my case (Win8.1, TortoiseGit running), it was the process called "TortoiseSVN status cache" that was locking the file.

Killing it allowed me to run "git gc" without any more problems. The above process is fired up by TortoiseGit, so there is no need to manually restart it.

Remove git mapping in Visual Studio 2015

Short Version

  1. Remove the appropriate entr(y|ies) under HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\14.0\TeamFoundation\GitSourceControl\Repositories.

  2. Remove HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\14.0\TeamFoundation\GitSourceControl\General\LastUsedRepository if it's the same as the repo you are trying to remove.

Background

It seems like Visual Studio tracks all of the git repositories that it has seen. Even if you close the project that was referencing a repository, old entries may still appear in the list.

This problem is not new to Visual Studio:

VS2013 - How do I remove local git repository from team explorer window when option Remove is always disabled?

Remove Git binding from Visual Studio 2013 solution?

This all seems like a lot of work for something that should probably be a built-in feature. The above "solutions" mention making modifications to the .git file etc.; I don't like the idea of having to change things outside of Visual Studio to affect things inside Visual Studio. Although my solution needs to make a few registry edits (and is external to VS), at least these only affect VS. Here is the work-around (read: hack):

Detailed Instructions

Be sure to have Visual Studio 2015 closed before following these steps.

1. Open regedit.exe and navigate to

HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\14.0\TeamFoundation\GitSourceControl\Repositories

Regedit repositories for VS

You might see multiple "hash" values that represent the repositories that VS is tracking.

2. Find the git repository you want to remove from the list. Look at the name and path values to verify the correct repository to delete:

verify repo to delete

3. Delete the key (and corresponding subkeys).

(Optional: before deleting, you can right click and choose Export to back up this key in case you make a mistake.) Now, right click on the key (in my case this is AE76C67B6CD2C04395248BFF8EBF96C7AFA15AA9 and select Delete).

4. Check that the LastUsedRepository key points to "something else."

If the repository mapping you are trying to remove in the above steps is stored in LastUsedRepository, then you'll need to remove this key, also. First navigate to:

HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\14.0\TeamFoundation\GitSourceControl\General

location of general key

and delete the key LastUsedRepository (the key will be re-created by VS if needed). If you are worried about removing the key, you can just modify the value and set it to an empty string:

delete last used repo

When you open Visual Studio 2015 again, the git repository binding should not appear in the list anymore.

Shortest way to print current year in a website

If you want to include a time frame in the future, with the current year (e.g. 2017) as the start year so that next year it’ll appear like this: “© 2017-2018, Company.”, then use the following code. It’ll automatically update each year:

&copy; Copyright 2017<script>new Date().getFullYear()>2017&&document.write("-"+new Date().getFullYear());</script>, Company.

© Copyright 2017-2018, Company.

But if the first year has already passed, the shortest code can be written like this:

&copy; Copyright 2010-<script>document.write(new Date().getFullYear())</script>, Company.

Error inflating class android.support.v7.widget.Toolbar?

Sorry Guys. I have solved this Issue long ago. I did a lot of changes. So I can't figure out which one does the trick.

  1. I have changed the id as suggested by Jared Burrows.

  2. Removed my support library and cleaned my project and Re added it.

  3. Go to File -> Invalidate Caches/Restart.

Hope it works.

This is how my code looks now

activity.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <include
        android:id="@+id/toolbar_actionbar"
        layout="@layout/toolbar_default"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    <android.support.v4.widget.DrawerLayout
        android:id="@+id/drawer"
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/toolbar_actionbar">

        <FrameLayout
            android:id="@+id/container"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>

        <fragment
            android:id="@+id/fragment_drawer"
            android:name="com.arul.anahy.drawer.NavigationDrawerFragment"
            android:layout_width="@dimen/navigation_drawer_width"
            android:layout_height="match_parent"
            android:layout_gravity="start"
            app:layout="@layout/fragment_navigation_drawer"/>
    </android.support.v4.widget.DrawerLayout>
</RelativeLayout>

toolbar_default.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
    style="@style/ToolBarStyle"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?attr/colorPrimary"
    android:minHeight="@dimen/abc_action_bar_default_height_material"/>

ToolBarStyle

<style name="ToolBarStyle" parent="">
        <item name="popupTheme">@style/ThemeOverlay.AppCompat.Light</item>
        <item name="theme">@style/ThemeOverlay.AppCompat.Dark.ActionBar</item>
 </style>

JsonMappingException: No suitable constructor found for type [simple type, class ]: can not instantiate from JSON object

Failing custom jackson Serializers/Deserializers could also be the problem. Though it's not your case, it's worth mentioning.

I faced the same exception and that was the case.

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

It is a little complicated, but you can draw all the objects by the following code:

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
from itertools import product, combinations


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

# draw cube
r = [-1, 1]
for s, e in combinations(np.array(list(product(r, r, r))), 2):
    if np.sum(np.abs(s-e)) == r[1]-r[0]:
        ax.plot3D(*zip(s, e), color="b")

# draw sphere
u, v = np.mgrid[0:2*np.pi:20j, 0:np.pi:10j]
x = np.cos(u)*np.sin(v)
y = np.sin(u)*np.sin(v)
z = np.cos(v)
ax.plot_wireframe(x, y, z, color="r")

# draw a point
ax.scatter([0], [0], [0], color="g", s=100)

# draw a vector
from matplotlib.patches import FancyArrowPatch
from mpl_toolkits.mplot3d import proj3d


class Arrow3D(FancyArrowPatch):

    def __init__(self, xs, ys, zs, *args, **kwargs):
        FancyArrowPatch.__init__(self, (0, 0), (0, 0), *args, **kwargs)
        self._verts3d = xs, ys, zs

    def draw(self, renderer):
        xs3d, ys3d, zs3d = self._verts3d
        xs, ys, zs = proj3d.proj_transform(xs3d, ys3d, zs3d, renderer.M)
        self.set_positions((xs[0], ys[0]), (xs[1], ys[1]))
        FancyArrowPatch.draw(self, renderer)

a = Arrow3D([0, 1], [0, 1], [0, 1], mutation_scale=20,
            lw=1, arrowstyle="-|>", color="k")
ax.add_artist(a)
plt.show()

output_figure

insert vertical divider line between two nested divs, not full height

Use a div for your divider. It will always be centered vertically regardless to whether left and right divs are equal in height. You can reuse it anywhere on your site.

.divider{
    position:absolute;
    left:50%;
    top:10%;
    bottom:10%;
    border-left:1px solid white;
}

Check working example at http://jsfiddle.net/gtKBs/

jQuery : select all element with custom attribute

Use the "has attribute" selector:

$('p[MyTag]')

Or to select one where that attribute has a specific value:

$('p[MyTag="Sara"]')

There are other selectors for "attribute value starts with", "attribute value contains", etc.

How do you create optional arguments in php?

Some notes that I also found useful:

  • Keep your default values on the right side.

    function whatever($var1, $var2, $var3="constant", $var4="another")
    
  • The default value of the argument must be a constant expression. It can't be a variable or a function call.

Saving a high resolution image in R

A simpler way is

ggplot(data=df, aes(x=xvar, y=yvar)) + 
geom_point()

ggsave(path = path, width = width, height = height, device='tiff', dpi=700)

WinSCP: Permission denied. Error code: 3 Error message from server: Permission denied

You possibly do not have create permissions to the folder. So WinSCP fails to create a temporary file for the transfer.

You have two options:

yii2 hidden input value

simple you can write:

<?= $form->field($model, 'hidden1')->hiddenInput(['value'=>'abc value'])->label(false); ?>

How to get distinct values from an array of objects in JavaScript?

Answering this old question is pretty pointless, but there is a simple answer that speaks to the nature of Javascript. Objects in Javascript are inherently hash tables. We can use this to get a hash of unique keys:

var o = {}; array.map(function(v){ o[v.age] = 1; });

Then we can reduce the hash to an array of unique values:

var a2 = []; for (k in o){ a2.push(k); }

That is all you need. The array a2 contains just the unique ages.

How to parse a date?

In response to: "How to convert Tue Sep 13 2016 00:00:00 GMT-0500 (Hora de verano central (México)) to dd-MM-yy in Java?", it was marked how duplicate

Try this: With java.util.Date, java.text.SimpleDateFormat, it's a simple solution.

public static void main(String[] args) throws ParseException {

    String fecha = "Tue Sep 13 2016 00:00:00 GMT-0500 (Hora de verano central (México))";
    Date f = new Date(fecha);

    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
    sdf.setTimeZone(TimeZone.getTimeZone("-5GMT"));
    fecha = sdf.format(f);
    System.out.println(fecha);
}

How to create a new component in Angular 4 using CLI

ng generate component componentName.

It will automatically import the component in module.ts

How to use jQuery with Angular?

If you use angular-cli you can do :

  1. Install the dependency :

    npm install jquery --save

    npm install @types/jquery --save-dev

  2. Import the file :

    Add "../node_modules/jquery/dist/jquery.min.js" to the "script" section in .angular-cli.json file

  3. Declare jquery :

    Add "$" to the "types" section of tsconfig.app.json

You can find more details on official angular cli doc

How to call a View Controller programmatically?

You can call ViewController this way, If you want with NavigationController

enter image description here

1.In current Screen : Load new screen

VerifyExpViewController *addProjectViewController = [[VerifyExpViewController alloc] init];
[self.navigationController pushViewController:addProjectViewController animated:YES];

2.1 In Loaded View : add below in .h file

@interface VerifyExpViewController : UIViewController <UINavigationControllerDelegate>

2.2 In Loaded View : add below in .m file

  @implementation VerifyExpViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.navigationController.delegate = self;
    [self setNavigationBar];
}
-(void)setNavigationBar
{
    self.navigationController.navigationBar.backgroundColor = [UIColor clearColor];
    self.navigationController.navigationBar.translucent = YES;
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"B_topbar.png"] forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName: [UIColor whiteColor]};
    self.navigationItem.hidesBackButton = YES;
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"Btn_topback.png"] style:UIBarButtonItemStylePlain target:self action:@selector(onBackButtonTap:)];
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor lightGrayColor];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"Save.png"] style:UIBarButtonItemStylePlain target:self action:@selector(onSaveButtonTap:)];
    self.navigationItem.rightBarButtonItem.tintColor = [UIColor lightGrayColor];
}

-(void)onBackButtonTap:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}
-(IBAction)onSaveButtonTap:(id)sender
{
    //todo for save button
}

@end

Hope this will be useful for someone there :)

How to read a list of files from a folder using PHP?

There is this function scandir():

$dir = 'dir';
$files = scandir($dir, 0);
for($i = 2; $i < count($files); $i++)
    print $files[$i]."<br>";

More here in the php.net manual

django import error - No module named core.management

I included the name of the new App to the INSTALLED_APPS list in the settings.py "before" I issued the startapp command. Once I removed the list entry, I could create the app.

Difference between signed / unsigned char

This because a char is stored at all effects as a 8-bit number. Speaking about a negative or positive char doesn't make sense if you consider it an ASCII code (which can be just signed*) but makes sense if you use that char to store a number, which could be in range 0-255 or in -128..127 according to the 2-complement representation.

*: it can be also unsigned, it actually depends on the implementation I think, in that case you will have access to extended ASCII charset provided by the encoding used

How to import a module given the full path?

This answer is a supplement to Sebastian Rittau's answer responding to the comment: "but what if you don't have the module name?" This is a quick and dirty way of getting the likely python module name given a filename -- it just goes up the tree until it finds a directory without an __init__.py file and then turns it back into a filename. For Python 3.4+ (uses pathlib), which makes sense since Py2 people can use "imp" or other ways of doing relative imports:

import pathlib

def likely_python_module(filename):
    '''
    Given a filename or Path, return the "likely" python module name.  That is, iterate
    the parent directories until it doesn't contain an __init__.py file.

    :rtype: str
    '''
    p = pathlib.Path(filename).resolve()
    paths = []
    if p.name != '__init__.py':
        paths.append(p.stem)
    while True:
        p = p.parent
        if not p:
            break
        if not p.is_dir():
            break

        inits = [f for f in p.iterdir() if f.name == '__init__.py']
        if not inits:
            break

        paths.append(p.stem)

    return '.'.join(reversed(paths))

There are certainly possibilities for improvement, and the optional __init__.py files might necessitate other changes, but if you have __init__.py in general, this does the trick.

ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)

Your problem is here:

2013-11-14 17:57:20 5180 [ERROR] InnoDB: .\ibdata1 can't be opened in read-write mode

There's some problem with the ibdata1 file - maybe the permissions have changed on it? Perhaps some other process has it open. Does it even exist?

Fix this and possibly everything else will fall into place.

Messagebox with input field

You can do it by making form and displaying it using ShowDialogBox....

Form.ShowDialog Method - Shows the form as a modal dialog box.

Example:

public void ShowMyDialogBox()
{
   Form2 testDialog = new Form2();

   // Show testDialog as a modal dialog and determine if DialogResult = OK.
   if (testDialog.ShowDialog(this) == DialogResult.OK)
   {
      // Read the contents of testDialog's TextBox.
      this.txtResult.Text = testDialog.TextBox1.Text;
   }
   else
   {
      this.txtResult.Text = "Cancelled";
   }
   testDialog.Dispose();
}

What is "Advanced" SQL?

Check out SQL For Smarties. I thought I was pretty good with SQL too, until I read that book... Goes into tons of depth, talks about things I've not seen elsewhere (I.E. difference between 3'rd and 4'th normal form, Boyce Codd Normal Form, etc)...

Check if a varchar is a number (TSQL)

you can check like this

declare @vchar varchar(50)
set @vchar ='34343';
select case when @vchar not like '%[^0-9]%' then 'Number' else 'Not a Number' end

Excel VBA Password via Hex Editor

If you deal with .xlsm file instead of .xls you can use the old method. I was trying to modify vbaProject.bin in .xlsm several times using DBP->DBx method by it didn't work, also changing value of DBP didn't. So I was very suprised that following worked :
1. Save .xlsm as .xls.
2. Use DBP->DBx method on .xls.
3. Unfortunately some erros may occur when using modified .xls file, I had to save .xls as .xlsx and add modules, then save as .xlsm.

Is it possible to have multiple statements in a python lambda expression?

Putting the expressions in a list may simulate multiple expressions:

E.g.:

lambda x: [f1(x), f2(x), f3(x), x+1]

This will not work with statements.

Pandas get topmost n records within each group

Since 0.14.1, you can now do nlargest and nsmallest on a groupby object:

In [23]: df.groupby('id')['value'].nlargest(2)
Out[23]: 
id   
1   2    3
    1    2
2   6    4
    5    3
3   7    1
4   8    1
dtype: int64

There's a slight weirdness that you get the original index in there as well, but this might be really useful depending on what your original index was.

If you're not interested in it, you can do .reset_index(level=1, drop=True) to get rid of it altogether.

(Note: From 0.17.1 you'll be able to do this on a DataFrameGroupBy too but for now it only works with Series and SeriesGroupBy.)

Center fixed div with dynamic width (CSS)

Here's another method if you can safely use CSS3's transform property:

.fixed-horizontal-center
{
    position: fixed;
    top: 100px; /* or whatever top you need */
    left: 50%;
    width: auto;
    -webkit-transform: translateX(-50%);
    -moz-transform: translateX(-50%);
    -ms-transform: translateX(-50%);
    -o-transform: translateX(-50%);
    transform: translateX(-50%);
}

...or if you want both horizontal AND vertical centering:

.fixed-center
{
    position: fixed;
    top: 50%;
    left: 50%;
    width: auto;
    height: auto;
    -webkit-transform: translate(-50%,-50%);
    -moz-transform: translate(-50%,-50%);
    -ms-transform: translate(-50%,-50%);
    -o-transform: translate(-50%,-50%);
    transform: translate(-50%,-50%);
}

How to make HTML Text unselectable

I altered the jQuery plugin posted above so it would work on live elements.

(function ($) {
$.fn.disableSelection = function () {
    return this.each(function () {
        if (typeof this.onselectstart != 'undefined') {
            this.onselectstart = function() { return false; };
        } else if (typeof this.style.MozUserSelect != 'undefined') {
            this.style.MozUserSelect = 'none';
        } else {
            this.onmousedown = function() { return false; };
        }
    });
};
})(jQuery);

Then you could so something like:

$(document).ready(function() {
    $('label').disableSelection();

    // Or to make everything unselectable
    $('*').disableSelection();
});

Does C have a "foreach" loop construct?

C does not have an implementation of for-each. When parsing an array as a point the receiver does not know how long the array is, thus there is no way to tell when you reach the end of the array. Remember, in C int* is a point to a memory address containing an int. There is no header object containing information about how many integers that are placed in sequence. Thus, the programmer needs to keep track of this.

However, for lists, it is easy to implement something that resembles a for-each loop.

for(Node* node = head; node; node = node.next) {
   /* do your magic here */
}

To achieve something similar for arrays you can do one of two things.

  1. use the first element to store the length of the array.
  2. wrap the array in a struct which holds the length and a pointer to the array.

The following is an example of such struct:

typedef struct job_t {
   int count;
   int* arr;
} arr_t;

Why am I getting the error "connection refused" in Python? (Sockets)

I was being able to ping my connection but was STILL getting the 'connection refused' error. Turns out I was pinging myself! That's what the problem was.

Http post and get request in angular 6

Update : In angular 7, they are the same as 6

In angular 6

the complete answer found in live example

  /** POST: add a new hero to the database */
  addHero (hero: Hero): Observable<Hero> {
 return this.http.post<Hero>(this.heroesUrl, hero, httpOptions)
  .pipe(
    catchError(this.handleError('addHero', hero))
  );
}
  /** GET heroes from the server */
 getHeroes (): Observable<Hero[]> {
return this.http.get<Hero[]>(this.heroesUrl)
  .pipe(
    catchError(this.handleError('getHeroes', []))
  );
}

it's because of pipeable/lettable operators which now angular is able to use tree-shakable and remove unused imports and optimize the app

some rxjs functions are changed

do -> tap
catch -> catchError
switch -> switchAll
finally -> finalize

more in MIGRATION

and Import paths

For JavaScript developers, the general rule is as follows:

rxjs: Creation methods, types, schedulers and utilities

import { Observable, Subject, asapScheduler, pipe, of, from, interval, merge, fromEvent } from 'rxjs';

rxjs/operators: All pipeable operators:

import { map, filter, scan } from 'rxjs/operators';

rxjs/webSocket: The web socket subject implementation

import { webSocket } from 'rxjs/webSocket';

rxjs/ajax: The Rx ajax implementation

import { ajax } from 'rxjs/ajax';

rxjs/testing: The testing utilities

import { TestScheduler } from 'rxjs/testing';

and for backward compatability you can use rxjs-compat

How to copy from CSV file to PostgreSQL table with headers in CSV file?

This worked. The first row had column names in it.

COPY wheat FROM 'wheat_crop_data.csv' DELIMITER ';' CSV HEADER

Get size of a View in React Native

for me setting the Dimensions to use % is what worked for me width:'100%'

Check if key exists and iterate the JSON array using Python

jsonData = """{"from": {"id": "8", "name": "Mary Pinter"}, "message": "How ARE you?", "comments": {"count": 0}, "updated_time": "2012-05-01", "created_time": "2012-05-01", "to": {"data": [{"id": "1543", "name": "Honey Pinter"}, {"name": "Joe Schmoe"}]}, "type": "status", "id": "id_7"}"""

def getTargetIds(jsonData):
    data = json.loads(jsonData)
    for dest in data['to']['data']:
        print("to_id:", dest.get('id', 'null'))

Try it:

>>> getTargetIds(jsonData)
to_id: 1543
to_id: null

Or, if you just want to skip over values missing ids instead of printing 'null':

def getTargetIds(jsonData):
    data = json.loads(jsonData)
    for dest in data['to']['data']:
        if 'id' in to_id:
            print("to_id:", dest['id'])

So:

>>> getTargetIds(jsonData)
to_id: 1543

Of course in real life, you probably don't want to print each id, but to store them and do something with them, but that's another issue.

[INSTALL_FAILED_NO_MATCHING_ABIS: Failed to extract native libraries, res=-113]

I faced same problem in emulator, but I solved it like this:

Create new emulator with x86_64 system image(ABI)

select device

select x86_64

That's it.

This error indicates the system(Device) not capable for run the application.

I hope this is helpful to someone.

convert:not authorized `aaaa` @ error/constitute.c/ReadImage/453

After a recent update on my Ubuntu 16.04 system I have also started getting this error when trying to run convert on .ps files to convert them into pdfs.

This fix worked for me:

In a terminal run:

sudo gedit /etc/ImageMagick-6/policy.xml

This should open the policy.xml file in the gedit text editor. If it doesn't, your image magick might be installed in a different place. Then change

rights="none" 

to

rights="read | write" 

for PDF, EPS and PS lines near the bottom of the file. Save and exit, and image magick should then work again.

call a function in success of datatable ajax call

The best way I have found is to use the initComplete method as it fires after the data has been retrieved and renders the table. NOTE this only fires once though.

$("#tableOfData").DataTable({
        "pageLength": 50,
        "ajax":{
            url: someurl,
            dataType : "json",
            type: "post",
            "data": {data to be sent}
        },
        "initComplete":function( settings, json){
            console.log(json);
            // call your function here
        }
    });

Return a value if no rows are found in Microsoft tSQL

No record matched means no record returned. There's no place for the "value" of 0 to go if no records are found. You could create a crazy UNION query to do what you want but much, much, much better simply to check the number of records in the result set.

E: gnupg, gnupg2 and gnupg1 do not seem to be installed, but one of them is required for this operation

Just install the updated versions of all of them.

apt-get install -y gnupg2 gnupg gnupg1

How can I get the current screen orientation?

int rotation =  getWindowManager().getDefaultDisplay().getRotation();

this will gives all orientation like normal and reverse

and handle it like

int angle = 0;
switch (rotation) {
    case Surface.ROTATION_90:
        angle = -90;
        break;
    case Surface.ROTATION_180:
        angle = 180;
        break;
    case Surface.ROTATION_270:
        angle = 90;
        break;
    default:
        angle = 0;
        break;
}

Check if url contains string with JQuery

window.location is an object, not a string so you need to use window.location.href to get the actual string url

if (window.location.href.indexOf("?added-to-cart=555") >= 0) {
    alert("found it");
}

Oracle insert from select into table with more columns

just select '0' as the value for the desired column

Why use multiple columns as primary keys (composite primary key)

Your understanding is correct.

You would do this in many cases. One example is in a relationship like OrderHeader and OrderDetail. The PK in OrderHeader might be OrderNumber. The PK in OrderDetail might be OrderNumber AND LineNumber. If it was either of those two, it would not be unique, but the combination of the two is guaranteed unique.

The alternative is to use a generated (non-intelligent) primary key, for example in this case OrderDetailId. But then you would not always see the relationship as easily. Some folks prefer one way; some prefer the other way.