Programs & Examples On #Locals

A tag for questions about accessing resources local to a given runtime environment or network.

React hooks useState Array

use state is not always needed you can just simply do this

let paymentList = [
    {"id":249,"txnid":"2","fname":"Rigoberto"}, {"id":249,"txnid":"33","fname":"manuel"},]

then use your data in a map loop like this in my case it was just a table and im sure many of you are looking for the same. here is how you use it.

<div className="card-body">
            <div className="table-responsive">
                <table className="table table-striped">
                    <thead>
                        <tr>
                            <th>Transaction ID</th>
                            <th>Name</th>
                        </tr>
                    </thead>
                    <tbody>
                        {
                            paymentList.map((payment, key) => (
                                <tr key={key}>
                                    <td>{payment.txnid}</td>
                                    <td>{payment.fname}</td>
                                </tr>
                            ))
                        }
                    </tbody>
                </table>
            </div>
        </div>

How to convert string to boolean in typescript Angular 4

Define extension: String+Extension.ts

interface String {
  toBoolean(): boolean
}

String.prototype.toBoolean = function (): boolean {
  switch (this) {
    case 'true':
    case '1':
    case 'on':
    case 'yes':
      return true
    default:
      return false
  }
}

And import in any file where you want to use it '@/path/to/String+Extension'

Angular 6: saving data to local storage

First you should understand how localStorage works. you are doing wrong way to set/get values in local storage. Please read this for more information : How to Use Local Storage with JavaScript

jwt check if token expired

verify itself returns an error if expired. Safer as @Gabriel said.

const jwt = require('jsonwebtoken')

router.use((req, res, next) => {
  const token = yourJwtService.getToken(req) // Get your token from the request
  jwt.verify(token, req.app.get('your-secret'), function(err, decoded) {
    if (err) throw new Error(err) // Manage different errors here (Expired, untrusted...)
    req.auth = decoded // If no error, token info is returned in 'decoded'
    next()
  });
})

And same written in async/await syntax:

const jwt = require('jsonwebtoken')
const jwtVerifyAsync = util.promisify(jwt.verify);

router.use(async (req, res, next) => {
  const token = yourJwtService.getToken(req) // Get your token from the request
  try {
    req.auth = await jwtVerifyAsync(token, req.app.get('your-secret')) // If no error, token info is returned
  } catch (err) {
    throw new Error(err) // Manage different errors here (Expired, untrusted...)
  }
  next()
});

How to reload current page in ReactJS?

You can use window.location.reload(); in your componentDidMount() lifecycle method. If you are using react-router, it has a refresh method to do that.

Edit: If you want to do that after a data update, you might be looking to a re-render not a reload and you can do that by using this.setState(). Here is a basic example of it to fire a re-render after data is fetched.

import React from 'react'

const ROOT_URL = 'https://jsonplaceholder.typicode.com';
const url = `${ROOT_URL}/users`;

class MyComponent extends React.Component {
    state = {
        users: null
    }
    componentDidMount() {
        fetch(url)
            .then(response => response.json())
            .then(users => this.setState({users: users}));
    }
    render() {
        const {users} = this.state;
        if (users) {
            return (
                <ul>
                    {users.map(user => <li>{user.name}</li>)}
                </ul>
            )
        } else {
            return (<h1>Loading ...</h1>)
        }
    }
}

export default MyComponent;

Vuex - passing multiple parameters to mutation

In simple terms you need to build your payload into a key array

payload = {'key1': 'value1', 'key2': 'value2'}

Then send the payload directly to the action

this.$store.dispatch('yourAction', payload)

No change in your action

yourAction: ({commit}, payload) => {
  commit('YOUR_MUTATION',  payload )
},

In your mutation call the values with the key

'YOUR_MUTATION' (state,  payload ){
  state.state1 = payload.key1
  state.state2 =  payload.key2
},

Is it safe to store a JWT in localStorage with ReactJS?

It is not safe if you use CDN's:

Malicious JavaScript can be embedded on the page, and Web Storage is compromised. These types of XSS attacks can get everyone’s Web Storage that visits your site, without their knowledge. This is probably why a bunch of organizations advise not to store anything of value or trust any information in web storage. This includes session identifiers and tokens.

via stormpath

Any script you require from the outside could potentially be compromised and could grab any JWTS from your client's storage and send personal data back to the attacker's server.

How to check undefined in Typescript

NOT STRICTLY RELATED TO TYPESCRIPT

Just to add to all the above answers, we can also use the shorthand syntax

var result = uemail || '';

This will give you the email if uemail variable has some value and it will simply return an empty string if uemail variable is undefined.

This gives a nice syntax for handling undefined variables and also provide a way to use a default value in case the variable is undefined.

How to push to History in React Router v4?

If you are using Redux, then I would recommend using npm package react-router-redux. It allows you to dispatch Redux store navigation actions.

You have to create store as described in their Readme file.

The easiest use case:

import { push } from 'react-router-redux'

this.props.dispatch(push('/second page'));

Second use case with Container/Component:

Container:

import { connect } from 'react-redux';
import { push } from 'react-router-redux';

import Form from '../components/Form';

const mapDispatchToProps = dispatch => ({
  changeUrl: url => dispatch(push(url)),
});

export default connect(null, mapDispatchToProps)(Form);

Component:

import React, { Component } from 'react';
import PropTypes from 'prop-types';

export default class Form extends Component {
  handleClick = () => {
    this.props.changeUrl('/secondPage');
  };

  render() {
    return (
      <div>
        <button onClick={this.handleClick}/>
      </div>Readme file
    );
  }
}

What is the best way to manage a user's session in React?

I would avoid using component state since this could be difficult to manage and prone to issues that can be difficult to troubleshoot.

You should use either cookies or localStorage for persisting a user's session data. You can also use a closure as a wrapper around your cookie or localStorage data.

Here is a simple example of a UserProfile closure that will hold the user's name.

var UserProfile = (function() {
  var full_name = "";

  var getName = function() {
    return full_name;    // Or pull this from cookie/localStorage
  };

  var setName = function(name) {
    full_name = name;     
    // Also set this in cookie/localStorage
  };

  return {
    getName: getName,
    setName: setName
  }

})();

export default UserProfile;

When a user logs in, you can populate this object with user name, email address etc.

import UserProfile from './UserProfile';

UserProfile.setName("Some Guy");

Then you can get this data from any component in your app when needed.

import UserProfile from './UserProfile';

UserProfile.getName();

Using a closure will keep data outside of the global namespace, and make it is easily accessible from anywhere in your app.

CORS error :Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response

You have to add options also in allowed headers. browser sends a preflight request before original request is sent. See below

 res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,PATCH,OPTIONS');

From source https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/OPTIONS

In CORS, a preflight request with the OPTIONS method is sent, so that the server can respond whether it is acceptable to send the request with these parameters. The Access-Control-Request-Method header notifies the server as part of a preflight request that when the actual request is sent, it will be sent with a POST request method. The Access-Control-Request-Headers header notifies the server that when the actual request is sent, it will be sent with a X-PINGOTHER and Content-Type custom headers. The server now has an opportunity to determine whether it wishes to accept a request under these circumstances.

EDITED

You can avoid this manual configuration by using npmjs.com/package/cors npm package.I have used this method also, it is clear and easy.

Remove all items from a FormArray in Angular

I am very late but I found some other way where you don't need to have loops. you can reset array by setting array control to empty.

Below code will reset your array.

this.form.setControl('name', this.fb.array([]))

Setting and getting localStorage with jQuery

Use setItem and getItem if you want to write simple strings to localStorage. Also you should be using text() if it's the text you're after as you say, else you will get the full HTML as a string.

Sample using .text()

// get the text
var text = $('#test').text();

// set the item in localStorage
localStorage.setItem('test', text);

// alert the value to check if we got it
alert(localStorage.getItem('test'));

JSFiddle: https://jsfiddle.net/f3zLa3zc/


Storing the HTML itself

// get html
var html = $('#test')[0].outerHTML;

// set localstorage
localStorage.setItem('htmltest', html);

// test if it works
alert(localStorage.getItem('htmltest'));

JSFiddle:
https://jsfiddle.net/psfL82q3/1/


Update on user comment

A user want to update the localStorage when the div's content changes. Since it's unclear how the div contents changes (ajax, other method?) contenteditable and blur() is used to change the contents of the div and overwrite the old localStorage entry.

// get the text
var text = $('#test').text();

// set the item in localStorage
localStorage.setItem('test', text);

// bind text to 'blur' event for div
$('#test').on('blur', function() {

    // check the new text
    var newText = $(this).text();

    // overwrite the old text
    localStorage.setItem('test', newText);

    // test if it works
    alert(localStorage.getItem('test'));

});

If we were using ajax we would instead trigger the function it via the function responsible for updating the contents.

JSFiddle:
https://jsfiddle.net/g1b8m1fc/

Angular 2 Checkbox Two Way Data Binding

When using <abc [(bar)]="foo"/> syntax on angular.

This translates to: <abc [bar]="foo" (barChange)="foo = $event" />

Which means your component should have:

@Input() bar;
@Output() barChange = new EventEmitter();

How to store token in Local or Session Storage in Angular 2?

As a general rule, the token should not be stored on the localStorage neither the sessionStorage. Both places are accessible from JS and the JS should not care about the authentication token.

IMHO The token should be stored on a cookie with the HttpOnly and Secure flag as suggested here: https://stormpath.com/blog/where-to-store-your-jwts-cookies-vs-html5-web-storage

Angular2 RC5: Can't bind to 'Property X' since it isn't a known property of 'Child Component'

There are multiple possible causes for this error:

1) When you put the property 'x' inside brackets you are trying to bind to it. Therefore first thing to check is if the property 'x' is defined in your component with an Input() decorator

Your html file:

<body [x]="...">

Your class file:

export class YourComponentClass {

  @Input()
  x: string;
  ...
}

(make sure you also have the parentheses)

2) Make sure you registered your component/directive/pipe classes in NgModule:

@NgModule({
  ...
  declarations: [
    ...,
    YourComponentClass
  ],
  ...
})

See https://angular.io/guide/ngmodule#declare-directives for more details about declare directives.

3) Also happens if you have a typo in your angular directive. For example:

<div *ngif="...">
     ^^^^^

Instead of:

<div *ngIf="...">

This happens because under the hood angular converts the asterisk syntax to:

<div [ngIf]="...">

ImportError: No module named google.protobuf

Had the same issue and I resolved it by using :

conda install protobuf

The response content cannot be parsed because the Internet Explorer engine is not available, or

In your invoke web request just use the parameter -UseBasicParsing

e.g. in your script (line 2) you should use:

$rss = Invoke-WebRequest -Uri $url -UseBasicParsing

According to the documentation, this parameter is necessary on systems where IE isn't installed or configured:

Uses the response object for HTML content without Document Object Model (DOM) parsing. This parameter is required when Internet Explorer is not installed on the computers, such as on a Server Core installation of a Windows Server operating system.

How to deal with http status codes other than 200 in Angular 2

Yes you can handle with the catch operator like this and show alert as you want but firstly you have to import Rxjs for the same like this way

import {Observable} from 'rxjs/Rx';

return this.http.request(new Request(this.requestoptions))
            .map((res: Response) => {
                if (res) {
                    if (res.status === 201) {
                        return [{ status: res.status, json: res }]
                    }
                    else if (res.status === 200) {
                        return [{ status: res.status, json: res }]
                    }
                }
            }).catch((error: any) => {
                if (error.status === 500) {
                    return Observable.throw(new Error(error.status));
                }
                else if (error.status === 400) {
                    return Observable.throw(new Error(error.status));
                }
                else if (error.status === 409) {
                    return Observable.throw(new Error(error.status));
                }
                else if (error.status === 406) {
                    return Observable.throw(new Error(error.status));
                }
            });
    }

also you can handel error (with err block) that is throw by catch block while .map function,

like this -

...
.subscribe(res=>{....}
           err => {//handel here});

Update

as required for any status without checking particluar one you can try this: -

return this.http.request(new Request(this.requestoptions))
            .map((res: Response) => {
                if (res) {
                    if (res.status === 201) {
                        return [{ status: res.status, json: res }]
                    }
                    else if (res.status === 200) {
                        return [{ status: res.status, json: res }]
                    }
                }
            }).catch((error: any) => {
                if (error.status < 400 ||  error.status ===500) {
                    return Observable.throw(new Error(error.status));
                }
            })
            .subscribe(res => {...},
                       err => {console.log(err)} );

Failed to load ApplicationContext (with annotation)

Your test requires a ServletContext: add @WebIntegrationTest

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = AppConfig.class, loader = AnnotationConfigContextLoader.class)
@WebIntegrationTest
public class UserServiceImplIT

...or look here for other options: https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-testing.html

UPDATE In Spring Boot 1.4.x and above @WebIntegrationTest is no longer preferred. @SpringBootTest or @WebMvcTest

Angular: Can't find Promise, Map, Set and Iterator

Since Angular 2 went to RC 0, /angular2/typings/browser.d.ts is no longer part of the Angular 2 distribution. The file can be installed separately.

From here: https://github.com/angular/angular/issues/8513 there are a few options. The one that worked for me was:

typings install es6-shim --ambient --save

// In your app.ts
/// <reference path="typings/browser.d.ts" />

configuring project ':app' failed to find Build Tools revision

For me, dataBinding { enabled true } was enabled in gradle, removing this helped me

How to inject window into a service?

Actually its very simple to access window object here is my basic component and i tested it its working

import { Component, OnInit,Inject } from '@angular/core';
import {DOCUMENT} from '@angular/platform-browser';

@Component({
  selector: 'app-verticalbanners',
  templateUrl: './verticalbanners.component.html',
  styleUrls: ['./verticalbanners.component.css']
})
export class VerticalbannersComponent implements OnInit {

  constructor(){ }

  ngOnInit() {
    console.log(window.innerHeight );
  }

}

Angular2 handling http response

in angular2 2.1.1 I was not able to catch the exception using the (data),(error) pattern, so I implemented it using .catch(...).

It's nice because it can be used with all other Observable chained methods like .retry .map etc.

import {Observable} from 'rxjs/Rx';


  Http
  .put(...)
  .catch(err =>  { 
     notify('UI error handling');
     return Observable.throw(err); // observable needs to be returned or exception raised
  })
  .subscribe(data => ...) // handle success

from documentation:

Returns

(Observable): An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully.

Angular and Typescript: Can't find names - Error: cannot find name

you can add the code at the beginning of .ts files.

/// <reference path="../typings/index.d.ts" />

python save image from url

import urllib.request
import os

img_url = "https://betanews.com/wp-content/uploads/2017/09/firefox-logo.jpg"
img_name = os.path.basename(img_url)
urllib.request.urlretrieve(img_url,img_name)

UnsatisfiedDependencyException: Error creating bean with name 'entityManagerFactory'

Well, you're getting a java.lang.NoClassDefFoundError. In your pom.xml, hibernate-core version is 3.3.2.GA and declared after hibernate-entitymanager, so it prevails. You can remove that dependency, since will be inherited version 3.6.7.Final from hibernate-entitymanager.

You're using spring-boot as parent, so no need to declare version of some dependencies, since they are managed by spring-boot.

Also, hibernate-commons-annotations is inherited from hibernate-entitymanager and hibernate-annotations is an old version of hibernate-commons-annotations, you can remove both.

Finally, your pom.xml can look like this:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.elsys.internetprogramming.trafficspy.server</groupId>
    <artifactId>TrafficSpyService</artifactId>
    <version>0.1.0</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.2.3.RELEASE</version>
    </parent>

    <dependencies>
        <!-- Spring -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cloud-connectors</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <dependency>
            <groupId>org.eclipse.persistence</groupId>
            <artifactId>javax.persistence</artifactId>
            <version>2.0.0</version>
        </dependency>

        <!-- Hibernate -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-pool</groupId>
            <artifactId>commons-pool</artifactId>
        </dependency>

        <!-- MySQL -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
    </dependencies>

    <properties>
        <java.version>1.7</java.version>
    </properties>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

    <repositories>
        <repository>
            <id>spring-releases</id>
            <url>https://repo.spring.io/libs-release</url>
        </repository>

        <repository>
            <id>codehaus</id>
            <url>http://repository.codehaus.org/org/codehaus</url>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <id>spring-releases</id>
            <url>https://repo.spring.io/libs-release</url>
        </pluginRepository>
    </pluginRepositories>

</project>

Let me know if you have a problem.

How to maintain state after a page refresh in React.js?

You can "persist" the state using local storage as Omar Suggest, but it should be done once the state has been set. For that you need to pass a callback to the setState function and you need to serialize and deserialize the objects put into local storage.

constructor(props) {
  super(props);
  this.state = {
    allProjects: JSON.parse(localStorage.getItem('allProjects')) || []
  }
}


addProject = (newProject) => {
  ...

  this.setState({
    allProjects: this.state.allProjects.concat(newProject)
  },() => {
    localStorage.setItem('allProjects', JSON.stringify(this.state.allProjects))
  });
}

Communication between tabs or windows

This is a development storage part of Tomas M answer for Chrome. We must add listener

window.addEventListener("storage", (e)=> { console.log(e) } );

Load/save item in storage not runt this event - we MUST trigger it manually by

window.dispatchEvent( new Event('storage') ); // THIS IS IMPORTANT ON CHROME

and now, all open tab-s will receive event

org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set

If the preceding error in log was this: "ERROR - HikariPool-1 - jdbcUrl is required with driverClassName" then the solution is to rewrite "url" to "jdbc-url" according to this: Database application.yml for Spring boot from applications.properties

Spring Hibernate - Could not obtain transaction-synchronized Session for current thread

Thanks for comment of mannedear. I use springmvc and in my case I have to use as

@Repository
@Transactional
@EnableTransactionManagement
public class UserDao {
...
}

and I also add spring-context to pom.xml and it works

No found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations:

Add repository annotation before your DAO Implementation Class. example:

@Repository
public class EmpDAOImpl extends BaseNamedParameterJdbcDaoSupportUAM 
implements EmpDAO{ 
}

AngularJS : ng-click not working

It just happend to me. I solved the problem by tracing backward from the point ng-click is coded. Found out that an extra

</div> 

was placed in the html to prematurely close the div block that contains the ng-click.

Removed the extra

</div> 

then everything is working fine.

java.lang.ClassNotFoundException: org.springframework.core.io.Resource

Right-Click on your project -> Properties -> Deployment Assembly.

On the Left-hand panel Click 'Add' and add the 'Project and External Dependencies'.

'Project and External Dependencies' will have all the spring related jars deployed along with your application

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'MyController':

Exception clearly indicates the problem.

CompteDAOHib: No default constructor found

For spring to instantiate your bean, you need to provide a empty constructor for your class CompteDAOHib.

How to handle ETIMEDOUT error?

We could look at error object for a property code that mentions the possible system error and in cases of ETIMEDOUT where a network call fails, act accordingly.

if (err.code === 'ETIMEDOUT') {
    console.log('My dish error: ', util.inspect(err, { showHidden: true, depth: 2 }));
}

How to use Morgan logger?

I faced the same problem ago and instead, I used winston. As fellas above said, morgan is for automated logging of request/response. Winston can be configured pretty much same way as log4Net/log4J, has severity levels, different streams to which you can log etc.

For example:

npm install winston

Then, if you call the below code somewhere on you application initialization:

var winston = require('winston');

// setup default logger (no category)
winston.loggers.add('default', {
    console: {
        colorize: 'true',
        handleExceptions: true,
        json: false,
        level: 'silly',
        label: 'default',
    },
    file: {
        filename: 'some/path/where/the/log/file/reside/default.log',
        level: 'silly',
        json: false,
        handleExceptions: true,
    },
});

//
// setup logger for category `usersessions`
// you can define as many looggers as you like
//
winston.loggers.add('usersessions', {
    console: {
        level: 'silly',
        colorize: 'true',
        label: 'usersessions',
        json: false,
        handleExceptions: true,
    },
    file: {
        filename: 'some/path/where/the/log/file/reside/usersessions.log',
        level: 'silly',
        json: false,
        handleExceptions: true,
    },
});

note: before calling above code, winston.loggers is empty, i.e you dont have any loggers configured yet. Pretty much like Log4Net/J XmlConfigure methods - you need to first call them, to init your logging.

Then, later wherever in you application server side code you may do:

var winston = require('winston');
// log instances as defined in first snippet
var defaultLog = winston.loggers.get('default'); 
var userSessionsLog = winston.loggers.get('usersessions');

defaultLog.info('this goes to file default.log');
userSessionsLog.debug('this goes to file usersessions.log')

Hope that helps.

for further documentation reference: https://www.npmjs.com/package/winston

Installation Issue with matplotlib Python

Problem Cause

In mac os image rendering back end of matplotlib (what-is-a-backend to render using the API of Cocoa by default). There are Qt4Agg and GTKAgg and as a back-end is not the default. Set the back end of macosx that is differ compare with other windows or linux os.

Solution

  • I assume you have installed the pip matplotlib, there is a directory in your root called ~/.matplotlib.
  • Create a file ~/.matplotlib/matplotlibrc there and add the following code: backend: TkAgg

From this link you can try different diagrams.

QuotaExceededError: Dom exception 22: An attempt was made to add something to storage that exceeded the quota

This can occur when Safari is in private mode browsing. While in private browsing, local storage is not available at all.

One solution is to warn the user that the app needs non-private mode to work.

UPDATE: This has been fixed in Safari 11, so the behaviour is now aligned with other browsers.

500.21 Bad module "ManagedPipelineHandler" in its module list

I discovered that the order of adding roles and features is important. On a fresh system I activate the role "application server" and there check explicitly .net, web server support and finally process activation service Then automatically a dialogue comes up that the role "Web server" needs to be added also.

How to display text in pygame?

This is slighly more OS independent way:

# do this init somewhere
import pygame
pygame.init()
screen = pygame.display.set_mode((640, 480))
font = pygame.font.Font(pygame.font.get_default_font(), 36)

# now print the text
text_surface = font.render('Hello world', antialias=True, color=(0, 0, 0))
screen.blit(text_surface, dest=(0,0))

"The system cannot find the file specified"

I got same error after publish my project to my physical server. My web application works perfectly on my computer when I compile on VS2013. When I checked connection string on sql server manager, everything works perfect on server too. I also checked firewall (I switched it off). But still didn't work. I remotely try to connect database by SQL Manager with exactly same user/pass and instance name etc with protocol pipe/tcp and I saw that everything working normally. But when I try to open website I'm getting this error. Is there anyone know 4th option for fix this problem?.

NOTE: My App: ASP.NET 4.5 (by VS2013), Server: Windows 2008 R2 64bit, SQL: MS-SQL WEB 2012 SP1 Also other web applications works great at web browsers with their database on same server.


After one day suffering I found the solution of my issue:

First I checked all the logs and other details but i could find nothing. Suddenly I recognize that; when I try to use connection string which is connecting directly to published DB and run application on my computer by VS2013, I saw that it's connecting another database file. I checked local directories and I found it. ASP.NET Identity not using my connection string as I wrote in web.config file. And because of this VS2013 is creating or connecting a new database with the name "DefaultConnection.mdf" in App_Data folder. Then I found the solution, it was in IdentityModel.cs.

I changed code as this:

public class ApplicationUser : IdentityUser
{
}

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    //public ApplicationDbContext() : base("DefaultConnection") ---> this was original
    public ApplicationDbContext() : base("<myConnectionStringNameInWebConfigFile>") //--> changed
    {
    }
}

So, after all, I re-builded and published my project and everything works fine now :)

@Autowired - No qualifying bean of type found for dependency

The thing is that both the application context and the web application context are registered in the WebApplicationContext during server startup. When you run the test you must explicitly tell which contexts to load.

Try this:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:/beans.xml", "/mvc-dispatcher-servlet.xml"})

could not extract ResultSet in hibernate

Another potential cause, for other people coming across the same error message is that this error will occur if you are accessing a table in a different schema from the one you have authenticated with.

In this case you would need to add the schema name to your entity entry:

@Table(name= "catalog", schema = "targetSchemaName")

What is the difference between localStorage, sessionStorage, session and cookies?

These are properties of 'window' object in JavaScript, just like document is one of a property of window object which holds DOM objects.

Session Storage property maintains a separate storage area for each given origin that's available for the duration of the page session i.e as long as the browser is open, including page reloads and restores.

Local Storage does the same thing, but persists even when the browser is closed and reopened.

You can set and retrieve stored data as follows:

sessionStorage.setItem('key', 'value');

var data = sessionStorage.getItem('key');

Similarly for localStorage.

How can I add some small utility functions to my AngularJS application?

Coming on this old thread i wanted to stress that

1°) utility functions may (should?) be added to the rootscope via module.run. There is no need to instanciate a specific root level controller for this purpose.

angular.module('myApp').run(function($rootScope){
  $rootScope.isNotString = function(str) {
   return (typeof str !== "string");
  }
});

2°) If you organize your code into separate modules you should use angular services or factory and then inject them into the function passed to the run block, as follow:

angular.module('myApp').factory('myHelperMethods', function(){
  return {
    isNotString: function(str) {
      return (typeof str !== 'string');
    }
  }
});

angular.module('myApp').run(function($rootScope, myHelperMethods){ 
  $rootScope.helpers = myHelperMethods;
});

3°) My understanding is that in views, for most of the cases you need these helper functions to apply some kind of formatting to strings you display. What you need in this last case is to use angular filters

And if you have structured some low level helper methods into angular services or factory, just inject them within your filter constructor :

angular.module('myApp').filter('myFilter', function(myHelperMethods){ 
  return function(aString){
    if (myHelperMethods.isNotString(aString)){
      return 
    }
    else{
      // something else 
    }
  }
);

And in your view :

{{ aString | myFilter }}   

How to save an image to localStorage and display it on the next page?

To whoever also needs this problem solved:

Firstly, I grab my image with getElementByID, and save the image as a Base64. Then I save the Base64 string as my localStorage value.

bannerImage = document.getElementById('bannerImg');
imgData = getBase64Image(bannerImage);
localStorage.setItem("imgData", imgData);

Here is the function that converts the image to a Base64 string:

function getBase64Image(img) {
    var canvas = document.createElement("canvas");
    canvas.width = img.width;
    canvas.height = img.height;

    var ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0);

    var dataURL = canvas.toDataURL("image/png");

    return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
}

Then, on my next page I created an image with a blank src like so:

<img src="" id="tableBanner" />

And straight when the page loads, I use these next three lines to get the Base64 string from localStorage, and apply it to the image with the blank src I created:

var dataImage = localStorage.getItem('imgData');
bannerImg = document.getElementById('tableBanner');
bannerImg.src = "data:image/png;base64," + dataImage;

Tested it in quite a few different browsers and versions, and it seems to work quite well.

Bootstrap 3: Keep selected tab on page refresh

Well, this is already in 2018 but I think it is better late than never (like a title in a TV program), lol. Down here is the jQuery code that I create during my thesis.

<script type="text/javascript">
$(document).ready(function(){
    $('a[data-toggle="tab"]').on('show.affectedDiv.tab', function(e) {
        localStorage.setItem('activeTab', $(e.target).attr('href'));
    });
    var activeTab = localStorage.getItem('activeTab');
    if(activeTab){
        $('#myTab a[href="' + activeTab + '"]').tab('show');
    }
});
</script>

and here is the code for bootstrap tabs:

<div class="affectedDiv">
    <ul class="nav nav-tabs" id="myTab">
        <li class="active"><a data-toggle="tab" href="#sectionA">Section A</a></li>
        <li><a data-toggle="tab" href="#sectionB">Section B</a></li>
        <li><a data-toggle="tab" href="#sectionC">Section C</a></li>
    </ul>
    <div class="tab-content">
        <div id="sectionA" class="tab-pane fade in active">
            <h3>Section A</h3>
            <p>Aliquip placeat salvia cillum iphone. Seitan aliquip quis cardigan american apparel, butcher voluptate nisi qui. Raw denim you probably haven't heard of them jean shorts Austin. Nesciunt tofu stumptown aliqua, retro synth master cleanse. Mustache cliche tempor, williamsburg carles vegan helvetica. Reprehenderit butcher retro keffiyeh dreamcatcher synth.</p>
        </div>
        <div id="sectionB" class="tab-pane fade">
            <h3>Section B</h3>
            <p>Vestibulum nec erat eu nulla rhoncus fringilla ut non neque. Vivamus nibh urna, ornare id gravida ut, mollis a magna. Aliquam porttitor condimentum nisi, eu viverra ipsum porta ut. Nam hendrerit bibendum turpis, sed molestie mi fermentum id. Aenean volutpat velit sem. Sed consequat ante in rutrum convallis. Nunc facilisis leo at faucibus adipiscing.</p>
        </div>
        <div id="sectionC" class="tab-pane fade">
            <h3>Section C</h3>
            <p>Vestibulum nec erat eu nulla rhoncus fringilla ut non neque. Vivamus nibh urna, ornare id gravida ut, mollis a magna. Aliquam porttitor condimentum nisi, eu viverra ipsum porta ut. Nam hendrerit bibendum turpis, sed molestie mi fermentum id. Aenean volutpat velit sem. Sed consequat ante in rutrum convallis. Nunc facilisis leo at faucibus adipiscing.</p>
        </div>
    </div>
</div>


Dont forget to call the bootstrap and other fundamental things 

here are quick codes for you:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>


Now let's come to the explanation:

The jQuery code in the above example simply gets the element's href attribute value when a new tab has been shown using the jQuery .attr() method and save it locally in the user's browser through HTML5 localStorage object. Later, when the user refresh the page it retrieves this data and activate the related tab via .tab('show') method.

Looking up for some examples? here is one for you guys.. https://jsfiddle.net/Wineson123/brseabdr/

I wish my answer could help you all.. Cheerio! :)

How do I configure php to enable pdo and include mysqli on CentOS?

mysqli is provided by php-mysql-5.3.3-40.el6_6.x86_64

You may need to try the following

yum install php-mysql-5.3.3-40.el6_6.x86_64

Spring not autowiring in unit tests with JUnit

I'm using JUnit 5 and for me the problem was that I had imported Test from the wrong package:

import org.junit.Test;

Replacing it with the following worked for me:

import org.junit.jupiter.api.Test;

Uncaught ReferenceError: function is not defined with onclick

I think you put the function in the $(document).ready....... The functions are always provided out the $(document).ready.......

How to create global variables accessible in all views using Express / Node.JS?

After having a chance to study the Express 3 API Reference a bit more I discovered what I was looking for. Specifically the entries for app.locals and then a bit farther down res.locals held the answers I needed.

I discovered for myself that the function app.locals takes an object and stores all of its properties as global variables scoped to the application. These globals are passed as local variables to each view. The function res.locals, however, is scoped to the request and thus, response local variables are accessible only to the view(s) rendered during that particular request/response.

So for my case in my app.js what I did was add:

app.locals({
    site: {
        title: 'ExpressBootstrapEJS',
        description: 'A boilerplate for a simple web application with a Node.JS and Express backend, with an EJS template with using Twitter Bootstrap.'
    },
    author: {
        name: 'Cory Gross',
        contact: '[email protected]'
    }
});

Then all of these variables are accessible in my views as site.title, site.description, author.name, author.contact.

I could also define local variables for each response to a request with res.locals, or simply pass variables like the page's title in as the optionsparameter in the render call.

EDIT: This method will not allow you to use these locals in your middleware. I actually did run into this as Pickels suggests in the comment below. In this case you will need to create a middleware function as such in his alternative (and appreciated) answer. Your middleware function will need to add them to res.locals for each response and then call next. This middleware function will need to be placed above any other middleware which needs to use these locals.

EDIT: Another difference between declaring locals via app.locals and res.locals is that with app.locals the variables are set a single time and persist throughout the life of the application. When you set locals with res.locals in your middleware, these are set everytime you get a request. You should basically prefer setting globals via app.locals unless the value depends on the request req variable passed into the middleware. If the value doesn't change then it will be more efficient for it to be set just once in app.locals.

The entity name must immediately follow the '&' in the entity reference

All answers posted so far are giving the right solutions, however no one answer was able to properly explain the underlying cause of the concrete problem.

Facelets is a XML based view technology which uses XHTML+XML to generate HTML output. XML has five special characters which has special treatment by the XML parser:

  • < the start of a tag.
  • > the end of a tag.
  • " the start and end of an attribute value.
  • ' the alternative start and end of an attribute value.
  • & the start of an entity (which ends with ;).

In case of & which is not followed by # (e.g. &#160;, &#xA0;, etc), the XML parser is implicitly looking for one of the five predefined entity names lt, gt, amp, quot and apos, or any manually defined entity name. However, in your particular case, you was using & as a JavaScript operator, not as an XML entity. This totally explains the XML parsing error you got:

The entity name must immediately follow the '&' in the entity reference

In essence, you're writing JavaScript code in the wrong place, a XML document instead of a JS file, so you should be escaping all XML special characters accordingly. The & must be escaped as &amp;.

So, in your particular case, the

if (Modernizr.canvas && Modernizr.localstorage && 

must become

if (Modernizr.canvas &amp;&amp; Modernizr.localstorage &amp;&amp;

to make it XML-valid.

However, this makes the JavaScript code harder to read and maintain. As stated in Mozilla Developer Network's excellent document Writing JavaScript for XHTML, you should be placing the JavaScript code in a character data (CDATA) block. Thus, in JSF terms, that would be:

<h:outputScript>
    <![CDATA[
        // ...
    ]]>
</h:outputScript>

The XML parser will interpret the block's contents as "plain vanilla" character data and not as XML and hence interpret the XML special characters "as-is".

But, much better is to just put the JS code in its own JS file which you include by <script src>, or in JSF terms, the <h:outputScript>.

<h:outputScript name="onload.js" target="body" />

(note the target="body"; this way JSF will automatically render the <script> at the very end of <body>, regardless of where <h:outputScript> itself is located, hereby achieving the same effect as with window.onload and $(document).ready(); so you don't need to use those anymore in that script)

This way you don't need to worry about XML-special characters in your JS code. As an additional bonus, this gives you the opportunity to let the browser cache the JS file so that total response size is smaller.

See also:

Rails 4 - passing variable to partial

If you are using JavaScript to render then use escape_JavaScript("<%=render partial: partial_name, locals=>{@newval=>@oldval}%>");

Push JSON Objects to array in localStorage

There are a few steps you need to take to properly store this information in your localStorage. Before we get down to the code however, please note that localStorage (at the current time) cannot hold any data type except for strings. You will need to serialize the array for storage and then parse it back out to make modifications to it.

Step 1:

The First code snippet below should only be run if you are not already storing a serialized array in your localStorage session variable.
To ensure your localStorage is setup properly and storing an array, run the following code snippet first:

var a = [];
a.push(JSON.parse(localStorage.getItem('session')));
localStorage.setItem('session', JSON.stringify(a));

The above code should only be run once and only if you are not already storing an array in your localStorage session variable. If you are already doing this skip to step 2.

Step 2:

Modify your function like so:

function SaveDataToLocalStorage(data)
{
    var a = [];
    // Parse the serialized data back into an aray of objects
    a = JSON.parse(localStorage.getItem('session')) || [];
    // Push the new data (whether it be an object or anything else) onto the array
    a.push(data);
    // Alert the array value
    alert(a);  // Should be something like [Object array]
    // Re-serialize the array back into a string and store it in localStorage
    localStorage.setItem('session', JSON.stringify(a));
}

This should take care of the rest for you. When you parse it out, it will become an array of objects.

Hope this helps.

Python: Passing variables between functions

You're just missing one critical step. You have to explicitly pass the return value in to the second function.

def main():
    l = defineAList()
    useTheList(l)

Alternatively:

def main():
    useTheList(defineAList())

Or (though you shouldn't do this! It might seem nice at first, but globals just cause you grief in the long run.):

l = []

def defineAList():
    global l
    l.extend(['1','2','3'])

def main():
    global l
    defineAList()
    useTheList(l)

The function returns a value, but it doesn't create the symbol in any sort of global namespace as your code assumes. You have to actually capture the return value in the calling scope and then use it for subsequent operations.

HTML5 LocalStorage: Checking if a key exists

This method worked for me:

if ("username" in localStorage) {
    alert('yes');
} else {
    alert('no');
}

how to clear localstorage,sessionStorage and cookies in javascript? and then retrieve?

The standard Web Storage, does not say anything about the restoring any of these. So there won't be any standard way to do it. You have to go through the way the browsers implement these, or find a way to backup these before you delete them.

Angular.js: How does $eval work and why is it different from vanilla eval?

I think one of the original questions here was not answered. I believe that vanilla eval() is not used because then angular apps would not work as Chrome apps, which explicitly prevent eval() from being used for security reasons.

Clear input fields on form submit

Use the reset function, which is available on the form element.

var form = document.getElementById("myForm");
form.reset();

Android update activity UI from service

I would recommend checking out Otto, an EventBus tailored specifically to Android. Your Activity/UI can listen to events posted on the Bus from the Service, and decouple itself from the backend.

html5 localStorage error with Safari: "QUOTA_EXCEEDED_ERR: DOM Exception 22: An attempt was made to add something to storage that exceeded the quota."

As mentioned in other answers, you'll always get the QuotaExceededError in Safari Private Browser Mode on both iOS and OS X when localStorage.setItem (or sessionStorage.setItem) is called.

One solution is to do a try/catch or Modernizr check in each instance of using setItem.

However if you want a shim that simply globally stops this error being thrown, to prevent the rest of your JavaScript from breaking, you can use this:

https://gist.github.com/philfreo/68ea3cd980d72383c951

// Safari, in Private Browsing Mode, looks like it supports localStorage but all calls to setItem
// throw QuotaExceededError. We're going to detect this and just silently drop any calls to setItem
// to avoid the entire page breaking, without having to do a check at each usage of Storage.
if (typeof localStorage === 'object') {
    try {
        localStorage.setItem('localStorage', 1);
        localStorage.removeItem('localStorage');
    } catch (e) {
        Storage.prototype._setItem = Storage.prototype.setItem;
        Storage.prototype.setItem = function() {};
        alert('Your web browser does not support storing settings locally. In Safari, the most common cause of this is using "Private Browsing Mode". Some settings may not save or some features may not work properly for you.');
    }
}

TypeError: 'NoneType' object has no attribute '__getitem__'

BrenBarn is correct. The error means you tried to do something like None[5]. In the backtrace, it says self.imageDef=self.values[2], which means that your self.values is None.

You should go through all the functions that update self.values and make sure you account for all the corner cases.

SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified

I had the same error and I started the SQL Server Express service and it worked. Hope this helps.

What's the simplest way of detecting keyboard input in a script from the terminal?

This needs run as root: (Warning, this is a system-wide keylogger)

#!/usr/bin/python3

import signal
import keyboard
import time
import os


if not os.geteuid() == 0:
  print("This script needs to be run as root.")
  exit()

def exitNice(signum, frame):
  global running 
  running = False

def keyEvent(e):
  global running
  if e.event_type == "up":
    print("Key up: " + str(e.name))
  if e.event_type == "down":
    print("Key down: " + str(e.name))
  if e.name == "q":
    exitNice("", "")
    print("Quitting")

running = True
signal.signal(signal.SIGINT, exitNice)
keyboard.hook(keyEvent)

print("Press 'q' to quit")
fps = 1/24
while running:
  time.sleep(fps)

Uncaught syntaxerror: unexpected identifier?

There are errors here :

var formTag = document.getElementsByTagName("form"), // form tag is an array
selectListItem = $('select'),
makeSelect = document.createElement('select'),
makeSelect.setAttribute("id", "groups");

The code must change to:

var formTag = document.getElementsByTagName("form");
var selectListItem = $('select');
var makeSelect = document.createElement('select');
makeSelect.setAttribute("id", "groups");

By the way, there is another error at line 129 :

var createLi.appendChild(createSubList);

Replace it with:

createLi.appendChild(createSubList);

How to remove and clear all localStorage data

localStorage.clear();

should work.

Jquery change <p> text programmatically

It seems you have the click event wrapped around a custom event name "pageinit", are you sure you're triggered the event before you click the button?

something like this:

$("#gender").trigger("pageinit");

an attempt was made to access a socket in a way forbbiden by its access permissions. why?

I'm developing an UWP application which connects to a MQTT broker in the LAN. I go a similar error.

MQTTnet.Exceptions.MqttCommunicationException: 'An attempt was made to access a socket in a way forbidden by its access permissions [::ffff:xxx.xxx.xxx.xxx]:1883'

ExtendedSocketException: An attempt was made to access a socket in a way forbidden by its access permissions [::ffff:xxx.xxx.xxx.xxx]:1883

Turned out that I forgot to give the app the correct capabilites ... enter image description here

How can I exit from a javascript function?

if ( condition ) {
    return;
}

The return exits the function returning undefined.

The exit statement doesn't exist in javascript.

The break statement allows you to exit a loop, not a function. For example:

var i = 0;
while ( i < 10 ) {
    i++;
    if ( i === 5 ) {
        break;
    }
}

This also works with the for and the switch loops.

configure: error: C compiler cannot create executables

I have 10.8 installed and Xcode 4.4 with Command Line tools, and yet I was still getting this error. Rather than reinstall Xcode, I noticed there were two relevant lines in my config.log:

configure:5130: checking for C compiler version
configure:5139: /Applications/Xcode.app/Contents/Developer/Toolchains/OSX10.8.xctoolchain/usr/bin/cc --version >&5

That path did not exist for me. Instead I had:

/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain

The C compiler ("cc") is located inside of that xctoolchain directory. I created a symlink for OSX10.8.xctoolchain to point to XcodeDefault.xctoolchain and that fixed it. Now the memcached installation script can find the compiler version and continue on its way.

cd /Applications/Xcode.app/Contents/Developer/Toolchains
sudo ln -s XcodeDefault.xctoolchain OSX10.8.xctoolchain

As suggested in the comments, if you are having this problem on Yosemite (10.10) or Mavericks (10.9), you can update the symlink command above to point to that specific version (OSX10.9.xctoolchain or OSX10.10.xctoolchain).

HTML5 Pre-resize images before uploading

Resizing images in a canvas element is generally bad idea since it uses the cheapest box interpolation. The resulting image noticeable degrades in quality. I'd recommend using http://nodeca.github.io/pica/demo/ which can perform Lanczos transformation instead. The demo page above shows difference between canvas and Lanczos approaches.

It also uses web workers for resizing images in parallel. There is also WEBGL implementation.

There are some online image resizers that use pica for doing the job, like https://myimageresizer.com

Usage of unicode() and encode() functions in Python

Make sure you've set your locale settings right before running the script from the shell, e.g.

$ locale -a | grep "^en_.\+UTF-8"
en_GB.UTF-8
en_US.UTF-8
$ export LC_ALL=en_GB.UTF-8
$ export LANG=en_GB.UTF-8

Docs: man locale, man setlocale.

How to delete a localStorage item when the browser window/tab is closed?

After looking at this question 6 years after it was asked, I found that there still is no sufficient answer to this question; which should achieve all of the following:

  • Clear Local Storage after closing the browser (or all tabs of the domain)
  • Preserve Local Storage across tabs, if at least one tab remains active
  • Preserve Local Storage when reloading a single tab

Execute this piece of javascript at the start of each page load in order to achieve the above:

((nm,tm) => {
    const
            l = localStorage,
            s = sessionStorage,
            tabid = s.getItem(tm) || (newid => s.setItem(tm, newid) || newid)((Math.random() * 1e8).toFixed()),
            update = set => {
                let cur = JSON.parse(l.getItem(nm) || '{}');
                if (set && typeof cur[tabid] == 'undefined' && !Object.values(cur).reduce((a, b) => a + b, 0)) {
                    l.clear();
                    cur = {};
                }
                cur[tabid] = set;
                l.setItem(nm, JSON.stringify(cur));
            };
    update(1);
    window.onbeforeunload = () => update(0);
})('tabs','tabid');

Edit: The basic idea here is the following:

  1. When starting from scratch, the session storage is assigned a random id in a key called tabid
  2. The local storage is then set with a key called tabs containing a object those key tabid is set to 1.
  3. When the tab is unloaded, the local storage's tabs is updated to an object containing tabid set to 0.
  4. If the tab is reloaded, it's first unloaded, and resumed. Since the session storage's key tabid exists, and so does the local storage tabs key with a sub-key of tabid the local storage is not cleared.
  5. When the browser is unloaded, all session storage will be cleared. When resuming the session storage tabid won't exists anymore and a new tabid will be generated. Since the local storage does not have a sub-key for this tabid, nor any other tabid (all session were closed), it's cleared.
  6. Upon a new created tab, a new tabid is generated in session storage, but since at least one tabs[tabid] exists, the local storage is not cleared

Cannot create PoolableConnectionFactory (Io exception: The Network Adapter could not establish the connection)

I was also facing the error "Error preloading the connection pool" while using Oracle 10g Express Edition with my Spring and CAS based application during login.

My CAS based application only has classes12.jar in its classpath, Placing ojdbc14.jar in the classpath has resolved my problem.

No matching bean of type ... found for dependency

In my case it was the wrong dependecy for CrudRepository. My IDE added also follwing:

    <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-commons</artifactId>
        <version>1.11.2.RELEASE</version>
    </dependency>

But I just needed:

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
        <version>RELEASE</version>
    </dependency>

I removed the first one and everything was fine.

JavaScript DOM remove element

In most browsers, there's a slightly more succinct way of removing an element from the DOM than calling .removeChild(element) on its parent, which is to just call element.remove(). In due course, this will probably become the standard and idiomatic way of removing an element from the DOM.

The .remove() method was added to the DOM Living Standard in 2011 (commit), and has since been implemented by Chrome, Firefox, Safari, Opera, and Edge. It was not supported in any version of Internet Explorer.

If you want to support older browsers, you'll need to shim it. This turns out to be a little irritating, both because nobody seems to have made a all-purpose DOM shim that contains these methods, and because we're not just adding the method to a single prototype; it's a method of ChildNode, which is just an interface defined by the spec and isn't accessible to JavaScript, so we can't add anything to its prototype. So we need to find all the prototypes that inherit from ChildNode and are actually defined in the browser, and add .remove to them.

Here's the shim I came up with, which I've confirmed works in IE 8.

(function () {
    var typesToPatch = ['DocumentType', 'Element', 'CharacterData'],
        remove = function () {
            // The check here seems pointless, since we're not adding this
            // method to the prototypes of any any elements that CAN be the
            // root of the DOM. However, it's required by spec (see point 1 of
            // https://dom.spec.whatwg.org/#dom-childnode-remove) and would
            // theoretically make a difference if somebody .apply()ed this
            // method to the DOM's root node, so let's roll with it.
            if (this.parentNode != null) {
                this.parentNode.removeChild(this);
            }
        };

    for (var i=0; i<typesToPatch.length; i++) {
        var type = typesToPatch[i];
        if (window[type] && !window[type].prototype.remove) {
            window[type].prototype.remove = remove;
        }
    }
})();

This won't work in IE 7 or lower, since extending DOM prototypes isn't possible before IE 8. I figure, though, that on the verge of 2015 most people needn't care about such things.

Once you've included them shim, you'll be able to remove a DOM element element from the DOM by simply calling

element.remove();

Get HTML5 localStorage keys

function listAllItems(){  
    for (i=0; i<localStorage.length; i++)  
    {  
        key = localStorage.key(i);  
        alert(localStorage.getItem(key));
    }  
}

What is limiting the # of simultaneous connections my ASP.NET application can make to a web service?

Most of the answers provided here address the number of incoming requests to your backend webservice, not the number of outgoing requests you can make from your ASP.net application to your backend service.

It's not your backend webservice that is throttling your request rate here, it is the number of open connections your calling application is willing to establish to the same endpoint (same URL).

You can remove this limitation by adding the following configuration section to your machine.config file:

<configuration>
  <system.net>
    <connectionManagement>
      <add address="*" maxconnection="65535"/>
    </connectionManagement>
  </system.net>
</configuration>

You could of course pick a more reasonable number if you'd like such as 50 or 100 concurrent connections. But the above will open it right up to max. You can also specify a specific address for the open limit rule above rather than the '*' which indicates all addresses.

MSDN Documentation for System.Net.connectionManagement

Another Great Resource for understanding ConnectManagement in .NET

Hope this solves your problem!

EDIT: Oops, I do see you have the connection management mentioned in your code above. I will leave my above info as it is relevant for future enquirers with the same problem. However, please note there are currently 4 different machine.config files on most up to date servers!

There is .NET Framework v2 running under both 32-bit and 64-bit as well as .NET Framework v4 also running under both 32-bit and 64-bit. Depending on your chosen settings for your application pool you could be using any one of these 4 different machine.config files! Please check all 4 machine.config files typically located here:

  • C:\Windows\Microsoft.NET\Framework\v2.0.50727\CONFIG
  • C:\Windows\Microsoft.NET\Framework64\v2.0.50727\CONFIG
  • C:\Windows\Microsoft.NET\Framework\v4.0.30319\Config
  • C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Config

Clearing localStorage in javascript?

To clear sessionStorage

sessionStorage.clear();

Converting between strings and ArrayBuffers

Well, here's a somewhat convoluted way of doing the same thing:

var string = "Blah blah blah", output;
var bb = new (window.BlobBuilder||window.WebKitBlobBuilder||window.MozBlobBuilder)();
bb.append(string);
var f = new FileReader();
f.onload = function(e) {
  // do whatever
  output = e.target.result;
}
f.readAsArrayBuffer(bb.getBlob());

Edit: BlobBuilder has long been deprecated in favor of the Blob constructor, which did not exist when I first wrote this post. Here's an updated version. (And yes, this has always been a very silly way to do the conversion, but it was just for fun!)

var string = "Blah blah blah", output;
var f = new FileReader();
f.onload = function(e) {
  // do whatever
  output = e.target.result;
};
f.readAsArrayBuffer(new Blob([string]));

Save Javascript objects in sessionStorage

Could you not 'stringify' your object...then use sessionStorage.setItem() to store that string representation of your object...then when you need it sessionStorage.getItem() and then use $.parseJSON() to get it back out?

Working example http://jsfiddle.net/pKXMa/

How do I format a string using a dictionary in python-3.x?

As Python 3.0 and 3.1 are EOL'ed and no one uses them, you can and should use str.format_map(mapping) (Python 3.2+):

Similar to str.format(**mapping), except that mapping is used directly and not copied to a dict. This is useful if for example mapping is a dict subclass.

What this means is that you can use for example a defaultdict that would set (and return) a default value for keys that are missing:

>>> from collections import defaultdict
>>> vals = defaultdict(lambda: '<unset>', {'bar': 'baz'})
>>> 'foo is {foo} and bar is {bar}'.format_map(vals)
'foo is <unset> and bar is baz'

Even if the mapping provided is a dict, not a subclass, this would probably still be slightly faster.

The difference is not big though, given

>>> d = dict(foo='x', bar='y', baz='z')

then

>>> 'foo is {foo}, bar is {bar} and baz is {baz}'.format_map(d)

is about 10 ns (2 %) faster than

>>> 'foo is {foo}, bar is {bar} and baz is {baz}'.format(**d)

on my Python 3.4.3. The difference would probably be larger as more keys are in the dictionary, and


Note that the format language is much more flexible than that though; they can contain indexed expressions, attribute accesses and so on, so you can format a whole object, or 2 of them:

>>> p1 = {'latitude':41.123,'longitude':71.091}
>>> p2 = {'latitude':56.456,'longitude':23.456}
>>> '{0[latitude]} {0[longitude]} - {1[latitude]} {1[longitude]}'.format(p1, p2)
'41.123 71.091 - 56.456 23.456'

Starting from 3.6 you can use the interpolated strings too:

>>> f'lat:{p1["latitude"]} lng:{p1["longitude"]}'
'lat:41.123 lng:71.091'

You just need to remember to use the other quote characters within the nested quotes. Another upside of this approach is that it is much faster than calling a formatting method.

Maven: repository element was not specified in the POM inside distributionManagement?

I got the same message ("repository element was not specified in the POM inside distributionManagement element"). I checked /target/checkout/pom.xml and as per another answer and it really lacked <distributionManagement>.

It turned out that the problem was that <distributionManagement> was missing in pom.xml in my master branch (using git).

After cleaning up (mvn release:rollback, mvn clean, mvn release:clean, git tag -d v1.0.0) I run mvn release again and it worked.

Android webview & localStorage

The following was missing:

settings.setDomStorageEnabled(true);

In Node.js, how do I "include" functions from my other files?

It worked with me like the following....

Lib1.js

//Any other private code here 

// Code you want to export
exports.function1 = function(params) {.......};
exports.function2 = function(params) {.......};

// Again any private code

now in the Main.js file you need to include Lib1.js

var mylib = requires('lib1.js');
mylib.function1(params);
mylib.function2(params);

Please remember to put the Lib1.js in node_modules folder.

Set a variable if undefined in JavaScript

var setVariable = (typeof localStorage.getItem('value') !== 'undefined' && localStorage.getItem('value')) || 0;

What is "pass-through authentication" in IIS 7?

Normally, IIS would use the process identity (the user account it is running the worker process as) to access protected resources like file system or network.

With passthrough authentication, IIS will attempt to use the actual identity of the user when accessing protected resources.

If the user is not authenticated, IIS will use the application pool identity instead. If pool identity is set to NetworkService or LocalSystem, the actual Windows account used is the computer account.

The IIS warning you see is not an error, it's just a warning. The actual check will be performed at execution time, and if it fails, it'll show up in the log.

How can I set the 'backend' in matplotlib in Python?

I hit this when trying to compile python, numpy, scipy, matplotlib in my own VIRTUAL_ENV

Before installing matplotlib you have to build and install: pygobject pycairo pygtk

And then do it with matplotlib: Before building matplotlib check with 'python ./setup.py build --help' if 'gtkagg' backend is enabled. Then build and install

Before export PKG_CONFIG_PATH=$VIRTUAL_ENV/lib/pkgconfig

How do I get user IP address in django?

In my case none of above works, so I have to check uwsgi + django source code and pass static param in nginx and see why/how, and below is what I have found.

Env info:
python version: 2.7.5
Django version: (1, 6, 6, 'final', 0)
nginx version: nginx/1.6.0
uwsgi: 2.0.7

Env setting info:
nginx as reverse proxy listening at port 80 uwsgi as upstream unix socket, will response to the request eventually

Django config info:

USE_X_FORWARDED_HOST = True # with or without this line does not matter

nginx config:

uwsgi_param      X-Real-IP              $remote_addr;
// uwsgi_param   X-Forwarded-For        $proxy_add_x_forwarded_for;
// uwsgi_param   HTTP_X_FORWARDED_FOR   $proxy_add_x_forwarded_for;

// hardcode for testing
uwsgi_param      X-Forwarded-For        "10.10.10.10";
uwsgi_param      HTTP_X_FORWARDED_FOR   "20.20.20.20";

getting all the params in django app:

X-Forwarded-For :       10.10.10.10
HTTP_X_FORWARDED_FOR :  20.20.20.20

Conclusion:

So basically, you have to specify exactly the same field/param name in nginx, and use request.META[field/param] in django app.

And now you can decide whether to add a middleware (interceptor) or just parse HTTP_X_FORWARDED_FOR in certain views.

use localStorage across subdomains

this kind of solution causes many problems like this. for consistency and SEO considerations redirect on the main domain is the best solution.

do it redirection at the server level

How To Redirect www to Non-www with Nginx

https://www.digitalocean.com/community/tutorials/how-to-redirect-www-to-non-www-with-nginx-on-centos-7

or any other level like route 53 if are using

Chrome extension: accessing localStorage in content script

Another option would be to use the chromestorage API. This allows storage of user data with optional syncing across sessions.

One downside is that it is asynchronous.

https://developer.chrome.com/extensions/storage.html

PHP & localStorage;

localStorage is something that is kept on the client side. There is no data transmitted to the server side.

You can only get the data with JavaScript and you can send it to the server side with Ajax.

How do I store an array in localStorage?

The localStorage and sessionStorage can only handle strings. You can extend the default storage-objects to handle arrays and objects. Just include this script and use the new methods:

Storage.prototype.setObj = function(key, obj) {
    return this.setItem(key, JSON.stringify(obj))
}
Storage.prototype.getObj = function(key) {
    return JSON.parse(this.getItem(key))
}

Use localStorage.setObj(key, value) to save an array or object and localStorage.getObj(key) to retrieve it. The same methods work with the sessionStorage object.

If you just use the new methods to access the storage, every value will be converted to a JSON-string before saving and parsed before it is returned by the getter.

Source: http://www.acetous.de/p/152

Set color of TextView span in Android

String text = "I don't like Hasina.";
textView.setText(spannableString(text, 8, 14));

private SpannableString spannableString(String text, int start, int end) {
    SpannableString spannableString = new SpannableString(text);
    ColorStateList redColor = new ColorStateList(new int[][]{new int[]{}}, new int[]{0xffa10901});
    TextAppearanceSpan highlightSpan = new TextAppearanceSpan(null, Typeface.BOLD, -1, redColor, null);

    spannableString.setSpan(highlightSpan, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    spannableString.setSpan(new BackgroundColorSpan(0xFFFCFF48), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    spannableString.setSpan(new RelativeSizeSpan(1.5f), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

    return spannableString;
}

Output:

enter image description here

How to check whether a Storage item is set?

You can also try this if you want to check for undefined:

if (localStorage.user === undefined) {
    localStorage.user = "username";
}

getItem is a method which returns null if value is not found.

What is the max size of localStorage values?

You can use the following code in modern browsers to efficiently check the storage quota (total & used) in real-time:

if ('storage' in navigator && 'estimate' in navigator.storage) {
        navigator.storage.estimate()
            .then(estimate => {
                console.log("Usage (in Bytes): ", estimate.usage,
                            ",  Total Quota (in Bytes): ", estimate.quota);
            });
}

Simpler way to create dictionary of separate variables?

I find that if you already have a specific list of values, that the way described by @S. Lotts is the best; however, the way described below works well to get all variables and Classes added throughout the code WITHOUT the need to provide variable name though you can specify them if you want. Code can be extend to exclude Classes.

import types
import math  # mainly showing that you could import what you will before d

# Everything after this counts
d = dict(globals())

def kv_test(k,v):
    return (k not in d and 
            k not in ['d','args'] and
            type(v) is not types.FunctionType)

def magic_print(*args):
    if len(args) == 0: 
        return {k:v for k,v in globals().iteritems() if kv_test(k,v)}
    else:
        return {k:v for k,v in magic_print().iteritems() if k in args}

if __name__ == '__main__':
    foo = 1
    bar = 2
    baz = 3
    print magic_print()
    print magic_print('foo')
    print magic_print('foo','bar')

Output:

{'baz': 3, 'foo': 1, 'bar': 2}
{'foo': 1}
{'foo': 1, 'bar': 2}

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

The NoSuchMethodError javadoc says this:

Thrown if an application tries to call a specified method of a class (either static or instance), and that class no longer has a definition of that method.

Normally, this error is caught by the compiler; this error can only occur at run time if the definition of a class has incompatibly changed.

In your case, this Error is a strong indication that your webapp is using the wrong version of the JAR defining the org.objectweb.asm.* classes.

When do items in HTML5 local storage expire?

You can try this one.

var hours = 24; // Reset when storage is more than 24hours
var now = Date.now();
var setupTime = localStorage.getItem('setupTime');
if (setupTime == null) {
     localStorage.setItem('setupTime', now)
} else if (now - setupTime > hours*60*60*1000) {
    localStorage.clear()
    localStorage.setItem('setupTime', now);
}

Storing Objects in HTML5 localStorage

https://github.com/adrianmay/rhaboo is a localStorage sugar layer that lets you write things like this:

var store = Rhaboo.persistent('Some name');
store.write('count', store.count ? store.count+1 : 1);
store.write('somethingfancy', {
  one: ['man', 'went'],
  2: 'mow',
  went: [  2, { mow: ['a', 'meadow' ] }, {}  ]
});
store.somethingfancy.went[1].mow.write(1, 'lawn');

It doesn't use JSON.stringify/parse because that would be inaccurate and slow on big objects. Instead, each terminal value has its own localStorage entry.

You can probably guess that I might have something to do with rhaboo.

What is the point of "Initial Catalog" in a SQL Server connection string?

This is the initial database of the data source when you connect.

Edited for clarity:

If you have multiple databases in your SQL Server instance and you don't want to use the default database, you need some way to specify which one you are going to use.

Append a Lists Contents to another List C#

With Linq

var newList = GlobalStrings.Append(localStrings)

What is exactly the base pointer and stack pointer? To what do they point?

EDIT: For a better description, see x86 Disassembly/Functions and Stack Frames in a WikiBook about x86 assembly. I try to add some info you might be interested in using Visual Studio.

Storing the caller EBP as the first local variable is called a standard stack frame, and this may be used for nearly all calling conventions on Windows. Differences exist whether the caller or callee deallocates the passed parameters, and which parameters are passed in registers, but these are orthogonal to the standard stack frame problem.

Speaking about Windows programs, you might probably use Visual Studio to compile your C++ code. Be aware that Microsoft uses an optimization called Frame Pointer Omission, that makes it nearly impossible to do walk the stack without using the dbghlp library and the PDB file for the executable.

This Frame Pointer Omission means that the compiler does not store the old EBP on a standard place and uses the EBP register for something else, therefore you have hard time finding the caller EIP without knowing how much space the local variables need for a given function. Of course Microsoft provides an API that allows you to do stack-walks even in this case, but looking up the symbol table database in PDB files takes too long for some use cases.

To avoid FPO in your compilation units, you need to avoid using /O2 or need to explicitly add /Oy- to the C++ compilation flags in your projects. You probably link against the C or C++ runtime, which uses FPO in the Release configuration, so you will have hard time to do stack walks without the dbghlp.dll.

Django: Redirect to previous page after login

I encountered the same problem. This solution allows me to keep using the generic login view:

urlpatterns += patterns('django.views.generic.simple',
    (r'^accounts/profile/$', 'redirect_to', {'url': 'generic_account_url'}),
)

Validating an XML against referenced XSD in C#

I had do this kind of automatic validation in VB and this is how I did it (converted to C#):

XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Schema;
settings.ValidationFlags = settings.ValidationFlags |
                           Schema.XmlSchemaValidationFlags.ProcessSchemaLocation;
XmlReader XMLvalidator = XmlReader.Create(reader, settings);

Then I subscribed to the settings.ValidationEventHandler event while reading the file.

Getting return value from stored procedure in C#

The value you are trying to get is not a return value but an output parameter. You need to change parametere direction to Output.

SqlParameter retval = sqlcomm.Parameters.Add("@b", SqlDbType.VarChar);
retval.Direction = ParameterDirection.Output;
command.ExecuteNonquery();
string retunvalue = (string)sqlcomm.Parameters["@b"].Value;

How to import a module given its name as string?

You can use exec:

exec("import myapp.commands.%s" % command)

NHibernate.MappingException: No persister for: XYZ

Something obvious, yet quite useful for someone new to NHibernate.

All XML Mapping files should be treated as Embedded Resources rather than the default Content. This option is set by editing the Build Action attribute in the file's properties.

XML files are then embedded into the assembly, and parsed at project startup during NHibernate's configuration phase.

How do I query for all dates greater than a certain date in SQL Server?

Try enclosing your date into a character string.

 select * 
 from dbo.March2010 A
 where A.Date >= '2010-04-01';

Convert string to hex-string in C#

For Unicode support:

public class HexadecimalEncoding
{
    public static string ToHexString(string str)
    {
        var sb = new StringBuilder();

        var bytes = Encoding.Unicode.GetBytes(str);
        foreach (var t in bytes)
        {
            sb.Append(t.ToString("X2"));
        }

        return sb.ToString(); // returns: "48656C6C6F20776F726C64" for "Hello world"
    }

    public static string FromHexString(string hexString)
    {
        var bytes = new byte[hexString.Length / 2];
        for (var i = 0; i < bytes.Length; i++)
        {
            bytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
        }

        return Encoding.Unicode.GetString(bytes); // returns: "Hello world" for "48656C6C6F20776F726C64"
    }
}

String escape into XML

public static string XmlEscape(string unescaped)
{
    XmlDocument doc = new XmlDocument();
    XmlNode node = doc.CreateElement("root");
    node.InnerText = unescaped;
    return node.InnerXml;
}

public static string XmlUnescape(string escaped)
{
    XmlDocument doc = new XmlDocument();
    XmlNode node = doc.CreateElement("root");
    node.InnerXml = escaped;
    return node.InnerText;
}

How to use adb command to push a file on device without sd card

As there are different paths for different versions. Here is a generic solution:

Find the path...

  1. Enter adb shell in command line.
  2. Then ls and Enter.

Now you'll see the files and directories of Android device. Now with combination of ls and cd dirName find the path to the Internal or External storage.

In the root directory, the directories names will be like mnt, sdcard, emulator0, etc

Example: adb push file.txt mnt/sdcard/myDir/Projects/

Warning: Each child in an array or iterator should have a unique "key" prop. Check the render method of `ListView`

The specific code I used to fix this was:

  renderSeparator(sectionID, rowID, adjacentRowHighlighted) {
    return (
      <View style={styles.separator} key={`${sectionID}-${rowID}`}/>
    )
  }

I'm including the specific code because you need the keys to be unique--even for separators. If you do something similar e.g., if you set this to a constant, you will just get another annoying error about reuse of keys. If you don't know JSX, constructing the callback to JS to execute the various parts can be quite a pain.

And on the ListView, obviously attaching this:

<ListView
  style={styles.listview}
  dataSource={this.state.dataSource}
  renderRow={this.renderRow.bind(this)}
  renderSeparator={this.renderSeparator.bind(this)}
  renderSectionHeader={this.renderSectionHeader.bind(this)}/>

Credit to coldbuffet and Nader Dabit who pointed me down this path.

How do I run all Python unit tests in a directory?

This is now possible directly from unittest: unittest.TestLoader.discover.

import unittest
loader = unittest.TestLoader()
start_dir = 'path/to/your/test/files'
suite = loader.discover(start_dir)

runner = unittest.TextTestRunner()
runner.run(suite)

How to generate List<String> from SQL query?

Or a nested List (okay, the OP was for a single column and this is for multiple columns..):

        //Base list is a list of fields, ie a data record
        //Enclosing list is then a list of those records, ie the Result set
        List<List<String>> ResultSet = new List<List<String>>();

        using (SqlConnection connection =
            new SqlConnection(connectionString))
        {
            // Create the Command and Parameter objects.
            SqlCommand command = new SqlCommand(qString, connection);

            // Create and execute the DataReader..
            connection.Open();
            SqlDataReader reader = command.ExecuteReader();
            while (reader.Read())
            {
                var rec = new List<string>();
                for (int i = 0; i <= reader.FieldCount-1; i++) //The mathematical formula for reading the next fields must be <=
                {                      
                    rec.Add(reader.GetString(i));
                }
                ResultSet.Add(rec);

            }
        }

How to run a maven created jar file using just the command line

I am not sure in your case. But as I know to run any jar file from cmd we can use following command:

Go up to the directory where your jar file is saved:

java -jar <jarfilename>.jar

But you can check following links. I hope it'll help you:

Run Netbeans maven project from command-line?

http://www.sonatype.com/books/mvnref-book/reference/running-sect-options.html

Setting environment variables on OS X

It's simple:

Edit ~/.profile and put your variables as follow

$ vim ~/.profile

In file put:

MY_ENV_VAR=value

  1. Save ( :wq )

  2. Restart the terminal (Quit and open it again)

  3. Make sure that`s all be fine:

$ echo $MY_ENV_VAR

$ value


Horizontal ListView in Android?

Download the jar file from here

now put it into your libs folder, right click it and select 'Add as library'

now in main.xml put this code

 <com.devsmart.android.ui.HorizontalListView
    android:id="@+id/hlistview"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    />

now in Activity class if you want Horizontal Listview with images then put this code

  HorizontalListView hListView = (HorizontalListView) findViewById(R.id.hlistview);
    hListView.setAdapter(new HAdapter(this));


 private class HAdapter extends BaseAdapter {

    LayoutInflater inflater;

    public HAdapter(Context context) {
        inflater = LayoutInflater.from(context);

    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return Const.template.length;
    }

    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return position;
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        HViewHolder holder;
        if (convertView == null) {
            convertView = inflater.inflate(R.layout.listinflate, null);
            holder = new HViewHolder();
            convertView.setTag(holder);

        } else {
            holder = (HViewHolder) convertView.getTag();
        }
        holder.img = (ImageView) convertView.findViewById(R.id.image);
        holder.img.setImageResource(Const.template[position]);
        return convertView;
    }

}

class HViewHolder {
    ImageView img;
}

Convert string to JSON array

Using json lib:-

String data="[{"A":"a","B":"b","C":"c","D":"d","E":"e","F":"f","G":"g"}]";
Object object=null;
JSONArray arrayObj=null;
JSONParser jsonParser=new JSONParser();
object=jsonParser.parse(data);
arrayObj=(JSONArray) object;
System.out.println("Json object :: "+arrayObj);

Using GSON lib:-

Gson gson = new Gson();
String data="[{\"A\":\"a\",\"B\":\"b\",\"C\":\"c\",\"D\":\"d\",\"E\":\"e\",\"F\":\"f\",\"G\":\"g\"}]";
JsonParser jsonParser = new JsonParser();
JsonArray jsonArray = (JsonArray) jsonParser.parse(data);

In Matplotlib, what does the argument mean in fig.add_subplot(111)?

The add_subplot() method has several call signatures:

  1. add_subplot(nrows, ncols, index, **kwargs)
  2. add_subplot(pos, **kwargs)
  3. add_subplot(ax)
  4. add_subplot() <-- since 3.1.0

Calls 1 and 2:

Calls 1 and 2 achieve the same thing as one another (up to a limit, explained below). Think of them as first specifying the grid layout with their first 2 numbers (2x2, 1x8, 3x4, etc), e.g:

f.add_subplot(3,4,1) 
# is equivalent to:
f.add_subplot(341)

Both produce a subplot arrangement of (3 x 4 = 12) subplots in 3 rows and 4 columns. The third number in each call indicates which axis object to return, starting from 1 at the top left, increasing to the right.

This code illustrates the limitations of using call 2:

#!/usr/bin/env python3
import matplotlib.pyplot as plt

def plot_and_text(axis, text):
  '''Simple function to add a straight line
  and text to an axis object'''
  axis.plot([0,1],[0,1])
  axis.text(0.02, 0.9, text)

f = plt.figure()
f2 = plt.figure()

_max = 12
for i in range(_max):
  axis = f.add_subplot(3,4,i+1, fc=(0,0,0,i/(_max*2)), xticks=[], yticks=[])
  plot_and_text(axis,chr(i+97) + ') ' + '3,4,' +str(i+1))

  # If this check isn't in place, a 
  # ValueError: num must be 1 <= num <= 15, not 0 is raised
  if i < 9:
    axis = f2.add_subplot(341+i, fc=(0,0,0,i/(_max*2)), xticks=[], yticks=[])
    plot_and_text(axis,chr(i+97) + ') ' + str(341+i))

f.tight_layout()
f2.tight_layout()
plt.show()

subplots

You can see with call 1 on the LHS you can return any axis object, however with call 2 on the RHS you can only return up to index = 9 rendering subplots j), k), and l) inaccessible using this call.

I.e it illustrates this point from the documentation:

pos is a three digit integer, where the first digit is the number of rows, the second the number of columns, and the third the index of the subplot. i.e. fig.add_subplot(235) is the same as fig.add_subplot(2, 3, 5). Note that all integers must be less than 10 for this form to work.


Call 3

In rare circumstances, add_subplot may be called with a single argument, a subplot axes instance already created in the present figure but not in the figure's list of axes.


Call 4 (since 3.1.0):

If no positional arguments are passed, defaults to (1, 1, 1).

i.e., reproducing the call fig.add_subplot(111) in the question.

When does System.gc() do something?

while system.gc works,it will stop the world:all respones are stopped so garbage collector can scan every object to check if it is needed deleted. if the application is a web project, all request are stopped until gc finishes,and this will cause your web project can not work in a monent.

Copying PostgreSQL database to another server


Dump your database : pg_dump database_name_name > backup.sql


Import your database back: psql db_name < backup.sql

Disabling swap files creation in vim

For anyone trying to set this for Rails projects, add

set directory=tmp,/tmp

into your

~/.vimrc

So the .swp files will be in their natural location - the tmp directory (per project).

libstdc++.so.6: cannot open shared object file: No such file or directory

I presume you're running Linux on an amd64 machine. The Folder your executable is residing in (lib32) suggests a 32-bit executable which requires 32-bit libraries.

These seem not to be present on your system, so you need to install them manually. The package name depends on your distribution, for Debian it's ia32-libs, for Fedora libstdc++.<version>.i686.

See full command of running/stopped container in Docker

TL-DR

docker ps --no-trunc and docker inspect CONTAINER provide the entrypoint executed to start the container, along the command passed to, but that may miss some parts such as ${ANY_VAR} because container environment variables are not printed as resolved.

To overcome that, docker inspect CONTAINER has an advantage because it also allow to retrieve separately env variables and their values defined in the container from the Config.Env property.

docker ps and docker inspect provide information about the executed entrypoint and its command. Often, that is a wrapper entrypoint script (.sh) and not the "real" program started by the container. To get information on that, requesting process information with ps or /proc/1/cmdline help.


1) docker ps --no-trunc

It prints the entrypoint and the command executed for all running containers. While it prints the command passed to the entrypoint (if we pass that), it doesn't show value of docker env variables (such as $FOO or ${FOO}).
If our containers use env variables, it may be not enough.

For example, run an alpine container :

docker run --name alpine-example -e MY_VAR=/var alpine:latest sh -c 'ls $MY_VAR'

When use docker -ps such as :

docker ps -a --filter name=alpine-example --no-trunc

It prints :

CONTAINER ID           IMAGE               COMMAND                CREATED             STATUS                     PORTS               NAMES
5b064a6de6d8417...   alpine:latest       "sh -c 'ls $MY_VAR'"   2 minutes ago       Exited (0) 2 minutes ago                       alpine-example

We see the command passed to the entrypoint : sh -c 'ls $MY_VAR' but $MY_VAR is indeed not resolved.

2) docker inspect CONTAINER

When we inspect the alpine-example container :

docker inspect alpine-example | grep -4 Cmd

The command is also there but we don't still see the env variable value :

        "Cmd": [
            "sh",
            "-c",
            "ls $MY_VAR"
        ],

In fact, we could not see interpolated variables with these docker commands.
While as a trade-off, we could display separately both command and env variables for a container with docker inspect :

docker inspect  alpine-example  | grep -4 -E "Cmd|Env"

That prints :

        "Env": [
            "MY_VAR=/var",
            "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
        ],
        "Cmd": [
            "sh",
            "-c",
            "ls $MY_VAR"
        ]

A more docker way would be to use the --format flag of docker inspect that allows to specify JSON attributes to render :

docker inspect --format '{{.Name}} {{.Config.Cmd}}  {{ (.Config.Env) }}'  alpine-example

That outputs :

/alpine-example [sh -c ls $MY_VAR]  [MY_VAR=/var PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin]

3) Retrieve the started process from the container itself for running containers

The entrypoint and command executed by docker may be helpful but in some cases, it is not enough because that is "only" a wrapper entrypoint script (.sh) that is responsible to start the real/core process.
For example when I run a Nexus container, the command executed and shown to run the container is "sh -c ${SONATYPE_DIR}/start-nexus-repository-manager.sh".
For PostgreSQL that is "docker-entrypoint.sh postgres".

To get more information, we could execute on a running container docker exec CONTAINER ps aux.
It may print other processes that may not interest us.
To narrow to the initial process launched by the entrypoint, we could do :

docker exec CONTAINER ps -1

I specify 1 because the process executed by the entrypoint is generally the one with the 1 id.

Without ps, we could still find the information in /proc/1/cmdline (in most of Linux distros but not all). For example :

docker exec CONTAINER cat /proc/1/cmdline | sed -e "s/\x00/ /g"; echo    

If we have access to the docker host that started the container, another alternative to get the full command of the process executed by the entrypoint is : : execute ps -PID where PID is the local process created by the Docker daemon to run the container such as :

ps -$(docker container inspect --format '{{.State.Pid}}'  CONTAINER)

User-friendly formatting with docker ps

docker ps --no-trunc is not always easy to read.
Specifying columns to print and in a tabular format may make it better :

docker ps   --no-trunc  --format "table{{.Names}}\t{{.CreatedAt}}\t{{.Command}}"

Create an alias may help :

alias dps='docker ps   --no-trunc  --format "table{{.Names}}\t{{.CreatedAt}}\t{{.Command}}"'

How to include JavaScript file or library in Chrome console?

If you're just starting out learning javascript & don't want to spend time creating an entire webpage just for embedding test scripts, just open Dev Tools in a new tab in Chrome Browser, and click on Console.

Then type out some test scripts: eg.

console.log('Aha!') 

Then press Enter after every line (to submit for execution by Chrome)

or load your own "external script file":

document.createElement('script').src = 'http://example.com/file.js';

Then call your functions:

console.log(file.function('?????'))

Tested in Google Chrome 85.0.4183.121

Gets byte array from a ByteBuffer in java

This is a simple way to get a byte[], but part of the point of using a ByteBuffer is avoiding having to create a byte[]. Perhaps you can get whatever you wanted to get from the byte[] directly from the ByteBuffer.

'npm' is not recognized as internal or external command, operable program or batch file

Had the same problem on Windows 8.1 64 bit.
Turns out i get that problem if I start cmd by typing it in the path bar at the top of a folder window
or
when i shift right click in a folder window and then open command prompt from the list.

When I run cmd using Run or Just from the cmd.exe executable it works.

Non-resolvable parent POM using Maven 3.0.3 and relativePath notation

Make sure you Double-Check that the version you refer to in the child-pom is the same as that in the parent-pom. For me, I'd bumped version in the parent and had it as 3.1.0.0-RELEASE, but in the child-pom, I was still referring to the previous version via relativePath, and had it defined as 2.0.0.0-SNAPSHOT. It did not make any difference if I included just the parent directory, or had the "pom.xml" appended to the directory:

    <parent>        
    <artifactId>eric-project-parent</artifactId>
    <groupId>com.eric.common</groupId>
     <!-- Should be 3.1.0.0-RELEASE -->
    <version>2.0.0.0-SNAPSHOT</version>     
    <relativePath>
                ../../EricParentAsset/projects/eric-project-parent</relativePath>           
</parent>

ZIP Code (US Postal Code) validation

To allow a user to enter a Canadian Postal code with lower case letters as well, the regex would need to look like this:

/^([a-zA-Z][0-9][a-zA-Z])\s*([0-9][a-zA-Z][0-9])$/

How to modify the nodejs request default timeout time?

Linking to express issue #3330

You may set the timeout either globally for entire server:

var server = app.listen();
server.setTimeout(500000);

or just for specific route:

app.post('/xxx', function (req, res) {
   req.setTimeout(500000);
});

Two column div layout with fluid left and fixed right column

Here's a solution (and it has some quirks, but let me know if you notice them and that they're a concern):

<div>
    <div style="width:200px;float:left;display:inline-block;">
        Hello world
    </div>
    <div style="margin-left:200px;">
        Hello world
    </div>
</div>

Reading a registry key in C#

You're looking for the cunningly named Registry.GetValue method.

How to pass variables from one php page to another without form?

You want sessions if you have data you want to have the data held for longer than one page.

$_GET for just one page.

<a href='page.php?var=data'>Data link</a>

on page.php

<?php
echo $_GET['var'];
?>

will output: data

How to find whether a ResultSet is empty or not in Java?

Do this using rs.next():

while (rs.next())
{
    ...
}

If the result set is empty, the code inside the loop won't execute.

What is the significance of url-pattern in web.xml and how to configure servlet?

url-pattern is used in web.xml to map your servlet to specific URL. Please see below xml code, similar code you may find in your web.xml configuration file.

<servlet>
    <servlet-name>AddPhotoServlet</servlet-name>  //servlet name
    <servlet-class>upload.AddPhotoServlet</servlet-class>  //servlet class
</servlet>
 <servlet-mapping>
    <servlet-name>AddPhotoServlet</servlet-name>   //servlet name
    <url-pattern>/AddPhotoServlet</url-pattern>  //how it should appear
</servlet-mapping>

If you change url-pattern of AddPhotoServlet from /AddPhotoServlet to /MyUrl. Then, AddPhotoServlet servlet can be accessible by using /MyUrl. Good for the security reason, where you want to hide your actual page URL.

Java Servlet url-pattern Specification:

  1. A string beginning with a '/' character and ending with a '/*' suffix is used for path mapping.
  2. A string beginning with a '*.' prefix is used as an extension mapping.
  3. A string containing only the '/' character indicates the "default" servlet of the application. In this case the servlet path is the request URI minus the context path and the path info is null.
  4. All other strings are used for exact matches only.

Reference : Java Servlet Specification

You may also read this Basics of Java Servlet

How to remove the left part of a string?

If you know list comprehensions:

lines = [line[5:] for line in file.readlines() if line[:5] == "Path="]

Can't accept license agreement Android SDK Platform 24

Go to Android\sdk\tools\bin

None of the above solutions worked for me and finally this single line accepted all android licences.

yes | sdkmanager --licenses && sdkmanager --update

Why am I suddenly getting a "Blocked loading mixed active content" issue in Firefox?

Its given the error because of security. for this please use "https" not "http" in the website url.

For example :

   "https://code.jquery.com/ui/1.8.10/themes/smoothness/jquery-ui.css"
   "https://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.10/jquery-ui.min.js"

Request Permission for Camera and Library in iOS 10 - Info.plist

I wrote an extension that takes into account all possible cases:

  • If access is allowed, then the code onAccessHasBeenGranted will be run.
  • If access is not determined, then requestAuthorization(_:) will be called.
  • If the user has denied your app photo library access, then the user will be shown a window offering to go to settings and allow access. In this window, the "Cancel" and "Settings" buttons will be available to him. When he presses the "settings" button, your application settings will open.

Usage example:

PHPhotoLibrary.execute(controller: self, onAccessHasBeenGranted: {
    // access granted... 
})

Extension code:

import Photos
import UIKit

public extension PHPhotoLibrary {

   static func execute(controller: UIViewController,
                       onAccessHasBeenGranted: @escaping () -> Void,
                       onAccessHasBeenDenied: (() -> Void)? = nil) {

      let onDeniedOrRestricted = onAccessHasBeenDenied ?? {
         let alert = UIAlertController(
            title: "We were unable to load your album groups. Sorry!",
            message: "You can enable access in Privacy Settings",
            preferredStyle: .alert)
         alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
         alert.addAction(UIAlertAction(title: "Settings", style: .default, handler: { _ in
            if let settingsURL = URL(string: UIApplication.openSettingsURLString) {
               UIApplication.shared.open(settingsURL)
            }
         }))
         controller.present(alert, animated: true)
      }

      let status = PHPhotoLibrary.authorizationStatus()
      switch status {
      case .notDetermined:
         onNotDetermined(onDeniedOrRestricted, onAccessHasBeenGranted)
      case .denied, .restricted:
         onDeniedOrRestricted()
      case .authorized:
         onAccessHasBeenGranted()
      @unknown default:
         fatalError("PHPhotoLibrary::execute - \"Unknown case\"")
      }
   }

}

private func onNotDetermined(_ onDeniedOrRestricted: @escaping (()->Void), _ onAuthorized: @escaping (()->Void)) {
   PHPhotoLibrary.requestAuthorization({ status in
      switch status {
      case .notDetermined:
         onNotDetermined(onDeniedOrRestricted, onAuthorized)
      case .denied, .restricted:
         onDeniedOrRestricted()
      case .authorized:
         onAuthorized()
      @unknown default:
         fatalError("PHPhotoLibrary::execute - \"Unknown case\"")
      }
   })
}

CodeIgniter Active Record not equal

It worked fine with me,

$this->db->where("your_id !=",$your_id);

Or try this one,

$this->db->where("your_id <>",$your_id);

Or try this one,

$this->db->where("your_id IS NOT NULL");

all will work.

Import Excel spreadsheet columns into SQL Server database

This may sound like the long way around, but you may want to look at using Excel to generate INSERT SQL code that you can past into Query Analyzer to create your table.

Works well if you cant use the wizards because the excel file isn't on the server

Asynchronous method call in Python?

My solution is:

import threading

class TimeoutError(RuntimeError):
    pass

class AsyncCall(object):
    def __init__(self, fnc, callback = None):
        self.Callable = fnc
        self.Callback = callback

    def __call__(self, *args, **kwargs):
        self.Thread = threading.Thread(target = self.run, name = self.Callable.__name__, args = args, kwargs = kwargs)
        self.Thread.start()
        return self

    def wait(self, timeout = None):
        self.Thread.join(timeout)
        if self.Thread.isAlive():
            raise TimeoutError()
        else:
            return self.Result

    def run(self, *args, **kwargs):
        self.Result = self.Callable(*args, **kwargs)
        if self.Callback:
            self.Callback(self.Result)

class AsyncMethod(object):
    def __init__(self, fnc, callback=None):
        self.Callable = fnc
        self.Callback = callback

    def __call__(self, *args, **kwargs):
        return AsyncCall(self.Callable, self.Callback)(*args, **kwargs)

def Async(fnc = None, callback = None):
    if fnc == None:
        def AddAsyncCallback(fnc):
            return AsyncMethod(fnc, callback)
        return AddAsyncCallback
    else:
        return AsyncMethod(fnc, callback)

And works exactly as requested:

@Async
def fnc():
    pass

Construct pandas DataFrame from list of tuples of (row,col,values)

This is what I expected to see when I came to this question:

#!/usr/bin/env python

import pandas as pd


df = pd.DataFrame([(1, 2, 3, 4),
                   (5, 6, 7, 8),
                   (9, 0, 1, 2),
                   (3, 4, 5, 6)],
                  columns=list('abcd'),
                  index=['India', 'France', 'England', 'Germany'])
print(df)

gives

         a  b  c  d
India    1  2  3  4
France   5  6  7  8
England  9  0  1  2
Germany  3  4  5  6

What is a reasonable length limit on person "Name" fields?

UK Government Data Standards Catalogue suggests 35 characters for each of Given Name and Family Name, or 70 characters for a single field to hold the Full Name.

Generating random numbers in C

#include <stdlib.h>

int main()
{
    int x;
    x = rand(6);
    printf("%d", x);
}

Especially as a beginner, you should ask your compiler to print every warning about bad code that it can generate. Modern compilers know lots of different warnings which help you to program better. For example, when you compile this program with the GNU C Compiler:

$ gcc -W -Wall rand.c
rand.c: In function `main':
rand.c:5: error: too many arguments to function `rand'
rand.c:6: warning: implicit declaration of function `printf'

You get two warnings here. The first one says that the rand function only takes zero arguments, not one as you tried. To get a random number between 0 and n, you can use the expression rand() % n, which is not perfect but ok for small n. The resulting random numbers are normally not evenly distributed; smaller values are returned more often.

The second warning tells you that you are calling a function that the compiler doesn't know at that point. You have to tell the compiler by saying #include <stdio.h>. Which include files are needed for which functions is not always simple, but asking the Open Group specification for portable operating systems works in many cases: http://www.google.com/search?q=opengroup+rand.

These two warnings tell you much about the history of the C programming language. 40 years back, the definition of a function didn't include the number of parameters or the types of the parameters. It was also ok to call an unknown function, which in most cases worked. If you want to write code today, you should not rely on these old features but instead enable your compiler's warnings, understand the warnings and then fix them properly.

How to print full stack trace in exception?

1. Create Method: If you pass your exception to the following function, it will give you all methods and details which are reasons of the exception.

public string GetAllFootprints(Exception x)
{
        var st = new StackTrace(x, true);
        var frames = st.GetFrames();
        var traceString = new StringBuilder();

        foreach (var frame in frames)
        {
            if (frame.GetFileLineNumber() < 1)
                continue;

            traceString.Append("File: " + frame.GetFileName());
            traceString.Append(", Method:" + frame.GetMethod().Name);
            traceString.Append(", LineNumber: " + frame.GetFileLineNumber());
            traceString.Append("  -->  ");
        }

        return traceString.ToString();
}

2. Call Method: You can call the method like this.

try
{
    // code part which you want to catch exception on it
}
catch(Exception ex)
{
    Debug.Writeline(GetAllFootprints(ex));
}

3. Get the Result:

File: c:\MyProject\Program.cs, Method:MyFunction, LineNumber: 29  -->  
File: c:\MyProject\Program.cs, Method:Main, LineNumber: 16  --> 

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);

Plot multiple columns on the same graph in R

The easiest is to convert your data to a "tall" format.

s <- 
"A       B        C       G       Xax
0.451   0.333   0.034   0.173   0.22        
0.491   0.270   0.033   0.207   0.34    
0.389   0.249   0.084   0.271   0.54    
0.425   0.819   0.077   0.281   0.34
0.457   0.429   0.053   0.386   0.53    
0.436   0.524   0.049   0.249   0.12    
0.423   0.270   0.093   0.279   0.61    
0.463   0.315   0.019   0.204   0.23
"
d <- read.delim(textConnection(s), sep="")

library(ggplot2)
library(reshape2)
d <- melt(d, id.vars="Xax")

# Everything on the same plot
ggplot(d, aes(Xax,value, col=variable)) + 
  geom_point() + 
  stat_smooth() 

# Separate plots
ggplot(d, aes(Xax,value)) + 
  geom_point() + 
  stat_smooth() +
  facet_wrap(~variable)

In Java, what is the best way to determine the size of an object?

I doubt you want to do it programmatically unless you just want to do it once and store it for future use. It's a costly thing to do. There's no sizeof() operator in Java, and even if there was, it would only count the cost of the references to other objects and the size of the primitives.

One way you could do it is to serialize the thing to a File and look at the size of the file, like this:

Serializable myObject;
ObjectOutputStream oos = new ObjectOutputStream (new FileOutputStream ("obj.ser"));
oos.write (myObject);
oos.close ();

Of course, this assumes that each object is distinct and doesn't contain non-transient references to anything else.

Another strategy would be to take each object and examine its members by reflection and add up the sizes (boolean & byte = 1 byte, short & char = 2 bytes, etc.), working your way down the membership hierarchy. But that's tedious and expensive and ends up doing the same thing the serialization strategy would do.

What does the C++ standard state the size of int, long type to be?

Updated: C++11 brought the types from TR1 officially into the standard:

  • long long int
  • unsigned long long int

And the "sized" types from <cstdint>

  • int8_t
  • int16_t
  • int32_t
  • int64_t
  • (and the unsigned counterparts).

Plus you get:

  • int_least8_t
  • int_least16_t
  • int_least32_t
  • int_least64_t
  • Plus the unsigned counterparts.

These types represent the smallest integer types with at least the specified number of bits. Likewise there are the "fastest" integer types with at least the specified number of bits:

  • int_fast8_t
  • int_fast16_t
  • int_fast32_t
  • int_fast64_t
  • Plus the unsigned versions.

What "fast" means, if anything, is up to the implementation. It need not be the fastest for all purposes either.

T-SQL XOR Operator

<> is generally a good replacement for XOR wherever it can apply to booleans.

invalid new-expression of abstract class type

for others scratching their heads, I came across this error because I had innapropriately const-qualified one of the arguments to a method in a base class, so the derived class member functions were not over-riding it. so make sure you don't have something like

class Base 
{
  public:
      virtual void foo(int a, const int b) = 0;
}
class D: public Base 
{
 public:
     void foo(int a, int b){};
}

Javascript to convert UTC to local time

Try:

var date = new Date('2012-11-29 17:00:34 UTC');
date.toString();

message box in jquery

using jQuery UI you can use the dialog that offers. More information at http://docs.jquery.com/UI/Dialog

How to remove new line characters from data rows in mysql?

your syntax is wrong:

update mytable SET title = TRIM(TRAILING '\n' FROM title)

Addition:

If the newline character is at the start of the field:

update mytable SET title = TRIM(LEADING '\n' FROM title)

How can I print out all possible letter combinations a given phone number can represent?

    private List<string> strs = new List<string>();        
    char[] numbersArray;
    private int End = 0;
    private int numberOfStrings;

    private void PrintLetters(string numbers)
    {
        this.End = numbers.Length;
        this.numbersArray = numbers.ToCharArray();
        this.PrintAllCombinations(this.GetCharacters(this.numbersArray[0]), string.Empty, 0);
    }

    private void PrintAllCombinations(char[] letters, string output, int depth)
    {
        depth++;
        for (int i = 0; i < letters.Length; i++)
        {
            if (depth != this.End)
            {
                output += letters[i];
                this.PrintAllCombinations(this.GetCharacters(Convert.ToChar(this.numbersArray[depth])), output, depth);
                output = output.Substring(0, output.Length - 1);
            }
            else
            {
                Console.WriteLine(output + letters[i] + (++numberOfStrings));
            }
        }
    }

    private char[] GetCharacters(char x)
    {
        char[] arr;
        switch (x)
        {
            case '0': arr = new char[1] { '.' };
                return arr;
            case '1': arr = new char[1] { '.' };
                return arr;
            case '2': arr = new char[3] { 'a', 'b', 'c' };
                return arr;
            case '3': arr = new char[3] { 'd', 'e', 'f' };
                return arr;
            case '4': arr = new char[3] { 'g', 'h', 'i' };
                return arr;
            case '5': arr = new char[3] { 'j', 'k', 'l' };
                return arr;
            case '6': arr = new char[3] { 'm', 'n', 'o' };
                return arr;
            case '7': arr = new char[4] { 'p', 'q', 'r', 's' };
                return arr;
            case '8': arr = new char[3] { 't', 'u', 'v' };
                return arr;
            case '9': arr = new char[4] { 'w', 'x', 'y', 'z' };
                return arr;
            default: return null;
        }
    }

Serial Port (RS -232) Connection in C++

Please take a look here:

1) You can use this with Windows (incl. MinGW) as well as Linux. Alternative you can only use the code as an example.

2) Step-by-step tutorial how to use serial ports on windows

3) You can use this literally on MinGW

Here's some very, very simple code (without any error handling or settings):

#include <windows.h>

/* ... */


// Open serial port
HANDLE serialHandle;

serialHandle = CreateFile("\\\\.\\COM1", GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);

// Do some basic settings
DCB serialParams = { 0 };
serialParams.DCBlength = sizeof(serialParams);

GetCommState(serialHandle, &serialParams);
serialParams.BaudRate = baudrate;
serialParams.ByteSize = byteSize;
serialParams.StopBits = stopBits;
serialParams.Parity = parity;
SetCommState(serialHandle, &serialParams);

// Set timeouts
COMMTIMEOUTS timeout = { 0 };
timeout.ReadIntervalTimeout = 50;
timeout.ReadTotalTimeoutConstant = 50;
timeout.ReadTotalTimeoutMultiplier = 50;
timeout.WriteTotalTimeoutConstant = 50;
timeout.WriteTotalTimeoutMultiplier = 10;

SetCommTimeouts(serialHandle, &timeout);

Now you can use WriteFile() / ReadFile() to write / read bytes. Don't forget to close your connection:

CloseHandle(serialHandle);

Generate preview image from Video file?

I recommend php-ffmpeg library.

Extracting image

You can extract a frame at any timecode using the FFMpeg\Media\Video::frame method.

This code returns a FFMpeg\Media\Frame instance corresponding to the second 42. You can pass any FFMpeg\Coordinate\TimeCode as argument, see dedicated documentation below for more information.

$frame = $video->frame(FFMpeg\Coordinate\TimeCode::fromSeconds(42));
$frame->save('image.jpg');

If you want to extract multiple images from the video, you can use the following filter:

$video
    ->filters()
    ->extractMultipleFrames(FFMpeg\Filters\Video\ExtractMultipleFramesFilter::FRAMERATE_EVERY_10SEC, '/path/to/destination/folder/')
    ->synchronize();

$video
    ->save(new FFMpeg\Format\Video\X264(), '/path/to/new/file');

By default, this will save the frames as jpg images.

You are able to override this using setFrameFileType to save the frames in another format:

$frameFileType = 'jpg'; // either 'jpg', 'jpeg' or 'png'
$filter = new ExtractMultipleFramesFilter($frameRate, $destinationFolder);
$filter->setFrameFileType($frameFileType);

$video->addFilter($filter);

Combining (concatenating) date and time into a datetime

Assuming the underlying data types are date/time/datetime types:

SELECT CONVERT(DATETIME, CONVERT(CHAR(8), CollectionDate, 112) 
  + ' ' + CONVERT(CHAR(8), CollectionTime, 108))
  FROM dbo.whatever;

This will convert CollectionDate and CollectionTime to char sequences, combine them, and then convert them to a datetime.

The parameters to CONVERT are data_type, expression and the optional style (see syntax documentation).

The date and time style value 112 converts to an ISO yyyymmdd format. The style value 108 converts to hh:mi:ss format. Evidently both are 8 characters long which is why the data_type is CHAR(8) for both.

The resulting combined char sequence is in format yyyymmdd hh:mi:ss and then converted to a datetime.

How to programmatically set SelectedValue of Dropdownlist when it is bound to XmlDataSource

This seems to work for me.

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            DropDownList1.DataBind(); // get the data into the list you can set it
            DropDownList1.Items.FindByValue("SOMECREDITPROBLEMS").Selected = true;
        }
    }

1052: Column 'id' in field list is ambiguous

SELECT tbl_names.id, tbl_names.name, tbl_names.section
  FROM tbl_names, tbl_section 
 WHERE tbl_names.id = tbl_section.id

Input and Output binary streams using JERSEY?

Using Jersey 2.16 File download is very easy.

Below is the example for the ZIP file

@GET
@Path("zipFile")
@Produces("application/zip")
public Response getFile() {
    File f = new File(ZIP_FILE_PATH);

    if (!f.exists()) {
        throw new WebApplicationException(404);
    }

    return Response.ok(f)
            .header("Content-Disposition",
                    "attachment; filename=server.zip").build();
}

Multiple INSERT statements vs. single INSERT with multiple VALUES

The issue probably has to do with the time it takes to compile the query.

If you want to speed up the inserts, what you really need to do is wrap them in a transaction:

BEGIN TRAN;
INSERT INTO T_TESTS (TestId, FirstName, LastName, Age) 
   VALUES ('6f3f7257-a3d8-4a78-b2e1-c9b767cfe1c1', 'First 0', 'Last 0', 0);
INSERT INTO T_TESTS (TestId, FirstName, LastName, Age) 
   VALUES ('32023304-2e55-4768-8e52-1ba589b82c8b', 'First 1', 'Last 1', 1);
...
INSERT INTO T_TESTS (TestId, FirstName, LastName, Age) 
   VALUES ('f34d95a7-90b1-4558-be10-6ceacd53e4c4', 'First 999', 'Last 999', 999);
COMMIT TRAN;

From C#, you might also consider using a table valued parameter. Issuing multiple commands in a single batch, by separating them with semicolons, is another approach that will also help.

How does strtok() split the string into tokens in C?

you can scan the char array looking for the token if you found it just print new line else print the char.

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

int main()
{
    char *s;
    s = malloc(1024 * sizeof(char));
    scanf("%[^\n]", s);
    s = realloc(s, strlen(s) + 1);
    int len = strlen(s);
    char delim =' ';
    for(int i = 0; i < len; i++) {
        if(s[i] == delim) {
            printf("\n");
        }
        else {
            printf("%c", s[i]);
        }
    }
    free(s);
    return 0;
}

Bulk create model objects in django

Using create will cause one query per new item. If you want to reduce the number of INSERT queries, you'll need to use something else.

I've had some success using the Bulk Insert snippet, even though the snippet is quite old. Perhaps there are some changes required to get it working again.

http://djangosnippets.org/snippets/446/

Can a shell script set environment variables of the calling shell?

Technically, that is correct -- only 'eval' doesn't fork another shell. However, from the point of view of the application you're trying to run in the modified environment, the difference is nil: the child inherits the environment of its parent, so the (modified) environment is conveyed to all descending processes.

Ipso facto, the changed environment variable 'sticks' -- as long as you are running under the parent program/shell.

If it is absolutely necessary for the environment variable to remain after the parent (Perl or shell) has exited, it is necessary for the parent shell to do the heavy lifting. One method I've seen in the documentation is for the current script to spawn an executable file with the necessary 'export' language, and then trick the parent shell into executing it -- always being cognizant of the fact that you need to preface the command with 'source' if you're trying to leave a non-volatile version of the modified environment behind. A Kluge at best.

The second method is to modify the script that initiates the shell environment (.bashrc or whatever) to contain the modified parameter. This can be dangerous -- if you hose up the initialization script it may make your shell unavailable the next time it tries to launch. There are plenty of tools for modifying the current shell; by affixing the necessary tweaks to the 'launcher' you effectively push those changes forward as well. Generally not a good idea; if you only need the environment changes for a particular application suite, you'll have to go back and return the shell launch script to its pristine state (using vi or whatever) afterwards.

In short, there are no good (and easy) methods. Presumably this was made difficult to ensure the security of the system was not irrevocably compromised.

What is the difference between encrypting and signing in asymmetric encryption?

Signing indicates you really are the source or vouch for of the object signed. Everyone can read the object, though.

Encrypting means only those with the corresponding private key can read it, but without signing there is no guarantee you are behind the encrypted object.

How can I use JQuery to post JSON data?

The top answer worked fine but I suggest saving your JSON data into a variable before posting it is a little bit cleaner when sending a long form or dealing with large data in general.

_x000D_
_x000D_
var Data = {_x000D_
"name":"jonsa",_x000D_
"e-mail":"[email protected]",_x000D_
"phone":1223456789_x000D_
};_x000D_
_x000D_
_x000D_
$.ajax({_x000D_
    type: 'POST',_x000D_
    url: '/form/',_x000D_
    data: Data,_x000D_
    success: function(data) { alert('data: ' + data); },_x000D_
    contentType: "application/json",_x000D_
    dataType: 'json'_x000D_
});
_x000D_
_x000D_
_x000D_

Two Page Login with Spring Security 3.2.x

There should be three pages here:

  1. Initial login page with a form that asks for your username, but not your password.
  2. You didn't mention this one, but I'd check whether the client computer is recognized, and if not, then challenge the user with either a CAPTCHA or else a security question. Otherwise the phishing site can simply use the tendered username to query the real site for the security image, which defeats the purpose of having a security image. (A security question is probably better here since with a CAPTCHA the attacker could have humans sitting there answering the CAPTCHAs to get at the security images. Depends how paranoid you want to be.)
  3. A page after that that displays the security image and asks for the password.

I don't see this short, linear flow being sufficiently complex to warrant using Spring Web Flow.

I would just use straight Spring Web MVC for steps 1 and 2. I wouldn't use Spring Security for the initial login form, because Spring Security's login form expects a password and a login processing URL. Similarly, Spring Security doesn't provide special support for CAPTCHAs or security questions, so you can just use Spring Web MVC once again.

You can handle step 3 using Spring Security, since now you have a username and a password. The form login page should display the security image, and it should include the user-provided username as a hidden form field to make Spring Security happy when the user submits the login form. The only way to get to step 3 is to have a successful POST submission on step 1 (and 2 if applicable).

Javascript dynamic array of strings

Please check http://jsfiddle.net/GEBrW/ for live test.

You can use similar method for dynamic arrays creation.

var i = 0;
var a = new Array();

a[i++] = i;
a[i++] = i;
a[i++] = i;
a[i++] = i;
a[i++] = i;
a[i++] = i;
a[i++] = i;
a[i++] = i;

The result:

a[0] = 1
a[1] = 2
a[2] = 3
a[3] = 4
a[4] = 5
a[5] = 6
a[6] = 7
a[7] = 8

How to run php files on my computer

I just put the content in the question in a file called test.php and ran php test.php. (In the folder where the test.php is.)

$ php foo.php                                                                                                                                                                                                                                                                                                                                    
15

Switch to another branch without changing the workspace files

It sounds like you made changes, committing them to master along the way, and now you want to combine them into a single commit.

If so, you want to rebase your commits, squashing them into a single commit.

I'm not entirely sure of what exactly you want, so I'm not going to tempt you with a script. But I suggest you read up on git rebase and the options for "squash"ing, and try a few things out.

Check file extension in upload form in PHP

How to validate file extension (jpg/jpeg only) on a form before upload takes place. A variation on another posted answer here with an included data filter which may be useful when evaluating other posted form values. Note: error is left blank if empty as this was an option for my users, not a requirement.

<?php
if(isset($_POST['save'])) {

//Validate image
if (empty($_POST["image"])) {
$imageError = "";
} else {
$image = test_input($_POST["image"]);
$allowed =  array('jpeg','jpg');
$ext = pathinfo($image, PATHINFO_EXTENSION);
if(!in_array($ext,$allowed) ) {
$imageError = "jpeg only";
}
}

}

// Validate data
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
<?

Your html will look something like this;

<html>
<head>
</head>

<body>
<!-- Validate -->
<?php include_once ('validate.php'); ?>

<!-- Form -->
<form method="post" action="">

<!-- Image -->
<p>Image <?php echo $imageError; ?></p>
<input type="file" name="image" value="<?php echo $image; ?>" />

<p><input type="submit" name="save" value="SAVE" /></p>
</form>

</body>
</html>

PHP Regex to get youtube video ID?

For extracting the id in a capturing group, the following expression or some derivative of that might be an option too:

(?im)\b(?:https?:\/\/)?(?:w{3}\.)?youtu(?:be)?\.(?:com|be)\/(?:(?:\??v=?i?=?\/?)|watch\?vi?=|watch\?.*?&v=|embed\/|)([A-Z0-9_-]{11})\S*(?=\s|$)

Demo

Test

$re = '/(?im)\b(?:https?:\/\/)?(?:w{3}\.)?youtu(?:be)?\.(?:com|be)\/(?:(?:\??v=?i?=?\/?)|watch\?vi?=|watch\?.*?&v=|embed\/|)([A-Z0-9_-]{11})\S*(?=\s|$)/';
$str = 'http://youtube.com/v/tFad5gHoBjY
https://youtube.com/vi/tFad5gHoBjY
http://www.youtube.com/?v=tFad5gHoBjY
http://www.youtube.com/?vi=tFad5gHoBjY
https://www.youtube.com/watch?v=tFad5gHoBjY
youtube.com/watch?vi=tFad5gHoBjY
youtu.be/tFad5gHoBjY
http://youtu.be/qokEYBNWA_0?t=30m26s
youtube.com/v/7HCZvhRAk-M
youtube.com/vi/7HCZvhRAk-M
youtube.com/?v=7HCZvhRAk-M
youtube.com/?vi=7HCZvhRAk-M
youtube.com/watch?v=7HCZvhRAk-M
youtube.com/watch?vi=7HCZvhRAk-M
youtu.be/7HCZvhRAk-M
youtube.com/embed/7HCZvhRAk-M
http://youtube.com/v/7HCZvhRAk-M
http://www.youtube.com/v/7HCZvhRAk-M
https://www.youtube.com/v/7HCZvhRAk-M
youtube.com/watch?v=7HCZvhRAk-M&wtv=wtv
http://www.youtube.com/watch?dev=inprogress&v=7HCZvhRAk-M&feature=related
youtube.com/watch?v=7HCZvhRAk-M
http://youtube.com/v/dQw4w9WgXcQ?feature=youtube_gdata_player
http://youtube.com/vi/dQw4w9WgXcQ?feature=youtube_gdata_player
http://youtube.com/?v=dQw4w9WgXcQ&feature=youtube_gdata_player
http://www.youtube.com/watch?v=dQw4w9WgXcQ&feature=youtube_gdata_player
http://youtube.com/?vi=dQw4w9WgXcQ&feature=youtube_gdata_player
http://youtube.com/watch?v=dQw4w9WgXcQ&feature=youtube_gdata_player
http://youtube.com/watch?vi=dQw4w9WgXcQ&feature=youtube_gdata_player
http://youtu.be/dQw4w9WgXcQ?feature=youtube_gdata_player';

preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);

var_dump($matches);

Output

array(30) {
  [0]=>
  array(2) {
    [0]=>
    string(32) "http://youtube.com/v/tFad5gHoBjY"
    [1]=>
    string(11) "tFad5gHoBjY"
  }
  [1]=>
  array(2) {
    [0]=>
    string(34) "https://youtube.com/vi/tFad5gHoBjY"
    [1]=>
    string(11) "tFad5gHoBjY"
  }
  [2]=>
  array(2) {
    [0]=>
    string(37) "http://www.youtube.com/?v=tFad5gHoBjY"
    [1]=>
    string(11) "tFad5gHoBjY"
  }
  [3]=>
  array(2) {
    [0]=>
    string(38) "http://www.youtube.com/?vi=tFad5gHoBjY"
    [1]=>
    string(11) "tFad5gHoBjY"
  }
  [4]=>
  array(2) {
    [0]=>
    string(43) "https://www.youtube.com/watch?v=tFad5gHoBjY"
    [1]=>
    string(11) "tFad5gHoBjY"
  }
  [5]=>
  array(2) {
    [0]=>
    string(32) "youtube.com/watch?vi=tFad5gHoBjY"
    [1]=>
    string(11) "tFad5gHoBjY"
  }
  [6]=>
  array(2) {
    [0]=>
    string(20) "youtu.be/tFad5gHoBjY"
    [1]=>
    string(11) "tFad5gHoBjY"
  }
  [7]=>
  array(2) {
    [0]=>
    string(27) "http://youtu.be/qokEYBNWA_0"
    [1]=>
    string(11) "qokEYBNWA_0"
  }
  [8]=>
  array(2) {
    [0]=>
    string(25) "youtube.com/v/7HCZvhRAk-M"
    [1]=>
    string(11) "7HCZvhRAk-M"
  }
  [9]=>
  array(2) {
    [0]=>
    string(26) "youtube.com/vi/7HCZvhRAk-M"
    [1]=>
    string(11) "7HCZvhRAk-M"
  }
  [10]=>
  array(2) {
    [0]=>
    string(26) "youtube.com/?v=7HCZvhRAk-M"
    [1]=>
    string(11) "7HCZvhRAk-M"
  }
  [11]=>
  array(2) {
    [0]=>
    string(27) "youtube.com/?vi=7HCZvhRAk-M"
    [1]=>
    string(11) "7HCZvhRAk-M"
  }
  [12]=>
  array(2) {
    [0]=>
    string(31) "youtube.com/watch?v=7HCZvhRAk-M"
    [1]=>
    string(11) "7HCZvhRAk-M"
  }
  [13]=>
  array(2) {
    [0]=>
    string(32) "youtube.com/watch?vi=7HCZvhRAk-M"
    [1]=>
    string(11) "7HCZvhRAk-M"
  }
  [14]=>
  array(2) {
    [0]=>
    string(20) "youtu.be/7HCZvhRAk-M"
    [1]=>
    string(11) "7HCZvhRAk-M"
  }
  [15]=>
  array(2) {
    [0]=>
    string(29) "youtube.com/embed/7HCZvhRAk-M"
    [1]=>
    string(11) "7HCZvhRAk-M"
  }
  [16]=>
  array(2) {
    [0]=>
    string(32) "http://youtube.com/v/7HCZvhRAk-M"
    [1]=>
    string(11) "7HCZvhRAk-M"
  }
  [17]=>
  array(2) {
    [0]=>
    string(36) "http://www.youtube.com/v/7HCZvhRAk-M"
    [1]=>
    string(11) "7HCZvhRAk-M"
  }
  [18]=>
  array(2) {
    [0]=>
    string(37) "https://www.youtube.com/v/7HCZvhRAk-M"
    [1]=>
    string(11) "7HCZvhRAk-M"
  }
  [19]=>
  array(2) {
    [0]=>
    string(31) "youtube.com/watch?v=7HCZvhRAk-M"
    [1]=>
    string(11) "7HCZvhRAk-M"
  }
  [20]=>
  array(2) {
    [0]=>
    string(57) "http://www.youtube.com/watch?dev=inprogress&v=7HCZvhRAk-M"
    [1]=>
    string(11) "7HCZvhRAk-M"
  }
  [21]=>
  array(2) {
    [0]=>
    string(31) "youtube.com/watch?v=7HCZvhRAk-M"
    [1]=>
    string(11) "7HCZvhRAk-M"
  }
  [22]=>
  array(2) {
    [0]=>
    string(32) "http://youtube.com/v/dQw4w9WgXcQ"
    [1]=>
    string(11) "dQw4w9WgXcQ"
  }
  [23]=>
  array(2) {
    [0]=>
    string(33) "http://youtube.com/vi/dQw4w9WgXcQ"
    [1]=>
    string(11) "dQw4w9WgXcQ"
  }
  [24]=>
  array(2) {
    [0]=>
    string(33) "http://youtube.com/?v=dQw4w9WgXcQ"
    [1]=>
    string(11) "dQw4w9WgXcQ"
  }
  [25]=>
  array(2) {
    [0]=>
    string(42) "http://www.youtube.com/watch?v=dQw4w9WgXcQ"
    [1]=>
    string(11) "dQw4w9WgXcQ"
  }
  [26]=>
  array(2) {
    [0]=>
    string(34) "http://youtube.com/?vi=dQw4w9WgXcQ"
    [1]=>
    string(11) "dQw4w9WgXcQ"
  }
  [27]=>
  array(2) {
    [0]=>
    string(38) "http://youtube.com/watch?v=dQw4w9WgXcQ"
    [1]=>
    string(11) "dQw4w9WgXcQ"
  }
  [28]=>
  array(2) {
    [0]=>
    string(39) "http://youtube.com/watch?vi=dQw4w9WgXcQ"
    [1]=>
    string(11) "dQw4w9WgXcQ"
  }
  [29]=>
  array(2) {
    [0]=>
    string(27) "http://youtu.be/dQw4w9WgXcQ"
    [1]=>
    string(11) "dQw4w9WgXcQ"
  }
}

If you wish to simplify/modify/explore the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.


RegEx Circuit

jex.im visualizes regular expressions:

enter image description here


How to set proxy for wget?

In Debian Linux wget can be configured to use a proxy both via environment variables and via wgetrc. In both cases the variable names to be used for HTTP and HTTPS connections are

http_proxy=hostname_or_IP:portNumber
https_proxy=hostname_or_IP:portNumber

Note that the file /etc/wgetrc takes precedence over the environment variables, hence if your system has a proxy configured there and you try to use the environment variables, they would seem to have no effect!

Alternative to file_get_contents?

If you have it available, using curl is your best option.

You can see if it is enabled by doing phpinfo() and searching the page for curl.

If it is enabled, try this:

$curl_handle=curl_init();
curl_setopt($curl_handle, CURLOPT_URL, SITE_PATH . 'cms/data.php');
$xml_file = curl_exec($curl_handle);
curl_close($curl_handle);

How to listen for 'props' changes

Not sure if you have resolved it (and if I understand correctly), but here's my idea:

If parent receives myProp, and you want it to pass to child and watch it in child, then parent has to have copy of myProp (not reference).

Try this:

new Vue({
  el: '#app',
  data: {
    text: 'Hello'
  },
  components: {
    'parent': {
      props: ['myProp'],
      computed: {
        myInnerProp() { return myProp.clone(); } //eg. myProp.slice() for array
      }
    },
    'child': {
      props: ['myProp'],
      watch: {
        myProp(val, oldval) { now val will differ from oldval }
      }
    }
  }
}

and in html:

<child :my-prop="myInnerProp"></child>

actually you have to be very careful when working on complex collections in such situations (passing down few times)

Use curly braces to initialize a Set in Python

There are two obvious issues with the set literal syntax:

my_set = {'foo', 'bar', 'baz'}
  1. It's not available before Python 2.7

  2. There's no way to express an empty set using that syntax (using {} creates an empty dict)

Those may or may not be important to you.

The section of the docs outlining this syntax is here.

String to HashMap JAVA

try

 String s = "SALES:0,SALE_PRODUCTS:1,EXPENSES:2,EXPENSES_ITEMS:3";
    HashMap<String,Integer> hm =new HashMap<String,Integer>();
    for(String s1:s.split(",")){
       String[] s2 = s1.split(":");
        hm.put(s2[0], Integer.parseInt(s2[1]));
    }

Increasing Heap Size on Linux Machines

You can use the following code snippet :

java -XX:+PrintFlagsFinal -Xms512m -Xmx1024m -Xss512k -XX:PermSize=64m -XX:MaxPermSize=128m
    -version | grep -iE 'HeapSize|PermSize|ThreadStackSize'

In my pc I am getting following output :

    uintx InitialHeapSize                          := 536870912       {product}
    uintx MaxHeapSize                              := 1073741824      {product}
    uintx PermSize                                 := 67108864        {pd product}
    uintx MaxPermSize                              := 134217728       {pd product}
     intx ThreadStackSize                          := 512             {pd product}

How to read until end of file (EOF) using BufferedReader in Java?

You are consuming a line at, which is discarded

while((str=input.readLine())!=null && str.length()!=0)

and reading a bigint at

BigInteger n = new BigInteger(input.readLine());

so try getting the bigint from string which is read as

BigInteger n = new BigInteger(str);

   Constructor used: BigInteger(String val)

Aslo change while((str=input.readLine())!=null && str.length()!=0) to

while((str=input.readLine())!=null)

see related post string to bigint

readLine()
Returns:
    A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached 

see javadocs

String representation of an Enum

I'm with Harvey but don't use const. I can mix and match string, int, whatever.

public class xlsLayout
{
    public int xlHeaderRow = 1;
    public int xlFirstDataRow = 2;
    public int xlSkipLinesBetweenFiles = 1; //so 0 would mean don't skip
    public string xlFileColumn = "A";
    public string xlFieldColumn = "B";
    public string xlFreindlyNameColumn = "C";
    public string xlHelpTextColumn = "D";
}

Then later ...

public partial class Form1 : Form
{
    xlsLayout xlLayout = new xlsLayout();

    xl.SetCell(xlLayout.xlFileColumn, xlLayout.xlHeaderRow, "File Name");
    xl.SetCell(xlLayout.xlFieldColumn, xlLayout.xlHeaderRow, "Code field name");
    xl.SetCell(xlLayout.xlFreindlyNameColumn, xlLayout.xlHeaderRow, "Freindly name");
    xl.SetCell(xlLayout.xlHelpTextColumn, xlLayout.xlHeaderRow, "Inline Help Text");
}

How to change the name of an iOS app?

You change the bundle display name in the info.plist. It's as simple as that.

Changing the 'bundle display name' (as opposed to 'bundle name') is the only way to include characters like '+' in your applications name. Including special characters in the project name will cause an error when uploading to the app store!

align 3 images in same row with equal spaces?

The modern approach: flexbox

Simply add the following CSS to the container element (here, the div):

div {
  display: flex;
  justify-content: space-between;
}

_x000D_
_x000D_
div {_x000D_
  display: flex;_x000D_
  justify-content: space-between;_x000D_
}
_x000D_
<div>_x000D_
 <img src="http://placehold.it/100x100" alt=""  /> _x000D_
 <img src="http://placehold.it/100x100" alt=""  />_x000D_
 <img src="http://placehold.it/100x100" alt="" />_x000D_
</div>
_x000D_
_x000D_
_x000D_

The old way (for ancient browsers - prior to flexbox)

Use text-align: justify; on the container element.

Then stretch the content to take up 100% width

MARKUP

<div>
 <img src="http://placehold.it/100x100" alt=""  /> 
 <img src="http://placehold.it/100x100" alt=""  />
 <img src="http://placehold.it/100x100" alt="" />
</div>

CSS

div {
    text-align: justify;
}

div img {
    display: inline-block;
    width: 100px;
    height: 100px;
}

div:after {
    content: '';
    display: inline-block;
    width: 100%;
}

_x000D_
_x000D_
div {_x000D_
    text-align: justify;_x000D_
}_x000D_
_x000D_
div img {_x000D_
    display: inline-block;_x000D_
    width: 100px;_x000D_
    height: 100px;_x000D_
}_x000D_
_x000D_
div:after {_x000D_
    content: '';_x000D_
    display: inline-block;_x000D_
    width: 100%;_x000D_
}
_x000D_
<div>_x000D_
 <img src="http://placehold.it/100x100" alt=""  /> _x000D_
 <img src="http://placehold.it/100x100" alt=""  />_x000D_
 <img src="http://placehold.it/100x100" alt="" />_x000D_
</div>
_x000D_
_x000D_
_x000D_

How many concurrent AJAX (XmlHttpRequest) requests are allowed in popular browsers?

Wrote my own test. tested the code on stackoverflow, works fine tells me that chrome/FF can do 6

var change = 0;
var simultanius = 0;
var que = 20; // number of tests

Array(que).join(0).split(0).forEach(function(a,i){
    var xhr = new XMLHttpRequest;
    xhr.open("GET", "/?"+i); // cacheBust
    xhr.onreadystatechange = function() {
        if(xhr.readyState == 2){
            change++;
            simultanius = Math.max(simultanius, change);
        }
        if(xhr.readyState == 4){
            change--;
            que--;
            if(!que){
                console.log(simultanius);
            }
        }
    };
    xhr.send();
});

it works for most websites that can trigger readystate change event at different times. (aka: flushing)

I notice on my node.js server that i had to output at least 1025 bytes to trigger the event/flush. otherwise the events would just trigger all three state at once when the request is complete so here is my backend:

var app = require('express')();

app.get("/", function(req,res) {
    res.write(Array(1025).join("a"));
    setTimeout(function() {
        res.end("a");
    },500);
});

app.listen(80);

Update

I notice that You can now have up to 2x request if you are using both xhr and fetch api at the same time

_x000D_
_x000D_
var change = 0;_x000D_
var simultanius = 0;_x000D_
var que = 30; // number of tests_x000D_
_x000D_
Array(que).join(0).split(0).forEach(function(a,i){_x000D_
    fetch("/?b"+i).then(r => {_x000D_
        change++;_x000D_
        simultanius = Math.max(simultanius, change);_x000D_
        return r.text()_x000D_
    }).then(r => {_x000D_
        change--;_x000D_
        que--;_x000D_
        if(!que){_x000D_
            console.log(simultanius);_x000D_
        }_x000D_
    });_x000D_
});_x000D_
_x000D_
Array(que).join(0).split(0).forEach(function(a,i){_x000D_
    var xhr = new XMLHttpRequest;_x000D_
    xhr.open("GET", "/?a"+i); // cacheBust_x000D_
    xhr.onreadystatechange = function() {_x000D_
        if(xhr.readyState == 2){_x000D_
            change++;_x000D_
            simultanius = Math.max(simultanius, change);_x000D_
        }_x000D_
        if(xhr.readyState == 4){_x000D_
            change--;_x000D_
            que--;_x000D_
            if(!que){_x000D_
                document.body.innerHTML = simultanius;_x000D_
            }_x000D_
        }_x000D_
    };_x000D_
    xhr.send();_x000D_
});
_x000D_
_x000D_
_x000D_

Using psql to connect to PostgreSQL in SSL mode

psql -h <host> -p <port> -U <user> -d <db>

and update /var/lib/pgsql/10/data/pg_hba.conf to change the auth method to cert. Check the following link for more information:

https://www.postgresql.org/docs/9.1/auth-pg-hba-conf.html

How to get all groups that a user is a member of?

Almost all above solutions used the ActiveDirecotry module which might not be available by default in most cases.

I used below method. A bit indirect, but served my purpose.

List all available groups

Get-WmiObject -Class Win32_Group

And then list the groups the user belongs to

[System.Security.Principal.WindowsIdentity]::GetCurrent().Groups

Comparison can then be done via checking through the SIDs. This works for the logged in user. Please correct me if I am wrong. Completely new to PowerShell, but had to get this done for a work commitment.

How to emulate a BEFORE INSERT trigger in T-SQL / SQL Server for super/subtype (Inheritance) entities?

While Andriy's proposal will work well for INSERTs of a small number of records, full table scans will be done on the final join as both 'enumerated' and '@new_super' are not indexed, resulting in poor performance for large inserts.

This can be resolved by specifying a primary key on the @new_super table, as follows:

DECLARE @new_super TABLE (
  row_num INT IDENTITY(1,1) PRIMARY KEY CLUSTERED,
  super_id   int
);

This will result in the SQL optimizer scanning through the 'enumerated' table but doing an indexed join on @new_super to get the new key.

How to play video with AVPlayerViewController (AVKit) in Swift

Swift 5.0

Improved from @ingconti answer . This worked for me.

 if let url = URL(string: "urUrlString"){
            let player = AVPlayer(url: url)
            let avController = AVPlayerViewController()
            avController.player = player
            // your desired frame
            avController.view.frame = self.view.frame
            self.view.addSubview(avController.view)
            self.addChild(avController)
            player.play()
        }

What is the best way to access redux store outside a react component?

Like @sanchit proposed middleware is a nice solution if you are already defining your axios instance globally.

You can create a middleware like:

function createAxiosAuthMiddleware() {
  return ({ getState }) => next => (action) => {
    const { token } = getState().authentication;
    global.axios.defaults.headers.common.Authorization = token ? `Bearer ${token}` : null;

    return next(action);
  };
}

const axiosAuth = createAxiosAuthMiddleware();

export default axiosAuth;

And use it like this:

import { createStore, applyMiddleware } from 'redux';
const store = createStore(reducer, applyMiddleware(axiosAuth))

It will set the token on every action but you could only listen for actions that change the token for example.

How do we control web page caching, across all browsers?

As @Kornel stated, what you want is not to deactivate the cache, but to deactivate the history buffer. Different browsers have their own subtle ways to disable the history buffer.

In Chrome (v28.0.1500.95 m) we can do this only by Cache-Control: no-store.

In FireFox (v23.0.1) any one of these will work:

  1. Cache-Control: no-store

  2. Cache-Control: no-cache (https only)

  3. Pragma: no-cache (https only)

  4. Vary: * (https only)

In Opera (v12.15) we only can do this by Cache-Control: must-revalidate (https only).

In Safari (v5.1.7, 7534.57.2) any one of these will work:

  1. Cache-Control: no-store
    <body onunload=""> in html

  2. Cache-Control: no-store (https only)

In IE8 (v8.0.6001.18702IC) any one of these will work:

  1. Cache-Control: must-revalidate, max-age=0

  2. Cache-Control: no-cache

  3. Cache-Control: no-store

  4. Cache-Control: must-revalidate
    Expires: 0

  5. Cache-Control: must-revalidate
    Expires: Sat, 12 Oct 1991 05:00:00 GMT

  6. Pragma: no-cache (https only)

  7. Vary: * (https only)

Combining the above gives us this solution which works for Chrome 28, FireFox 23, IE8, Safari 5.1.7, and Opera 12.15: Cache-Control: no-store, must-revalidate (https only)

Note that https is needed because Opera wouldn't deactivate history buffer for plain http pages. If you really can't get https and you are prepared to ignore Opera, the best you can do is this:

Cache-Control: no-store
<body onunload="">

Below shows the raw logs of my tests:

HTTP:

  1. Cache-Control: private, no-cache, no-store, must-revalidate, max-age=0, proxy-revalidate, s-maxage=0
    Expires: 0
    Pragma: no-cache
    Vary: *
    <body onunload="">
    Fail: Opera 12.15
    Success: Chrome 28, FireFox 23, IE8, Safari 5.1.7

  2. Cache-Control: private, no-cache, no-store, must-revalidate, max-age=0, proxy-revalidate, s-maxage=0
    Expires: Sat, 12 Oct 1991 05:00:00 GMT
    Pragma: no-cache
    Vary: *
    <body onunload="">
    Fail: Opera 12.15
    Success: Chrome 28, FireFox 23, IE8, Safari 5.1.7

  3. Cache-Control: private, no-cache, no-store, must-revalidate, max-age=0, proxy-revalidate, s-maxage=0
    Expires: 0
    Pragma: no-cache
    Vary: *
    Fail: Safari 5.1.7, Opera 12.15
    Success: Chrome 28, FireFox 23, IE8

  4. Cache-Control: private, no-cache, no-store, must-revalidate, max-age=0, proxy-revalidate, s-maxage=0
    Expires: Sat, 12 Oct 1991 05:00:00 GMT
    Pragma: no-cache
    Vary: *
    Fail: Safari 5.1.7, Opera 12.15
    Success: Chrome 28, FireFox 23, IE8

  5. Cache-Control: private, no-cache, must-revalidate, max-age=0, proxy-revalidate, s-maxage=0
    Expires: 0
    Pragma: no-cache
    Vary: *
    <body onunload="">
    Fail: Chrome 28, FireFox 23, Safari 5.1.7, Opera 12.15
    Success: IE8

  6. Cache-Control: private, no-cache, must-revalidate, max-age=0, proxy-revalidate, s-maxage=0
    Expires: Sat, 12 Oct 1991 05:00:00 GMT
    Pragma: no-cache
    Vary: *
    <body onunload="">
    Fail: Chrome 28, FireFox 23, Safari 5.1.7, Opera 12.15
    Success: IE8

  7. Cache-Control: private, no-cache, must-revalidate, max-age=0, proxy-revalidate, s-maxage=0
    Expires: 0
    Pragma: no-cache
    Vary: *
    <body onunload="">
    Fail: Chrome 28, FireFox 23, Safari 5.1.7, Opera 12.15
    Success: IE8

  8. Cache-Control: private, no-cache, must-revalidate, max-age=0, proxy-revalidate, s-maxage=0
    Expires: Sat, 12 Oct 1991 05:00:00 GMT
    Pragma: no-cache
    Vary: *
    <body onunload="">
    Fail: Chrome 28, FireFox 23, Safari 5.1.7, Opera 12.15
    Success: IE8

  9. Cache-Control: no-store
    Fail: Safari 5.1.7, Opera 12.15
    Success: Chrome 28, FireFox 23, IE8

  10. Cache-Control: no-store
    <body onunload="">
    Fail: Opera 12.15
    Success: Chrome 28, FireFox 23, IE8, Safari 5.1.7

  11. Cache-Control: no-cache
    Fail: Chrome 28, FireFox 23, Safari 5.1.7, Opera 12.15
    Success: IE8

  12. Vary: *
    Fail: Chrome 28, FireFox 23, IE8, Safari 5.1.7, Opera 12.15
    Success: none

  13. Pragma: no-cache
    Fail: Chrome 28, FireFox 23, IE8, Safari 5.1.7, Opera 12.15
    Success: none

  14. Cache-Control: private, no-cache, must-revalidate, max-age=0, proxy-revalidate, s-maxage=0
    Expires: Sat, 12 Oct 1991 05:00:00 GMT
    Pragma: no-cache
    Vary: *
    <body onunload="">
    Fail: Chrome 28, FireFox 23, Safari 5.1.7, Opera 12.15
    Success: IE8

  15. Cache-Control: private, no-cache, must-revalidate, max-age=0, proxy-revalidate, s-maxage=0
    Expires: 0
    Pragma: no-cache
    Vary: *
    <body onunload="">
    Fail: Chrome 28, FireFox 23, Safari 5.1.7, Opera 12.15
    Success: IE8

  16. Cache-Control: must-revalidate, max-age=0
    Fail: Chrome 28, FireFox 23, Safari 5.1.7, Opera 12.15
    Success: IE8

  17. Cache-Control: must-revalidate
    Expires: 0
    Fail: Chrome 28, FireFox 23, Safari 5.1.7, Opera 12.15
    Success: IE8

  18. Cache-Control: must-revalidate
    Expires: Sat, 12 Oct 1991 05:00:00 GMT
    Fail: Chrome 28, FireFox 23, Safari 5.1.7, Opera 12.15
    Success: IE8

  19. Cache-Control: private, must-revalidate, proxy-revalidate, s-maxage=0
    Pragma: no-cache
    Vary: *
    <body onunload="">
    Fail: Chrome 28, FireFox 23, IE8, Safari 5.1.7, Opera 12.15
    Success: none

HTTPS:

  1. Cache-Control: private, max-age=0, proxy-revalidate, s-maxage=0
    Expires: 0
    <body onunload="">
    Fail: Chrome 28, FireFox 23, IE8, Safari 5.1.7, Opera 12.15
    Success: none

  2. Cache-Control: private, max-age=0, proxy-revalidate, s-maxage=0
    Expires: Sat, 12 Oct 1991 05:00:00 GMT
    <body onunload="">
    Fail: Chrome 28, FireFox 23, IE8, Safari 5.1.7, Opera 12.15
    Success: none

  3. Vary: *
    Fail: Chrome 28, Safari 5.1.7, Opera 12.15
    Success: FireFox 23, IE8

  4. Pragma: no-cache
    Fail: Chrome 28, Safari 5.1.7, Opera 12.15
    Success: FireFox 23, IE8

  5. Cache-Control: no-cache
    Fail: Chrome 28, Safari 5.1.7, Opera 12.15
    Success: FireFox 23, IE8

  6. Cache-Control: private, no-cache, max-age=0, proxy-revalidate, s-maxage=0
    Fail: Chrome 28, Safari 5.1.7, Opera 12.15
    Success: FireFox 23, IE8

  7. Cache-Control: private, no-cache, max-age=0, proxy-revalidate, s-maxage=0
    Expires: 0
    Pragma: no-cache
    Vary: *
    Fail: Chrome 28, Safari 5.1.7, Opera 12.15
    Success: FireFox 23, IE8

  8. Cache-Control: private, no-cache, max-age=0, proxy-revalidate, s-maxage=0
    Expires: Sat, 12 Oct 1991 05:00:00 GMT
    Pragma: no-cache
    Vary: *
    Fail: Chrome 28, Safari 5.1.7, Opera 12.15
    Success: FireFox 23, IE8

  9. Cache-Control: must-revalidate
    Fail: Chrome 28, FireFox 23, IE8, Safari 5.1.7
    Success: Opera 12.15

  10. Cache-Control: private, must-revalidate, proxy-revalidate, s-maxage=0
    <body onunload="">
    Fail: Chrome 28, FireFox 23, IE8, Safari 5.1.7
    Success: Opera 12.15

  11. Cache-Control: must-revalidate, max-age=0
    Fail: Chrome 28, FireFox 23, Safari 5.1.7
    Success: IE8, Opera 12.15

  12. Cache-Control: private, no-cache, must-revalidate, max-age=0, proxy-revalidate, s-maxage=0
    Expires: Sat, 12 Oct 1991 05:00:00 GMT
    Pragma: no-cache
    Vary: *
    <body onunload="">
    Fail: Chrome 28, Safari 5.1.7
    Success: FireFox 23, IE8, Opera 12.15

  13. Cache-Control: private, no-cache, must-revalidate, max-age=0, proxy-revalidate, s-maxage=0
    Expires: 0
    Pragma: no-cache
    Vary: *
    <body onunload="">
    Fail: Chrome 28, Safari 5.1.7
    Success: FireFox 23, IE8, Opera 12.15

  14. Cache-Control: no-store
    Fail: Opera 12.15
    Success: Chrome 28, FireFox 23, IE8, Safari 5.1.7

  15. Cache-Control: private, no-cache, no-store, max-age=0, proxy-revalidate, s-maxage=0
    Expires: 0
    Pragma: no-cache
    Vary: *
    <body onunload="">
    Fail: Opera 12.15
    Success: Chrome 28, FireFox 23, IE8, Safari 5.1.7

  16. Cache-Control: private, no-cache, no-store, max-age=0, proxy-revalidate, s-maxage=0
    Expires: Sat, 12 Oct 1991 05:00:00 GMT
    Pragma: no-cache
    Vary: *
    <body onunload="">
    Fail: Opera 12.15
    Success: Chrome 28, FireFox 23, IE8, Safari 5.1.7

  17. Cache-Control: private, no-cache
    Expires: Sat, 12 Oct 1991 05:00:00 GMT
    Pragma: no-cache
    Vary: *
    Fail: Chrome 28, Safari 5.1.7, Opera 12.15
    Success: FireFox 23, IE8

  18. Cache-Control: must-revalidate
    Expires: 0
    Fail: Chrome 28, FireFox 23, Safari 5.1.7,
    Success: IE8, Opera 12.15

  19. Cache-Control: must-revalidate
    Expires: Sat, 12 Oct 1991 05:00:00 GMT
    Fail: Chrome 28, FireFox 23, Safari 5.1.7,
    Success: IE8, Opera 12.15

  20. Cache-Control: private, must-revalidate, max-age=0, proxy-revalidate, s-maxage=0
    Expires: 0
    <body onunload="">
    Fail: Chrome 28, FireFox 23, Safari 5.1.7,
    Success: IE8, Opera 12.15

  21. Cache-Control: private, must-revalidate, max-age=0, proxy-revalidate, s-maxage=0
    Expires: Sat, 12 Oct 1991 05:00:00 GMT
    <body onunload="">
    Fail: Chrome 28, FireFox 23, Safari 5.1.7,
    Success: IE8, Opera 12.15

  22. Cache-Control: private, must-revalidate
    Expires: Sat, 12 Oct 1991 05:00:00 GMT
    Pragma: no-cache
    Vary: *
    Fail: Chrome 28, Safari 5.1.7
    Success: FireFox 23, IE8, Opera 12.15

  23. Cache-Control: no-store, must-revalidate
    Fail: none
    Success: Chrome 28, FireFox 23, IE8, Safari 5.1.7, Opera 12.15

Are there any style options for the HTML5 Date picker?

The following eight pseudo-elements are made available by WebKit for customizing a date input’s textbox:

::-webkit-datetime-edit
::-webkit-datetime-edit-fields-wrapper
::-webkit-datetime-edit-text
::-webkit-datetime-edit-month-field
::-webkit-datetime-edit-day-field
::-webkit-datetime-edit-year-field
::-webkit-inner-spin-button
::-webkit-calendar-picker-indicator

So if you thought the date input could use more spacing and a ridiculous color scheme you could add the following:

_x000D_
_x000D_
::-webkit-datetime-edit { padding: 1em; }_x000D_
::-webkit-datetime-edit-fields-wrapper { background: silver; }_x000D_
::-webkit-datetime-edit-text { color: red; padding: 0 0.3em; }_x000D_
::-webkit-datetime-edit-month-field { color: blue; }_x000D_
::-webkit-datetime-edit-day-field { color: green; }_x000D_
::-webkit-datetime-edit-year-field { color: purple; }_x000D_
::-webkit-inner-spin-button { display: none; }_x000D_
::-webkit-calendar-picker-indicator { background: orange; }
_x000D_
<input type="date">
_x000D_
_x000D_
_x000D_

Screenshot

Google drive limit number of download

It looks like that this limitation can be avoided if you use the following URL pattern:

https://googledrive.com/host/file-id

For your case the download URL will look like this - https://googledrive.com/host/0ByvXJAlpPqQPYWNqY0V3MGs0Ujg

Please keep in mind that this method works only if file is shared with "Public on the web" option.

Iterate over object in Angular

Angular 2.x && Angular 4.x do not support this out of the box

You can use this two pipes to iterate either by key or by value.

Keys pipe:

import {Pipe, PipeTransform} from '@angular/core'

@Pipe({
  name: 'keys',
  pure: false
})
export class KeysPipe implements PipeTransform {
  transform(value: any, args: any[] = null): any {
    return Object.keys(value)
  }
}

Values pipe:

import {Pipe, PipeTransform} from '@angular/core'

@Pipe({
  name: 'values',
  pure: false
})
export class ValuesPipe implements PipeTransform {
  transform(value: any, args: any[] = null): any {
    return Object.keys(value).map(key => value[key])
  }
}

How to use:

let data = {key1: 'value1', key2: 'value2'}

<div *ngFor="let key of data | keys"></div>
<div *ngFor="let value of data | values"></div>

Dockerfile if else condition with external arguments

You can use the conditional system that best fits your needs.

Dockerfile

ARG ENV

FROM foo as base

ARG ENV

# run common
RUN ...

# For long running tasks that would slow down deployments
RUN if [[ "$ENV" == "dev" ]] ; then \
        yum install -y lots of big dev packages ; \
    fi

# Build dev image
FROM base as image-dev

RUN ...
COPY ...

# Build prod image
FROM base as image-prod

RUN ...
COPY ...

FROM image-$ENV AS final

Note that we define ENV twice - you need to define ENV globally, and in each image where it is used.

Use docker:

docker build -t my_docker . --build-arg ENV="dev"

Use docker-compose:

version: '3'

services:

  dev:
    container_name: dev
    ports:
      - 3000:8080
    volumes:
      - ./:/var/task
    tty: true
    build:
      context: .
      dockerfile: Dockerfile
      args:
        ENV: dev
docker-compose build --no-cache dev && docker-compose up dev

generating variable names on fly in python

If you really want to create them on the fly you can assign to the dict that is returned by either globals() or locals() depending on what namespace you want to create them in:

globals()['somevar'] = 'someval'
print somevar  # prints 'someval'

But I wouldn't recommend doing that. In general, avoid global variables. Using locals() often just obscures what you are really doing. Instead, create your own dict and assign to it.

mydict = {}
mydict['somevar'] = 'someval'
print mydict['somevar']

Learn the python zen; run this and grok it well:

>>> import this

Why does JPA have a @Transient annotation?

Java's transient keyword is used to denote that a field is not to be serialized, whereas JPA's @Transient annotation is used to indicate that a field is not to be persisted in the database, i.e. their semantics are different.

Spring: how do I inject an HttpServletRequest into a request-scoped bean?

As suggested here you can also inject the HttpServletRequest as a method param, e.g.:

public MyResponseObject myApiMethod(HttpServletRequest request, ...) {
    ...
}

Detect if checkbox is checked or unchecked in Angular.js ng-change event

The state of the checkbox will be reflected on whatever model you have it bound to, in this case, $scope.answers[item.questID]

Check which element has been clicked with jQuery

Use this, I think I can get your idea.

Live demo: http://jsfiddle.net/oscarj24/h722g/1/

$('body').click(function(e) {

    var target = $(e.target), article;

    if (target.is('#news_gallery li .over')) {
       article = $('#news-article .news-article');
    } else if (target.is('#work_gallery li .over')) {
       article = $('#work-article .work-article');
    } else if (target.is('#search-item li')) {
       article = $('#search-item .search-article');
    }

    if (article) {
       // Do Something
    }
});?

Android - Start service on boot

Your Service may be getting shut down before it completes due to the device going to sleep after booting. You need to obtain a wake lock first. Luckily, the Support library gives us a class to do this:

public class SimpleWakefulReceiver extends WakefulBroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        // This is the Intent to deliver to our service.
        Intent service = new Intent(context, SimpleWakefulService.class);

        // Start the service, keeping the device awake while it is launching.
        Log.i("SimpleWakefulReceiver", "Starting service @ " + SystemClock.elapsedRealtime());
        startWakefulService(context, service);
    }
}

then, in your Service, make sure to release the wake lock:

    @Override
    protected void onHandleIntent(Intent intent) {
        // At this point SimpleWakefulReceiver is still holding a wake lock
        // for us.  We can do whatever we need to here and then tell it that
        // it can release the wakelock.

...
        Log.i("SimpleWakefulReceiver", "Completed service @ " + SystemClock.elapsedRealtime());
        SimpleWakefulReceiver.completeWakefulIntent(intent);
    }

Don't forget to add the WAKE_LOCK permission:

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.WAKE_LOCK" />

How to Delete a topic in apache kafka

Deletion of a topic has been supported since 0.8.2.x version. You have to enable topic deletion (setting delete.topic.enable to true) on all brokers first.

Note: Ever since 1.0.x, the functionality being stable, delete.topic.enable is by default true.

Follow this step by step process for manual deletion of topics

  1. Stop Kafka server
  2. Delete the topic directory, on each broker (as defined in the logs.dirs and log.dir properties) with rm -rf command
  3. Connect to Zookeeper instance: zookeeper-shell.sh host:port
  4. From within the Zookeeper instance:
    1. List the topics using: ls /brokers/topics
    2. Remove the topic folder from ZooKeeper using: rmr /brokers/topics/yourtopic
    3. Exit the Zookeeper instance (Ctrl+C)
  5. Restart Kafka server
  6. Confirm if it was deleted or not by using this command kafka-topics.sh --list --zookeeper host:port

docker: "build" requires 1 argument. See 'docker build --help'

enter image description hereJust provide dot (.) at the end of command including one space.

example:

command: docker build -t "blink:v1" .

Here you can see "blink:v1" then a space then dot(.)

Thats it.

Bootstrap modal: close current, open new

With BootStrap 3, you can try this:-

var visible_modal = jQuery('.modal.in').attr('id'); // modalID or undefined
if (visible_modal) { // modal is active
    jQuery('#' + visible_modal).modal('hide'); // close modal
}

Tested to work with: http://getbootstrap.com/javascript/#modals (click on "Launch Demo Modal" first).

REST API - Bulk Create or Update in single request

I think that you could use a POST or PATCH method to handle this since they typically design for this.

  • Using a POST method is typically used to add an element when used on list resource but you can also support several actions for this method. See this answer: How to Update a REST Resource Collection. You can also support different representation formats for the input (if they correspond to an array or a single elements).

    In the case, it's not necessary to define your format to describe the update.

  • Using a PATCH method is also suitable since corresponding requests correspond to a partial update. According to RFC5789 (http://tools.ietf.org/html/rfc5789):

    Several applications extending the Hypertext Transfer Protocol (HTTP) require a feature to do partial resource modification. The existing HTTP PUT method only allows a complete replacement of a document. This proposal adds a new HTTP method, PATCH, to modify an existing HTTP resource.

    In the case, you have to define your format to describe the partial update.

I think that in this case, POST and PATCH are quite similar since you don't really need to describe the operation to do for each element. I would say that it depends on the format of the representation to send.

The case of PUT is a bit less clear. In fact, when using a method PUT, you should provide the whole list. As a matter of fact, the provided representation in the request will be in replacement of the list resource one.

You can have two options regarding the resource paths.

  • Using the resource path for doc list

In this case, you need to explicitely provide the link of docs with a binder in the representation you provide in the request.

Here is a sample route for this /docs.

The content of such approach could be for method POST:

[
    { "doc_number": 1, "binder": 4, (other fields in the case of creation) },
    { "doc_number": 2, "binder": 4, (other fields in the case of creation) },
    { "doc_number": 3, "binder": 5, (other fields in the case of creation) },
    (...)
]
  • Using sub resource path of binder element

In addition you could also consider to leverage sub routes to describe the link between docs and binders. The hints regarding the association between a doc and a binder doesn't have now to be specified within the request content.

Here is a sample route for this /binder/{binderId}/docs. In this case, sending a list of docs with a method POST or PATCH will attach docs to the binder with identifier binderId after having created the doc if it doesn't exist.

The content of such approach could be for method POST:

[
    { "doc_number": 1, (other fields in the case of creation) },
    { "doc_number": 2, (other fields in the case of creation) },
    { "doc_number": 3, (other fields in the case of creation) },
    (...)
]

Regarding the response, it's up to you to define the level of response and the errors to return. I see two levels: the status level (global level) and the payload level (thinner level). It's also up to you to define if all the inserts / updates corresponding to your request must be atomic or not.

  • Atomic

In this case, you can leverage the HTTP status. If everything goes well, you get a status 200. If not, another status like 400 if the provided data aren't correct (for example binder id not valid) or something else.

  • Non atomic

In this case, a status 200 will be returned and it's up to the response representation to describe what was done and where errors eventually occur. ElasticSearch has an endpoint in its REST API for bulk update. This could give you some ideas at this level: http://www.elasticsearch.org/guide/en/elasticsearch/guide/current/bulk.html.

  • Asynchronous

You can also implement an asynchronous processing to handle the provided data. In this case, the HTTP status returns will be 202. The client needs to pull an additional resource to see what happens.

Before finishing, I also would want to notice that the OData specification addresses the issue regarding relations between entities with the feature named navigation links. Perhaps could you have a look at this ;-)

The following link can also help you: https://templth.wordpress.com/2014/12/15/designing-a-web-api/.

Hope it helps you, Thierry

Is there a cross-browser onload event when clicking the back button?

I have used an html template. In this template's custom.js file, there was a function like this:

    jQuery(document).ready(function($) {

       $(window).on('load', function() {
          //...
       });

    });

But this function was not working when I go to back after go to other page.

So, I tried this and it has worked:

    jQuery(document).ready(function($) {
       //...
    });

   //Window Load Start
   window.addEventListener('load', function() {
       jQuery(document).ready(function($) {
          //...
       });
   });

Now, I have 2 "ready" function but it doesn't give any error and the page is working very well.

Nevertheless, I have to declare that it has tested on Windows 10 - Opera v53 and Edge v42 but no other browsers. Keep in mind this...

Note: jquery version was 3.3.1 and migrate version was 3.0.0

@RequestBody and @ResponseBody annotations in Spring

There is a whole Section in the docs called 16.3.3.4 Mapping the request body with the @RequestBody annotation. And one called 16.3.3.5 Mapping the response body with the @ResponseBody annotation. I suggest you consult those sections. Also relevant: @RequestBody javadocs, @ResponseBody javadocs

Usage examples would be something like this:

Using a JavaScript-library like JQuery, you would post a JSON-Object like this:

{ "firstName" : "Elmer", "lastName" : "Fudd" }

Your controller method would look like this:

// controller
@ResponseBody @RequestMapping("/description")
public Description getDescription(@RequestBody UserStats stats){
    return new Description(stats.getFirstName() + " " + stats.getLastname() + " hates wacky wabbits");
}

// domain / value objects
public class UserStats{
    private String firstName;
    private String lastName;
    // + getters, setters
}
public class Description{
    private String description;
    // + getters, setters, constructor
}

Now if you have Jackson on your classpath (and have an <mvc:annotation-driven> setup), Spring would convert the incoming JSON to a UserStats object from the post body (because you added the @RequestBody annotation) and it would serialize the returned object to JSON (because you added the @ResponseBody annotation). So the Browser / Client would see this JSON result:

{ "description" : "Elmer Fudd hates wacky wabbits" }

See this previous answer of mine for a complete working example: https://stackoverflow.com/a/5908632/342852

Note: RequestBody / ResponseBody is of course not limited to JSON, both can handle multiple formats, including plain text and XML, but JSON is probably the most used format.


Update

Ever since Spring 4.x, you usually won't use @ResponseBody on method level, but rather @RestController on class level, with the same effect.

Here is a quote from the official Spring MVC documentation:

@RestController is a composed annotation that is itself meta-annotated with @Controller and @ResponseBody to indicate a controller whose every method inherits the type-level @ResponseBody annotation and, therefore, writes directly to the response body versus view resolution and rendering with an HTML template.

How to add number of days to today's date?

You could extend the javascript Date object like this

Date.prototype.addDays = function(days) {
    this.setDate(this.getDate() + parseInt(days));
    return this;
};

and in your javascript code you could call

var currentDate = new Date();
// to add 4 days to current date
currentDate.addDays(4);

Cannot start session without errors in phpMyAdmin

STOP 777!


If you use nginx (like me), just change the ownership of the folders under /var/lib/php/ from apache to nginx:

[root@centos ~]# cd /var/lib/php/
[root@centos php]# ll
total 12
drwxrwx---. 2 root apache 4096 Jan 30 16:23 opcache
drwxrwx---. 2 root apache 4096 Feb  5 20:56 session
drwxrwx---. 2 root apache 4096 Jan 30 16:23 wsdlcache

[root@centos php]# chown -R :nginx opcache/
[root@centos php]# chown -R :nginx session/
[root@centos php]# chown -R :nginx wsdlcache/
[root@centos php]# ll
total 12
drwxrwx---. 2 root nginx 4096 Jan 30 16:23 opcache
drwxrwx---. 2 root nginx 4096 Feb  5 20:56 session
drwxrwx---. 2 root nginx 4096 Jan 30 16:23 wsdlcache

And also for the folders under /var/lib/phpMyAdmin/:

[root@centos php]# cd /var/lib/phpMyAdmin
[root@centos phpMyAdmin]# ll
total 12
drwxr-x---. 2 apache apache 4096 Dec 23 20:29 config
drwxr-x---. 2 apache apache 4096 Dec 23 20:29 save
drwxr-x---. 2 apache apache 4096 Dec 23 20:29 upload

[root@centos phpMyAdmin]# chown -R nginx:nginx config/
[root@centos phpMyAdmin]# chown -R nginx:nginx save/
[root@centos phpMyAdmin]# chown -R nginx:nginx upload/
[root@centos phpMyAdmin]# ll
total 12
drwxr-x---. 2 nginx nginx 4096 Dec 23 20:29 config
drwxr-x---. 2 nginx nginx 4096 Dec 23 20:29 save
drwxr-x---. 2 nginx nginx 4096 Dec 23 20:29 upload

How do I check if a directory exists? "is_dir", "file_exists" or both?

A way to check if a path is directory can be following:

function isDirectory($path) {
    $all = @scandir($path);
    return $all !== false;
}

NOTE: It will return false for non-existant path too, but works perfectly for UNIX/Windows

Gradle project refresh failed after Android Studio update

  1. Close Android Studio
  2. Go to C:\Users\Username
  3. delete the .gradle folder

That's it you are done

How to count items in JSON object using command line?

You can also use jq to track down the array within the returned json and then pipe that in to a second jq call to get its length. Suppose it was in a property called records, like {"records":[...]}.

$ curl https://my-source-of-json.com/list | jq -r '.records' | jq length
2
$ 

Using Default Arguments in a Function

You can also check if you have an empty string as argument so you can call like:

foo('blah', "", 'non-default y value', null);

Below the function:

function foo($blah, $x = null, $y = null, $z = null) {
    if (null === $x || "" === $x) {
        $x = "some value";
    }

    if (null === $y || "" === $y) {
        $y = "some other value";
    }

    if (null === $z || "" === $z) {
        $z = "some other value";
    }

    code here!

}

It doesn't matter if you fill null or "", you will still get the same result.

How to uninstall/upgrade Angular CLI?

I tried all the above things, and still ng as sticking around globally. So in powershell I ran Get-Command ng, and then it became clear what my problem was. I was using yarn heavily in the past, and all the old angular cli packages were also installed globally in the yarn cache location. I deleted my yarn cache for good measure, but probably could have just updated the global angular cli via yarn. In any case, I hope this helps remind some of you that if you use yarn, then global commands like ng can also live in another path than where npm puts them.

Validate date in dd/mm/yyyy format using JQuery Validate

You don't need the date validator. It doesn't support dd/mm/yyyy format, and that's why you are getting "Please enter a valid date" message for input like 13/01/2014. You already have the dateITA validator, which uses dd/mm/yyyy format as you need.

Just like the date validator, your code for dateGreaterThan and dateLessThan calls new Date for input string and has the same issue parsing dates. You can use a function like this to parse the date:

function parseDMY(value) {
    var date = value.split("/");
    var d = parseInt(date[0], 10),
        m = parseInt(date[1], 10),
        y = parseInt(date[2], 10);
    return new Date(y, m - 1, d);
}

How to turn off the Eclipse code formatter for certain sections of Java code?

I'm using fixed width string-parts (padded with whitespace) to avoid having the formatter mess up my SQL string indentation. This gives you mixed results, and won't work where whitespace is not ignored as it is in SQL, but can be helpful.

    final String sql = "SELECT v.value FROM properties p               "
            + "JOIN property_values v ON p.property_id = v.property_id "
            + "WHERE p.product_id = ?                                  "
            + "AND v.value        IS NOT NULL                          ";

Django: Calling .update() on a single model instance retrieved by .get()?

I don't know how good or bad this is, but you can try something like this:

try:
    obj = Model.objects.get(id=some_id)
except Model.DoesNotExist:
    obj = Model.objects.create()
obj.__dict__.update(your_fields_dict) 
obj.save()

Retrieve a Fragment from a ViewPager

The easiest and the most concise way. If all your fragments in ViewPager are of different classes you may retrieve and distinguish them as following:

public class MyActivity extends Activity
{

    @Override
    public void onAttachFragment(Fragment fragment) {
        super.onAttachFragment(fragment);
        if (fragment.getClass() == MyFragment.class) {
            mMyFragment = (MyFragment) fragment;
        }
    }

}

How do I add an existing Solution to GitHub from Visual Studio 2013

There is a lot easier way to do this that doesn't even require you to do anything outside Visual Studio.

  • Open your project in Visual Studio
  • File> Add to source control
  • Open Team Explorer, click on Home button, proceed to "Sync" and there you'd find the "Publish to GitHub". Click on "Get Started"
  • Type title of your repository and description (optionally).
  • Click on "Publish"

That's all. Visual Studio github plugin automatically created repository for you and configured everything. Now just click on Home and choose "Changes" tab and finally commit your first commit.

Referenced Project gets "lost" at Compile Time

Check your build types of each project under project properties - I bet one or the other will be set to build against .NET XX - Client Profile.

With inconsistent versions, specifically with one being Client Profile and the other not, then it works at design time but fails at compile time. A real gotcha.

There is something funny going on in Visual Studio 2010 for me, which keeps setting projects seemingly randomly to Client Profile, sometimes when I create a project, and sometimes a few days later. Probably some keyboard shortcut I'm accidentally hitting...

PHP XML Extension: Not installed

If you are working with php in windows, you can just access to the file "php.ini" located in your php instalation folder and uncomment the ";extension=xmlrpc" line deleting the ";" ("extension=xmlrpc")

Log all queries in mysql

Start mysql with the --log option:

mysqld --log=log_file_name

or place the following in your my.cnf file:

log = log_file_name

Either one will log all queries to log_file_name.

You can also log only slow queries using the --log-slow-queries option instead of --log. By default, queries that take 10 seconds or longer are considered slow, you can change this by setting long_query_time to the number of seconds a query must take to execute before being logged.

How to send Request payload to REST API in java?

The following code works for me.

//escape the double quotes in json string
String payload="{\"jsonrpc\":\"2.0\",\"method\":\"changeDetail\",\"params\":[{\"id\":11376}],\"id\":2}";
String requestUrl="https://git.eclipse.org/r/gerrit/rpc/ChangeDetailService";
sendPostRequest(requestUrl, payload);

method implementation:

public static String sendPostRequest(String requestUrl, String payload) {
    try {
        URL url = new URL(requestUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Accept", "application/json");
        connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
        writer.write(payload);
        writer.close();
        BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        StringBuffer jsonString = new StringBuffer();
        String line;
        while ((line = br.readLine()) != null) {
                jsonString.append(line);
        }
        br.close();
        connection.disconnect();
        return jsonString.toString();
    } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
    }

}

CSS Always On Top

Ensure position is on your element and set the z-index to a value higher than the elements you want to cover.

element {
    position: fixed;
    z-index: 999;
}

div {
    position: relative;
    z-index: 99;
}

It will probably require some more work than that but it's a start since you didn't post any code.

How to make a select with array contains value clause in psql

Try

SELECT * FROM table WHERE arr @> ARRAY['s']::varchar[]

Turn off deprecated errors in PHP 5.3

I just faced a similar problem where a SEO plugin issued a big number of warnings making my blog disk use exceed the plan limit.

I found out that you must include the error_reporting command after the wp-settings.php require in the wp-config.php file:

   require_once( ABSPATH .'wp-settings.php' );
   error_reporting( E_ALL ^ ( E_NOTICE | E_WARNING | E_DEPRECATED ) );

by doing this no more warnings, notices nor deprecated lines are appended to your error log file!

Tested on WordPress 3.8 but I guess it works for every installation.

How to install APK from PC?

Airdroid , android market install the app on android then go onto the computer type in the address given, type in the password given (or scan the QR code). Go to settings and under security (if your running the new ICS or Jellybean) or go to settings->apps->managment and select unknown sources(for gingerbread) then click on (I think) speed install, or something along those lines. it will be on the top of the page slightly towards the left. drag and drop as many .apks as you want then on you android just tap the install buttons that appear. Airdroid is wonderful and does a lot more than just apks.

if checkbox is checked, do this

It may happen that "this.checked" is always "on". Therefore, I recommend:

$('#checkbox').change(function() {
  if ($(this).is(':checked')) {
    console.log('Checked');
  } else {
    console.log('Unchecked');
  }
});

YAML: Do I need quotes for strings in YAML?

I had this concern when working on a Rails application with Docker.

My most preferred approach is to generally not use quotes. This includes not using quotes for:

  • variables like ${RAILS_ENV}
  • values separated by a colon (:) like postgres-log:/var/log/postgresql
  • other strings values

I, however, use double-quotes for integer values that need to be converted to strings like:

  • docker-compose version like version: "3.8"
  • port numbers like "8080:8080"

However, for special cases like booleans, floats, integers, and other cases, where using double-quotes for the entry values could be interpreted as strings, please do not use double-quotes.

Here's a sample docker-compose.yml file to explain this concept:

version: "3"

services:
  traefik:
    image: traefik:v2.2.1
    command:
      - --api.insecure=true # Don't do that in production
      - --providers.docker=true
      - --providers.docker.exposedbydefault=false
      - --entrypoints.web.address=:80
    ports:
      - "80:80"
      - "8080:8080"
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock:ro

That's all.

I hope this helps

android.widget.Switch - on/off event listener?

Switch inherits CompoundButton's attributes, so I would recommend the OnCheckedChangeListener

mySwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        // do something, the isChecked will be
        // true if the switch is in the On position
    }
});

What is the difference between Task.Run() and Task.Factory.StartNew()

In my application which calls two services, I compared both Task.Run and Task.Factory.StartNew. I found that in my case both of them work fine. However, the second one is faster.

VBA Public Array : how to?

You are using the wrong type. The Array(...) function returns a Variant, not a String.

Thus, in the Declaration section of your module (it does not need to be a different module!), you define

Public colHeader As Variant

and somewhere at the beginning of your program code (for example, in the Workbook_Open event) you initialize it with

colHeader = Array("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L")

Another (simple) alternative would be to create a function that returns the array, e.g. something like

Public Function GetHeaders() As Variant
    GetHeaders = Array("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L")
End Function

This has the advantage that you do not need to initialize the global variable and the drawback that the array is created again on every function call.

How do I trim whitespace from a string?

Just one space or all consecutive spaces? If the second, then strings already have a .strip() method:

>>> ' Hello '.strip()
'Hello'
>>> ' Hello'.strip()
'Hello'
>>> 'Bob has a cat'.strip()
'Bob has a cat'
>>> '   Hello   '.strip()  # ALL consecutive spaces at both ends removed
'Hello'

If you only need to remove one space however, you could do it with:

def strip_one_space(s):
    if s.endswith(" "): s = s[:-1]
    if s.startswith(" "): s = s[1:]
    return s

>>> strip_one_space("   Hello ")
'  Hello'

Also, note that str.strip() removes other whitespace characters as well (e.g. tabs and newlines). To remove only spaces, you can specify the character to remove as an argument to strip, i.e.:

>>> "  Hello\n".strip(" ")
'Hello\n'

Is there an easy way to check the .NET Framework version?

If your machine is connected to the internet, going to smallestdotnet, downloading and executing the .NET Checker is probably the easiest way.

If you need the actual method to deterine the version look at its source on github, esp. the Constants.cs which will help you for .net 4.5 and later, where the Revision part is the relvant one:

                           { int.MinValue, "4.5" },
                           { 378389, "4.5" },
                           { 378675, "4.5.1" },
                           { 378758, "4.5.1" },
                           { 379893, "4.5.2" },
                           { 381029, "4.6 Preview" },
                           { 393273, "4.6 RC1" },
                           { 393292, "4.6 RC2" },
                           { 393295, "4.6" },
                           { 393297, "4.6" },
                           { 394254, "4.6.1" },
                           { 394271, "4.6.1" },
                           { 394747, "4.6.2 Preview" },
                           { 394748, "4.6.2 Preview" },
                           { 394757, "4.6.2 Preview" },
                           { 394802, "4.6.2" },
                           { 394806, "4.6.2" },

What causes: "Notice: Uninitialized string offset" to appear?

Try to test and initialize your arrays before you use them :

if( !isset($catagory[$i]) ) $catagory[$i] = '' ;
if( !isset($task[$i]) ) $task[$i] = '' ;
if( !isset($fullText[$i]) ) $fullText[$i] = '' ;
if( !isset($dueDate[$i]) ) $dueDate[$i] = '' ;
if( !isset($empId[$i]) ) $empId[$i] = '' ;

If $catagory[$i] doesn't exist, you create (Uninitialized) one ... that's all ; => PHP try to read on your table in the address $i, but at this address, there's nothing, this address doesn't exist => PHP return you a notice, and it put nothing to you string. So you code is not very clean, it takes you some resources that down you server's performance (just a very little).

Take care about your MySQL tables default values

if( !isset($dueDate[$i]) ) $dueDate[$i] = '0000-00-00 00:00:00' ;

or

if( !isset($dueDate[$i]) ) $dueDate[$i] = 'NULL' ;

This could be due to the service endpoint binding not using the HTTP protocol

In my instance, the error was generated because one of my complex types had a property with no set method.

The serializer threw an exception because of that fact. Added internal set methods and it all worked fine.

Best way to find out why this is happening (in my opinion) is to enable trace logging.

I achieved this by adding the following section to my web.config:

<system.diagnostics>
  <sources>
    <source name="System.ServiceModel.MessageLogging" switchValue="Warning,ActivityTracing">
      <listeners>
        <add name="traceListener"
              type="System.Diagnostics.XmlWriterTraceListener"
              initializeData= "c:\log\Traces.svclog" />
        <add type="System.Diagnostics.DefaultTraceListener" name="Default" />
      </listeners>
    </source>
    <source propagateActivity="true" name="System.ServiceModel" switchValue="Verbose,ActivityTracing">
      <listeners>
        <add name="traceListener"
              type="System.Diagnostics.XmlWriterTraceListener"
              initializeData= "c:\log\Traces.svclog" />
        <add type="System.Diagnostics.DefaultTraceListener" name="Default" />
      </listeners>
    </source>
  </sources>
  <trace autoflush="true" />
</system.diagnostics>

Once set, I ran my client, got exception and checked the 'Traces.svclog' file. From there, I only needed to find the exception.

'Found the synthetic property @panelState. Please include either "BrowserAnimationsModule" or "NoopAnimationsModule" in your application.'

My problem was that my @angular/platform-browser was on version 2.3.1

npm install @angular/platform-browser@latest --save

Upgrading to 4.4.6 did the trick and added /animations folder under node_modules/@angular/platform-browser

How do I compute derivative using Numpy?

I'll throw another method on the pile...

scipy.interpolate's many interpolating splines are capable of providing derivatives. So, using a linear spline (k=1), the derivative of the spline (using the derivative() method) should be equivalent to a forward difference. I'm not entirely sure, but I believe using a cubic spline derivative would be similar to a centered difference derivative since it uses values from before and after to construct the cubic spline.

from scipy.interpolate import InterpolatedUnivariateSpline

# Get a function that evaluates the linear spline at any x
f = InterpolatedUnivariateSpline(x, y, k=1)

# Get a function that evaluates the derivative of the linear spline at any x
dfdx = f.derivative()

# Evaluate the derivative dydx at each x location...
dydx = dfdx(x)

How to read file with space separated values in pandas

If you can't get text parsing to work using the accepted answer (e.g if your text file contains non uniform rows) then it's worth trying with Python's csv library - here's an example using a user defined Dialect:

 import csv

 csv.register_dialect('skip_space', skipinitialspace=True)
 with open(my_file, 'r') as f:
      reader=csv.reader(f , delimiter=' ', dialect='skip_space')
      for item in reader:
          print(item)

Easiest way to compare arrays in C#

For some applications may be better:

string.Join(",", arr1) == string.Join(",", arr2)

MacOSX homebrew mysql root password

None of these worked for me. I think i already had mysql somewhere on my computer so a password was set there or something. After spending hours trying every solution out there this is what worked for me:

$ brew services stop mysql
$ pkill mysqld
$ rm -rf /usr/local/var/mysql/ # NOTE: this will delete your existing database!!!
$ brew postinstall mysql
$ brew services restart mysql
$ mysql -uroot

all credit to @Ghrua

Passing string to a function in C - with or without pointers?

An array is a pointer. It points to the start of a sequence of "objects".

If we do this: ìnt arr[10];, then arr is a pointer to a memory location, from which ten integers follow. They are uninitialised, but the memory is allocated. It is exactly the same as doing int *arr = new int[10];.

What's the best way to add a drop shadow to my UIView

You can create an extension for UIView to access these values in the design editor

Shadow options in design editor

extension UIView{

    @IBInspectable var shadowOffset: CGSize{
        get{
            return self.layer.shadowOffset
        }
        set{
            self.layer.shadowOffset = newValue
        }
    }

    @IBInspectable var shadowColor: UIColor{
        get{
            return UIColor(cgColor: self.layer.shadowColor!)
        }
        set{
            self.layer.shadowColor = newValue.cgColor
        }
    }

    @IBInspectable var shadowRadius: CGFloat{
        get{
            return self.layer.shadowRadius
        }
        set{
            self.layer.shadowRadius = newValue
        }
    }

    @IBInspectable var shadowOpacity: Float{
        get{
            return self.layer.shadowOpacity
        }
        set{
            self.layer.shadowOpacity = newValue
        }
    }
}

A server with the specified hostname could not be found

In Xcode, select Target -> Capabilities, and check "Outgoing Connections (Client)" to enable App Sandbox.

Mysql: Select rows from a table that are not in another

This worked for me in Oracle:

SELECT a.* 
    FROM tbl1 a 
MINUS 
SELECT b.* 
    FROM tbl2 b;

Are static class variables possible in Python?

To avoid any potential confusion, I would like to contrast static variables and immutable objects.

Some primitive object types like integers, floats, strings, and touples are immutable in Python. This means that the object that is referred to by a given name cannot change if it is of one of the aforementioned object types. The name can be reassigned to a different object, but the object itself may not be changed.

Making a variable static takes this a step further by disallowing the variable name to point to any object but that to which it currently points. (Note: this is a general software concept and not specific to Python; please see others' posts for information about implementing statics in Python).

Find the greatest number in a list of numbers

Use max()

>>> l = [1, 2, 5]
>>> max(l)
5
>>> 

Excel formula to get cell color

Anticipating that I already had the answer, which is that there is no built-in worksheet function that returns the background color of a cell, I decided to review this article, in case I was wrong. I was amused to notice a citation to the very same MVP article that I used in the course of my ongoing research into colors in Microsoft Excel.

While I agree that, in the purest sense, color is not data, it is meta-data, and it has uses as such. To that end, I shall attempt to develop a function that returns the color of a cell. If I succeed, I plan to put it into an add-in, so that I can use it in any workbook, where it will join a growing legion of other functions that I think Microsoft left out of the product.

Regardless, IMO, the ColorIndex property is virtually useless, since there is essentially no connection between color indexes and the colors that can be selected in the standard foreground and background color pickers. See Color Combinations: Working with Colors in Microsoft Office and the associated binary workbook, Color_Combinations Workbook.

About .bash_profile, .bashrc, and where should alias be written in?

From the bash manpage:

When bash is invoked as an interactive login shell, or as a non-interactive shell with the --login option, it first reads and executes commands from the file /etc/profile, if that file exists. After reading that file, it looks for ~/.bash_profile, ~/.bash_login, and ~/.profile, in that order, and reads and executes commands from the first one that exists and is readable. The --noprofile option may be used when the shell is started to inhibit this behavior.

When a login shell exits, bash reads and executes commands from the file ~/.bash_logout, if it exists.

When an interactive shell that is not a login shell is started, bash reads and executes commands from ~/.bashrc, if that file exists. This may be inhibited by using the --norc option. The --rcfile file option will force bash to read and execute commands from file instead of ~/.bashrc.

Thus, if you want to get the same behavior for both login shells and interactive non-login shells, you should put all of your commands in either .bashrc or .bash_profile, and then have the other file source the first one.

How do I find the last column with data?

Try using the code after you active the sheet:

Dim J as integer
J = ActiveSheet.UsedRange.SpecialCells(xlCellTypeLastCell).Row

If you use Cells.SpecialCells(xlCellTypeLastCell).Row only, the problem will be that the xlCellTypeLastCell information will not be updated unless one do a "Save file" action. But use UsedRange will always update the information in realtime.

Faster way to zero memory than with memset?

memset could be inlined by compiler as a series of efficient opcodes, unrolled for a few cycles. For very large memory blocks, like 4000x2000 64bit framebuffer, you can try optimizing it across several threads (which you prepare for that sole task), each setting its own part. Note that there is also bzero(), but it is more obscure, and less likely to be as optimized as memset, and the compiler will surely notice you pass 0.

What compiler usually assumes, is that you memset large blocks, so for smaller blocks it would likely be more efficient to just do *(uint64_t*)p = 0, if you init large number of small objects.

Generally, all x86 CPUs are different (unless you compile for some standardized platform), and something you optimize for Pentium 2 will behave differently on Core Duo or i486. So if you really into it and want to squeeze the last few bits of toothpaste, it makes sense to ship several versions your exe compiled and optimized for different popular CPU models. From personal experience Clang -march=native boosted my game's FPS from 60 to 65, compared to no -march.

Add a string of text into an input field when user clicks a button

Example for you to work from

HTML:

<input type="text" value="This is some text" id="text" style="width: 150px;" />
<br />
<input type="button" value="Click Me" id="button" />?

jQuery:

<script type="text/javascript">
$(function () {
    $('#button').on('click', function () {
        var text = $('#text');
        text.val(text.val() + ' after clicking');    
    });
});
<script>

Javascript

<script type="text/javascript">
document.getElementById("button").addEventListener('click', function () {
    var text = document.getElementById('text');
    text.value += ' after clicking';
});
</script>

Working jQuery example: http://jsfiddle.net/geMtZ/ ?

Get everything after and before certain character in SQL Server

If you want to get this out of your table using SQL, take a look at the following functions that will help you: SUBSTRING and CHARINDEX. You can use those to trim your entries.

A possible query will look like this (where col is the name of the column that contains your image directories:

SELECT SUBSTRING(col, LEN(SUBSTRING(col, 0, LEN(col) - CHARINDEX ('/', col))) + 1, 
    LEN(col) - LEN(SUBSTRING(col, 0, LEN(col) - CHARINDEX ('/', col))) - LEN(SUBSTRING(
    col, CHARINDEX ('.', col), LEN(col))));

Bit of an ugly beast. It also depends on the standard format of 'dir/name.ext'.

Edit:
This one (inspired by praveen) is more generic and deals with extensions of different length:

SELECT SUBSTRING(col, LEN(LEFT(col, CHARINDEX ('/', col))) + 1, LEN(col) - LEN(LEFT(col, 
    CHARINDEX ('/', col))) - LEN(RIGHT(col, LEN(col) - CHARINDEX ('.', col))) - 1);

Filezilla FTP Server Fails to Retrieve Directory Listing

File > Site Manager > Select your site > Transfer Settings > Active

Works for me.

What's the equivalent of Java's Thread.sleep() in JavaScript?

You can either write a spin loop (a loop that just loops for a long period of time performing some sort of computation to delay the function) or use:

setTimeout("Func1()", 3000);

This will call 'Func1()' after 3 seconds.

Edit:

Credit goes to the commenters, but you can pass anonymous functions to setTimeout.

setTimeout(function() {
   //Do some stuff here
}, 3000);

This is much more efficient and does not invoke javascript's eval function.

Powershell: count members of a AD group

How about this?

Get-ADGroupMember 'Group name' | measure-object | select count

How to embed fonts in CSS?

When I went to Google fonts all they gave me were true type font files .ttf and didn't explain at all how to use the @font-face to include them into my document. I tried the web font generator from font squirrel too, which just kept running the loading gif and not working... I then found this site -

https://transfonter.org/

I had great success using the following method:

I selected the Add Fonts button, leaving the default options, added all of my .ttf that Google gave me for Open Sans (which was like 10, I chose a lot of options...).

Then I selected the Convert button.

Heres the best part!

They gave me a zip file with all the font format files I selected, .ttf, .woff and .eot. Inside that zip file they had a demo.html file that I just double clicked on and it opened up a web page in my browser showing me example usages of all the different css font options, how to implement them, and what they looked like etc.

@font-face

I still didn't know at this point how to include the fonts into my stylesheet properly using @font-face but then I noticed that this demo.html came with it's own stylesheet in the zip as well. I opened the stylesheet and it showed how to bring in all of the fonts using @font-face so I was able to quickly, and easily, copy paste this into my project -

@font-face {
    font-family: 'Open Sans';
    src: url('fonts/Open_Sans/OpenSans-BoldItalic.eot');
    src: url('fonts/Open_Sans/OpenSans-BoldItalic.eot?#iefix') format('embedded-opentype'),
        url('fonts/Open_Sans/OpenSans-BoldItalic.woff') format('woff'),
        url('fonts/Open_Sans/OpenSans-BoldItalic.ttf') format('truetype');
    font-weight: bold;
    font-style: italic;
}

@font-face {
    font-family: 'Open Sans';
    src: url('fonts/Open_Sans/OpenSans-LightItalic.eot');
    src: url('fonts/Open_Sans/OpenSans-LightItalic.eot?#iefix') format('embedded-opentype'),
        url('fonts/Open_Sans/OpenSans-LightItalic.woff') format('woff'),
        url('fonts/Open_Sans/OpenSans-LightItalic.ttf') format('truetype');
    font-weight: 300;
    font-style: italic;
}

@font-face {
    font-family: 'Open Sans';
    src: url('fonts/Open_Sans/OpenSans-SemiBold.eot');
    src: url('fonts/Open_Sans/OpenSans-SemiBold.eot?#iefix') format('embedded-opentype'),
        url('fonts/Open_Sans/OpenSans-SemiBold.woff') format('woff'),
        url('fonts/Open_Sans/OpenSans-SemiBold.ttf') format('truetype');
    font-weight: 600;
    font-style: normal;
}

@font-face {
    font-family: 'Open Sans';
    src: url('fonts/Open_Sans/OpenSans-Regular.eot');
    src: url('fonts/Open_Sans/OpenSans-Regular.eot?#iefix') format('embedded-opentype'),
        url('fonts/Open_Sans/OpenSans-Regular.woff') format('woff'),
        url('fonts/Open_Sans/OpenSans-Regular.ttf') format('truetype');
    font-weight: normal;
    font-style: normal;
}

@font-face {
    font-family: 'Open Sans';
    src: url('fonts/Open_Sans/OpenSans-Light.eot');
    src: url('fonts/Open_Sans/OpenSans-Light.eot?#iefix') format('embedded-opentype'),
        url('fonts/Open_Sans/OpenSans-Light.woff') format('woff'),
        url('fonts/Open_Sans/OpenSans-Light.ttf') format('truetype');
    font-weight: 300;
    font-style: normal;
}

@font-face {
    font-family: 'Open Sans';
    src: url('fonts/Open_Sans/OpenSans-Italic.eot');
    src: url('fonts/Open_Sans/OpenSans-Italic.eot?#iefix') format('embedded-opentype'),
        url('fonts/Open_Sans/OpenSans-Italic.woff') format('woff'),
        url('fonts/Open_Sans/OpenSans-Italic.ttf') format('truetype');
    font-weight: normal;
    font-style: italic;
}

@font-face {
    font-family: 'Open Sans';
    src: url('fonts/Open_Sans/OpenSans-SemiBoldItalic.eot');
    src: url('fonts/Open_Sans/OpenSans-SemiBoldItalic.eot?#iefix') format('embedded-opentype'),
        url('fonts/Open_Sans/OpenSans-SemiBoldItalic.woff') format('woff'),
        url('fonts/Open_Sans/OpenSans-SemiBoldItalic.ttf') format('truetype');
    font-weight: 600;
    font-style: italic;
}

@font-face {
    font-family: 'Open Sans';
    src: url('fonts/Open_Sans/OpenSans-ExtraBold.eot');
    src: url('fonts/Open_Sans/OpenSans-ExtraBold.eot?#iefix') format('embedded-opentype'),
        url('fonts/Open_Sans/OpenSans-ExtraBold.woff') format('woff'),
        url('fonts/Open_Sans/OpenSans-ExtraBold.ttf') format('truetype');
    font-weight: 800;
    font-style: normal;
}

@font-face {
    font-family: 'Open Sans';
    src: url('fonts/Open_Sans/OpenSans-ExtraBoldItalic.eot');
    src: url('fonts/Open_Sans/OpenSans-ExtraBoldItalic.eot?#iefix') format('embedded-opentype'),
        url('fonts/Open_Sans/OpenSans-ExtraBoldItalic.woff') format('woff'),
        url('fonts/Open_Sans/OpenSans-ExtraBoldItalic.ttf') format('truetype');
    font-weight: 800;
    font-style: italic;
}

@font-face {
    font-family: 'Open Sans';
    src: url('fonts/Open_Sans/OpenSans-Bold.eot');
    src: url('fonts/Open_Sans/OpenSans-Bold.eot?#iefix') format('embedded-opentype'),
        url('fonts/Open_Sans/OpenSans-Bold.woff') format('woff'),
        url('fonts/Open_Sans/OpenSans-Bold.ttf') format('truetype');
    font-weight: bold;
    font-style: normal;
}

The demo.html also had it's own inline stylesheet that was interesting to take a look at, though I am familiar with working with font weights and styles once they are included so I didn't need it much. For an example of how to implement a font style onto an html element for reference purposes you could use the following method in a similar case to mine after @font-face has been used properly -

html, body{
    margin: 0;
    font-family: 'Open Sans';
}
.banner h1{
    font-size: 43px;
    font-weight: 700;
}
.banner p{
    font-size: 24px;
    font-weight: 300;
    font-style: italic;
}

What is the difference between "Class.forName()" and "Class.forName().newInstance()"?

just adding to above answers, when we have a static code (ie code block is instance independent) that needs to be present in memory, we can have the class returned so we'll use Class.forname("someName") else if we dont have static code we can go for Class.forname().newInstance("someName") as it will load object level code blocks(non static) to memory

Copy file remotely with PowerShell

Simply use the administrative shares to copy files between systems. It's much easier this way.

Copy-Item -Path \\serverb\c$\programs\temp\test.txt -Destination \\servera\c$\programs\temp\test.txt;

By using UNC paths instead of local filesystem paths, you help to ensure that your script is executable from any client system with access to those UNC paths. If you use local filesystem paths, then you are cornering yourself into running the script on a specific computer.

This only works when a PowerShell session runs under the user who has rights to both administrative shares.

I suggest to use regular network share on server B with read-only access to everyone and simply call (from Server A):

Copy-Item -Path "\\\ServerB\SharedPathToSourceFile" -Destination "$Env:USERPROFILE" -Force -PassThru -Verbose

Is it possible to disable the network in iOS Simulator?

There are two way to disable IOS Simulator internet:

  • Unplug your network connection
  • Turn Wi-Fi off

It's the simplest way

Custom checkbox image android

res/drawable/day_selector.xml

    <?xml version="1.0" encoding="utf-8"?>
    <selector xmlns:android="http://schemas.android.com/apk/res/android" >
        <item android:drawable="@drawable/dayselectionunselected"
              android:state_checked="false"/>
        <item android:drawable="@drawable/daysselectionselected"
              android:state_checked="true"/>
        <item android:drawable="@drawable/dayselectionunselected"/>
    </selector>

res/layout/my_layout.xml

<CheckBox
    android:id="@+id/check"
    android:layout_width="39dp"
    android:layout_height="39dp"
    android:background="@drawable/day_selector"
    android:button="@null"
    android:gravity="center"
    android:text="S"
    android:textColor="@color/black"
    android:textSize="12sp" />

Don't reload application when orientation changes

http://animeshrivastava.blogspot.in/2017/08/activity-lifecycle-oncreate-beating_3.html

@Override
protected void onSaveInstanceState(Bundle b)
{
        super.onSaveInstanceState(b);
    String str="Screen Change="+String.valueOf(screenChange)+"....";
        Toast.makeText(ctx,str+"You are changing orientation...",Toast.LENGTH_SHORT).show();
    screenChange=true;

}

How do I center floated elements?

Removing floats, and using inline-block may fix your problems:

 .pagination a {
-    display: block;
+    display: inline-block;
     width: 30px;
     height: 30px;
-    float: left;
     margin-left: 3px;
     background: url(/images/structure/pagination-button.png);
 }

(remove the lines starting with - and add the lines starting with +.)

_x000D_
_x000D_
.pagination {_x000D_
  text-align: center;_x000D_
}_x000D_
.pagination a {_x000D_
  + display: inline-block;_x000D_
  width: 30px;_x000D_
  height: 30px;_x000D_
  margin-left: 3px;_x000D_
  background: url(/images/structure/pagination-button.png);_x000D_
}_x000D_
.pagination a.last {_x000D_
  width: 90px;_x000D_
  background: url(/images/structure/pagination-button-last.png);_x000D_
}_x000D_
.pagination a.first {_x000D_
  width: 60px;_x000D_
  background: url(/images/structure/pagination-button-first.png);_x000D_
}
_x000D_
<div class='pagination'>_x000D_
  <a class='first' href='#'>First</a>_x000D_
  <a href='#'>1</a>_x000D_
  <a href='#'>2</a>_x000D_
  <a href='#'>3</a>_x000D_
  <a class='last' href='#'>Last</a>_x000D_
</div>_x000D_
<!-- end: .pagination -->
_x000D_
_x000D_
_x000D_

inline-block works cross-browser, even on IE6 as long as the element is originally an inline element.

Quote from quirksmode:

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

this often can effectively replace floats:

The real use of this value is when you want to give an inline element a width. In some circumstances some browsers don't allow a width on a real inline element, but if you switch to display: inline-block you are allowed to set a width.” ( http://www.quirksmode.org/css/display.html#inlineblock ).

From the W3C spec:

[inline-block] causes an element to generate an inline-level block container. The inside of an inline-block is formatted as a block box, and the element itself is formatted as an atomic inline-level box.

Where are static methods and static variables stored in Java?

It is stored in the heap referenced by the class definition. If you think about it, it has nothing to do with stack because there is no scope.

How does RewriteBase work in .htaccess

RewriteBase is only useful in situations where you can only put a .htaccess at the root of your site. Otherwise, you may be better off placing your different .htaccess files in different directories of your site and completely omitting the RewriteBase directive.

Lately, for complex sites, I've been taking them out, because it makes deploying files from testing to live just one more step complicated.

How to sum a list of integers with java streams?

I have declared a list of Integers.

ArrayList<Integer> numberList = new ArrayList<Integer>(Arrays.asList(1, 2, 3, 4, 5));

You can try using these different ways below.

Using mapToInt

int sum = numberList.stream().mapToInt(Integer::intValue).sum();

Using summarizingInt

int sum = numberList.stream().collect(Collectors.summarizingInt(Integer::intValue)).getSum();

Using reduce

int sum = numberList.stream().reduce(Integer::sum).get().intValue();

How can INSERT INTO a table 300 times within a loop in SQL?

DECLARE @first AS INT = 1
DECLARE @last AS INT = 300

WHILE(@first <= @last)
BEGIN
    INSERT INTO tblFoo VALUES(@first)
    SET @first += 1
END

How do I tell if .NET 3.5 SP1 is installed?

Check is the following directory exists:

In 64bit machines: %SYSTEMROOT%\Microsoft.NET\Framework64\v3.5\Microsoft .NET Framework 3.5 SP1\

In 32bit machines: %SYSTEMROOT%\Microsoft.NET\Framework\v3.5\Microsoft .NET Framework 3.5 SP1\

Where %SYSTEMROOT% is the SYSTEMROOT enviromental variable (e.g. C:\Windows).

Send inline image in email

We all have our preferred coding styles. This is what I did:

var pictures = new[]
{
    new { id = Guid.NewGuid(), type = "image/jpeg", tag = "justme", path = @"C:\Pictures\JustMe.jpg" },
    new { id = Guid.NewGuid(), type = "image/jpeg", tag = "justme-bw", path = @"C:\Pictures\JustMe-BW.jpg" }
}.ToList();

var content = $@"
<style type=""text/css"">
    body {{ font-family: Arial; font-size: 10pt; }}
</style>
<body>
<h4>{DateTime.Now:dddd, MMMM d, yyyy h:mm:ss tt}</h4>
<p>Some pictures</p>
<div>
    <p>Color Picture</p>
    <img src=cid:{{justme}} />
</div>
<div>
    <p>Black and White Picture</p>
    <img src=cid:{{justme-bw}} />
</div>
<div>
    <p>Color Picture repeated</p>
    <img src=cid:{{justme}} />
</div>
</body>
";

// Update content with picture guid
pictures.ForEach(p => content = content.Replace($"{{{p.tag}}}", $"{p.id}"));
// Create Alternate View
var view = AlternateView.CreateAlternateViewFromString(content, Encoding.UTF8, MediaTypeNames.Text.Html);
// Add the resources
pictures.ForEach(p => view.LinkedResources.Add(new LinkedResource(p.path, p.type) { ContentId = p.id.ToString() }));

using (var client = new SmtpClient()) // Set properties as needed or use config file
using (MailMessage message = new MailMessage()
{
    IsBodyHtml = true,
    BodyEncoding = Encoding.UTF8,
    Subject = "Picture Email",
    SubjectEncoding = Encoding.UTF8,
})
{
    message.AlternateViews.Add(view);
    message.From = new MailAddress("[email protected]");
    message.To.Add(new MailAddress("[email protected]"));
    client.Send(message);
}

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

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

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


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

React component initialize state from props

Update for React 16.3 alpha introduced static getDerivedStateFromProps(nextProps, prevState) (docs) as a replacement for componentWillReceiveProps.

getDerivedStateFromProps is invoked after a component is instantiated as well as when it receives new props. It should return an object to update state, or null to indicate that the new props do not require any state updates.

Note that if a parent component causes your component to re-render, this method will be called even if props have not changed. You may want to compare new and previous values if you only want to handle changes.

https://reactjs.org/docs/react-component.html#static-getderivedstatefromprops

It is static, therefore it does not have direct access to this (however it does have access to prevState, which could store things normally attached to this e.g. refs)

edited to reflect @nerfologist's correction in comments

Can (a== 1 && a ==2 && a==3) ever evaluate to true?

This is possible in case of variable a being accessed by, say 2 web workers through a SharedArrayBuffer as well as some main script. The possibility is low, but it is possible that when the code is compiled to machine code, the web workers update the variable a just in time so the conditions a==1, a==2 and a==3 are satisfied.

This can be an example of race condition in multi-threaded environment provided by web workers and SharedArrayBuffer in JavaScript.

Here is the basic implementation of above:

main.js

// Main Thread

const worker = new Worker('worker.js')
const modifiers = [new Worker('modifier.js'), new Worker('modifier.js')] // Let's use 2 workers
const sab = new SharedArrayBuffer(1)

modifiers.forEach(m => m.postMessage(sab))
worker.postMessage(sab)

worker.js

let array

Object.defineProperty(self, 'a', {
  get() {
    return array[0]
  }
});

addEventListener('message', ({data}) => {
    array = new Uint8Array(data)
    let count = 0
    do {
        var res = a == 1 && a == 2 && a == 3
        ++count
    } while(res == false) // just for clarity. !res is fine
    console.log(`It happened after ${count} iterations`)
    console.log('You should\'ve never seen this')
})

modifier.js

addEventListener('message' , ({data}) => {
    setInterval( () => {
        new Uint8Array(data)[0] = Math.floor(Math.random()*3) + 1
    })
})

On my MacBook Air, it happens after around 10 billion iterations on the first attempt:

enter image description here

Second attempt:

enter image description here

As I said, the chances will be low, but given enough time, it'll hit the condition.

Tip: If it takes too long on your system. Try only a == 1 && a == 2 and change Math.random()*3 to Math.random()*2. Adding more and more to list drops the chance of hitting.

How to Import .bson file format on mongodb

Just for reference if anyone is still struggling with mongorestore.

You have to run monogorestore in terminal/command prompt and not in mongo console.

$ mongorestore -d db_name /path_to_mongo_dump/

for more details you can visit official documentations

https://docs.mongodb.com/manual/reference/program/mongorestore/

Aborting a shell script if any command returns a non-zero value

An expression like

dosomething1 && dosomething2 && dosomething3

will stop processing when one of the commands returns with a non-zero value. For example, the following command will never print "done":

cat nosuchfile && echo "done"
echo $?
1

Correct Semantic tag for copyright info - html5

it is better to include it in a <small> tag The HTML <small> tag is used for specifying small print.

Small print (also referred to as "fine print" or "mouseprint") usually refers to the part of a document that contains disclaimers, caveats, or legal restrictions, such as copyrights. And this tag is supported in all major browsers.

<footer>
 <small>&copy; Copyright 2058, Example Corporation</small>
</footer>

Changing PowerShell's default output encoding to UTF-8

To be short, use:

write-output "your text" | out-file -append -encoding utf8 "filename"

Error: EPERM: operation not permitted, unlink 'D:\Sources\**\node_modules\fsevents\node_modules\abbrev\package.json'

This was the only thing that worked for me:

npm cache clean --force

npm install -g npm@latest --force

rm package-lock.json

npm i -force

Replace an element into a specific position of a vector

You can do that using at. You can try out the following simple example:

const size_t N = 20;
std::vector<int> vec(N);
try {
    vec.at(N - 1) = 7;
} catch (std::out_of_range ex) {
    std::cout << ex.what() << std::endl;
}
assert(vec.at(N - 1) == 7);

Notice that method at returns an allocator_type::reference, which is that case is a int&. Using at is equivalent to assigning values like vec[i]=....


There is a difference between at and insert as it can be understood with the following example:

const size_t N = 8;
std::vector<int> vec(N);
for (size_t i = 0; i<5; i++){
    vec[i] = i + 1;
}

vec.insert(vec.begin()+2, 10);

If we now print out vec we will get:

1 2 10 3 4 5 0 0 0

If, instead, we did vec.at(2) = 10, or vec[2]=10, we would get

1 2 10 4 5 0 0 0

How to find good looking font color if background color is known?

This is an interesting question, but I don't think this is actually possible. Whether or not two colors "fit" as background and foreground colors is dependent upon display technology and physiological characteristics of human vision, but most importantly on upon personal tastes shaped by experience. A quick run through MySpace shows pretty clearly that not all human beings perceive colors in the same way. I don't think this is a problem that can be solved algorithmically, although there may be a huge database somewhere of acceptable matching colors.

Best way to deploy Visual Studio application that can run without installing

It is possible and is deceptively easy:

  1. "Publish" the application (to, say, some folder on drive C), either from menu Build or from the project's properties ? Publish. This will create an installer for a ClickOnce application.
  2. But instead of using the produced installer, find the produced files (the EXE file and the .config, .manifest, and .application files, along with any DLL files, etc.) - they are all in the same folder and typically in the bin\Debug folder below the project file (.csproj).
  3. Zip that folder (leave out any *.vhost.* files and the app.publish folder (they are not needed), and the .pdb files unless you foresee debugging directly on your user's system (for example, by remote control)), and provide it to the users.

An added advantage is that, as a ClickOnce application, it does not require administrative privileges to run (if your application follows the normal guidelines for which folders to use for application data, etc.).

As for .NET, you can check for the minimum required version of .NET being installed (or at all) in the application (most users will already have it installed) and present a dialog with a link to the download page on the Microsoft website (or point to one of your pages that could redirect to the Microsoft page - this makes it more robust if the Microsoft URL change). As it is a small utility, you could target .NET 2.0 to reduce the probability of a user to have to install .NET.

It works. We use this method during development and test to avoid having to constantly uninstall and install the application and still being quite close to how the final application will run.

Action Image MVC3 Razor

You can create an extension method for HtmlHelper to simplify the code in your CSHTML file. You could replace your tags with a method like this:

// Sample usage in CSHTML
@Html.ActionImage("Edit", new { id = MyId }, "~/Content/Images/Image.bmp", "Edit")

Here is a sample extension method for the code above:

// Extension method
public static MvcHtmlString ActionImage(this HtmlHelper html, string action, object routeValues, string imagePath, string alt)
{
    var url = new UrlHelper(html.ViewContext.RequestContext);

    // build the <img> tag
    var imgBuilder = new TagBuilder("img");
    imgBuilder.MergeAttribute("src", url.Content(imagePath));
    imgBuilder.MergeAttribute("alt", alt);
    string imgHtml = imgBuilder.ToString(TagRenderMode.SelfClosing);

    // build the <a> tag
    var anchorBuilder = new TagBuilder("a");
    anchorBuilder.MergeAttribute("href", url.Action(action, routeValues));
    anchorBuilder.InnerHtml = imgHtml; // include the <img> tag inside
    string anchorHtml = anchorBuilder.ToString(TagRenderMode.Normal);

    return MvcHtmlString.Create(anchorHtml);
}

Prevent browser caching of AJAX call result

What about using a POST request instead of a GET...? (Which you should anyway...)

How to get full path of selected file on change of <input type=‘file’> using javascript, jquery-ajax?

You cannot do so - the browser will not allow this because of security concerns.

When a file is selected by using the input type=file object, the value of the value property depends on the value of the "Include local directory path when uploading files to a server" security setting for the security zone used to display the Web page containing the input object.

The fully qualified filename of the selected file is returned only when this setting is enabled. When the setting is disabled, Internet Explorer 8 replaces the local drive and directory path with the string C:\fakepath\ in order to prevent inappropriate information disclosure.

And other

You missed ); this at the end of the change event function.

Also do not create function for change event instead just use it as below,

<script type="text/javascript">

    $(function()
    {
        $('#fileUpload').on('change',function ()
        {
            var filePath = $(this).val();
            console.log(filePath);
        });
    });

</script>

Is calling destructor manually always a sign of bad design?

Found another example where you would have to call destructor(s) manually. Suppose you have implemented a variant-like class that holds one of several types of data:

struct Variant {
    union {
        std::string str;
        int num;
        bool b;
    };
    enum Type { Str, Int, Bool } type;
};

If the Variant instance was holding a std::string, and now you're assigning a different type to the union, you must destruct the std::string first. The compiler will not do that automatically.

cannot make a static reference to the non-static field

Just write:

private static double balance = 0;

and you could also write those like that:

private static int id = 0;
private static double annualInterestRate = 0;
public static java.util.Date dateCreated;

What's the difference between SCSS and Sass?

Difference between SASS and SCSS article explains the difference in details. Don’t be confused by the SASS and SCSS options, although I also was initially, .scss is Sassy CSS and is the next generation of .sass.

If that didn’t make sense you can see the difference in code below.

/* SCSS */
$blue: #3bbfce;
$margin: 16px;

.content-navigation {
  border-color: $blue;
  color: darken($blue, 9%);
}

.border {
  padding: $margin / 2; margin: $margin / 2; border-color: $blue;
}

In the code above we use ; to separate the declarations. I’ve even added all the declarations for .border onto a single line to illustrate this point further. In contrast, the SASS code below must be on different lines with indentation and there is no use of the ;.

/* SASS */
$blue: #3bbfce
$margin: 16px

.content-navigation
  border-color: $blue
  color: darken($blue, 9%)

.border
  padding: $margin / 2
  margin: $margin / 2
  border-color: $blue

You can see from the CSS below that the SCSS style is a lot more similar to regular CSS than the older SASS approach.

/* CSS */
.content-navigation {
  border-color: #3bbfce;
  color: #2b9eab;
}

.border {
  padding: 8px;
  margin: 8px;
  border-color: #3bbfce;
}

I think most of the time these days if someone mentions that they are working with Sass they are referring to authoring in .scss rather than the traditional .sass way.

How may I sort a list alphabetically using jQuery?

If you are using jQuery you can do this:

_x000D_
_x000D_
$(function() {_x000D_
_x000D_
  var $list = $("#list");_x000D_
_x000D_
  $list.children().detach().sort(function(a, b) {_x000D_
    return $(a).text().localeCompare($(b).text());_x000D_
  }).appendTo($list);_x000D_
_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
_x000D_
<ul id="list">_x000D_
  <li>delta</li>_x000D_
  <li>cat</li>_x000D_
  <li>alpha</li>_x000D_
  <li>cat</li>_x000D_
  <li>beta</li>_x000D_
  <li>gamma</li>_x000D_
  <li>gamma</li>_x000D_
  <li>alpha</li>_x000D_
  <li>cat</li>_x000D_
  <li>delta</li>_x000D_
  <li>bat</li>_x000D_
  <li>cat</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

Note that returning 1 and -1 (or 0 and 1) from the compare function is absolutely wrong.

Nullable type as a generic parameter possible?

Just do two things to your original code – remove the where constraint, and change the last return from return null to return default(T). This way you can return whatever type you want.

By the way, you can avoid the use of is by changing your if statement to if (columnValue != DBNull.Value).

Setting a timeout for socket operations

You don't set a timeout for the socket, you set a timeout for the operations you perform on that socket.

For example socket.connect(otherAddress, timeout)

Or socket.setSoTimeout(timeout) for setting a timeout on read() operations.

See: http://docs.oracle.com/javase/7/docs/api/java/net/Socket.html

a href link for entire div in HTML/CSS

What I would do is put a span inside the <a> tag, set the span to block, and add size to the span, or just apply the styling to the <a> tag. Definitely handle the positioning in the <a> tag style. Add an onclick event to the a where JavaScript will catch the event, then return false at the end of the JavaScript event to prevent default action of the href and bubbling of the click. This works in cases with or without JavaScript enabled, and any AJAX can be handled in the Javascript listener.

If you're using jQuery, you can use this as your listener and omit the onclick in the a tag.

$('#idofdiv').live("click", function(e) {
    //add stuff here
    e.preventDefault; //or use return false
}); 

this allows you to attach listeners to any changed elements as necessary.

What is the easiest way to get the current day of the week in Android?

Using both method you find easy if you wont last seven days you use (currentdaynumber+7-1)%7,(currentdaynumber+7-2)%7.....upto 6

public static String getDayName(int day){
    switch(day){
        case 0:
            return "Sunday";
        case 1:
            return "Monday";
        case 2:
            return "Tuesday";
        case 3:
            return "Wednesday";
        case 4:
            return "Thursday";
        case 5:
            return  "Friday";
        case 6:
            return "Saturday";
    }

    return "Worng Day";
}
public static String getCurrentDay(){
    SimpleDateFormat dayFormat = new SimpleDateFormat("EEEE", Locale.US);
    Calendar calendar = Calendar.getInstance();
    return dayFormat.format(calendar.getTime());

}

How do I get a plist as a Dictionary in Swift?

Swift - Read/Write plist and text file....

override func viewDidLoad() {
    super.viewDidLoad()

    let fileManager = (NSFileManager .defaultManager())
    let directorys : [String]? = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory,NSSearchPathDomainMask.AllDomainsMask, true) as? [String]

    if (directorys != nil){
        let directories:[String] = directorys!;
        let dictionary = directories[0]; //documents directory


        //  Create and insert the data into the Plist file  ....
        let plistfile = "myPlist.plist"
        var myDictionary: NSMutableDictionary = ["Content": "This is a sample Plist file ........."]
        let plistpath = dictionary.stringByAppendingPathComponent(plistfile);

        if !fileManager .fileExistsAtPath(plistpath){//writing Plist file
            myDictionary.writeToFile(plistpath, atomically: false)
        }
        else{            //Reading Plist file
            println("Plist file found")

            let resultDictionary = NSMutableDictionary(contentsOfFile: plistpath)
            println(resultDictionary?.description)
        }


        //  Create and insert the data into the Text file  ....
        let textfile = "myText.txt"
        let sampleText = "This is a sample text file ......... "

        let textpath = dictionary.stringByAppendingPathComponent(textfile);
        if !fileManager .fileExistsAtPath(textpath){//writing text file
            sampleText.writeToFile(textpath, atomically: false, encoding: NSUTF8StringEncoding, error: nil);
        } else{
            //Reading text file
            let reulttext  = String(contentsOfFile: textpath, encoding: NSUTF8StringEncoding, error: nil)
            println(reulttext)
        }
    }
    else {
        println("directory is empty")
    }
}

git push rejected: error: failed to push some refs

What I did to solve the problem was:

git pull origin [branch]
git push origin [branch]

Also make sure that you are pointing to the right branch by running:

git remote set-url origin [url]

How to solve Object reference not set to an instance of an object.?

You need to initialize the list first:

protected List<string> list = new List<string>();

Spring cron expression for every day 1:01:am

You can use annotate your method with @Scheduled(cron ="0 1 1 * * ?").

0 - is for seconds

1- 1 minute

1 - hour of the day.

What is the proper way to comment functions in Python?

Use a docstring:

A string literal that occurs as the first statement in a module, function, class, or method definition. Such a docstring becomes the __doc__ special attribute of that object.

All modules should normally have docstrings, and all functions and classes exported by a module should also have docstrings. Public methods (including the __init__ constructor) should also have docstrings. A package may be documented in the module docstring of the __init__.py file in the package directory.

String literals occurring elsewhere in Python code may also act as documentation. They are not recognized by the Python bytecode compiler and are not accessible as runtime object attributes (i.e. not assigned to __doc__ ), but two types of extra docstrings may be extracted by software tools:

  1. String literals occurring immediately after a simple assignment at the top level of a module, class, or __init__ method are called "attribute docstrings".
  2. String literals occurring immediately after another docstring are called "additional docstrings".

Please see PEP 258 , "Docutils Design Specification" [2] , for a detailed description of attribute and additional docstrings...

Parse json string using JSON.NET

You can use .NET 4's dynamic type and built-in JavaScriptSerializer to do that. Something like this, maybe:

string json = "{\"items\":[{\"Name\":\"AAA\",\"Age\":\"22\",\"Job\":\"PPP\"},{\"Name\":\"BBB\",\"Age\":\"25\",\"Job\":\"QQQ\"},{\"Name\":\"CCC\",\"Age\":\"38\",\"Job\":\"RRR\"}]}";

var jss = new JavaScriptSerializer();

dynamic data = jss.Deserialize<dynamic>(json);

StringBuilder sb = new StringBuilder();

sb.Append("<table>\n  <thead>\n    <tr>\n");

// Build the header based on the keys in the
//  first data item.
foreach (string key in data["items"][0].Keys) {
        sb.AppendFormat("      <th>{0}</th>\n", key);
}

sb.Append("    </tr>\n  </thead>\n  <tbody>\n");

foreach (Dictionary<string, object> item in data["items"]) {
    sb.Append("    <tr>\n");

    foreach (string val in item.Values) {
        sb.AppendFormat("      <td>{0}</td>\n", val);
    }
}

sb.Append("    </tr>\n  </tbody>\n</table>");

string myTable = sb.ToString();

At the end, myTable will hold a string that looks like this:

<table>
    <thead>
        <tr>
            <th>Name</th>
            <th>Age</th>
            <th>Job</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>AAA</td>
            <td>22</td>
            <td>PPP</td>
        <tr>
            <td>BBB</td>
            <td>25</td>
            <td>QQQ</td>
        <tr>
            <td>CCC</td>
            <td>38</td>
            <td>RRR</td>
        </tr>
    </tbody>
</table>

Focus Next Element In Tab Index

I created a simple jQuery plugin which does just this. It uses the ':tabbable' selector of jQuery UI to find the next 'tabbable' element and selects it.

Example usage:

// Simulate tab key when element is clicked 
$('.myElement').bind('click', function(event){
    $.tabNext();
    return false;
});

Maven: add a folder or jar file into current classpath

This might have been asked before. See Can I add jars to maven 2 build classpath without installing them?

In a nutshell: include your jar as dependency with system scope. This requires specifying the absolute path to the jar.

See also http://maven.apache.org/guides/introduction/introduction-to-dependency-mechanism.html

Changing the git user inside Visual Studio Code

Press Ctrl + Shift + G in Visual Studio Code and go to more and select Show git output. Click Terminal and type git remote -v and verify that the origin branch has latest username in it like:

origin [email protected]:DroidPulkit/Facebook-Chat-Bot.git (fetch)

origin [email protected]:DroidPulkit/Facebook-Chat-Bot.git (push)

Here DroidPulkit is my username.

If the username is not what you wanted it to be then change it with:

git add remote origin [email protected]:newUserName/RepoName.git

Node Version Manager (NVM) on Windows

I created a universal nvm that works on both Unix (bash) and Windows, base on another simple nvm.

It doesn't need admin on Windows, but requires PowerShell 4+ and the right to execute scripts.

https://www.npmjs.com/package/@jchip/nvm#installation

Windows batch - concatenate multiple text files into one

Place all files need to copied in a separate folder, for ease place them in c drive.

Open Command Prompt - windows>type cmd>select command prompt.

You can see the default directory pointing - Ex : C:[Folder_Name]>. Change the directory to point to the folder which you have placed files to be copied, using ' cd [Folder_Name] ' command.

After pointing to directory - type 'dir' which shows all the files present in folder, just to make sure everything at place.

Now type : 'copy *.txt [newfile_name].txt' and press enter.

Done!

All the text in individual files will be copied to [newfile_name].txt

How to squash all git commits into one?

Perhaps the easiest way is to just create a new repository with current state of the working copy. If you want to keep all the commit messages you could first do git log > original.log and then edit that for your initial commit message in the new repository:

rm -rf .git
git init
git add .
git commit

or

git log > original.log
# edit original.log as desired
rm -rf .git
git init
git add .
git commit -F original.log

Could not load type from assembly error

The solution to this for me was not mentioned above, so I thought I would add my answer to the long tail...

I ended up having an old reference to a class (an HttpHandler) in web.config that was no longer being used (and was no longer a valid reference). For some reason it was ignored while running in Studio (or maybe I have that class still accessible within my dev setup?) and so I only got this error once I tried deploying to IIS. I searched on the assembly name in web.config, removed the unused handler reference, then this error went away and everything works great. Hope this helps someone else.