Programs & Examples On #Sens

System Event Notification Service

How to implement a simple scenario the OO way

The approach I would take is: when reading the chapters from the database, instead of a collection of chapters, use a collection of books. This will have your chapters organised into books and you'll be able to use information from both classes to present the information to the user (you can even present it in a hierarchical way easily when using this approach).

Empty brackets '[]' appearing when using .where

Stuarts' answer is correct, but if you are not sure if you are saving the titles in lowercase, you can also make a case insensitive search

There are a lot of answered questions in Stack Overflow with more data on this:

Example 1

Example 2

Understanding esModuleInterop in tsconfig file

esModuleInterop generates the helpers outlined in the docs. Looking at the generated code, we can see exactly what these do:

//ts 
import React from 'react'
//js 
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var react_1 = __importDefault(require("react"));

__importDefault: If the module is not an es module then what is returned by require becomes the default. This means that if you use default import on a commonjs module, the whole module is actually the default.

__importStar is best described in this PR:

TypeScript treats a namespace import (i.e. import * as foo from "foo") as equivalent to const foo = require("foo"). Things are simple here, but they don't work out if the primary object being imported is a primitive or a value with call/construct signatures. ECMAScript basically says a namespace record is a plain object.

Babel first requires in the module, and checks for a property named __esModule. If __esModule is set to true, then the behavior is the same as that of TypeScript, but otherwise, it synthesizes a namespace record where:

  1. All properties are plucked off of the require'd module and made available as named imports.
  2. The originally require'd module is made available as a default import.

So we get this:

// ts
import * as React from 'react'

// emitted js
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
var React = __importStar(require("react"));

allowSyntheticDefaultImports is the companion to all of this, setting this to false will not change the emitted helpers (both of them will still look the same). But it will raise a typescript error if you are using default import for a commonjs module. So this import React from 'react' will raise the error Module '".../node_modules/@types/react/index"' has no default export. if allowSyntheticDefaultImports is false.

Pylint "unresolved import" error in Visual Studio Code

That happens because Visual Studio Code considers your current folder as the main folder, instead of considering the actual main folder.

The quick way to fix is it provide the interpreter path to the main folder.

Press Command + Shift + P (or Ctrl + Shift + P on most other systems).

Type Python interpreter

Select the path where you installed Python in from the options available.

Google Maps shows "For development purposes only"

As recommended in a comment, I used the "Google Maps Platform API Checker" Chrome add-in to identify and resolve the issue.

Essentially, this add-in directed me to here where I was able to sign in to Google and create a free API key.

Afterwards, I updated my JavaScript and it immediately resolved this issue.

Old JavaScript: ...script src="https://maps.googleapis.com/maps/api/js?v=3" ...

Updated Javascript:...script src="https://maps.googleapis.com/maps/api/js?key=*****GOOGLE API KEY******&v=3" ...

The add-in then validated the JS API call. Hope this helps someone resolve the issue quickly!

enter image description here

js 'types' can only be used in a .ts file - Visual Studio Code using @ts-check

For anyone who lands here and all the other solutions did not work give this a try. I am using typescript + react and my problem was that I was associating the files in vscode as javascriptreact not typescriptreact so check your settings for the following entries.

   "files.associations": {
    "*.tsx": "typescriptreact",
    "*.ts": "typescriptreact"
  },

How to solve npm install throwing fsevents warning on non-MAC OS?

I also had the same issue though am using MacOS. The issue is kind of bug. I solved this issue by repeatedly running the commands,

sudo npm cache clean --force 
sudo npm uninstall 
sudo npm install

One time it did not work but when I repeatedly cleaned the cache and after uninstalling npm, reinstalling npm, the error went off. I am using Angular 8 and this issue is common

Property 'json' does not exist on type 'Object'

UPDATE: for rxjs > v5.5

As mentioned in some of the comments and other answers, by default the HttpClient deserializes the content of a response into an object. Some of its methods allow passing a generic type argument in order to duck-type the result. Thats why there is no json() method anymore.

import {throwError} from 'rxjs';
import {catchError, map} from 'rxjs/operators';

export interface Order {
  // Properties
}

interface ResponseOrders {
  results: Order[];
}

@Injectable()
export class FooService {
 ctor(private http: HttpClient){}

 fetch(startIndex: number, limit: number): Observable<Order[]> {
    let params = new HttpParams();
    params = params.set('startIndex',startIndex.toString()).set('limit',limit.toString());
    // base URL should not have ? in it at the en
    return this.http.get<ResponseOrders >(this.baseUrl,{
       params
    }).pipe(
       map(res => res.results || []),
       catchError(error => _throwError(error.message || error))
    );
} 

Notice that you could easily transform the returned Observable to a Promise by simply invoking toPromise().

ORIGINAL ANSWER:

In your case, you can

Assumming that your backend returns something like:

{results: [{},{}]}

in JSON format, where every {} is a serialized object, you would need the following:

// Somewhere in your src folder

export interface Order {
  // Properties
}

import { HttpClient, HttpParams } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';

import { Order } from 'somewhere_in_src';    

@Injectable()
export class FooService {
 ctor(private http: HttpClient){}

 fetch(startIndex: number, limit: number): Observable<Order[]> {
    let params = new HttpParams();
    params = params.set('startIndex',startIndex.toString()).set('limit',limit.toString());
    // base URL should not have ? in it at the en
    return this.http.get(this.baseUrl,{
       params
    })
    .map(res => res.results as Order[] || []); 
   // in case that the property results in the res POJO doesnt exist (res.results returns null) then return empty array ([])
  }
} 

I removed the catch section, as this could be archived through a HTTP interceptor. Check the docs. As example:

https://gist.github.com/jotatoledo/765c7f6d8a755613cafca97e83313b90

And to consume you just need to call it like:

// In some component for example
this.fooService.fetch(...).subscribe(data => ...); // data is Order[]

#include errors detected in vscode

The answer is here: How to use C/Cpp extension and add includepath to configurations.

Click the light bulb and then edit the JSON file which is opened. Choose the right block corresponding to your platform (there are Mac, Linux, Win32 – ms-vscode.cpptools version: 3). Update paths in includePath (matters if you compile with VS Code) or browse.paths (matters if you navigate with VS Code) or both.

Thanks to @Francesco Borzì, I will append his answer here:

You have to Left click on the bulb next to the squiggled code line.

If a #include file or one of its dependencies cannot be found, you can also click on the red squiggles under the include statements to view suggestions for how to update your configuration.

enter image description here

Specifying onClick event type with Typescript and React.Konva

You should be using event.currentTarget. React is mirroring the difference between currentTarget (element the event is attached to) and target (the element the event is currently happening on). Since this is a mouse event, type-wise the two could be different, even if it doesn't make sense for a click.

https://github.com/facebook/react/issues/5733 https://developer.mozilla.org/en-US/docs/Web/API/Event/currentTarget

Visual Studio Code - Target of URI doesn't exist 'package:flutter/material.dart'

Also happened to me while trying to run the project inside of another directory.

Worked by using the root directory of the main project

Build .NET Core console application to output an EXE

The following will produce, in the output directory,

  • all the package references
  • the output assembly
  • the bootstrapping exe

But it does not contain all .NET Core runtime assemblies.

<PropertyGroup>
  <Temp>$(SolutionDir)\packaging\</Temp>
</PropertyGroup>

<ItemGroup>
  <BootStrapFiles Include="$(Temp)hostpolicy.dll;$(Temp)$(ProjectName).exe;$(Temp)hostfxr.dll;"/>
</ItemGroup>

<Target Name="GenerateNetcoreExe"
        AfterTargets="Build"
        Condition="'$(IsNestedBuild)' != 'true'">
  <RemoveDir Directories="$(Temp)" />
  <Exec
    ConsoleToMSBuild="true"
    Command="dotnet build $(ProjectPath) -r win-x64 /p:CopyLocalLockFileAssemblies=false;IsNestedBuild=true --output $(Temp)" >
    <Output TaskParameter="ConsoleOutput" PropertyName="OutputOfExec" />
  </Exec>
  <Copy
    SourceFiles="@(BootStrapFiles)"
    DestinationFolder="$(OutputPath)"
  />

</Target>

I wrapped it up in a sample here: https://github.com/SimonCropp/NetCoreConsole

How to print a Groovy variable in Jenkins?

You shouldn't use ${varName} when you're outside of strings, you should just use varName. Inside strings you use it like this; echo "this is a string ${someVariable}";. Infact you can place an general java expression inside of ${...}; echo "this is a string ${func(arg1, arg2)}.

How to check if a key exists in Json Object and get its value

From the structure of your source Object, I would try:

containerObject= new JSONObject(container);
 if(containerObject.has("LabelData")){
  JSONObject innerObject = containerObject.getJSONObject("LabelData");
     if(innerObject.has("video")){
        //Do with video
    }
}

Why binary_crossentropy and categorical_crossentropy give different performances for the same problem?

As it is a multi-class problem, you have to use the categorical_crossentropy, the binary cross entropy will produce bogus results, most likely will only evaluate the first two classes only.

50% for a multi-class problem can be quite good, depending on the number of classes. If you have n classes, then 100/n is the minimum performance you can get by outputting a random class.

Vue template or render function not defined yet I am using neither?

If someone else keeps getting the same error. Just add one extra div in your component template.

As the documentation says:

Component template should contain exactly one root element

Check this simple example:

 import yourComponent from '{path to component}'
    export default {
        components: {
            yourComponent
        },
}

 // Child component
 <template>
     <div> This is the one! </div>
 </template>

Passing data into "router-outlet" child components

Günters answer is great, I just want to point out another way without using Observables.

Here we though have to remember that these objects are passed by reference, so if you want to do some work on the object in the child and not affect the parent object, I would suggest using Günther's solution. But if it doesn't matter, or actually is desired behavior, I would suggest the following.

@Injectable()
export class SharedService {

    sharedNode = {
      // properties
    };
}

In your parent you can assign the value:

this.sharedService.sharedNode = this.node;

And in your children (AND parent), inject the shared Service in your constructor. Remember to provide the service at module level providers array if you want a singleton service all over the components in that module. Alternatively, just add the service in the providers array in the parent only, then the parent and child will share the same instance of service.

node: Node;

ngOnInit() {
    this.node = this.sharedService.sharedNode;    
}

And as newman kindly pointed, you can also have this.sharedService.sharedNode in the html template or a getter:

get sharedNode(){
  return this.sharedService.sharedNode;
}

React - Display loading screen while DOM is rendering?

What about using Pace

Use this link address here.

https://github.hubspot.com/pace/docs/welcome/

1.On their website select the style you want and paste in index.css

2.go to cdnjs Copy the link for Pace Js and add to your script tags in public/index.html

3.It automatically detect web loads and displays the pace at the browser Top.

You can also modify the height and animation in the css also.

How to check if a file exists in a shell script

Internally, the rm command must test for file existence anyway,
so why add another test? Just issue

rm filename

and it will be gone after that, whether it was there or not.
Use rm -f is you don't want any messages about non-existent files.

If you need to take some action if the file does NOT exist, then you must test for that yourself. Based on your example code, this is not the case in this instance.

Getting a UnhandledPromiseRejectionWarning when testing using mocha/chai

The issue is caused by this:

.catch((error) => {
  assert.isNotOk(error,'Promise error');
  done();
});

If the assertion fails, it will throw an error. This error will cause done() never to get called, because the code errored out before it. That's what causes the timeout.

The "Unhandled promise rejection" is also caused by the failed assertion, because if an error is thrown in a catch() handler, and there isn't a subsequent catch() handler, the error will get swallowed (as explained in this article). The UnhandledPromiseRejectionWarning warning is alerting you to this fact.

In general, if you want to test promise-based code in Mocha, you should rely on the fact that Mocha itself can handle promises already. You shouldn't use done(), but instead, return a promise from your test. Mocha will then catch any errors itself.

Like this:

it('should transition with the correct event', () => {
  ...
  return new Promise((resolve, reject) => {
    ...
  }).then((state) => {
    assert(state.action === 'DONE', 'should change state');
  })
  .catch((error) => {
    assert.isNotOk(error,'Promise error');
  });
});

Postgres: check if array field contains value?

This worked for me

let exampleArray = [1, 2, 3, 4, 5];
let exampleToString = exampleArray.toString(); //convert to toString
let query = `Select * from table_name where column_name in (${exampleToString})`; //Execute the query to get response

I have got the same problem, then after an hour of effort I got to know that the array should not be directly accessed in the query. So I then found that the data should be sent in the paranthesis it self, then again I have converted that array to string using toString method in js. So I have worked by executing the above query and got my expected result

NSCameraUsageDescription in iOS 10.0 runtime crash?

the xcode UI has changed a bit from one version to the next so here is where you update the plist for 9.0 beta 4 if it helps Project ->Target ->Infoenter image description here

What is mapDispatchToProps?

I feel like none of the answers have crystallized why mapDispatchToProps is useful.

This can really only be answered in the context of the container-component pattern, which I found best understood by first reading:Container Components then Usage with React.

In a nutshell, your components are supposed to be concerned only with displaying stuff. The only place they are supposed to get information from is their props.

Separated from "displaying stuff" (components) is:

  • how you get the stuff to display,
  • and how you handle events.

That is what containers are for.

Therefore, a "well designed" component in the pattern look like this:

class FancyAlerter extends Component {
    sendAlert = () => {
        this.props.sendTheAlert()
    }

    render() {
        <div>
          <h1>Today's Fancy Alert is {this.props.fancyInfo}</h1>
          <Button onClick={sendAlert}/>
        </div>
     }
}

See how this component gets the info it displays from props (which came from the redux store via mapStateToProps) and it also gets its action function from its props: sendTheAlert().

That's where mapDispatchToProps comes in: in the corresponding container

// FancyButtonContainer.js

function mapDispatchToProps(dispatch) {
    return({
        sendTheAlert: () => {dispatch(ALERT_ACTION)}
    })
}

function mapStateToProps(state) {
    return({fancyInfo: "Fancy this:" + state.currentFunnyString})
}

export const FancyButtonContainer = connect(
    mapStateToProps, mapDispatchToProps)(
    FancyAlerter
)

I wonder if you can see, now that it's the container 1 that knows about redux and dispatch and store and state and ... stuff.

The component in the pattern, FancyAlerter, which does the rendering doesn't need to know about any of that stuff: it gets its method to call at onClick of the button, via its props.

And ... mapDispatchToProps was the useful means that redux provides to let the container easily pass that function into the wrapped component on its props.

All this looks very like the todo example in docs, and another answer here, but I have tried to cast it in the light of the pattern to emphasize why.

(Note: you can't use mapStateToProps for the same purpose as mapDispatchToProps for the basic reason that you don't have access to dispatch inside mapStateToProp. So you couldn't use mapStateToProps to give the wrapped component a method that uses dispatch.

I don't know why they chose to break it into two mapping functions - it might have been tidier to have mapToProps(state, dispatch, props) IE one function to do both!


1 Note that I deliberately explicitly named the container FancyButtonContainer, to highlight that it is a "thing" - the identity (and hence existence!) of the container as "a thing" is sometimes lost in the shorthand

export default connect(...) ????????????

syntax that is shown in most examples

Updates were rejected because the tip of your current branch is behind its remote counterpart

Set current branch name like master

git pull --rebase origin master git push origin master

Or branch name develop

git pull --rebase origin develop git push origin develop

How to convert JSON object to an Typescript array?

That's correct, your response is an object with fields:

{
    "page": 1,
    "results": [ ... ]
}

So you in fact want to iterate the results field only:

this.data = res.json()['results'];

... or even easier:

this.data = res.json().results;

Angular get object from array by Id

CASE - 1

Using array.filter() We can get an array of objects which will match with our condition.
see the working example.

_x000D_
_x000D_
var questions = [
      {id: 1, question: "Do you feel a connection to a higher source and have a sense of comfort knowing that you are part of something greater than yourself?", category: "Spiritual", subs: []},
      {id: 2, question: "Do you feel you are free of unhealthy behavior that impacts your overall well-being?", category: "Habits", subs: []},
      {id: 3, question: "1 Do you feel you have healthy and fulfilling relationships?", category: "Relationships", subs: []},
      {id: 3, question: "2 Do you feel you have healthy and fulfilling relationships?", category: "Relationships", subs: []},
      {id: 3, question: "3 Do you feel you have healthy and fulfilling relationships?", category: "Relationships", subs: []},
      {id: 4, question: "Do you feel you have a sense of purpose and that you have a positive outlook about yourself and life?", category: "Emotional Well-being", subs: []},
      {id: 5, question: "Do you feel you have a healthy diet and that you are fueling your body for optimal health? ", category: "Eating Habits ", subs: []},
      {id: 6, question: "Do you feel that you get enough rest and that your stress level is healthy?", category: "Relaxation ", subs: []},
      {id: 7, question: "Do you feel you get enough physical activity for optimal health?", category: "Exercise ", subs: []},
      {id: 8, question: "Do you feel you practice self-care and go to the doctor regularly?", category: "Medical Maintenance", subs: []},
      {id: 9, question: "Do you feel satisfied with your income and economic stability?", category: "Financial", subs: []},
      {id: 10, question: "1 Do you feel you do fun things and laugh enough in your life?", category: "Play", subs: []},
      {id: 10, question: "2 Do you feel you do fun things and laugh enough in your life?", category: "Play", subs: []},
      {id: 11, question: "Do you feel you have a healthy sense of balance in this area of your life?", category: "Work-life Balance", subs: []},
      {id: 12, question: "Do you feel a sense of peace and contentment  in your home? ", category: "Home Environment", subs: []},
      {id: 13, question: "Do you feel that you are challenged and growing as a person?", category: "Intellectual Wellbeing", subs: []},
      {id: 14, question: "Do you feel content with what you see when you look in the mirror?", category: "Self-image", subs: []},
      {id: 15, question: "Do you feel engaged at work and a sense of fulfillment with your job?", category: "Work Satisfaction", subs: []}
];

function filter(){
  console.clear();
  var filter_id = document.getElementById("filter").value;
  var filter_array = questions.filter(x => x.id == filter_id);
  console.log(filter_array);
}
_x000D_
button {
  background: #0095ff;
  color: white;
  border: none;
  border-radius: 3px;
  padding: 8px;
  cursor: pointer;
}

input {
  padding: 8px;
}
_x000D_
<div>
  <label for="filter"></label>
  <input id="filter" type="number" name="filter" placeholder="Enter id which you want to filter">
  <button onclick="filter()">Filter</button>
</div>
_x000D_
_x000D_
_x000D_

CASE - 2

Using array.find() we can get first matched item and break the iteration.

_x000D_
_x000D_
var questions = [
      {id: 1, question: "Do you feel a connection to a higher source and have a sense of comfort knowing that you are part of something greater than yourself?", category: "Spiritual", subs: []},
      {id: 2, question: "Do you feel you are free of unhealthy behavior that impacts your overall well-being?", category: "Habits", subs: []},
      {id: 3, question: "1 Do you feel you have healthy and fulfilling relationships?", category: "Relationships", subs: []},
      {id: 3, question: "2 Do you feel you have healthy and fulfilling relationships?", category: "Relationships", subs: []},
      {id: 3, question: "3 Do you feel you have healthy and fulfilling relationships?", category: "Relationships", subs: []},
      {id: 4, question: "Do you feel you have a sense of purpose and that you have a positive outlook about yourself and life?", category: "Emotional Well-being", subs: []},
      {id: 5, question: "Do you feel you have a healthy diet and that you are fueling your body for optimal health? ", category: "Eating Habits ", subs: []},
      {id: 6, question: "Do you feel that you get enough rest and that your stress level is healthy?", category: "Relaxation ", subs: []},
      {id: 7, question: "Do you feel you get enough physical activity for optimal health?", category: "Exercise ", subs: []},
      {id: 8, question: "Do you feel you practice self-care and go to the doctor regularly?", category: "Medical Maintenance", subs: []},
      {id: 9, question: "Do you feel satisfied with your income and economic stability?", category: "Financial", subs: []},
      {id: 10, question: "1 Do you feel you do fun things and laugh enough in your life?", category: "Play", subs: []},
      {id: 10, question: "2 Do you feel you do fun things and laugh enough in your life?", category: "Play", subs: []},
      {id: 11, question: "Do you feel you have a healthy sense of balance in this area of your life?", category: "Work-life Balance", subs: []},
      {id: 12, question: "Do you feel a sense of peace and contentment  in your home? ", category: "Home Environment", subs: []},
      {id: 13, question: "Do you feel that you are challenged and growing as a person?", category: "Intellectual Wellbeing", subs: []},
      {id: 14, question: "Do you feel content with what you see when you look in the mirror?", category: "Self-image", subs: []},
      {id: 15, question: "Do you feel engaged at work and a sense of fulfillment with your job?", category: "Work Satisfaction", subs: []}
];

function find(){
  console.clear();
  var find_id = document.getElementById("find").value;
  var find_object = questions.find(x => x.id == find_id);
  console.log(find_object);
}
_x000D_
button {
  background: #0095ff;
  color: white;
  border: none;
  border-radius: 3px;
  padding: 8px;
  cursor: pointer;
}

input {
  padding: 8px;
  width: 200px;
}
_x000D_
<div>
  <label for="find"></label>
  <input id="find" type="number" name="find" placeholder="Enter id which you want to find">
  <button onclick="find()">Find</button>
</div>
_x000D_
_x000D_
_x000D_

Homebrew refusing to link OpenSSL

By default, homebrew gave me OpenSSL version 1.1 and I was looking for version 1.0 instead. This worked for me.

To install version 1.0:

brew install https://github.com/tebelorg/Tump/releases/download/v1.0.0/openssl.rb

Then I tried to symlink my way through it but it gave me the following error:

ln -s /usr/local/Cellar/openssl/1.0.2t/include/openssl /usr/bin/openssl
ln: /usr/bin/openssl: Operation not permitted

Finally linked openssl to point to 1.0 version using brew switch command:

brew switch openssl 1.0.2t
Cleaning /usr/local/Cellar/openssl/1.0.2t
Opt link created for /usr/local/Cellar/openssl/1.0.2t

How to pass data from child component to its parent in ReactJS?

You can create the state in the ParentComponent using useState and pass down the setIsParentData function as prop into the ChildComponent.

In the ChildComponent, update the data using the received function through prop to send the data back to ParentComponent.

I use this technique especially when my code in the ParentComponent is getting too long, therefore I will create child components from the ParentComponent. Typically, it will be only 1 level down and using useContext or redux seems overkill in order to share states between components.

ParentComponent.js

import React, { useState } from 'react';
import ChildComponent from './ChildComponent';

export function ParentComponent(){
  const [isParentData, setIsParentData] = useState(True);

  return (
    <p>is this a parent data?: {isParentData}</p>
    <ChildComponent toChild={isParentData} sendToParent={setIsParentData} />
  );
}

ChildComponent.js

import React from 'react';

export function ChildComponent(props){

  return (
    <button onClick={() => {props.sendToParent(False)}}>Update</button>
    <p>The state of isParentData is {props.toChild}</p>
  );
};

error TS2339: Property 'x' does not exist on type 'Y'

If you want to be able to access images.main then you must define it explicitly:

interface Images {
    main: string;
    [key:string]: string;
}

function getMainImageUrl(images: Images): string {
    return images.main;
}

You can not access indexed properties using the dot notation because typescript has no way of knowing whether or not the object has that property.
However, when you specifically define a property then the compiler knows that it's there (or not), whether it's optional or not and what's the type.


Edit

You can have a helper class for map instances, something like:

class Map<T> {
    private items: { [key: string]: T };

    public constructor() {
        this.items = Object.create(null);
    }

    public set(key: string, value: T): void {
        this.items[key] = value;
    }

    public get(key: string): T {
        return this.items[key];
    }

    public remove(key: string): T {
        let value = this.get(key);
        delete this.items[key];
        return value;
    }
}

function getMainImageUrl(images: Map<string>): string {
    return images.get("main");
}

I have something like that implemented, and I find it very useful.

javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure

Issue resolved.!!! Below are the solutions.

For Java 6: Add below jars into {JAVA_HOME}/jre/lib/ext. 1. bcprov-ext-jdk15on-154.jar 2. bcprov-jdk15on-154.jar

Add property into {JAVA_HOME}/jre/lib/security/java.security security.provider.1=org.bouncycastle.jce.provider.BouncyCastleProvider

Java 7:download jar from below link and add to {JAVA_HOME}/jre/lib/security http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html

Java 8:download jar from below link and add to {JAVA_HOME}/jre/lib/security http://www.oracle.com/technetwork/java/javase/downloads/jce8-download-2133166.html

Issue is that it is failed to decrypt 256 bits of encryption.

How do I select and store columns greater than a number in pandas?

Sample DF:

In [79]: df = pd.DataFrame(np.random.randint(5, 15, (10, 3)), columns=list('abc'))

In [80]: df
Out[80]:
    a   b   c
0   6  11  11
1  14   7   8
2  13   5  11
3  13   7  11
4  13   5   9
5   5  11   9
6   9   8   6
7   5  11  10
8   8  10  14
9   7  14  13

present only those rows where b > 10

In [81]: df[df.b > 10]
Out[81]:
   a   b   c
0  6  11  11
5  5  11   9
7  5  11  10
9  7  14  13

Minimums (for all columns) for the rows satisfying b > 10 condition

In [82]: df[df.b > 10].min()
Out[82]:
a     5
b    11
c     9
dtype: int32

Minimum (for the b column) for the rows satisfying b > 10 condition

In [84]: df.loc[df.b > 10, 'b'].min()
Out[84]: 11

UPDATE: starting from Pandas 0.20.1 the .ix indexer is deprecated, in favor of the more strict .iloc and .loc indexers.

.NET Core vs Mono

This is one of my favorite topics and the content here was just amazing. I was thinking if it would be worth while or effective to compare the methods available in Runtime vs. Mono. I hope I got my terms right, but I think you know what I mean. In order to have a somewhat better understanding of what each Runtime supports currently, would it make sense to compare the methods they provide? I realize implementations may vary, and I have not considered the Framework Class libraries or the slew of other libraries available in one environment vs. the other. I also realize someone might have already done this work even more efficiently. I would be most grateful if you would let me know so I can review it. I feel doing a diff between the outcome of such activity would be of value, and wanted to see how more experienced developers feel about it, and would they provide useful guidance. While back I was playing with reflection, and wrote some lines that traverse the .net directory, and list the assemblies.

WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

The exception indicates a problem with the unobtrusive JavaScript validation mode. This issue is not Sitefinity specific and occurs in any standard ASP.NET applications when the project targets .NET 4.5 framework and the pre-4.5 validation is not enabled in the web.config file.

Open the web.config file and make sure that there is a ValidationSettings:UnobtrusiveValidationMode in the app settings:

<appSettings>
  <add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
</appSettings>

Service located in another namespace

To access services in two different namespaces you can use url like this:

HTTP://<your-service-name>.<namespace-with-that-service>.svc.cluster.local

To list out all your namespaces you can use:

kubectl get namespace

And for service in that namespace you can simply use:

kubectl get services -n <namespace-name>

this will help you.

Dynamic classname inside ngClass in angular 2

  <div *ngFor="let celeb of singers">
  <p [ngClass]="{
    'text-success':celeb.country === 'USA',
    'text-secondary':celeb.country === 'Canada',
    'text-danger':celeb.country === 'Puorto Rico',
    'text-info':celeb.country === 'India'
  }">{{ celeb.artist }} ({{ celeb.country }})
</p>
</div>

Retrofit 2 - URL Query Parameter

I am new to retrofit and I am enjoying it. So here is a simple way to understand it for those that might want to query with more than one query: The ? and & are automatically added for you.

Interface:

 public interface IService {

      String BASE_URL = "https://api.test.com/";
      String API_KEY = "SFSDF24242353434";

      @GET("Search") //i.e https://api.test.com/Search?
      Call<Products> getProducts(@Query("one") String one, @Query("two") String two,    
                                @Query("key") String key)
}

It will be called this way. Considering you did the rest of the code already.

  Call<Results> call = service.productList("Whatever", "here", IService.API_KEY);

For example, when a query is returned, it will look like this.

//-> https://api.test.com/Search?one=Whatever&two=here&key=SFSDF24242353434 

Link to full project: Please star etc: https://github.com/Cosmos-it/ILoveZappos

If you found this useful, don't forget to star it please. :)

Bootstrap 4 card-deck with number of columns based on viewport

This answer is for those who are using Bootstrap 4.1+ and for those who care about IE 11 as well

Card-deck does not adapt the number visible of cards according to the viewport size.

Above methods work but do not support IE. With the below method, you can achieve similar functionality and responsive cards.

You can manage the number of cards to show/hide in different breakpoints.

In Bootstrap 4.1+ columns are same height by default, just make sure your card/content uses all available space. Run the snippet, you'll understand

_x000D_
_x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
<div class="container">_x000D_
    <div class="row">_x000D_
        <div class="col-sm-6 col-lg-4 mb-3">_x000D_
            <div class="card mb-3 h-100">_x000D_
_x000D_
                <div class="card-body">_x000D_
                    <h5 class="card-title">Card title</h5>_x000D_
                    <p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p>_x000D_
                    <p class="card-text"><small class="text-muted">Last updated 3 mins ago</small></p>_x000D_
                </div>_x000D_
            </div>_x000D_
        </div>_x000D_
        <div class="col-sm-6 col-lg-4 mb-3">_x000D_
            <div class="card mb-3 h-100">_x000D_
                <div class="card-body">_x000D_
                    <h5 class="card-title">Card title</h5>_x000D_
                    <p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p>_x000D_
                    <p class="card-text"><small class="text-muted">Last updated 3 mins ago</small></p>_x000D_
                </div>_x000D_
            </div>_x000D_
        </div>_x000D_
        <div class="col-sm-6 col-lg-4 mb-3">_x000D_
            <div class="card mb-3 h-100">_x000D_
                <div class="card-body">_x000D_
                    <h5 class="card-title">Card title</h5>_x000D_
                    <p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p>_x000D_
                    <p class="card-text"><small class="text-muted">Last updated 3 mins ago</small></p>_x000D_
                </div>_x000D_
            </div>_x000D_
        </div>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How can I trigger another job from a jenkins pipeline (jenkinsfile) with GitHub Org Plugin?

You can use the build job step from Jenkins Pipeline (Minimum Jenkins requirement: 2.130).

Here's the full API for the build step: https://jenkins.io/doc/pipeline/steps/pipeline-build-step/

How to use build:

  • job: Name of a downstream job to build. May be another Pipeline job, but more commonly a freestyle or other project.
    • Use a simple name if the job is in the same folder as this upstream Pipeline job;
    • You can instead use relative paths like ../sister-folder/downstream
    • Or you can use absolute paths like /top-level-folder/nested-folder/downstream

Trigger another job using a branch as a param

At my company many of our branches include "/". You must replace any instances of "/" with "%2F" (as it appears in the URL of the job).

In this example we're using relative paths

    stage('Trigger Branch Build') {
        steps {
            script {
                    echo "Triggering job for branch ${env.BRANCH_NAME}"
                    BRANCH_TO_TAG=env.BRANCH_NAME.replace("/","%2F")
                    build job: "../my-relative-job/${BRANCH_TO_TAG}", wait: false
            }
        }
    }

Trigger another job using build number as a param

build job: 'your-job-name', 
    parameters: [
        string(name: 'passed_build_number_param', value: String.valueOf(BUILD_NUMBER)),
        string(name: 'complex_param', value: 'prefix-' + String.valueOf(BUILD_NUMBER))
    ]

Trigger many jobs in parallel

Source: https://jenkins.io/blog/2017/01/19/converting-conditional-to-pipeline/

More info on Parallel here: https://jenkins.io/doc/book/pipeline/syntax/#parallel

    stage ('Trigger Builds In Parallel') {
        steps {
            // Freestyle build trigger calls a list of jobs
            // Pipeline build() step only calls one job
            // To run all three jobs in parallel, we use "parallel" step
            // https://jenkins.io/doc/pipeline/examples/#jobs-in-parallel
            parallel (
                linux: {
                    build job: 'full-build-linux', parameters: [string(name: 'GIT_BRANCH_NAME', value: env.BRANCH_NAME)]
                },
                mac: {
                    build job: 'full-build-mac', parameters: [string(name: 'GIT_BRANCH_NAME', value: env.BRANCH_NAME)]
                },
                windows: {
                    build job: 'full-build-windows', parameters: [string(name: 'GIT_BRANCH_NAME', value: env.BRANCH_NAME)]
                },
                failFast: false)
        }
    }

Or alternatively:

    stage('Build A and B') {
            failFast true
            parallel {
                stage('Build A') {
                    steps {
                            build job: "/project/A/${env.BRANCH}", wait: true
                    }
                }
                stage('Build B') {
                    steps {
                            build job: "/project/B/${env.BRANCH}", wait: true
                    }
                }
            }
    }

What is the purpose of meshgrid in Python / NumPy?

meshgrid helps in creating a rectangular grid from two 1-D arrays of all pairs of points from the two arrays.

x = np.array([0, 1, 2, 3, 4])
y = np.array([0, 1, 2, 3, 4])

Now, if you have defined a function f(x,y) and you wanna apply this function to all the possible combination of points from the arrays 'x' and 'y', then you can do this:

f(*np.meshgrid(x, y))

Say, if your function just produces the product of two elements, then this is how a cartesian product can be achieved, efficiently for large arrays.

Referred from here

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

I ran into the same problem while I was changing some npm settings. I did a mistake with one npm config set command and this added a line referring to a non-existing directory to C:\Users\{User}\.npmrc. After I deleted that line manually from .npmrc, the problem was gone.

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

In my case, I was using the Semantic UI React "Card" view. Once I added a key to each card I constructed, the warning went away, for example:

return (
        <Card fluid key={'message-results-card'}>
          ...
        </Card>
)

How to create JSON object Node.js

What I believe you're looking for is a way to work with arrays as object values:

var o = {} // empty Object
var key = 'Orientation Sensor';
o[key] = []; // empty Array, which you can push() values into


var data = {
    sampleTime: '1450632410296',
    data: '76.36731:3.4651554:0.5665419'
};
var data2 = {
    sampleTime: '1450632410296',
    data: '78.15431:0.5247617:-0.20050584'
};
o[key].push(data);
o[key].push(data2);

This is standard JavaScript and not something NodeJS specific. In order to serialize it to a JSON string you can use the native JSON.stringify:

JSON.stringify(o);
//> '{"Orientation Sensor":[{"sampleTime":"1450632410296","data":"76.36731:3.4651554:0.5665419"},{"sampleTime":"1450632410296","data":"78.15431:0.5247617:-0.20050584"}]}'

Setting up and using Meld as your git difftool and mergetool

I prefer to setup meld as a separate command, like so:

git config --global alias.meld '!git difftool -t meld --dir-diff'

This makes it similar to the git-meld.pl script here: https://github.com/wmanley/git-meld

You can then just run

git meld

Global npm install location on windows?

These are typical npm paths if you install a package globally:

Windows XP -             %USERPROFILE%\Application Data\npm\node_modules
Newer Windows Versions - %AppData%\npm\node_modules
or -                     %AppData%\roaming\npm\node_modules

How to use refs in React with Typescript

Since React 16.3 the way to add refs is to use React.createRef as Jeff Bowen pointed in his answer. However you can take advantage of Typescript to better type your ref.

In your example you're using ref on input element. So they way I would do it is:

class SomeComponent extends React.Component<IProps, IState> {
    private inputRef: React.RefObject<HTMLInputElement>;
    constructor() {
        ...
        this.inputRef = React.createRef();
    }

    ...

    render() {
        <input type="text" ref={this.inputRef} />;
    }
}

By doing this when you want to make use of that ref you have access to all input methods:

someMethod() {
    this.inputRef.current.focus(); // 'current' is input node, autocompletion, yay!
}

You can use it on custom components as well:

private componentRef: React.RefObject<React.Component<IProps>>;

and then have, for example, access to props :

this.componentRef.current.props; // 'props' satisfy IProps interface

How to change environment's font size?

you can use editor.fontSize into your setting.json file of the editor.

for example :

{
"editor.fontSize": 14
}

how to read certain columns from Excel using Pandas - Python

"usecols" should help, use range of columns (as per excel worksheet, A,B...etc.) below are the examples

  1. Selected Columns
df = pd.read_excel(file_location,sheet_name='Sheet1', usecols="A,C,F")
  1. Range of Columns and selected column
df = pd.read_excel(file_location,sheet_name='Sheet1', usecols="A:F,H")
  1. Multiple Ranges
df = pd.read_excel(file_location,sheet_name='Sheet1', usecols="A:F,H,J:N")
  1. Range of columns
df = pd.read_excel(file_location,sheet_name='Sheet1', usecols="A:N")

Mockito - NullpointerException when stubbing Method

When using JUnit 5 or above. You have to inject the class annotated with @Mock in an @BeforeEach setup.

How do I prevent the error "Index signature of object type implicitly has an 'any' type" when compiling typescript with noImplicitAny flag enabled?

Create an interface to define the 'indexer' interface

Then create your object with that index.

Note: this will still have same issues other answers have described with respect to enforcing the type of each item - but that's often exactly what you want.

You can make the generic type parameter whatever you need : ObjectIndexer< Dog | Cat>

// this should be global somewhere, or you may already be 
// using a library that provides such a type
export interface ObjectIndexer<T> {
  [id: string]: T;
}

interface ISomeObject extends ObjectIndexer<string>
{
    firstKey:   string;
    secondKey:  string;
    thirdKey:   string;
}

let someObject: ISomeObject = {
    firstKey:   'firstValue',
    secondKey:  'secondValue',
    thirdKey:   'thirdValue'
};

let key: string = 'secondKey';

let secondValue: string = someObject[key];

Typescript Playground


You can even use this in a generic constraint when defining a generic type:

export class SmartFormGroup<T extends IndexableObject<any>> extends FormGroup

Then T inside the class can be indexed :-)

Fork() function in C

System call fork() is used to create processes. It takes no arguments and returns a process ID. The purpose of fork() is to create a new process, which becomes the child process of the caller. After a new child process is created, both processes will execute the next instruction following the fork() system call. Therefore, we have to distinguish the parent from the child. This can be done by testing the returned value of fork()

Fork is a system call and you shouldnt think of it as a normal C function. When a fork() occurs you effectively create two new processes with their own address space.Variable that are initialized before the fork() call store the same values in both the address space. However values modified within the address space of either of the process remain unaffected in other process one of which is parent and the other is child. So if,

pid=fork();

If in the subsequent blocks of code you check the value of pid.Both processes run for the entire length of your code. So how do we distinguish them. Again Fork is a system call and here is difference.Inside the newly created child process pid will store 0 while in the parent process it would store a positive value.A negative value inside pid indicates a fork error.

When we test the value of pid to find whether it is equal to zero or greater than it we are effectively finding out whether we are in the child process or the parent process.

Read more about Fork

Declaring static constants in ES6 classes?

You can define it like this:

class Foo {
  static MyConst = 200;

  myFunc() {
    const doubleConst = Foo.MyConst * 2;
  }
}

How to to send mail using gmail in Laravel?

The problem for me is that for some reason the username/password came NULL from mail config. To check that before sending a email check with the follow code:

dd(Config::get('mail'));

If your username/password came nulled just set with:

Config::set('mail.username', 'yourusername');
Config::set('mail.password', 'yourpassword');

How do I define the name of image built with docker-compose

According to 3.9 version of Docker compose, you can use image: myapp:tag to specify name and tag.

version: "3.9"
services:
  webapp:
    build:
      context: .
      dockerfile: Dockerfile
    image: webapp:tag

Reference: https://docs.docker.com/compose/compose-file/compose-file-v3/

Why should Java 8's Optional not be used in arguments

I know that this question is more about opinion rather than hard facts. But I recently moved from being a .net developer to a java one, so I have only recently joined the Optional party. Also, I'd prefer to state this as a comment, but since my point level does not allow me to comment, I am forced to put this as an answer instead.

What I have been doing, which has served me well as a rule of thumb. Is to use Optionals for return types, and only use Optionals as parameters, if I require both the value of the Optional, and weather or not the Optional had a value within the method.

If I only care about the value, I check isPresent before calling the method, if I have some kind of logging or different logic within the method that depends on if the value exists, then I will happily pass in the Optional.

Check if a file exists or not in Windows PowerShell?

You want to use Test-Path:

Test-Path <path to file> -PathType Leaf

Scikit-learn: How to obtain True Positive, True Negative, False Positive and False Negative

#FalseNegatives

test = pd.merge(Variables_test, Banknote_test,left_index=True, right_index=True)
Banknote_test_pred = pd.DataFrame(banknote_test_pred)
Banknote_test_pred.rename(columns={0 :'Predicted'}, inplace=True )
test = test.reset_index(drop=True).merge(Banknote_test_pred.reset_index(drop=True), left_index=True, right_index=True)
test['FN'] = np.where((test['Banknote']=="Genuine") & (test['Predicted']=="Forged"),1,0)
test[test.FN != 0]

Simple line plots using seaborn

Since seaborn also uses matplotlib to do its plotting you can easily combine the two. If you only want to adopt the styling of seaborn the set_style function should get you started:

import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns

sns.set_style("darkgrid")
plt.plot(np.cumsum(np.random.randn(1000,1)))
plt.show()

Result:

enter image description here

When do I use path params vs. query params in a RESTful API?

In a REST API, you shouldn't be overly concerned by predictable URI's. The very suggestion of URI predictability alludes to a misunderstanding of RESTful architecture. It assumes that a client should be constructing URIs themselves, which they really shouldn't have to.

However, I assume that you are not creating a true REST API, but a 'REST inspired' API (such as the Google Drive one). In these cases the rule of thumb is 'path params = resource identification' and 'query params = resource sorting'. So, the question becomes, can you uniquely identify your resource WITHOUT status / region? If yes, then perhaps its a query param. If no, then its a path param.

HTH.

Cannot execute RUN mkdir in a Dockerfile

The problem is that /var/www doesn't exist either, and mkdir isn't recursive by default -- it expects the immediate parent directory to exist.

Use:

mkdir -p /var/www/app

...or install a package that creates a /var/www prior to reaching this point in your Dockerfile.

Can you force a React component to rerender without calling setState?

forceUpdate(), but every time I've ever heard someone talk about it, it's been followed up with you should never use this.

How to compile c# in Microsoft's new Visual Studio Code?

Install the extension "Code Runner". Check if you can compile your program with csc (ex.: csc hello.cs). The command csc is shipped with Mono. Then add this to your VS Code user settings:

"code-runner.executorMap": {
        "csharp": "echo '# calling mono\n' && cd $dir && csc /nologo $fileName && mono $dir$fileNameWithoutExt.exe",
        // "csharp": "echo '# calling dotnet run\n' && dotnet run"
    }

Open your C# file and use the execution key of Code Runner.

Edit: also added dotnet run, so you can choose how you want to execute your program: with Mono, or with dotnet. If you choose dotnet, then first create the project (dotnet new console, dotnet restore).

Check if returned value is not null and if so assign it, in one line, with one method call

Using Java 1.8 you can use Optional

public class Main  {

    public static void main(String[] args) {

        //example call, the methods are just dumb templates, note they are static
        FutureMeal meal = getChicken().orElse(getFreeRangeChicken());

        //another possible way to call this having static methods is
        FutureMeal meal = getChicken().orElseGet(Main::getFreeRangeChicken); //method reference

        //or if you would use a Instance of Main and call getChicken and getFreeRangeChicken
        // as nonstatic methods (assume static would be replaced with public for this)
        Main m = new Main();
        FutureMeal meal = m.getChicken().orElseGet(m::getFreeRangeChicken); //method reference

        //or
        FutureMeal meal = m.getChicken().orElse(m.getFreeRangeChicken()); //method call


    }

    static Optional<FutureMeal> getChicken(){

        //instead of returning null, you would return Optional.empty() 
        //here I just return it to demonstrate
        return Optional.empty();

        //if you would return a valid object the following comment would be the code
        //FutureMeal ret = new FutureMeal(); //your return object
        //return Optional.of(ret);            

    }

    static FutureMeal getFreeRangeChicken(){
        return new FutureMeal();
    }
}

You would implement a logic for getChicken to return either Optional.empty() instead of null, or Optional.of(myReturnObject), where myReturnObject is your chicken.

Then you can call getChicken() and if it would return Optional.empty() the orElse(fallback) would give you whatever the fallback would be, in your case the second method.

How to loop and render elements in React.js without an array of objects to map?

Array.from() takes an iterable object to convert to an array and an optional map function. You could create an object with a .length property as follows:

return Array.from({length: this.props.level}, (item, index) => 
  <span className="indent" key={index}></span>
);

Spring Boot REST service exception handling

Although this is an older question, I would like to share my thoughts on this. I hope, that it will be helpful to some of you.

I am currently building a REST API which makes use of Spring Boot 1.5.2.RELEASE with Spring Framework 4.3.7.RELEASE. I use the Java Config approach (as opposed to XML configuration). Also, my project uses a global exception handling mechanism using the @RestControllerAdvice annotation (see later below).

My project has the same requirements as yours: I want my REST API to return a HTTP 404 Not Found with an accompanying JSON payload in the HTTP response to the API client when it tries to send a request to an URL which does not exist. In my case, the JSON payload looks like this (which clearly differs from the Spring Boot default, btw.):

{
    "code": 1000,
    "message": "No handler found for your request.",
    "timestamp": "2017-11-20T02:40:57.628Z"
}

I finally made it work. Here are the main tasks you need to do in brief:

  • Make sure that the NoHandlerFoundException is thrown if API clients call URLS for which no handler method exists (see Step 1 below).
  • Create a custom error class (in my case ApiError) which contains all the data that should be returned to the API client (see step 2).
  • Create an exception handler which reacts on the NoHandlerFoundException and returns a proper error message to the API client (see step 3).
  • Write a test for it and make sure, it works (see step 4).

Ok, now on to the details:

Step 1: Configure application.properties

I had to add the following two configuration settings to the project's application.properties file:

spring.mvc.throw-exception-if-no-handler-found=true
spring.resources.add-mappings=false

This makes sure, the NoHandlerFoundException is thrown in cases where a client tries to access an URL for which no controller method exists which would be able to handle the request.

Step 2: Create a Class for API Errors

I made a class similar to the one suggested in this article on Eugen Paraschiv's blog. This class represents an API error. This information is sent to the client in the HTTP response body in case of an error.

public class ApiError {

    private int code;
    private String message;
    private Instant timestamp;

    public ApiError(int code, String message) {
        this.code = code;
        this.message = message;
        this.timestamp = Instant.now();
    }

    public ApiError(int code, String message, Instant timestamp) {
        this.code = code;
        this.message = message;
        this.timestamp = timestamp;
    }

    // Getters and setters here...
}

Step 3: Create / Configure a Global Exception Handler

I use the following class to handle exceptions (for simplicity, I have removed import statements, logging code and some other, non-relevant pieces of code):

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(NoHandlerFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public ApiError noHandlerFoundException(
            NoHandlerFoundException ex) {

        int code = 1000;
        String message = "No handler found for your request.";
        return new ApiError(code, message);
    }

    // More exception handlers here ...
}

Step 4: Write a test

I want to make sure, the API always returns the correct error messages to the calling client, even in the case of failure. Thus, I wrote a test like this:

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SprintBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc
@ActiveProfiles("dev")
public class GlobalExceptionHandlerIntegrationTest {

    public static final String ISO8601_DATE_REGEX =
        "^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{3}Z$";

    @Autowired
    private MockMvc mockMvc;

    @Test
    @WithMockUser(roles = "DEVICE_SCAN_HOSTS")
    public void invalidUrl_returnsHttp404() throws Exception {
        RequestBuilder requestBuilder = getGetRequestBuilder("/does-not-exist");
        mockMvc.perform(requestBuilder)
            .andExpect(status().isNotFound())
            .andExpect(jsonPath("$.code", is(1000)))
            .andExpect(jsonPath("$.message", is("No handler found for your request.")))
            .andExpect(jsonPath("$.timestamp", RegexMatcher.matchesRegex(ISO8601_DATE_REGEX)));
    }

    private RequestBuilder getGetRequestBuilder(String url) {
        return MockMvcRequestBuilders
            .get(url)
            .accept(MediaType.APPLICATION_JSON);
    }

The @ActiveProfiles("dev") annotation can be left away. I use it only as I work with different profiles. The RegexMatcher is a custom Hamcrest matcher I use to better handle timestamp fields. Here's the code (I found it here):

public class RegexMatcher extends TypeSafeMatcher<String> {

    private final String regex;

    public RegexMatcher(final String regex) {
        this.regex = regex;
    }

    @Override
    public void describeTo(final Description description) {
        description.appendText("matches regular expression=`" + regex + "`");
    }

    @Override
    public boolean matchesSafely(final String string) {
        return string.matches(regex);
    }

    // Matcher method you can call on this matcher class
    public static RegexMatcher matchesRegex(final String string) {
        return new RegexMatcher(regex);
    }
}

Some further notes from my side:

  • In many other posts on StackOverflow, people suggested setting the @EnableWebMvc annotation. This was not necessary in my case.
  • This approach works well with MockMvc (see test above).

Use of PUT vs PATCH methods in REST API real life scenarios

I was curious about this as well and found a few interesting articles. I may not answer your question to its full extent, but this at least provides some more information.

http://restful-api-design.readthedocs.org/en/latest/methods.html

The HTTP RFC specifies that PUT must take a full new resource representation as the request entity. This means that if for example only certain attributes are provided, those should be remove (i.e. set to null).

Given that, then a PUT should send the entire object. For instance,

/users/1
PUT {id: 1, username: 'skwee357', email: '[email protected]'}

This would effectively update the email. The reason PUT may not be too effective is that your only really modifying one field and including the username is kind of useless. The next example shows the difference.

/users/1
PUT {id: 1, email: '[email protected]'}

Now, if the PUT was designed according the spec, then the PUT would set the username to null and you would get the following back.

{id: 1, username: null, email: '[email protected]'}

When you use a PATCH, you only update the field you specify and leave the rest alone as in your example.

The following take on the PATCH is a little different than I have never seen before.

http://williamdurand.fr/2014/02/14/please-do-not-patch-like-an-idiot/

The difference between the PUT and PATCH requests is reflected in the way the server processes the enclosed entity to modify the resource identified by the Request-URI. In a PUT request, the enclosed entity is considered to be a modified version of the resource stored on the origin server, and the client is requesting that the stored version be replaced. With PATCH, however, the enclosed entity contains a set of instructions describing how a resource currently residing on the origin server should be modified to produce a new version. The PATCH method affects the resource identified by the Request-URI, and it also MAY have side effects on other resources; i.e., new resources may be created, or existing ones modified, by the application of a PATCH.

PATCH /users/123

[
    { "op": "replace", "path": "/email", "value": "[email protected]" }
]

You are more or less treating the PATCH as a way to update a field. So instead of sending over the partial object, you're sending over the operation. i.e. Replace email with value.

The article ends with this.

It is worth mentioning that PATCH is not really designed for truly REST APIs, as Fielding's dissertation does not define any way to partially modify resources. But, Roy Fielding himself said that PATCH was something [he] created for the initial HTTP/1.1 proposal because partial PUT is never RESTful. Sure you are not transferring a complete representation, but REST does not require representations to be complete anyway.

Now, I don't know if I particularly agree with the article as many commentators point out. Sending over a partial representation can easily be a description of the changes.

For me, I am mixed on using PATCH. For the most part, I will treat PUT as a PATCH since the only real difference I have noticed so far is that PUT "should" set missing values to null. It may not be the 'most correct' way to do it, but good luck coding perfect.

Can not deserialize instance of java.lang.String out of START_ARRAY token

The error is:

Can not deserialize instance of java.lang.String out of START_ARRAY token at [Source: line: 1, column: 1095] (through reference chain: JsonGen["platforms"])

In JSON, platforms look like this:

"platforms": [
    {
        "platform": "iphone"
    },
    {
        "platform": "ipad"
    },
    {
        "platform": "android_phone"
    },
    {
        "platform": "android_tablet"
    }
]

So try change your pojo to something like this:

private List platforms;

public List getPlatforms(){
    return this.platforms;
}

public void setPlatforms(List platforms){
    this.platforms = platforms;
}

EDIT: you will need change mobile_networks too. Will look like this:

private List mobile_networks;

public List getMobile_networks() {
    return mobile_networks;
}

public void setMobile_networks(List mobile_networks) {
    this.mobile_networks = mobile_networks;
}

SSL cert "err_cert_authority_invalid" on mobile chrome only

I solved my problem with this commands:

cat __mydomain_com.crt __mydomain_com.ca-bundle > __mydomain_com_combine.crt

and after:

cat __mydomain_com_combine.crt COMODORSADomainValidationSecureServerCA.crt 
COMODORSAAddTrustCA.crt AddTrustExternalCARoot.crt > mydomain.pem

And in my domain nginx .conf I put on the server 443:

ssl_certificate          ssl/mydomain.pem;
ssl_certificate_key      ssl/mydomain.private.key;

I don't forget restart your "Nginx"

service nginx restart

How do I create a master branch in a bare Git repository?

A branch is just a reference to a commit. Until you commit anything to the repository, you don't have any branches. You can see this in a non-bare repository as well.

$ mkdir repo
$ cd repo
$ git init
Initialized empty Git repository in /home/me/repo/.git/
$ git branch
$ touch foo
$ git add foo
$ git commit -m "new file"
1 file changed, 0 insertions(+), 0 deletions(-)
create mode 100644 foo
$ git branch
* master

How to include scripts located inside the node_modules folder?

I did the below changes to AUTO-INCLUDE the files in the index html. So that when you add a file in the folder it will automatically be picked up from the folder, without you having to include the file in index.html

//// THIS WORKS FOR ME 
///// in app.js or server.js

var app = express();

app.use("/", express.static(__dirname));
var fs = require("fs"),

function getFiles (dir, files_){
    files_ = files_ || [];
    var files = fs.readdirSync(dir);
    for (var i in files){
        var name = dir + '/' + files[i];
        if (fs.statSync(name).isDirectory()){
            getFiles(name, files_);
        } else {
            files_.push(name);
        }
    }
    return files_;
}
//// send the files in js folder as variable/array 
ejs = require('ejs');

res.render('index', {
    'something':'something'...........
    jsfiles: jsfiles,
});

///--------------------------------------------------

///////// in views/index.ejs --- the below code will list the files in index.ejs

<% for(var i=0; i < jsfiles.length; i++) { %>
   <script src="<%= jsfiles[i] %>"></script>
<% } %>

Correct way of getting Client's IP Addresses from http.Request

This is how I come up with the IP

func ReadUserIP(r *http.Request) string {
    IPAddress := r.Header.Get("X-Real-Ip")
    if IPAddress == "" {
        IPAddress = r.Header.Get("X-Forwarded-For")
    }
    if IPAddress == "" {
        IPAddress = r.RemoteAddr
    }
    return IPAddress
}
  • X-Real-Ip - fetches first true IP (if the requests sits behind multiple NAT sources/load balancer)

  • X-Forwarded-For - if for some reason X-Real-Ip is blank and does not return response, get from X-Forwarded-For

  • Remote Address - last resort (usually won't be reliable as this might be the last ip or if it is a naked http request to server ie no load balancer)

pandas create new column based on values from other columns / apply a function of multiple columns, row-wise

.apply() takes in a function as the first parameter; pass in the label_race function as so:

df['race_label'] = df.apply(label_race, axis=1)

You don't need to make a lambda function to pass in a function.

$rootScope.$broadcast vs. $scope.$emit

tl;dr (this tl;dr is from @sp00m's answer below)

$emit dispatches an event upwards ... $broadcast dispatches an event downwards

Detailed explanation

$rootScope.$emit only lets other $rootScope listeners catch it. This is good when you don't want every $scope to get it. Mostly a high level communication. Think of it as adults talking to each other in a room so the kids can't hear them.

$rootScope.$broadcast is a method that lets pretty much everything hear it. This would be the equivalent of parents yelling that dinner is ready so everyone in the house hears it.

$scope.$emit is when you want that $scope and all its parents and $rootScope to hear the event. This is a child whining to their parents at home (but not at a grocery store where other kids can hear).

$scope.$broadcast is for the $scope itself and its children. This is a child whispering to its stuffed animals so their parents can't hear.

What does Include() do in LINQ?

I just wanted to add that "Include" is part of eager loading. It is described in Entity Framework 6 tutorial by Microsoft. Here is the link: https://docs.microsoft.com/en-us/aspnet/mvc/overview/getting-started/getting-started-with-ef-using-mvc/reading-related-data-with-the-entity-framework-in-an-asp-net-mvc-application


Excerpt from the linked page:

Here are several ways that the Entity Framework can load related data into the navigation properties of an entity:

Lazy loading. When the entity is first read, related data isn't retrieved. However, the first time you attempt to access a navigation property, the data required for that navigation property is automatically retrieved. This results in multiple queries sent to the database — one for the entity itself and one each time that related data for the entity must be retrieved. The DbContext class enables lazy loading by default.

Eager loading. When the entity is read, related data is retrieved along with it. This typically results in a single join query that retrieves all of the data that's needed. You specify eager loading by using the Include method.

Explicit loading. This is similar to lazy loading, except that you explicitly retrieve the related data in code; it doesn't happen automatically when you access a navigation property. You load related data manually by getting the object state manager entry for an entity and calling the Collection.Load method for collections or the Reference.Load method for properties that hold a single entity. (In the following example, if you wanted to load the Administrator navigation property, you'd replace Collection(x => x.Courses) with Reference(x => x.Administrator).) Typically you'd use explicit loading only when you've turned lazy loading off.

Because they don't immediately retrieve the property values, lazy loading and explicit loading are also both known as deferred loading.

How to modify WooCommerce cart, checkout pages (main theme portion)

You can use the is_cart() conditional tag:

if (! is_cart() ) {
  // Do something.
}

Wildcard string comparison in Javascript

You should use RegExp (they are awesome) an easy solution is:

if( /^bird/.test(animals[i]) ){
    // a bird :D
}

How to check cordova android version of a cordova/phonegap project?

The file platforms/platforms.json lists all of the platform versions.

COLLATION 'utf8_general_ci' is not valid for CHARACTER SET 'latin1'

In my case I created a database and gave the collation 'utf8_general_ci' but the required collation was 'latin1'. After changing my collation type to latin1_bin the error was gone.

How to check if input file is empty in jQuery

Questions : how to check File is empty or not?

Ans: I have slove this issue using this Jquery code

_x000D_
_x000D_
//If your file Is Empty :     _x000D_
      if (jQuery('#videoUploadFile').val() == '') {_x000D_
                       $('#message').html("Please Attach File");_x000D_
                   }else {_x000D_
                            alert('not work');_x000D_
                   }_x000D_
_x000D_
    
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input type="file" id="videoUploadFile">_x000D_
<br>_x000D_
<br>_x000D_
<div id="message"></div>
_x000D_
_x000D_
_x000D_

Fatal error: Please read "Security" section of the manual to find out how to run mysqld as root

in my case (RHEL7 and MariaDB) this works.

sudo systemctl restart mariadb

How to validate an e-mail address in swift?

Here is an extension in Swift 3

extension String {
    func isValidEmail() -> Bool {
        let emailRegex = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"
        return NSPredicate(format: "SELF MATCHES %@", emailRegex).evaluate(with: self)
    }
}

Just use it like this:

if yourEmailString.isValidEmail() {
    //code for valid email address
} else {
    //code for not valid email address
}

How to parse unix timestamp to time.Time

You can directly use time.Unix function of time which converts the unix time stamp to UTC

package main

import (
  "fmt"
  "time"
)


func main() {
    unixTimeUTC:=time.Unix(1405544146, 0) //gives unix time stamp in utc 

    unitTimeInRFC3339 :=unixTimeUTC.Format(time.RFC3339) // converts utc time to RFC3339 format

    fmt.Println("unix time stamp in UTC :--->",unixTimeUTC)
    fmt.Println("unix time stamp in unitTimeInRFC3339 format :->",unitTimeInRFC3339)
}

Output

unix time stamp in UTC :---> 2014-07-16 20:55:46 +0000 UTC
unix time stamp in unitTimeInRFC3339 format :----> 2014-07-16T20:55:46Z

Check in Go Playground: https://play.golang.org/p/5FtRdnkxAd

Disable Proximity Sensor during call

edit build.prop in folder /system if below line is exist change the value and if not exist add this line and save.(device must be rooted)

ro.lge.proximity.delay=25
mot.proximity.delay=25  

Bulk package updates using Conda

# list packages that can be updated
conda search --outdated

# update all packages prompted(by asking the user yes/no)
conda update --all

# update all packages unprompted
conda update --all -y

How to set the action for a UIBarButtonItem in Swift

Swift 5

if you have created UIBarButtonItem in Interface Builder and you connected outlet to item and want to bind selector programmatically.

Don't forget to set target and selector.

addAppointmentButton.action = #selector(moveToAddAppointment)
addAppointmentButton.target = self

@objc private func moveToAddAppointment() {
     self.presenter.goToCreateNewAppointment()
}

Swift Beta performance: sorting arrays

func partition(inout list : [Int], low: Int, high : Int) -> Int {
    let pivot = list[high]
    var j = low
    var i = j - 1
    while j < high {
        if list[j] <= pivot{
            i += 1
            (list[i], list[j]) = (list[j], list[i])
        }
        j += 1
    }
    (list[i+1], list[high]) = (list[high], list[i+1])
    return i+1
}

func quikcSort(inout list : [Int] , low : Int , high : Int) {

    if low < high {
        let pIndex = partition(&list, low: low, high: high)
        quikcSort(&list, low: low, high: pIndex-1)
        quikcSort(&list, low: pIndex + 1, high: high)
    }
}

var list = [7,3,15,10,0,8,2,4]
quikcSort(&list, low: 0, high: list.count-1)

var list2 = [ 10, 0, 3, 9, 2, 14, 26, 27, 1, 5, 8, -1, 8 ]
quikcSort(&list2, low: 0, high: list2.count-1)

var list3 = [1,3,9,8,2,7,5]
quikcSort(&list3, low: 0, high: list3.count-1) 

This is my Blog about Quick Sort- Github sample Quick-Sort

You can take a look at Lomuto's partitioning algorithm in Partitioning the list. Written in Swift.

Retrofit and GET using parameters

@QueryMap worked for me instead of FieldMap

If you have a bunch of GET params, another way to pass them into your url is a HashMap.

class YourActivity extends Activity {

private static final String BASEPATH = "http://www.example.com";

private interface API {
    @GET("/thing")
    void getMyThing(@QueryMap Map<String, String> params, new Callback<String> callback);
}

public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.your_layout);

   RestAdapter rest = new RestAdapter.Builder().setEndpoint(BASEPATH).build();
   API service = rest.create(API.class);

   Map<String, String> params = new HashMap<String, String>();
   params.put("key1", "val1");
   params.put("key2", "val2");
   // ... as much as you need.

   service.getMyThing(params, new Callback<String>() {
       // ... do some stuff here.
   });
}
}

The URL called will be http://www.example.com/thing/?key1=val1&key2=val2

What does an exclamation mark mean in the Swift language?

ASK YOURSELF

  • Does the type person? have an apartment member/property? OR
  • Does the type person have an apartment member/property?

If you can't answer this question, then continue reading:

To understand you may need super-basic level of understanding of Generics. See here. A lot of things in Swift are written using Generics. Optionals included

The code below has been made available from this Stanford video. Highly recommend you to watch the first 5 minutes

An Optional is an enum with only 2 cases

enum Optional<T>{
    case None
    case Some(T)
}

let x: String? = nil //actually means:

let x = Optional<String>.None

let x :String? = "hello" //actually means:

let x = Optional<String>.Some("hello")

var y = x! // actually means:

switch x {
case .Some(let value): y = value
case .None: // Raise an exception
}

Optional binding:

let x:String? = something
if let y = x {
    // do something with y
}
//Actually means:

switch x{
case .Some(let y): print)(y) // or whatever else you like using 
case .None: break
}

when you say var john: Person? You actually mean such:

enum Optional<Person>{
case .None
case .Some(Person)
}

Does the above enum have any property named apartment? Do you see it anywhere? It's not there at all! However if you unwrap it ie do person! then you can ... what it does under the hood is : Optional<Person>.Some(Person(name: "John Appleseed"))


Had you defined var john: Person instead of: var john: Person? then you would have no longer needed to have the ! used, because Person itself does have a member of apartment


As a future discussion on why using ! to unwrap is sometimes not recommended see this Q&A

Mipmap drawables for icons

Since I was looking for an clarifying answer to this to determine the right type for notification icons, I'd like to add this clear statement to the topic. It's from http://developer.android.com/tools/help/image-asset-studio.html#saving

Note: Launcher icon files reside in a different location from that of other icons. They are located in the mipmap/ folder. All other icon files reside in the drawable/ folder of your project.

html5 <input type="file" accept="image/*" capture="camera"> display as image rather than "choose file" button

For those who need the input file to open directly the camera, you just have to declare capture parameter to the input file, like this :

<input type="file" accept="image/*" capture>

How to remove/ignore :hover css style on touch devices

Pointer adaptation to the rescue!

Since this hasn't been touched in awhile, you can use:

a:link, a:visited {
   color: red;
}

a:hover {
   color:blue;
}

@media (hover: none) {
   a:link, a:visited {
      color: red;
   }
}

See this demo in both your desktop browser and your phone browser. Supported by modern touch devices.

Note: Keep in mind that since a Surface PC's primary input (capability) is a mouse, it will end up being a blue link, even if it's a detached (tablet) screen. Browsers will (should) always default to the most precise input's capability.

Why can't I use Docker CMD multiple times to run multiple services?

To address why CMD is designed to run only one service per container, let's just realize what would happen if the secondary servers run in the same container are not trivial / auxiliary but "major" (e.g. storage bundled with the frontend app). For starters, it would break down several important containerization features such as horizontal (auto-)scaling and rescheduling between nodes, both of which assume there is only one application (source of CPU load) per container. Then there is the issue of vulnerabilities - more servers exposed in a container means more frequent patching of CVEs...

So let's admit that it is a 'nudge' from Docker (and Kubernetes/Openshift) designers towards good practices and we should not reinvent workarounds (SSH is not necessary - we have docker exec / kubectl exec / oc rsh designed to replace it).

  • More info

https://devops.stackexchange.com/questions/447/why-it-is-recommended-to-run-only-one-process-in-a-container

What's the difference between integer class and numeric class in R

There are multiple classes that are grouped together as "numeric" classes, the 2 most common of which are double (for double precision floating point numbers) and integer. R will automatically convert between the numeric classes when needed, so for the most part it does not matter to the casual user whether the number 3 is currently stored as an integer or as a double. Most math is done using double precision, so that is often the default storage.

Sometimes you may want to specifically store a vector as integers if you know that they will never be converted to doubles (used as ID values or indexing) since integers require less storage space. But if they are going to be used in any math that will convert them to double, then it will probably be quickest to just store them as doubles to begin with.

Start redis-server with config file

To start redis with a config file all you need to do is specifiy the config file as an argument:

redis-server /root/config/redis.rb

Instead of using and killing PID's I would suggest creating an init script for your service

I would suggest taking a look at the Installing Redis more properly section of http://redis.io/topics/quickstart. It will walk you through setting up an init script with redis so you can just do something like service redis_server start and service redis_server stop to control your server.

I am not sure exactly what distro you are using, that article describes instructions for a Debian based distro. If you are are using a RHEL/Fedora distro let me know, I can provide you with instructions for the last couple of steps, the config file and most of the other steps will be the same.

Asking the user for input until they give a valid response

Functional approach or "look mum no loops!":

from itertools import chain, repeat

prompts = chain(["Enter a number: "], repeat("Not a number! Try again: "))
replies = map(input, prompts)
valid_response = next(filter(str.isdigit, replies))
print(valid_response)
Enter a number:  a
Not a number! Try again:  b
Not a number! Try again:  1
1

or if you want to have a "bad input" message separated from an input prompt as in other answers:

prompt_msg = "Enter a number: "
bad_input_msg = "Sorry, I didn't understand that."
prompts = chain([prompt_msg], repeat('\n'.join([bad_input_msg, prompt_msg])))
replies = map(input, prompts)
valid_response = next(filter(str.isdigit, replies))
print(valid_response)
Enter a number:  a
Sorry, I didn't understand that.
Enter a number:  b
Sorry, I didn't understand that.
Enter a number:  1
1

How does it work?

  1. prompts = chain(["Enter a number: "], repeat("Not a number! Try again: "))
    
    This combination of itertools.chain and itertools.repeat will create an iterator which will yield strings "Enter a number: " once, and "Not a number! Try again: " an infinite number of times:
    for prompt in prompts:
        print(prompt)
    
    Enter a number: 
    Not a number! Try again: 
    Not a number! Try again: 
    Not a number! Try again: 
    # ... and so on
    
  2. replies = map(input, prompts) - here map will apply all the prompts strings from the previous step to the input function. E.g.:
    for reply in replies:
        print(reply)
    
    Enter a number:  a
    a
    Not a number! Try again:  1
    1
    Not a number! Try again:  it doesn't care now
    it doesn't care now
    # and so on...
    
  3. We use filter and str.isdigit to filter out those strings that contain only digits:
    only_digits = filter(str.isdigit, replies)
    for reply in only_digits:
        print(reply)
    
    Enter a number:  a
    Not a number! Try again:  1
    1
    Not a number! Try again:  2
    2
    Not a number! Try again:  b
    Not a number! Try again: # and so on...
    
    And to get only the first digits-only string we use next.

Other validation rules:

  1. String methods: Of course you can use other string methods like str.isalpha to get only alphabetic strings, or str.isupper to get only uppercase. See docs for the full list.

  2. Membership testing:
    There are several different ways to perform it. One of them is by using __contains__ method:

    from itertools import chain, repeat
    
    fruits = {'apple', 'orange', 'peach'}
    prompts = chain(["Enter a fruit: "], repeat("I don't know this one! Try again: "))
    replies = map(input, prompts)
    valid_response = next(filter(fruits.__contains__, replies))
    print(valid_response)
    
    Enter a fruit:  1
    I don't know this one! Try again:  foo
    I don't know this one! Try again:  apple
    apple
    
  3. Numbers comparison:
    There are useful comparison methods which we can use here. For example, for __lt__ (<):

    from itertools import chain, repeat
    
    prompts = chain(["Enter a positive number:"], repeat("I need a positive number! Try again:"))
    replies = map(input, prompts)
    numeric_strings = filter(str.isnumeric, replies)
    numbers = map(float, numeric_strings)
    is_positive = (0.).__lt__
    valid_response = next(filter(is_positive, numbers))
    print(valid_response)
    
    Enter a positive number: a
    I need a positive number! Try again: -5
    I need a positive number! Try again: 0
    I need a positive number! Try again: 5
    5.0
    

    Or, if you don't like using dunder methods (dunder = double-underscore), you can always define your own function, or use the ones from the operator module.

  4. Path existance:
    Here one can use pathlib library and its Path.exists method:

    from itertools import chain, repeat
    from pathlib import Path
    
    prompts = chain(["Enter a path: "], repeat("This path doesn't exist! Try again: "))
    replies = map(input, prompts)
    paths = map(Path, replies)
    valid_response = next(filter(Path.exists, paths))
    print(valid_response)
    
    Enter a path:  a b c
    This path doesn't exist! Try again:  1
    This path doesn't exist! Try again:  existing_file.txt
    existing_file.txt
    

Limiting number of tries:

If you don't want to torture a user by asking him something an infinite number of times, you can specify a limit in a call of itertools.repeat. This can be combined with providing a default value to the next function:

from itertools import chain, repeat

prompts = chain(["Enter a number:"], repeat("Not a number! Try again:", 2))
replies = map(input, prompts)
valid_response = next(filter(str.isdigit, replies), None)
print("You've failed miserably!" if valid_response is None else 'Well done!')
Enter a number: a
Not a number! Try again: b
Not a number! Try again: c
You've failed miserably!

Preprocessing input data:

Sometimes we don't want to reject an input if the user accidentally supplied it IN CAPS or with a space in the beginning or an end of the string. To take these simple mistakes into account we can preprocess the input data by applying str.lower and str.strip methods. For example, for the case of membership testing the code will look like this:

from itertools import chain, repeat

fruits = {'apple', 'orange', 'peach'}
prompts = chain(["Enter a fruit: "], repeat("I don't know this one! Try again: "))
replies = map(input, prompts)
lowercased_replies = map(str.lower, replies)
stripped_replies = map(str.strip, lowercased_replies)
valid_response = next(filter(fruits.__contains__, stripped_replies))
print(valid_response)
Enter a fruit:  duck
I don't know this one! Try again:     Orange
orange

In the case when you have many functions to use for preprocessing, it might be easier to use a function performing a function composition. For example, using the one from here:

from itertools import chain, repeat

from lz.functional import compose

fruits = {'apple', 'orange', 'peach'}
prompts = chain(["Enter a fruit: "], repeat("I don't know this one! Try again: "))
replies = map(input, prompts)
process = compose(str.strip, str.lower)  # you can add more functions here
processed_replies = map(process, replies)
valid_response = next(filter(fruits.__contains__, processed_replies))
print(valid_response)
Enter a fruit:  potato
I don't know this one! Try again:   PEACH
peach

Combining validation rules:

For a simple case, for example, when the program asks for age between 1 and 120, one can just add another filter:

from itertools import chain, repeat

prompt_msg = "Enter your age (1-120): "
bad_input_msg = "Wrong input."
prompts = chain([prompt_msg], repeat('\n'.join([bad_input_msg, prompt_msg])))
replies = map(input, prompts)
numeric_replies = filter(str.isdigit, replies)
ages = map(int, numeric_replies)
positive_ages = filter((0).__lt__, ages)
not_too_big_ages = filter((120).__ge__, positive_ages)
valid_response = next(not_too_big_ages)
print(valid_response)

But in the case when there are many rules, it's better to implement a function performing a logical conjunction. In the following example I will use a ready one from here:

from functools import partial
from itertools import chain, repeat

from lz.logical import conjoin


def is_one_letter(string: str) -> bool:
    return len(string) == 1


rules = [str.isalpha, str.isupper, is_one_letter, 'C'.__le__, 'P'.__ge__]

prompt_msg = "Enter a letter (C-P): "
bad_input_msg = "Wrong input."
prompts = chain([prompt_msg], repeat('\n'.join([bad_input_msg, prompt_msg])))
replies = map(input, prompts)
valid_response = next(filter(conjoin(*rules), replies))
print(valid_response)
Enter a letter (C-P):  5
Wrong input.
Enter a letter (C-P):  f
Wrong input.
Enter a letter (C-P):  CDE
Wrong input.
Enter a letter (C-P):  Q
Wrong input.
Enter a letter (C-P):  N
N

Unfortunately, if someone needs a custom message for each failed case, then, I'm afraid, there is no pretty functional way. Or, at least, I couldn't find one.

python object() takes no parameters error

You've mixed tabs and spaces. __init__ is actually defined nested inside another method, so your class doesn't have its own __init__ method, and it inherits object.__init__ instead. Open your code in Notepad instead of whatever editor you're using, and you'll see your code as Python's tab-handling rules see it.

This is why you should never mix tabs and spaces. Stick to one or the other. Spaces are recommended.

Disable developer mode extensions pop up in Chrome

Now, we need to handle it using following -

ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.addArguments("chrome.switches", "--disable-extensions --disable-extensions-file-access-check --disable-extensions-http-throttling");

Apart from --disable-extensions, we also need to add --disable-extensions-file-access-check (and/or) --disable-extensions-http-throttling chrome switches.

3-dimensional array in numpy

Read this article for better insight. Note: Numpy reports the shape of 3D arrays in the order layers, rows, columns.

https://opensourceoptions.com/blog/numpy-array-shapes-and-reshaping-arrays/#:~:text=3D%20arrays,order%20layers%2C%20rows%2C%20columns.

'and' (boolean) vs '&' (bitwise) - Why difference in behavior with lists vs numpy arrays?

For the first example and base on the django's doc
It will always return the second list, indeed a non empty list is see as a True value for Python thus python return the 'last' True value so the second list

In [74]: mylist1 = [False]
In [75]: mylist2 = [False, True, False,  True, False]
In [76]: mylist1 and mylist2
Out[76]: [False, True, False, True, False]
In [77]: mylist2 and mylist1
Out[77]: [False]

Checkout another branch when there are uncommitted changes on the current branch

You have two choices: stash your changes:

git stash

then later to get them back:

git stash apply

or put your changes on a branch so you can get the remote branch and then merge your changes onto it. That's one of the greatest things about git: you can make a branch, commit to it, then fetch other changes on to the branch you were on.

You say it doesn't make any sense, but you are only doing it so you can merge them at will after doing the pull. Obviously your other choice is to commit on your copy of the branch and then do the pull. The presumption is you either don't want to do that (in which case I am puzzled that you don't want a branch) or you are afraid of conflicts.

Sequelize, convert entity to plain object

you can use map function. this is worked for me.

db.Sensors
    .findAll({
        where: { nodeid: node.nodeid }
     })
    .map(el => el.get({ plain: true }))
    .then((rows)=>{
        response.json( rows )
     });

This IP, site or mobile application is not authorized to use this API key

Also the corresponding API should be enabled for the given project

https://console.developers.google.com/apis/library?project=projectnamehere

Does JSON syntax allow duplicate keys in an object?

From the standard (p. ii):

It is expected that other standards will refer to this one, strictly adhering to the JSON text format, while imposing restrictions on various encoding details. Such standards may require specific behaviours. JSON itself specifies no behaviour.

Further down in the standard (p. 2), the specification for a JSON object:

An object structure is represented as a pair of curly bracket tokens surrounding zero or more name/value pairs. A name is a string. A single colon token follows each name, separating the name from the value. A single comma token separates a value from a following name.

Diagram for JSON Object

It does not make any mention of duplicate keys being invalid or valid, so according to the specification I would safely assume that means they are allowed.

That most implementations of JSON libraries do not accept duplicate keys does not conflict with the standard, because of the first quote.

Here are two examples related to the C++ standard library. When deserializing some JSON object into a std::map it would make sense to refuse duplicate keys. But when deserializing some JSON object into a std::multimap it would make sense to accept duplicate keys as normal.

How to deploy correctly when using Composer's develop / production switch?

Why

There is IMHO a good reason why Composer will use the --dev flag by default (on install and update) nowadays. Composer is mostly run in scenario's where this is desired behavior:

The basic Composer workflow is as follows:

  • A new project is started: composer.phar install --dev, json and lock files are commited to VCS.
  • Other developers start working on the project: checkout of VCS and composer.phar install --dev.
  • A developer adds dependancies: composer.phar require <package>, add --dev if you want the package in the require-dev section (and commit).
  • Others go along: (checkout and) composer.phar install --dev.
  • A developer wants newer versions of dependencies: composer.phar update --dev <package> (and commit).
  • Others go along: (checkout and) composer.phar install --dev.
  • Project is deployed: composer.phar install --no-dev

As you can see the --dev flag is used (far) more than the --no-dev flag, especially when the number of developers working on the project grows.

Production deploy

What's the correct way to deploy this without installing the "dev" dependencies?

Well, the composer.json and composer.lock file should be committed to VCS. Don't omit composer.lock because it contains important information on package-versions that should be used.

When performing a production deploy, you can pass the --no-dev flag to Composer:

composer.phar install --no-dev

The composer.lock file might contain information about dev-packages. This doesn't matter. The --no-dev flag will make sure those dev-packages are not installed.

When I say "production deploy", I mean a deploy that's aimed at being used in production. I'm not arguing whether a composer.phar install should be done on a production server, or on a staging server where things can be reviewed. That is not the scope of this answer. I'm merely pointing out how to composer.phar install without installing "dev" dependencies.

Offtopic

The --optimize-autoloader flag might also be desirable on production (it generates a class-map which will speed up autoloading in your application):

composer.phar install --no-dev --optimize-autoloader

Or when automated deployment is done:

composer.phar install --no-ansi --no-dev --no-interaction --no-plugins --no-progress --no-scripts --optimize-autoloader

If your codebase supports it, you could swap out --optimize-autoloader for --classmap-authoritative. More info here

Why not inherit from List<T>?

Let me rewrite your question. so you might see the subject from a different perspective.

When I need to represent a football team, I understand that it is basically a name. Like: "The Eagles"

string team = new string();

Then later I realized teams also have players.

Why can't I just extend the string type so that it also holds a list of players?

Your point of entry into the problem is arbitrary. Try to think what does a team have (properties), not what it is.

After you do that, you could see if it shares properties with other classes. And think about inheritance.

Node.js Generate html

You can use jsdom

const jsdom = require("jsdom");
const { JSDOM } = jsdom;
const { document } = (new JSDOM(`...`)).window;

or, take a look at cheerio, it may more suitable in your case.

What is the difference between CMD and ENTRYPOINT in a Dockerfile?

There are some good answers for it. I want to explain it through demo per Doc

  • CMD defines default commands and/or parameters for a container. CMD is an instruction that is best to use if you need a default command which users can easily override. If a Dockerfile has multiple CMDs, it only applies the instructions from the last one.
  • ENTRYPOINT is preferred when you want to define a container with a specific executable.

You cannot override an ENTRYPOINT when starting a container unless you add the --entrypoint flag.

  1. CMD

Docker file

  FROM centos:8.1.1911

  CMD ["echo", "Hello Docker"]

Run result

$ sudo docker run <image-id>
Hello Docker
$ sudo docker run <image-id> hostname   # hostname is exec to override CMD
244be5006f32
  1. ENTRYPOINT

Docker file

  FROM centos:8.1.1911

  ENTRYPOINT ["echo", "Hello Docker"]

Run result

$ sudo docker run <image-id>
Hello Docker
$ sudo docker run <image-id> hostname   # hostname as parameter to exec
Hello Docker hostname
  1. There are many situations in which combining CMD and ENTRYPOINT would be the best solution for your Docker container. In such cases, the executable is defined with ENTRYPOINT, while CMD specifies the default parameter.

Docker file

  FROM centos:8.1.1911

  ENTRYPOINT ["echo", "Hello"]
  CMD ["Docker"]

Run result

$ sudo docker run <image-id>
Hello Docker
$ sudo docker run <image-id> Ben
Hello Ben

Converting milliseconds to minutes and seconds with Javascript

Best is this!

function msToTime(duration) {
var milliseconds = parseInt((duration%1000))
    , seconds = parseInt((duration/1000)%60)
    , minutes = parseInt((duration/(1000*60))%60)
    , hours = parseInt((duration/(1000*60*60))%24);

hours = (hours < 10) ? "0" + hours : hours;
minutes = (minutes < 10) ? "0" + minutes : minutes;
seconds = (seconds < 10) ? "0" + seconds : seconds;

return hours + ":" + minutes + ":" + seconds + "." + milliseconds;
}

It will return 00:04:21.223 You can format this string then as you wish.

Uncaught ReferenceError: $ is not defined error in jQuery

The MVC 5 stock install puts javascript references in the _Layout.cshtml file that is shared in all pages. So the javascript files were below the main content and document.ready function where all my $'s were.

BOTTOM PART OF _Layout.cshtml:

    <div class="container body-content">
        @RenderBody()
        <hr />
        <footer>
            <p>&copy; @DateTime.Now.Year - My ASP.NET Application</p>
        </footer>
    </div>

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
    @RenderSection("scripts", required: false)

</body>
</html>

I moved them above the @RenderBody() and all was fine.

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
    @RenderSection("scripts", required: false)

    <div class="container body-content">
        @RenderBody()
        <hr />
        <footer>
            <p>&copy; @DateTime.Now.Year - My ASP.NET Application</p>
        </footer>
    </div>

</body>
</html>

JSON to pandas DataFrame

Optimization of the accepted answer:

The accepted answer has some functioning problems, so I want to share my code that does not rely on urllib2:

import requests
from pandas import json_normalize
url = 'https://www.energidataservice.dk/proxy/api/datastore_search?resource_id=nordpoolmarket&limit=5'

response = requests.get(url)
dictr = response.json()
recs = dictr['result']['records']
df = json_normalize(recs)
print(df)

Output:

        _id                    HourUTC               HourDK  ... ElbasAveragePriceEUR  ElbasMaxPriceEUR  ElbasMinPriceEUR
0    264028  2019-01-01T00:00:00+00:00  2019-01-01T01:00:00  ...                  NaN               NaN               NaN
1    138428  2017-09-03T15:00:00+00:00  2017-09-03T17:00:00  ...                33.28              33.4              32.0
2    138429  2017-09-03T16:00:00+00:00  2017-09-03T18:00:00  ...                35.20              35.7              34.9
3    138430  2017-09-03T17:00:00+00:00  2017-09-03T19:00:00  ...                37.50              37.8              37.3
4    138431  2017-09-03T18:00:00+00:00  2017-09-03T20:00:00  ...                39.65              42.9              35.3
..      ...                        ...                  ...  ...                  ...               ...               ...
995  139290  2017-10-09T13:00:00+00:00  2017-10-09T15:00:00  ...                38.40              38.4              38.4
996  139291  2017-10-09T14:00:00+00:00  2017-10-09T16:00:00  ...                41.90              44.3              33.9
997  139292  2017-10-09T15:00:00+00:00  2017-10-09T17:00:00  ...                46.26              49.5              41.4
998  139293  2017-10-09T16:00:00+00:00  2017-10-09T18:00:00  ...                56.22              58.5              49.1
999  139294  2017-10-09T17:00:00+00:00  2017-10-09T19:00:00  ...                56.71              65.4              42.2 

PS: API is for Danish electricity prices

How does Java resolve a relative path in new File()?

There is a concept of a working directory.
This directory is represented by a . (dot).
In relative paths, everything else is relative to it.

Simply put the . (the working directory) is where you run your program.
In some cases the working directory can be changed but in general this is
what the dot represents. I think this is C:\JavaForTesters\ in your case.

So test\..\test.txt means: the sub-directory test
in my working directory, then one level up, then the
file test.txt. This is basically the same as just test.txt.

For more details check here.

http://docs.oracle.com/javase/7/docs/api/java/io/File.html

http://docs.oracle.com/javase/tutorial/essential/io/pathOps.html

Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2

Response you are getting is in object form i.e.

{ 
  "dstOffset" : 3600, 
  "rawOffset" : 36000, 
  "status" : "OK", 
  "timeZoneId" : "Australia/Hobart", 
  "timeZoneName" : "Australian Eastern Daylight Time" 
}

Replace below line of code :

List<Post> postsList = Arrays.asList(gson.fromJson(reader,Post.class))

with

Post post = gson.fromJson(reader, Post.class);

Has Facebook sharer.php changed to no longer accept detailed parameters?

Starting from July 18, 2017 Facebook has decided to disregard custom parameters set by users. This choice blocks many of the possibilities offered by this answer and it also breaks buttons used on several websites.

The quote and hashtag parameters work as of Dec 2018.


Does anyone know if there have been recent changes which could have suddenly stopped this from working?

The parameters have changed. The currently accepted answer states:

Facebook no longer supports custom parameters in sharer.php

But this is not entirely correct. Well, maybe they do not support or endorse them, but custom parameters can be used if you know the correct names. These include:

  • URL (of course) ? u
  • custom image ? picture
  • custom title ? title
  • custom quote ? quote
  • custom description ? description
  • caption (aka website name) ? caption

For instance, you can share this very question with the following URL:

https://www.facebook.com/sharer/sharer.php?u=http%3A%2F%2Fstackoverflow.com%2Fq%2F20956229%2F1101509&picture=http%3A%2F%2Fwww.applezein.net%2Fwordpress%2Fwp-content%2Fuploads%2F2015%2F03%2Ffacebook-logo.jpg&title=A+nice+question+about+Facebook&quote=Does+anyone+know+if+there+have+been+recent+changes+which+could+have+suddenly+stopped+this+from+working%3F&description=Apparently%2C+the+accepted+answer+is+not+correct.

Try it!

I've built a tool which makes it easier to share URLs on Facebook with custom parameters. You can use it to generate your sharer.php link, just press the button and copy the URL from the tab that opens.

What are best practices for REST nested resources?

I've read all of the above answers but it seems like they have no common strategy. I found a good article about best practices in Design API from Microsoft Documents. I think you should refer.

In more complex systems, it can be tempting to provide URIs that enable a client to navigate through several levels of relationships, such as /customers/1/orders/99/products. However, this level of complexity can be difficult to maintain and is inflexible if the relationships between resources change in the future. Instead, try to keep URIs relatively simple. Once an application has a reference to a resource, it should be possible to use this reference to find items related to that resource. The preceding query can be replaced with the URI /customers/1/orders to find all the orders for customer 1, and then /orders/99/products to find the products in this order.

.

Tip

Avoid requiring resource URIs more complex than collection/item/collection.

Are PostgreSQL column names case-sensitive?

Identifiers (including column names) that are not double-quoted are folded to lower case in PostgreSQL. Column names that were created with double-quotes and thereby retained upper-case letters (and/or other syntax violations) have to be double-quoted for the rest of their life:

"first_Name"

Values (string literals / constants) are enclosed in single quotes:

'xyz'

So, yes, PostgreSQL column names are case-sensitive (when double-quoted):

SELECT * FROM persons WHERE "first_Name" = 'xyz';

Read the manual on identifiers here.

My standing advice is to use legal, lower-case names exclusively so double-quoting is not needed.

Replace all non Alpha Numeric characters, New Lines, and multiple White Space with one Space

Well I think you just need to add a quantifier to each pattern. Also the carriage-return thing is a little funny:

text.replace(/[^a-z0-9]+|\s+/gmi, " ");

edit The \s thing matches \r and \n too.

Exists Angularjs code/naming conventions?

I started this gist a year ago: https://gist.github.com/PascalPrecht/5411171

Brian Ford (member of the core team) has written this blog post about it: http://briantford.com/blog/angular-bower

And then we started with this component spec (which is not quite complete): https://github.com/angular/angular-component-spec

Since the last ng-conf there's this document for best practices by the core team: https://docs.google.com/document/d/1XXMvReO8-Awi1EZXAXS4PzDzdNvV6pGcuaF4Q9821Es/pub

Python : Trying to POST form using requests

You can use the Session object

import requests
headers = {'User-Agent': 'Mozilla/5.0'}
payload = {'username':'niceusername','password':'123456'}

session = requests.Session()
session.post('https://admin.example.com/login.php',headers=headers,data=payload)
# the session instance holds the cookie. So use it to get/post later.
# e.g. session.get('https://example.com/profile')

Controlling execution order of unit tests in Visual Studio

I'll not address the order of tests, sorry. Others already did it. Also, if you know about "ordered tests" - well, this is MS VS's response to the problem. I know that those ordered-tests are no fun. But they thought it will be "it" and there's really nothing more in MSTest about that.

I write about one of your assumptions:

as there is no way to tear down the static class.

Unless your static class represents some process-wide external state external to your code (like ie. the state of an unmanaged native DLL library thats P/Invoked by the rest of your code), your assumption that there is no way is not true.

If your static class refers to this, then sorry, you are perfectly right, the rest of this anwer is irrelevant. Still, as you didn't say that, I assume your code is "managed".

Think and check the AppDomain thingy. Rarely it is needed, but this is exactly the case when you'd probably like to use them.

You can create a new AppDomain, and instantiate the test there, and run the test method there. Static data used by managed code will isolated there and upon completion, you will be able to unload the AppDomain and all the data, statics included, will evaporate. Then, next test would initialize another appdomain, and so on.

This will work unless you have external state that you must track. AppDomains only isolate the managed memory. Any native DLL will still be load per-process and their state will be shared by all AppDomains.

Also, creating/tearing down the appdomains will, well, slow down the tests. Also, you may have problems with assembly resolution in the child appdomain, but they are solvable with reasonable amount of reusable code.

Also, you may have small problems with passing test data to - and back from - the child AppDomain. Objects passed will either have to be serializable in some way, or be MarshalByRef or etc. Talking cross-domain is almost like IPC.

However, take care here, it will be 100% managed talking. If you take some extra care and add a little work to the AppDomain setup, you will be able to even pass delegates and run them in the target domain. Then, instead of making some hairy cross-domain setup, you can wrap your tests with to something like:

void testmethod()
{
    TestAppDomainHelper.Run( () =>
    {
        // your test code
    });
}

or even

[IsolatedAppDomain]
void testmethod()
{
    // your test code
}

if your test framework supports creating such wrappers/extensions. After some initial research and work, using them is almost trivial.

How to fix Uncaught InvalidValueError: setPosition: not a LatLng or LatLngLiteral: in property lat: not a number?

I had the same problem, and resolved it. In my case it was error due to the non-proper format. Please check the first and last coordinates array in geometry coordinates they must be same then and only then it will work. Hope it may help you!

python dictionary sorting in descending order based on values

sort dictionary 'in_dict' by value in decreasing order

sorted_dict = {r: in_dict[r] for r in sorted(in_dict, key=in_dict.get, reverse=True)}

example above

sorted_d = {r: d[r] for r in sorted(d, key=d.get('key3'), reverse=True)}

bootstrap multiselect get selected values

In my case i was using jQuery validation rules with

submitHandler function and submitting the data as new FormData(form);

Select Option

<select class="selectpicker" id="branch" name="branch" multiple="multiple" title="Of Branch" data-size="6" required>
  <option disabled>Multiple Branch Select</option>
  <option value="Computer">Computer</option>
  <option value="Civil">Civil</option>
  <option value="EXTC">EXTC</option>
  <option value="ETRX">ETRX</option>
  <option value="Mechinical">Mechinical</option>
</select>

<input type="hidden" name="new_branch" id="new_branch">

Get the multiple selected value and set to new_branch input value & while submitting the form get value from new_branch

Just replace hidden with text to view on the output

<input type="text" name="new_branch" id="new_branch">

Script (jQuery / Ajax)

<script>
    $(document).ready(function() {

      $('#branch').on('change', function(){
          var selected = $(this).find("option:selected"); //get current selected value
          var arrSelected = []; //Array to store your multiple value in stack
          selected.each(function(){
            arrSelected.push($(this).val()); //Stack the value
          });
          $('#new_branch').val(arrSelected); //It will set the multiple selected value to input new_branch
      });

    });
</script>

canvas.toDataURL() SecurityError

By using fabric js we can solve this security error issue in IE.

    function getBase64FromImageUrl(URL) {
        var canvas  = new fabric.Canvas('c');
        var img = new Image();
        img.onload = function() {
            var canvas1 = document.createElement("canvas");
            canvas1.width = this.width;
            canvas1.height = this.height;
            var ctx = canvas.getContext('2d');
            ctx.drawImage(this, 0, 0);
            var dataURL = canvas.toDataURL({format: "png"});
        };
        img.src = URL;
    }

Dilemma: when to use Fragments vs Activities:

My philosophy is this:

Create an activity only if it's absolutely absolutely required. With the back stack made available for committing bunch of fragment transactions, I try to create as few activities in my app as possible. Also, communicating between various fragments is much easier than sending data back and forth between activities.

Activity transitions are expensive, right? At least I believe so - since the old activity has to be destroyed/paused/stopped, pushed onto the stack, and then the new activity has to be created/started/resumed.

It's just my philosophy since fragments were introduced.

Could not resolve placeholder in string value

I had the same problem, resolved it by adding

<filtering>true</filtering> 

in pom.xml :

before (didn't work):

<build>
    <resources>
        <resource>
            <directory>src/main/resources</directory>               
        </resource>
    </resources>
</build>

after(it worked):

<build>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <filtering>true</filtering>
        </resource>
    </resources>
</build>

After that you just run mvn clean install and deploy application.

ipynb import another ipynb file

Install ipynb from your command prompt

pip install import-ipynb

Import in your notebook file

import import_ipynb

Now use regular import command to import your file

import MyOtherNotebook

How can I use onItemSelected in Android?

If you don't want to implement the listener, you can set it up like this directly where you want it (call on your spinner after your adapter has been set):

spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                switch (position) {
                    case 0:
                        Toast.makeText(parent.getContext(), "Spinner item 1!", Toast.LENGTH_SHORT).show();
                        break;
                    case 1:
                        Toast.makeText(parent.getContext(), "Spinner item 2!", Toast.LENGTH_SHORT).show();
                        break;
                    case 2:
                        Toast.makeText(parent.getContext(), "Spinner item 3!", Toast.LENGTH_SHORT).show();
                        break;
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

               // sometimes you need nothing here
            }
        });

Showing percentages above bars on Excel column graph

In Excel for Mac 2016 at least,if you place the labels in any spot on the graph and are looking to move them anywhere else (in this case above the bars), select:

Chart Design->Add Chart Element->Data Labels -> More Data Label Options

then you can grab each individual label and pull it where you would like it.

Chrome Extension - Get DOM content

You don't have to use the message passing to obtain or modify DOM. I used chrome.tabs.executeScriptinstead. In my example I am using only activeTab permission, therefore the script is executed only on the active tab.

part of manifest.json

"browser_action": {
    "default_title": "Test",
    "default_popup": "index.html"
},
"permissions": [
    "activeTab",
    "<all_urls>"
]

index.html

<!DOCTYPE html>
<html>
  <head></head>
  <body>
    <button id="test">TEST!</button>
    <script src="test.js"></script>
  </body>
</html>

test.js

document.getElementById("test").addEventListener('click', () => {
    console.log("Popup DOM fully loaded and parsed");

    function modifyDOM() {
        //You can play with your DOM here or check URL against your regex
        console.log('Tab script:');
        console.log(document.body);
        return document.body.innerHTML;
    }

    //We have permission to access the activeTab, so we can call chrome.tabs.executeScript:
    chrome.tabs.executeScript({
        code: '(' + modifyDOM + ')();' //argument here is a string but function.toString() returns function's code
    }, (results) => {
        //Here we have just the innerHTML and not DOM structure
        console.log('Popup script:')
        console.log(results[0]);
    });
});

How to define object in array in Mongoose schema correctly with 2d geo index

The problem I need to solve is to store contracts containing a few fields (address, book, num_of_days, borrower_addr, blk_data), blk_data is a transaction list (block number and transaction address). This question and answer helped me. I would like to share my code as below. Hope this helps.

  1. Schema definition. See blk_data.
var ContractSchema = new Schema(
    {
        address: {type: String, required: true, max: 100},  //contract address
        // book_id: {type: String, required: true, max: 100},  //book id in the book collection
        book: { type: Schema.ObjectId, ref: 'clc_books', required: true }, // Reference to the associated book.
        num_of_days: {type: Number, required: true, min: 1},
        borrower_addr: {type: String, required: true, max: 100},
        // status: {type: String, enum: ['available', 'Created', 'Locked', 'Inactive'], default:'Created'},

        blk_data: [{
            tx_addr: {type: String, max: 100}, // to do: change to a list
            block_number: {type: String, max: 100}, // to do: change to a list
        }]
    }
);
  1. Create a record for the collection in the MongoDB. See blk_data.
// Post submit a smart contract proposal to borrowing a specific book.
exports.ctr_contract_propose_post = [

    // Validate fields
    body('book_id', 'book_id must not be empty.').isLength({ min: 1 }).trim(),
    body('req_addr', 'req_addr must not be empty.').isLength({ min: 1 }).trim(),
    body('new_contract_addr', 'contract_addr must not be empty.').isLength({ min: 1 }).trim(),
    body('tx_addr', 'tx_addr must not be empty.').isLength({ min: 1 }).trim(),
    body('block_number', 'block_number must not be empty.').isLength({ min: 1 }).trim(),
    body('num_of_days', 'num_of_days must not be empty.').isLength({ min: 1 }).trim(),

    // Sanitize fields.
    sanitizeBody('*').escape(),
    // Process request after validation and sanitization.
    (req, res, next) => {

        // Extract the validation errors from a request.
        const errors = validationResult(req);
        if (!errors.isEmpty()) {
            // There are errors. Render form again with sanitized values/error messages.
            res.status(400).send({ errors: errors.array() });
            return;
        }

        // Create a Book object with escaped/trimmed data and old id.
        var book_fields =
            {
                _id: req.body.book_id, // This is required, or a new ID will be assigned!
                cur_contract: req.body.new_contract_addr,
                status: 'await_approval'
            };

        async.parallel({
            //call the function get book model
            books: function(callback) {
                Book.findByIdAndUpdate(req.body.book_id, book_fields, {}).exec(callback);
            },
        }, function(error, results) {
            if (error) {
                res.status(400).send({ errors: errors.array() });
                return;
            }

            if (results.books.isNew) {
                // res.render('pg_error', {
                //     title: 'Proposing a smart contract to borrow the book',
                //     c: errors.array()
                // });
                res.status(400).send({ errors: errors.array() });
                return;
            }

            var contract = new Contract(
                {
                    address: req.body.new_contract_addr,
                    book: req.body.book_id,
                    num_of_days: req.body.num_of_days,
                    borrower_addr: req.body.req_addr

                });

            var blk_data = {
                    tx_addr: req.body.tx_addr,
                    block_number: req.body.block_number
                };
            contract.blk_data.push(blk_data);

            // Data from form is valid. Save book.
            contract.save(function (err) {
                if (err) { return next(err); }
                // Successful - redirect to new book record.
                resObj = {
                    "res": contract.url
                };
                res.status(200).send(JSON.stringify(resObj));
                // res.redirect();
            });

        });

    },
];
  1. Update a record. See blk_data.
// Post lender accept borrow proposal.
exports.ctr_contract_propose_accept_post = [

    // Validate fields
    body('book_id', 'book_id must not be empty.').isLength({ min: 1 }).trim(),
    body('contract_id', 'book_id must not be empty.').isLength({ min: 1 }).trim(),
    body('tx_addr', 'tx_addr must not be empty.').isLength({ min: 1 }).trim(),
    body('block_number', 'block_number must not be empty.').isLength({ min: 1 }).trim(),

    // Sanitize fields.
    sanitizeBody('*').escape(),
    // Process request after validation and sanitization.
    (req, res, next) => {

        // Extract the validation errors from a request.
        const errors = validationResult(req);
        if (!errors.isEmpty()) {
            // There are errors. Render form again with sanitized values/error messages.
            res.status(400).send({ errors: errors.array() });
            return;
        }

        // Create a Book object with escaped/trimmed data
        var book_fields =
            {
                _id: req.body.book_id, // This is required, or a new ID will be assigned!
                status: 'on_loan'
            };

        // Create a contract object with escaped/trimmed data
        var contract_fields = {
            $push: {
                blk_data: {
                    tx_addr: req.body.tx_addr,
                    block_number: req.body.block_number
                }
            }
        };

        async.parallel({
            //call the function get book model
            book: function(callback) {
                Book.findByIdAndUpdate(req.body.book_id, book_fields, {}).exec(callback);
            },
            contract: function(callback) {
                Contract.findByIdAndUpdate(req.body.contract_id, contract_fields, {}).exec(callback);
            },
        }, function(error, results) {
            if (error) {
                res.status(400).send({ errors: errors.array() });
                return;
            }

            if ((results.book.isNew) || (results.contract.isNew)) {
                res.status(400).send({ errors: errors.array() });
                return;
            }

            var resObj = {
                "res": results.contract.url
            };
            res.status(200).send(JSON.stringify(resObj));
        });
    },
];

Is it possible to use global variables in Rust?

I am new to Rust, but this solution seems to work:

#[macro_use]
extern crate lazy_static;

use std::sync::{Arc, Mutex};

lazy_static! {
    static ref GLOBAL: Arc<Mutex<GlobalType> =
        Arc::new(Mutex::new(GlobalType::new()));
}

Another solution is to declare a crossbeam channel tx/rx pair as an immutable global variable. The channel should be bounded and can only hold 1 element. When you initialize the global variable, push the global instance into the channel. When using the global variable, pop the channel to acquire it and push it back when done using it.

Both solutions should provide a safe approach to using global variables.

ng-repeat: access key and value for each object in array of objects

In case this is an option for you, if you put your data into object form it works the way I think you're hoping for:

$scope.steps = {
 companyName: true,
 businessType: true,
 physicalAddress: true
};

Here's a fiddle of this: http://jsfiddle.net/zMjVp/

Entity framework self referencing loop detected

If you are trying to change this setting in the Blazor (ASP.NET Core Hosted) template, you need to pass the following to the AddNewtonsoftJson call in Startup.cs in the Server project:

services.AddMvc().AddNewtonsoftJson(options => 
    options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore
);

Converting characters to integers in Java

Character.getNumericValue(c)

The java.lang.Character.getNumericValue(char ch) returns the int value that the specified Unicode character represents. For example, the character '\u216C' (the roman numeral fifty) will return an int with a value of 50.

The letters A-Z in their uppercase ('\u0041' through '\u005A'), lowercase ('\u0061' through '\u007A'), and full width variant ('\uFF21' through '\uFF3A' and '\uFF41' through '\uFF5A') forms have numeric values from 10 through 35. This is independent of the Unicode specification, which does not assign numeric values to these char values.

This method returns the numeric value of the character, as a nonnegative int value;

-2 if the character has a numeric value that is not a nonnegative integer;

-1 if the character has no numeric value.

And here is the link.

bootstrap jquery show.bs.modal event won't fire

Sometimes this doesn't work if:

1) you have an error in the java script code before your line with $('#myModal').on('show.bs.modal'...). To troubleshoot put an alert message before the line to see if it comes up when you load the page. To resolve eliminate JSs above to see which one is the problem

2) Another problem is if you load up the JS in wrong order. For example you can have the $('#myModal').on('show.bs.modal'...) part before you actually load JQuery.js. In that case your call will be ignored, so first in the HTML (view page source to be sure) check if the script link to JQuery is above your modal onShow call, otherwise it will be ignored. To troubleshoot put an alert inside the on show an one before. If you see the one before and not the one inside the onShow function it is clear that the function cannot execute. If the spelling is right more than likely your call to JQuery.js is not made or it is made after the onShow part

Best practice multi language website

I suggest you not to invent a wheel and use gettext and ISO languages abbrevs list. Have you seen how i18n/l10n implemented in popular CMSes or frameworks?

Using gettext you will have a powerful tool where many of cases is already implemented like plural forms of numbers. In english you have only 2 options: singular and plural. But in Russian for example there are 3 forms and its not as simple as in english.

Also many translators already have experience to work with gettext.

Take a look to CakePHP or Drupal . Both multilingual enabled. CakePHP as example of interface localization and Drupal as example of content translation.

For l10n using database isn't the case at all. It will be tons on queries. Standard approach is to get all l10n data in memory in early stage (or during first call to i10n function if you prefer lazy loading). It can be reading from .po file or from DB all data at once. And than just read requested strings from array.

If you need to implement online tool to translate interface you can have all that data in DB but than still save all data to file to work with it. To reduce amount of data in memory you can split all your translated messages/strings into groups and than load only that groups you need if it will be possible.

So you totally right in your #3. With one exception: usually it is one big file not a per-controller file or so. Because it is best for performance to open one file. You probably know that some highloaded web apps compiles all PHP code in one file to avoid file operations when include/require called.

About URLs. Google indirectly suggest to use translation:

to clearly indicate French content: http://example.ca/fr/vélo-de-montagne.html

Also i think you need to redirect user to default language prefix e.g. http://examlpe.com/about-us will redirects to http://examlpe.com/en/about-us But if your site use only one language so you don't need prefixes at all.

Check out: http://www.audiomicro.com/trailer-hit-impact-psychodrama-sound-effects-836925 http://nl.audiomicro.com/aanhangwagen-hit-effect-psychodrama-geluidseffecten-836925 http://de.audiomicro.com/anhanger-hit-auswirkungen-psychodrama-sound-effekte-836925

Translating content is more difficult task. I think it will be some differences with different types of content e.g. articles, menu items etc. But in #4 you're in the right way. Take a look in Drupal to have more ideas. It have clear enough DB schema and good enough interface for translating. Like you creating article and select language for it. And than you can later translate it to other languages.

Drupal translation interface

I think it isn't problem with URL slugs. You can just create separate table for slugs and it will be right decision. Also using right indexes it isn't problem to query table even with huge amount of data. And it wasn't full text search but string match if will use varchar data type for slug and you can have an index on that field too.

PS Sorry, my English is far from perfect though.

How to change icon on Google map marker

var marker = new google.maps.Marker({
                position: new google.maps.LatLng(23.016427,72.571156),
                map: map,
                icon: 'images/map_marker_icon.png',
                title: 'Hi..!'
            });

apply local path on icon only

Using any() and all() to check if a list contains one set of values or another

Generally speaking:

all and any are functions that take some iterable and return True, if

  • in the case of all(), no values in the iterable are falsy;
  • in the case of any(), at least one value is truthy.

A value x is falsy iff bool(x) == False. A value x is truthy iff bool(x) == True.

Any non-booleans in the iterable will be fine — bool(x) will coerce any x according to these rules: 0, 0.0, None, [], (), [], set(), and other empty collections will yield False, anything else True. The docstring for bool uses the terms 'true'/'false' for 'truthy'/'falsy', and True/False for the concrete boolean values.


In your specific code samples:

You misunderstood a little bit how these functions work. Hence, the following does something completely not what you thought:

if any(foobars) == big_foobar:

...because any(foobars) would first be evaluated to either True or False, and then that boolean value would be compared to big_foobar, which generally always gives you False (unless big_foobar coincidentally happened to be the same boolean value).

Note: the iterable can be a list, but it can also be a generator/generator expression (˜ lazily evaluated/generated list) or any other iterator.

What you want instead is:

if any(x == big_foobar for x in foobars):

which basically first constructs an iterable that yields a sequence of booleans—for each item in foobars, it compares the item to big_foobar and emits the resulting boolean into the resulting sequence:

tmp = (x == big_foobar for x in foobars)

then any walks over all items in tmp and returns True as soon as it finds the first truthy element. It's as if you did the following:

In [1]: foobars = ['big', 'small', 'medium', 'nice', 'ugly']                                        

In [2]: big_foobar = 'big'                                                                          

In [3]: any(['big' == big_foobar, 'small' == big_foobar, 'medium' == big_foobar, 'nice' == big_foobar, 'ugly' == big_foobar])        
Out[3]: True

Note: As DSM pointed out, any(x == y for x in xs) is equivalent to y in xs but the latter is more readable, quicker to write and runs faster.

Some examples:

In [1]: any(x > 5 for x in range(4))
Out[1]: False

In [2]: all(isinstance(x, int) for x in range(10))
Out[2]: True

In [3]: any(x == 'Erik' for x in ['Erik', 'John', 'Jane', 'Jim'])
Out[3]: True

In [4]: all([True, True, True, False, True])
Out[4]: False

See also: http://docs.python.org/2/library/functions.html#all

'Best' practice for restful POST response

Returning the whole object on an update would not seem very relevant, but I can hardly see why returning the whole object when it is created would be a bad practice in a normal use case. This would be useful at least to get the ID easily and to get the timestamps when relevant. This is actually the default behavior got when scaffolding with Rails.

I really do not see any advantage to returning only the ID and doing a GET request after, to get the data you could have got with your initial POST.

Anyway as long as your API is consistent I think that you should choose the pattern that fits your needs the best. There is not any correct way of how to build a REST API, imo.

Jenkins - How to access BUILD_NUMBER environment variable

For Groovy script in the Jenkinsfile using the $BUILD_NUMBER it works.

How do I create a new user in a SQL Azure database?

I found this link very helpful:
https://azure.microsoft.com/en-gb/documentation/articles/sql-database-manage-logins/

It details things like:
- Azure SQL Database subscriber account
- Using Azure Active Directory users to access the database
- Server-level principal accounts (unrestricted access)
- Adding users to the dbmanager database role

I used this and Stuart's answer to do the following:
On the master database (see link as to who has permissions on this):

CREATE LOGIN [MyAdmin] with password='ReallySecurePassword'

And then on the database in question:

CREATE USER [MyAdmin] FROM LOGIN [MyAdmin]
ALTER ROLE db_owner ADD MEMBER [MyAdmin]

You can also create users like this, according to the link:

CREATE USER [[email protected]] FROM EXTERNAL PROVIDER;

Conda: Installing / upgrading directly from github

The answers are outdated. You simply have to conda install pip and git. Then you can use pip normally:

  1. Activate your conda environment source activate myenv

  2. conda install git pip

  3. pip install git+git://github.com/scrappy/scrappy@master

Compare two different files line by line in python

This solution reads both files in one pass, excludes blank lines, and prints common lines regardless of their position in the file:

with open('some_file_1.txt', 'r') as file1:
    with open('some_file_2.txt', 'r') as file2:
        same = set(file1).intersection(file2)

same.discard('\n')

with open('some_output_file.txt', 'w') as file_out:
    for line in same:
        file_out.write(line)

addClass and removeClass in jQuery - not removing class

What happens is that your close button is placed inside your .clickable div, so the click event will be triggered in both elements.

The event bubbling will make the click event propagate from the child nodes to their parents. So your .close_button callback will be executed first, and when .clickable is reached, it will toggle the classes again. As this run very fast you can't notice the two events happened.

                    / \
--------------------| |-----------------
| .clickable        | |                |
|   ----------------| |-----------     |
|   | .close_button | |          |     |
|   ------------------------------     |
|             event bubbling           |
----------------------------------------

To prevent your event from reaching .clickable, you need to add the event parameter to your callback function and then call the stopPropagation method on it.

$(".close_button").click(function (e) { 
    $("#spot1").addClass("spot");
    $("#spot1").removeClass("grown");
    e.stopPropagation();
});

Fiddle: http://jsfiddle.net/u4GCk/1/

More info about event order in general: http://www.quirksmode.org/js/events_order.html (that's where I picked that pretty ASCII art =])

How to set HTML5 required attribute in Javascript?

Short version

element.setAttribute("required", "");    //turns required on
element.required = true;                 //turns required on through reflected attribute
jQuery(element).attr('required', '');    //turns required on
$("#elementId").attr('required', '');    //turns required on

element.removeAttribute("required");     //turns required off
element.required = false;                //turns required off through reflected attribute
jQuery(element).removeAttr('required');  //turns required off
$("#elementId").removeAttr('required');  //turns required off

if (edName.hasAttribute("required")) { }  //check if required
if (edName.required) { }                 //check if required using reflected attribute

Long Version

Once T.J. Crowder managed to point out reflected properties, i learned that following syntax is wrong:

element.attributes["name"] = value; //bad! Overwrites the HtmlAttribute object
element.attributes.name = value;    //bad! Overwrites the HtmlAttribute object
value = element.attributes.name;    //bad! Returns the HtmlAttribute object, not its value
value = element.attributes["name"]; //bad! Returns the HtmlAttribute object, not its value

You must go through element.getAttribute and element.setAttribute:

element.getAttribute("foo");         //correct
element.setAttribute("foo", "test"); //correct

This is because the attribute actually contains a special HtmlAttribute object:

element.attributes["foo"];           //returns HtmlAttribute object, not the value of the attribute
element.attributes.foo;              //returns HtmlAttribute object, not the value of the attribute

By setting an attribute value to "true", you are mistakenly setting it to a String object, rather than the HtmlAttribute object it requires:

element.attributes["foo"] = "true";  //error because "true" is not a HtmlAttribute object
element.setAttribute("foo", "true"); //error because "true" is not an HtmlAttribute object

Conceptually the correct idea (expressed in a typed language), is:

HtmlAttribute attribute = new HtmlAttribute();
attribute.value = "";
element.attributes["required"] = attribute;

This is why:

  • getAttribute(name)
  • setAttribute(name, value)

exist. They do the work on assigning the value to the HtmlAttribute object inside.

On top of this, some attribute are reflected. This means that you can access them more nicely from Javascript:

//Set the required attribute
//element.setAttribute("required", ""); 
element.required = true;

//Check the attribute
//if (element.getAttribute("required")) {...}
if (element.required) {...}

//Remove the required attribute
//element.removeAttribute("required");
element.required = false;

What you don't want to do is mistakenly use the .attributes collection:

element.attributes.required = true;     //WRONG!
if (element.attributes.required) {...}  //WRONG!
element.attributes.required = false;    //WRONG!

Testing Cases

This led to testing around the use of a required attribute, comparing the values returned through the attribute, and the reflected property

document.getElementById("name").required;
document.getElementById("name").getAttribute("required");

with results:

HTML                         .required        .getAttribute("required")
==========================   ===============  =========================
<input>                      false (Boolean)  null (Object)
<input required>             true  (Boolean)  "" (String)
<input required="">          true  (Boolean)  "" (String)
<input required="required">  true  (Boolean)  "required" (String)
<input required="true">      true  (Boolean)  "true" (String)
<input required="false">     true  (Boolean)  "false" (String)
<input required="0">         true  (Boolean)  "0" (String)

Trying to access the .attributes collection directly is wrong. It returns the object that represents the DOM attribute:

edName.attributes["required"] => [object Attr]
edName.attributes.required    => [object Attr]

This explains why you should never talk to the .attributes collect directly. You're not manipulating the values of the attributes, but the objects that represent the attributes themselves.

How to set required?

What's the correct way to set required on an attribute? You have two choices, either the reflected property, or through correctly setting the attribute:

element.setAttribute("required", "");         //Correct
edName.required = true;                       //Correct

Strictly speaking, any other value will "set" the attribute. But the definition of Boolean attributes dictate that it should only be set to the empty string "" to indicate true. The following methods all work to set the required Boolean attribute,

but do not use them:

element.setAttribute("required", "required"); //valid, but not preferred
element.setAttribute("required", "foo");      //works, but silly
element.setAttribute("required", "true");     //Works, but don't do it, because:
element.setAttribute("required", "false");    //also sets required boolean to true
element.setAttribute("required", false);      //also sets required boolean to true
element.setAttribute("required", 0);          //also sets required boolean to true

We already learned that trying to set the attribute directly is wrong:

edName.attributes["required"] = true;       //wrong
edName.attributes["required"] = "";         //wrong
edName.attributes["required"] = "required"; //wrong
edName.attributes.required = true;          //wrong
edName.attributes.required = "";            //wrong
edName.attributes.required = "required";    //wrong

How to clear required?

The trick when trying to remove the required attribute is that it's easy to accidentally turn it on:

edName.removeAttribute("required");     //Correct
edName.required = false;                //Correct

With the invalid ways:

edName.setAttribute("required", null);    //WRONG! Actually turns required on!
edName.setAttribute("required", "");      //WRONG! Actually turns required on!
edName.setAttribute("required", "false"); //WRONG! Actually turns required on!
edName.setAttribute("required", false);   //WRONG! Actually turns required on!
edName.setAttribute("required", 0);       //WRONG! Actually turns required on!

When using the reflected .required property, you can also use any "falsey" values to turn it off, and truthy values to turn it on. But just stick to true and false for clarity.

How to check for required?

Check for the presence of the attribute through the .hasAttribute("required") method:

if (edName.hasAttribute("required"))
{
}

You can also check it through the Boolean reflected .required property:

if (edName.required)
{
}

Nginx: Permission denied for nginx on Ubuntu

For me, I just changed the selinux from enforcing to permissive and then I was able to start nginx without any error.

Trying to load local JSON file to show data in a html page using JQuery

You can simply include a Javascript file in your HTML that declares your JSON object as a variable. Then you can access your JSON data from your global Javascript scope using data.employees, for example.

index.html:

<html>
<head>
</head>
<body>
  <script src="data.js"></script>
</body>
</html>

data.js:

var data = {
  "start": {
    "count": "5",
    "title": "start",
    "priorities": [{
      "txt": "Work"
    }, {
      "txt": "Time Sense"
    }, {
      "txt": "Dicipline"
    }, {
      "txt": "Confidence"
    }, {
      "txt": "CrossFunctional"
    }]
  }
}

Arduino error: does not name a type?

My code was out of void setup() or void loop() in Arduino.

Pass variable to function in jquery AJAX success callback

I'm doing it this way:

    function f(data,d){
    console.log(d);
    console.log(data);
}
$.ajax({
    url:u,
    success:function(data){ f(data,d);  }
});

Simulate CREATE DATABASE IF NOT EXISTS for PostgreSQL?

Restrictions

You can ask the system catalog pg_database - accessible from any database in the same database cluster. The tricky part is that CREATE DATABASE can only be executed as a single statement. The manual:

CREATE DATABASE cannot be executed inside a transaction block.

So it cannot be run directly inside a function or DO statement, where it would be inside a transaction block implicitly.

(SQL procedures, introduced with Postgres 11, cannot help with this either.)

Workaround from within psql

You can work around it from within psql by executing the DDL statement conditionally:

SELECT 'CREATE DATABASE mydb'
WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = 'mydb')\gexec

The manual:

\gexec

Sends the current query buffer to the server, then treats each column of each row of the query's output (if any) as a SQL statement to be executed.

Workaround from the shell

With \gexec you only need to call psql once:

echo "SELECT 'CREATE DATABASE mydb' WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = 'mydb')\gexec" | psql

You may need more psql options for your connection; role, port, password, ... See:

The same cannot be called with psql -c "SELECT ...\gexec" since \gexec is a psql meta-command and the -c option expects a single command for which the manual states:

command must be either a command string that is completely parsable by the server (i.e., it contains no psql-specific features), or a single backslash command. Thus you cannot mix SQL and psql meta-commands within a -c option.

Workaround from within Postgres transaction

You could use a dblink connection back to the current database, which runs outside of the transaction block. Effects can therefore also not be rolled back.

Install the additional module dblink for this (once per database):

Then:

DO
$do$
BEGIN
   IF EXISTS (SELECT FROM pg_database WHERE datname = 'mydb') THEN
      RAISE NOTICE 'Database already exists';  -- optional
   ELSE
      PERFORM dblink_exec('dbname=' || current_database()  -- current db
                        , 'CREATE DATABASE mydb');
   END IF;
END
$do$;

Again, you may need more psql options for the connection. See Ortwin's added answer:

Detailed explanation for dblink:

You can make this a function for repeated use.

Are there any SHA-256 javascript implementations that are generally considered trustworthy?

OUTDATED: Many modern browsers now have first-class support for crypto operations. See Vitaly Zdanevich's answer below.


The Stanford JS Crypto Library contains an implementation of SHA-256. While crypto in JS isn't really as well-vetted an endeavor as other implementation platforms, this one is at least partially developed by, and to a certain extent sponsored by, Dan Boneh, who is a well-established and trusted name in cryptography, and means that the project has some oversight by someone who actually knows what he's doing. The project is also supported by the NSF.

It's worth pointing out, however...
... that if you hash the password client-side before submitting it, then the hash is the password, and the original password becomes irrelevant. An attacker needs only to intercept the hash in order to impersonate the user, and if that hash is stored unmodified on the server, then the server is storing the true password (the hash) in plain-text.

So your security is now worse because you decided add your own improvements to what was previously a trusted scheme.

Github "Updates were rejected because the remote contains work that you do not have locally."

The error possibly comes because of the different structure of the code that you are committing and that present on GitHub. It creates conflicts which can be solved by

git pull

Merge conflicts resolving:

git push

If you confirm that your new code is all fine you can use:

git push -f origin master

Where -f stands for "force commit".

Display DateTime value in dd/mm/yyyy format in Asp.NET MVC

Since the question was "display" :

@Html.ValueFor(model => model.RegistrationDate, "{0:dd/MM/yyyy}")

JavaScript string encryption and decryption?

Use SimpleCrypto

Using encrypt() and decrypt()

To use SimpleCrypto, first create a SimpleCrypto instance with a secret key (password). Secret key parameter MUST be defined when creating a SimpleCrypto instance.

To encrypt and decrypt data, simply use encrypt() and decrypt() function from an instance. This will use AES-CBC encryption algorithm.

var _secretKey = "some-unique-key";

var simpleCrypto = new SimpleCrypto(_secretKey);

var plainText = "Hello World!";
var chiperText = simpleCrypto.encrypt(plainText);
console.log("Encryption process...");
console.log("Plain Text    : " + plainText);
console.log("Cipher Text   : " + cipherText);
var decipherText = simpleCrypto.decrypt(cipherText);
console.log("... and then decryption...");
console.log("Decipher Text : " + decipherText);
console.log("... done.");

Comparing two columns, and returning a specific adjacent cell in Excel

I would advise you to swap B and C columns for the reason that I will explain. Then in D2 type: =VLOOKUP(A2, B2:C4, 2, FALSE)

Finally, copy the formula for the remaining cells.

Explanation: VLOOKUP will first find the value of A2 in the range B2 to C4 (second argument). NOTE: VLOOKUP always searches the first column in this range. This is the reason why you have to swap the two columns before doing anything.

Once the exact match is found, it will return the value in the adjacent cell (third argument).

This means that, if you put 1 as the third argument, the function will return the value in the first column of the range (which will be the same value you were looking for). If you put 2, it will return the value from the second column in the range (the value in the adjacent cell-RIGHT SIDE of the found value).

FALSE indicates that you are finding the exact match. If you put TRUE, you will be searching for the approximate match.

Using onBackPressed() in Android Fragments

requireActivity().onBackPressedDispatcher.addCallback(viewLifecycleOwner, object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                Log.w("a","")
            }
        })

Compiling dynamic HTML strings from database

Found in a google discussion group. Works for me.

var $injector = angular.injector(['ng', 'myApp']);
$injector.invoke(function($rootScope, $compile) {
  $compile(element)($rootScope);
});

Constructors in Go

There are actually two accepted best practices:

  1. Make the zero value of your struct a sensible default. (While this looks strange to most people coming from "traditional" oop it often works and is really convenient).
  2. Provide a function func New() YourTyp or if you have several such types in your package functions func NewYourType1() YourType1 and so on.

Document if a zero value of your type is usable or not (in which case it has to be set up by one of the New... functions. (For the "traditionalist" oops: Someone who does not read the documentation won't be able to use your types properly, even if he cannot create objects in undefined states.)

Data truncated for column?

By issuing this statement:

ALTER TABLES call MODIFY incoming_Cid CHAR;

... you omitted the length parameter. Your query was therefore equivalent to:

ALTER TABLE calls MODIFY incoming_Cid CHAR(1);

You must specify the field size for sizes larger than 1:

ALTER TABLE calls MODIFY incoming_Cid CHAR(34);

java.lang.ClassNotFoundException: com.sun.jersey.spi.container.servlet.ServletContainer

Coming back to the original problem - java.lang.ClassNotFoundException: com.sun.jersey.spi.container.servlet.ServletContainer

As rightly said above, in JAX 2.x version, the ServletContainer class has been moved to the package - org.glassfish.jersey.servlet.ServletContainer. The related jar is jersey-container-servlet-core.jar which comes bundled within the jaxrs-ri-2.2.1.zip

JAX RS can be worked out without mvn by manually copying all jars contained within zip file jaxrs-ri-2.2.1.zip (i have used this version, would work with any 2.x version) to WEB-INF/lib folder. Copying libs to right folder makes them available at runtime.

This is required if you are using eclipse to build and deploy your project.

SQL Server : Columns to Rows

You can use the UNPIVOT function to convert the columns into rows:

select id, entityId,
  indicatorname,
  indicatorvalue
from yourtable
unpivot
(
  indicatorvalue
  for indicatorname in (Indicator1, Indicator2, Indicator3)
) unpiv;

Note, the datatypes of the columns you are unpivoting must be the same so you might have to convert the datatypes prior to applying the unpivot.

You could also use CROSS APPLY with UNION ALL to convert the columns:

select id, entityid,
  indicatorname,
  indicatorvalue
from yourtable
cross apply
(
  select 'Indicator1', Indicator1 union all
  select 'Indicator2', Indicator2 union all
  select 'Indicator3', Indicator3 union all
  select 'Indicator4', Indicator4 
) c (indicatorname, indicatorvalue);

Depending on your version of SQL Server you could even use CROSS APPLY with the VALUES clause:

select id, entityid,
  indicatorname,
  indicatorvalue
from yourtable
cross apply
(
  values
  ('Indicator1', Indicator1),
  ('Indicator2', Indicator2),
  ('Indicator3', Indicator3),
  ('Indicator4', Indicator4)
) c (indicatorname, indicatorvalue);

Finally, if you have 150 columns to unpivot and you don't want to hard-code the entire query, then you could generate the sql statement using dynamic SQL:

DECLARE @colsUnpivot AS NVARCHAR(MAX),
   @query  AS NVARCHAR(MAX)

select @colsUnpivot 
  = stuff((select ','+quotename(C.column_name)
           from information_schema.columns as C
           where C.table_name = 'yourtable' and
                 C.column_name like 'Indicator%'
           for xml path('')), 1, 1, '')

set @query 
  = 'select id, entityId,
        indicatorname,
        indicatorvalue
     from yourtable
     unpivot
     (
        indicatorvalue
        for indicatorname in ('+ @colsunpivot +')
     ) u'

exec sp_executesql @query;

Making an iframe responsive

If you happen to be using the Bootstrap CSS library, you can use the responsive embed classes that it provides:

<div class="embed-responsive embed-responsive-16by9">
  <iframe class="embed-responsive-item" src="https://www.youtube.com/embed/zpOULjyy-n8?rel=0" allowfullscreen></iframe>
</div>

Several different aspect ratios are supported, see the documentation.

How do I commit case-sensitive only filename changes in Git?

Under OSX, to avoid this issue and avoid other problems with developing on a case-insensitive filesystem, you can use Disk Utility to create a case sensitive virtual drive / disk image.

Run disk utility, create new disk image, and use the following settings (or change as you like, but keep it case sensitive):

Mac Disk Utility Screenshot

Make sure to tell git it is now on a case sensitive FS:

git config core.ignorecase false

How to make String.Contains case insensitive?

You can create your own extension method to do this:

public static bool Contains(this string source, string toCheck, StringComparison comp)
  {
    return source != null && toCheck != null && source.IndexOf(toCheck, comp) >= 0;
  }

And then call:

 mystring.Contains(myStringToCheck, StringComparison.OrdinalIgnoreCase);

Make anchor link go some pixels above where it's linked to

Here's the 2020 answer for this:

#anchor {
  scroll-margin-top: 100px;
}

Because it's widely supported!

How to draw interactive Polyline on route google maps v2 android

I've created a couple of map tutorials that will cover what you need

Animating the map describes howto create polylines based on a set of LatLngs. Using Google APIs on your map : Directions and Places describes howto use the Directions API and animate a marker along the path.

Take a look at these 2 tutorials and the Github project containing the sample app.

It contains some tips to make your code cleaner and more efficient:

  • Using Google HTTP Library for more efficient API access and easy JSON handling.
  • Using google-map-utils library for maps-related functions (like decoding the polylines)
  • Animating markers

How can I select rows with most recent timestamp for each key value?

For the sake of completeness, here's another possible solution:

SELECT sensorID,timestamp,sensorField1,sensorField2 
FROM sensorTable s1
WHERE timestamp = (SELECT MAX(timestamp) FROM sensorTable s2 WHERE s1.sensorID = s2.sensorID)
ORDER BY sensorID, timestamp;

Pretty self-explaining I think, but here's more info if you wish, as well as other examples. It's from the MySQL manual, but above query works with every RDBMS (implementing the sql'92 standard).

Differences between hard real-time, soft real-time, and firm real-time?

Hard Real-Time

The hard real-time definition considers any missed deadline to be a system failure. This scheduling is used extensively in mission critical systems where failure to conform to timing constraints results in a loss of life or property.

Examples:

  • Air France Flight 447 crashed into the ocean after a sensor malfunction caused a series of system errors. The pilots stalled the aircraft while responding to outdated instrument readings. All 12 crew and 216 passengers were killed.

  • Mars Pathfinder spacecraft was nearly lost when a priority inversion caused system restarts. A higher priority task was not completed on time due to being blocked by a lower priority task. The problem was corrected and the spacecraft landed successfully.

  • An Inkjet printer has a print head with control software for depositing the correct amount of ink onto a specific part of the paper. If a deadline is missed then the print job is ruined.


Firm Real-Time

The firm real-time definition allows for infrequently missed deadlines. In these applications the system can survive task failures so long as they are adequately spaced, however the value of the task's completion drops to zero or becomes impossible.

Examples:

  • Manufacturing systems with robot assembly lines where missing a deadline results in improperly assembling a part. As long as ruined parts are infrequent enough to be caught by quality control and not too costly, then production continues.

  • A digital cable set-top box decodes time stamps for when frames must appear on the screen. Since the frames are time order sensitive a missed deadline causes jitter, diminishing quality of service. If the missed frame later becomes available it will only cause more jitter to display it, so it's useless. The viewer can still enjoy the program if jitter doesn't occur too often.


Soft Real-Time

The soft real-time definition allows for frequently missed deadlines, and as long as tasks are timely executed their results continue to have value. Completed tasks may have increasing value up to the deadline and decreasing value past it.

Examples:

  • Weather stations have many sensors for reading temperature, humidity, wind speed, etc. The readings should be taken and transmitted at regular intervals, however the sensors are not synchronized. Even though a sensor reading may be early or late compared with the others it can still be relevant as long as it is close enough.

  • A video game console runs software for a game engine. There are many resources that must be shared between its tasks. At the same time tasks need to be completed according to the schedule for the game to play correctly. As long as tasks are being completely relatively on time the game will be enjoyable, and if not it may only lag a little.


Siewert: Real-Time Embedded Systems and Components.
Liu & Layland: Scheduling Algorithms for Multiprogramming in a Hard Real-Time Environment.
Marchand & Silly-Chetto: Dynamic Scheduling of Soft Aperiodic Tasks and Periodic Tasks with Skips.

How To Launch Git Bash from DOS Command Line?

I prefer, putting git in environment variable and just calling

c:\Users\[myname]>sh
or 
c:\Users\[myname]>bash

Steps to create Environment variable (Win7)

  • From the desktop, right click the Computer icon.
  • Choose Properties from the context menu.
  • Click the Advanced system settings link.
  • Click Environment Variables.
  • In the section User variables, hit button NEW, put variable name as GIT_HOME, value as (folder-where-you-installed-git).

    • for me it is was c:\tools\git, others maybe have C:\Program Files\Git
  • find the PATH environment variable and select it. Click Edit. (If the PATH environment variable does not exist, click New).

  • In the Edit window, add a new value %GIT_HOME% and %GIT_HOME%\bin. Click OK. Close all remaining windows by clicking OK.
  • [Make sure you close the CMD which you want use for git]
  • open new Command prompt, and just type sh or bash or git-bash

Hashing with SHA1 Algorithm in C#

Fastest way is this :

    public static string GetHash(string input)
    {
        return string.Join("", (new SHA1Managed().ComputeHash(Encoding.UTF8.GetBytes(input))).Select(x => x.ToString("X2")).ToArray());
    }

For Small character output use x2 in replace of of X2

Can local storage ever be considered secure?

WebCrypto

The concerns with cryptography in client-side (browser) javascript are detailed below. All but one of these concerns does not apply to the WebCrypto API, which is now reasonably well supported.

For an offline app, you must still design and implement a secure keystore.

Aside: If you are using Node.js, use the builtin crypto API.

Native-Javascript Cryptography (pre-WebCrypto)

I presume the primary concern is someone with physical access to the computer reading the localStorage for your site, and you want cryptography to help prevent that access.

If someone has physical access you are also open to attacks other and worse than reading. These include (but are not limited to): keyloggers, offline script modification, local script injection, browser cache poisoning, and DNS redirects. Those attacks only work if the user uses the machine after it has been compromised. Nevertheless, physical access in such a scenario means you have bigger problems.

So keep in mind that the limited scenario where local crypto is valuable would be if the machine is stolen.

There are libraries that do implement the desired functionality, e.g. Stanford Javascript Crypto Library. There are inherent weaknesses, though (as referred to in the link from @ircmaxell's answer):

  1. Lack of entropy / random number generation;
  2. Lack of a secure keystore i.e. the private key must be password-protected if stored locally, or stored on the server (which bars offline access);
  3. Lack of secure-erase;
  4. Lack of timing characteristics.

Each of these weaknesses corresponds with a category of cryptographic compromise. In other words, while you may have "crypto" by name, it will be well below the rigour one aspires to in practice.

All that being said, the actuarial assessment is not as trivial as "Javascript crypto is weak, do not use it". This is not an endorsement, strictly a caveat and it requires you to completely understand the exposure of the above weaknesses, the frequency and cost of the vectors you face, and your capacity for mitigation or insurance in the event of failure: Javascript crypto, in spite of its weaknesses, may reduce your exposure but only against thieves with limited technical capacity. However, you should presume Javascript crypto has no value against a determined and capable attacker who is targeting that information. Some would consider it misleading to call the data "encrypted" when so many weaknesses are known to be inherent to the implementation. In other words, you can marginally decrease your technical exposure but you increase your financial exposure from disclosure. Each situation is different, of course - and the analysis of reducing the technical exposure to financial exposure is non-trivial. Here is an illustrative analogy: Some banks require weak passwords, in spite of the inherent risk, because their exposure to losses from weak passwords is less than the end-user costs of supporting strong passwords.

If you read the last paragraph and thought "Some guy on the Internet named Brian says I can use Javascript crypto", do not use Javascript crypto.

For the use case described in the question it would seem to make more sense for users to encrypt their local partition or home directory and use a strong password. That type of security is generally well tested, widely trusted, and commonly available.

Insertion sort vs Bubble Sort Algorithms

Bubble Sort is not online (it cannot sort a stream of inputs without knowing how many items there will be) because it does not really keep track of a global maximum of the sorted elements. When an item is inserted you will need to start the bubbling from the very beginning

How do I truly reset every setting in Visual Studio 2012?

Click on Tools menu > Import and Export Settings > Reset all settings > Next > "No, just reset settings, overwriting all current settings" > Next > Finish.

In VBA get rid of the case sensitivity when comparing words?

You can convert both the values to lower case and compare.

Here is an example:

If LCase(Range("J6").Value) = LCase("Tawi") Then
   Range("J6").Value = "Tawi-Tawi"
End If

OnClickListener in Android Studio

Button button= (Button) findViewById(R.id.standingsButton);
button.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        startActivity(new Intent(MainActivity.this,StandingsActivity.class));
    }
});

This code is not in any method. If you want to use it, it must be within a method like OnCreate()

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Button button= (Button) findViewById(R.id.standingsButton);
    button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            startActivity(new Intent(MainActivity.this,StandingsActivity.class));
        }
    });
}

Find duplicate values in R

You could use table, i.e.

n_occur <- data.frame(table(vocabulary$id))

gives you a data frame with a list of ids and the number of times they occurred.

n_occur[n_occur$Freq > 1,]

tells you which ids occurred more than once.

vocabulary[vocabulary$id %in% n_occur$Var1[n_occur$Freq > 1],]

returns the records with more than one occurrence.

A variable modified inside a while loop is not remembered

UPDATED#2

Explanation is in Blue Moons's answer.

Alternative solutions:

Eliminate echo

while read line; do
...
done <<EOT
first line
second line
third line
EOT

Add the echo inside the here-is-the-document

while read line; do
...
done <<EOT
$(echo -e $lines)
EOT

Run echo in background:

coproc echo -e $lines
while read -u ${COPROC[0]} line; do 
...
done

Redirect to a file handle explicitly (Mind the space in < <!):

exec 3< <(echo -e  $lines)
while read -u 3 line; do
...
done

Or just redirect to the stdin:

while read line; do
...
done < <(echo -e  $lines)

And one for chepner (eliminating echo):

arr=("first line" "second line" "third line");
for((i=0;i<${#arr[*]};++i)) { line=${arr[i]}; 
...
}

Variable $lines can be converted to an array without starting a new sub-shell. The characters \ and n has to be converted to some character (e.g. a real new line character) and use the IFS (Internal Field Separator) variable to split the string into array elements. This can be done like:

lines="first line\nsecond line\nthird line"
echo "$lines"
OIFS="$IFS"
IFS=$'\n' arr=(${lines//\\n/$'\n'}) # Conversion
IFS="$OIFS"
echo "${arr[@]}", Length: ${#arr[*]}
set|grep ^arr

Result is

first line\nsecond line\nthird line
first line second line third line, Length: 3
arr=([0]="first line" [1]="second line" [2]="third line")

Rails 4 image-path, image-url and asset-url no longer work in SCSS files

Your first formulation, image_url('logo.png'), is correct. If the image is found, it will generate the path /assets/logo.png (plus a hash in production). However, if Rails cannot find the image that you named, it will fall back to /images/logo.png.

The next question is: why isn't Rails finding your image? If you put it in app/assets/images/logo.png, then you should be able to access it by going to http://localhost:3000/assets/logo.png.

If that works, but your CSS isn't updating, you may need to clear the cache. Delete tmp/cache/assets from your project directory and restart the server (webrick, etc.).

If that fails, you can also try just using background-image: url(logo.png); That will cause your CSS to look for files with the same relative path (which in this case is /assets).

Python string.replace regular expression

As a summary

import sys
import re

f = sys.argv[1]
find = sys.argv[2]
replace = sys.argv[3]
with open (f, "r") as myfile:
     s=myfile.read()
ret = re.sub(find,replace, s)   # <<< This is where the magic happens
print ret

Scrollview can host only one direct child

Wrap all the children inside of another LinearLayout with wrap_content for both the width and the height as well as the vertical orientation.

JavaScript null check

In JavaScript, null is a special singleton object which is helpful for signaling "no value". You can test for it by comparison and, as usual in JavaScript, it's a good practice to use the === operator to avoid confusing type coercion:

var a = null;
alert(a === null); // true

As @rynah mentions, "undefined" is a bit confusing in JavaScript. However, it's always safe to test if the typeof(x) is the string "undefined", even if "x" is not a declared variable:

alert(typeof(x) === 'undefined'); // true

Also, variables can have the "undefined value" if they are not initialized:

var y;
alert(typeof(y) === 'undefined'); // true

Putting it all together, your check should look like this:

if ((typeof(data) !== 'undefined') && (data !== null)) {
  // ...

However, since the variable "data" is always defined since it is a formal function parameter, using the "typeof" operator is unnecessary and you can safely compare directly with the "undefined value".

function(data) {
  if ((data !== undefined) && (data !== null)) {
    // ...

This snippet amounts to saying "if the function was called with an argument which is defined and is not null..."

WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for 'jquery'. Please add a ScriptResourceMapping named jquery(case-sensitive)

Rather than disabling a new feature, I opted to follow the instructions of the error. In my global.asax.cs I added:

protected void Application_Start(object sender, EventArgs e)
{
    string JQueryVer = "1.7.1";
    ScriptManager.ScriptResourceMapping.AddDefinition("jquery", new ScriptResourceDefinition
    {
        Path = "~/Scripts/jquery-" + JQueryVer + ".min.js",
        DebugPath = "~/Scripts/jquery-" + JQueryVer + ".js",
        CdnPath = "http://ajax.aspnetcdn.com/ajax/jQuery/jquery-" + JQueryVer + ".min.js",
        CdnDebugPath = "http://ajax.aspnetcdn.com/ajax/jQuery/jquery-" + JQueryVer + ".js",
        CdnSupportsSecureConnection = true,
        LoadSuccessExpression = "window.jQuery"
    });
}

This comes from an msdn blog post which highlights some of the advantages of script resource mappings. Of particular interest to me was centralized control over the delivery of the script files based on "debug=true", EnableCDN, etc.

jQuery function to open link in new window

Try adding return false; in your click callback like this -

$(document).ready(function() {
  $('.popup').click(function(event) {
      window.open($(this).attr("href"), "popupWindow", "width=600,height=600,scrollbars=yes");
      return false;
  });
});

Map isn't showing on Google Maps JavaScript API v3 when nested in a div tag

Add style="width:100%; height:100%;" to the div see what that does

not to the #map_canvas but the main div

example

<body>
    <div style="height:100%; width:100%;">
         <div id="map-canvas"></div>
    </div>
</body> 

There are some other answers on here the explain why this is necessary

label or @html.Label ASP.net MVC 4

@html.label and @html.textbox are use when you want bind it to your model in a easy way...which cannot be achieve by input etc. in one line

jquery to loop through table rows and cells, where checkob is checked, concatenate

Try this:

function createcodes() {

    $('.authors-list tr').each(function () {
        //processing this row
        //how to process each cell(table td) where there is checkbox
        $(this).find('td input:checked').each(function () {

             // it is checked, your code here...
        });
    });
}

Get HTML inside iframe using jQuery

Try this code:

$('#iframe').contents().find("html").html();

This will return all the html in your iframe. Instead of .find("html") you can use any selector you want eg: .find('body'),.find('div#mydiv').

MAMP mysql server won't start. No mysql processes are running

Best way to find the real cause is to check the MAMP error log in MAMP > logs > mysql_error_log.err

I found the ERROR "Do you already have another mysql server running on port: 3306 ?" - which was actually the cause for my MAMP MYSQL not starting.

Port 3306 was already "busy", so I have changed it to 8306 and that solved my issue.

How to increase size of DOSBox window?

Here's how to change the dosbox.conf file in Linux to increase the size of the window. I actually DID what follows, so I can say it works (in 32-bit PCLinuxOS fullmontyKDE, anyway). The question's answer is in the .conf file itself.

You find this file in Linux at /home/(username)/.dosbox . In Konqueror or Dolphin, you must first check 'Hidden files' or you won't see the folder. Open it with KWrite superuser or your fav editor.

  1. Save the file with another name like 'dosbox-0.74original.conf' to preserve the original file in case you need to restore it.
  2. Search on 'resolution' and carefully read what the conf file says about changing it. There are essentially two variables: resolution and output. You want to leave fullresolution alone for now. Your question was about WINDOW, not full. So look for windowresolution, see what the comments in conf file say you can do. The best suggestion is to use a bigger-window resolution like 900x800 (which is what I used on a 1366x768 screen), but NOT the actual resolution of your machine (which would make the window fullscreen, and you said you didn't want that). Be specific, replacing the 'windowresolution=original' with 'windowresolution=900x800' or other dimensions. On my screen, that doubled the window size just as it does with the max Font tab in Windows Properties (for the exe file; as you'll see below the ==== marks, 32-bit Windows doesn't need Dosbox).

Then, search on 'output', and as the instruction in the conf file warns, if and only if you have 'hardware scaling', change the default 'output=surface' to something else; he then lists the optional other settings. I changed it to 'output=overlay'. There's one other setting to test: aspect. Search the file for 'aspect', and change the 'false' to 'true' if you want an even bigger window. When I did this, the window took up over half of the screen. With 'false' left alone, I had a somewhat smaller window (I use widescreen monitors, whether laptop or desktop, maybe that's why).

So after you've made the changes, save the file with the original name of dosbox-0.74.conf . Then, type dosbox at the command line or create a Launcher (in KDE, this is a right click on the desktop) with the command dosbox. You still have to go through the mount command (i.e., mount c~ c:\123 if that's the location and file you'll execute). I'm sure there's a way to make a script, but haven't yet learned how to do that.

How to do a SOAP Web Service call from Java class?

Or just use Apache CXF's wsdl2java to generate objects you can use.

It is included in the binary package you can download from their website. You can simply run a command like this:

$ ./wsdl2java -p com.mynamespace.for.the.api.objects -autoNameResolution http://www.someurl.com/DefaultWebService?wsdl

It uses the wsdl to generate objects, which you can use like this (object names are also grabbed from the wsdl, so yours will be different a little):

DefaultWebService defaultWebService = new DefaultWebService();
String res = defaultWebService.getDefaultWebServiceHttpSoap11Endpoint().login("webservice","dadsadasdasd");
System.out.println(res);

There is even a Maven plug-in which generates the sources: https://cxf.apache.org/docs/maven-cxf-codegen-plugin-wsdl-to-java.html

Note: If you generate sources using CXF and IDEA, you might want to look at this: https://stackoverflow.com/a/46812593/840315

Using Address Instead Of Longitude And Latitude With Google Maps API

You can parse the geolocation through the addresses. Create an Array with jquery like this:

//follow this structure
var addressesArray = [
  'Address Str.No, Postal Area/city'
]

//loop all the addresses and call a marker for each one
for (var x = 0; x < addressesArray.length; x++) {
  $.getJSON('http://maps.googleapis.com/maps/api/geocode/json?address='+addressesArray[x]+'&sensor=false', null, function (data) {
    var p = data.results[0].geometry.location
    var latlng = new google.maps.LatLng(p.lat, p.lng);
    //it will place marker based on the addresses, which they will be translated as geolocations.
    var aMarker= new google.maps.Marker({
      position: latlng,
      map: map
    });
  });
}

Also please note that Google limit your results if you don't have a business account with them, and you my get an error if you use too many addresses.

Reset/remove CSS styles for element only

For future readers. I think this is what was meant but currently isn't really wide supported (see below):

#someselector {
  all: initial;
  * {
    all: unset;
  }
}
  • Supported in (source): Chrome 37, Firefox 27, IE 11, Opera 24
  • Not supported: Safari

phpmailer - The following SMTP Error: Data not accepted

Interestingly, I had the same exact issue and for me the problem was that my connection was timing out. To be able to see more details on my connections, I added $mail->SMTPDebug = 4; to my phpmailer (look up how to capture the debug since the default output function is echo).

Here's the result:

SMTP -> get_lines(): $data was ""
SMTP -> get_lines(): $str is ""
SMTP -> get_lines(): $data is ""
SMTP -> get_lines(): timed-out (10 seconds)
SMTP -> FROM SERVER:
SMTP -> ERROR: DATA not accepted from server: 

The default timeout is set to 10 seconds. If your app can support more, add this line to your phpmailer:

$mail->Timeout = 20;

Linq filter List<string> where it contains a string value from another List<string>

you can do that

var filteredFileList = fileList.Where(fl => filterList.Contains(fl.ToString()));

Option to ignore case with .contains method?

With a null check on the dvdList and your searchString

    if (!StringUtils.isEmpty(searchString)) {
        return Optional.ofNullable(dvdList)
                       .map(Collection::stream)
                       .orElse(Stream.empty())
                       .anyMatch(dvd >searchString.equalsIgnoreCase(dvd.getTitle()));
      }

sql insert into table with select case values

You need commas after end finishing the case statement. And, the "as" goes after the case statement, not inside it:

Insert into TblStuff(FullName, Address, City, Zip)
    Select (Case When Middle is Null Then Fname + LName
                 Else Fname +' ' + Middle + ' '+ Lname
            End)  as FullName,
           (Case When Address2 is Null Then Address1
                 else Address1 +', ' + Address2
            End)  as  Address,
           City as City,
           Zip as Zip
    from tblImport

Java Regex to Validate Full Name allow only Spaces and Letters

You could even try this expression ^[a-zA-Z\\s]*$ for checking a string with only letters and spaces (nothing else).

For me it worked. Hope it works for you as well.

Or go through this piece of code once:

    CharSequence inputStr = expression;
    Pattern pattern = Pattern.compile(new String ("^[a-zA-Z\\s]*$"));
    Matcher matcher = pattern.matcher(inputStr);
    if(matcher.matches())
    {
         //if pattern matches
    }
    else
    {
         //if pattern does not matches
    }

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

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

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

Initial bytes incorrect after Java AES/CBC decryption

Another solution using java.util.Base64 with Spring Boot

Encryptor Class

package com.jmendoza.springboot.crypto.cipher;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

@Component
public class Encryptor {

    @Value("${security.encryptor.key}")
    private byte[] key;
    @Value("${security.encryptor.algorithm}")
    private String algorithm;

    public String encrypt(String plainText) throws Exception {
        SecretKeySpec secretKey = new SecretKeySpec(key, algorithm);
        Cipher cipher = Cipher.getInstance(algorithm);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        return new String(Base64.getEncoder().encode(cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8))));
    }

    public String decrypt(String cipherText) throws Exception {
        SecretKeySpec secretKey = new SecretKeySpec(key, algorithm);
        Cipher cipher = Cipher.getInstance(algorithm);
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        return new String(cipher.doFinal(Base64.getDecoder().decode(cipherText)));
    }
}

EncryptorController Class

package com.jmendoza.springboot.crypto.controller;

import com.jmendoza.springboot.crypto.cipher.Encryptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/cipher")
public class EncryptorController {

    @Autowired
    Encryptor encryptor;

    @GetMapping(value = "encrypt/{value}")
    public String encrypt(@PathVariable("value") final String value) throws Exception {
        return encryptor.encrypt(value);
    }

    @GetMapping(value = "decrypt/{value}")
    public String decrypt(@PathVariable("value") final String value) throws Exception {
        return encryptor.decrypt(value);
    }
}

application.properties

server.port=8082
security.encryptor.algorithm=AES
security.encryptor.key=M8jFt46dfJMaiJA0

Example

http://localhost:8082/cipher/encrypt/jmendoza

2h41HH8Shzc4BRU3hVDOXA==

http://localhost:8082/cipher/decrypt/2h41HH8Shzc4BRU3hVDOXA==

jmendoza

WPF Check box: Check changed handling

I know this is an old question, but how about just binding to Command if using MVVM?

ex:

<CheckBox Content="Case Sensitive" Command="{Binding bSearchCaseSensitive}"/>

For me it triggers on both Check and Uncheck.

How do I disable the security certificate check in Python requests

Also can be done from the environment variable:

export CURL_CA_BUNDLE=""

Received an invalid column length from the bcp client for colid 6

Great piece of code, thanks for sharing!

I ended up using reflection to get the actual DataMemberName to throw back to a client on an error (I'm using bulk save in a WCF service). Hopefully someone else will find how I did it useful.

_x000D_
_x000D_
static string GetDataMemberName(string colName, object t) {_x000D_
  foreach(PropertyInfo propertyInfo in t.GetType().GetProperties()) {_x000D_
    if (propertyInfo.CanRead) {_x000D_
      if (propertyInfo.Name == colName) {_x000D_
        var attributes = propertyInfo.GetCustomAttributes(typeof(DataMemberAttribute), false).FirstOrDefault() as DataMemberAttribute;_x000D_
        if (attributes != null && !string.IsNullOrEmpty(attributes.Name))_x000D_
          return attributes.Name;_x000D_
        return colName;_x000D_
      }_x000D_
    }_x000D_
  }_x000D_
  return colName;_x000D_
}
_x000D_
_x000D_
_x000D_

Why does instanceof return false for some literals?

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

Returns a string-representation of instanceof (the constructors name)

function instanceOf(object) {
  var type = typeof object

  if (type === 'undefined') {
    return 'undefined'
  }

  if (object) {
    type = object.constructor.name
  } else if (type === 'object') {
    type = Object.prototype.toString.call(object).slice(8, -1)
  }

  return type.toLowerCase()
}

instanceOf(false)                  // "boolean"
instanceOf(new Promise(() => {}))  // "promise"
instanceOf(null)                   // "null"
instanceOf(undefined)              // "undefined"
instanceOf(1)                      // "number"
instanceOf(() => {})               // "function"
instanceOf([])                     // "array"

Can we overload the main method in Java?

Yes, by method overloading. You can have any number of main methods in a class by method overloading. Let's see the simple example:

class Simple{  
  public static void main(int a){  
  System.out.println(a);  
  }  

  public static void main(String args[]){  
  System.out.println("main() method invoked");  
  main(10);  
  }  
}  

It will give the following output:

main() method invoked
10

HTML5 <video> element on Android

After much research, in many different devices, up to now, I've reached the simple conclusion that MP4 is much less supported than MOV format. So, I'm using MOV format, which is supported by all Android and Apple devices, on all browsers. I've detected weather the device is a mobile device or a desktop browser, and set the SRC accordingly:

if (IsMobile()) {
    $('#vid').attr('src', '/uploads/' + name + '.mov');
}
else {
    $('#vid').attr('src', '/uploads/' + name + '.webm');        
}

function IsMobile() {
    var isMobile = false; //initiate as false

    if (/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|ipad|iris|kindle|Android|Silk|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(navigator.userAgent)
                || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(navigator.userAgent.substr(0, 4))) isMobile = true;
    return isMobile;
}

Find location of a removable SD card

By writing below code you will get the location:

/storage/663D-554E/Android/data/app_package_name/files/

which stores your app data at /android/data location inside the sd_card.

File[] list = ContextCompat.getExternalFilesDirs(MainActivity.this, null);

list[1]+"/fol" 

for getting location pass 0 for internal and 1 for sdcard to file array.

I have tested this code on a moto g4 plus and Samsung device (all works fine).

hope this might helpful.

Mongoose.js: Find user by username LIKE value

For dynamic search, you can follow like this also,

const { keyword, skip, limit, sort } = pagination(params);
const search = keyword
      ? {
          title: {
            $regex: new RegExp(keyword, 'i')
          }
        }
      : {};

Model.find(search)
      .sort(sort)
      .skip(skip)
      .limit(limit);

How to run html file using node js

Either you use a framework or you write your own server with nodejs.

A simple fileserver may look like this:

import * as http from 'http';
import * as url from 'url';
import * as fs from 'fs';
import * as path from 'path';

var mimeTypes = {
     "html": "text/html",
     "jpeg": "image/jpeg",
     "jpg": "image/jpeg",
     "png": "image/png",
     "js": "text/javascript",
     "css": "text/css"};

http.createServer((request, response)=>{
    var pathname = url.parse(request.url).pathname;
    var filename : string;
    if(pathname === "/"){
        filename = "index.html";
    }
    else
        filename = path.join(process.cwd(), pathname);

    try{
        fs.accessSync(filename, fs.F_OK);
        var fileStream = fs.createReadStream(filename);
        var mimeType = mimeTypes[path.extname(filename).split(".")[1]];
        response.writeHead(200, {'Content-Type':mimeType});
        fileStream.pipe(response);
    }
    catch(e) {
            console.log('File not exists: ' + filename);
            response.writeHead(404, {'Content-Type': 'text/plain'});
            response.write('404 Not Found\n');
            response.end();
            return;
    }
    return;
    }
}).listen(5000);

Selecting a row in DataGridView programmatically

You can use the Select method if you have a datasource: http://msdn.microsoft.com/en-us/library/b51xae2y%28v=vs.71%29.aspx

Or use linq if you have objects in you datasource

PHP function ssh2_connect is not working

Honestly, I'd recommend using phpseclib, a pure PHP SSH2 implementation. Example:

<?php
include('Net/SSH2.php');

$ssh = new Net_SSH2('www.domain.tld');
if (!$ssh->login('username', 'password')) {
    exit('Login Failed');
}

echo $ssh->exec('pwd');
echo $ssh->exec('ls -la');
?>

It's a ton more portable, easier to use and more feature packed too.

Print Pdf in C#

It is possible to use Ghostscript to read PDF files and print them to a named printer.

Warning: X may be used uninitialized in this function

You get the warning because you did not assign a value to one, which is a pointer. This is undefined behavior.

You should declare it like this:

Vector* one = malloc(sizeof(Vector));

or like this:

Vector one;

in which case you need to replace -> operator with . like this:

one.a = 12;
one.b = 13;
one.c = -11;

Finally, in C99 and later you can use designated initializers:

Vector one = {
   .a = 12
,  .b = 13
,  .c = -11
};

Print string and variable contents on the same line in R

{glue} offers much better string interpolation, see my other answer. Also, as Dainis rightfully mentions, sprintf() is not without problems.

There's also sprintf():

sprintf("Current working dir: %s", wd)

To print to the console output, use cat() or message():

cat(sprintf("Current working dir: %s\n", wd))
message(sprintf("Current working dir: %s\n", wd))

How to disable Paste (Ctrl+V) with jQuery?

The following code will disable cut, copy and paste from full page.

$(document).ready(function () {
   $('body').bind('cut copy paste', function (e) {
      e.preventDefault();
   });
});

The full tutorial and working demo can be found from here - Disable cut, copy and paste using jQuery

Node.js: for each … in not working

This might be an old qustion, but just to keep things updated, there is a forEach method in javascript that works with NodeJS. Here's the link from the docs. And an example:

     count = countElements.length;
        if (count > 0) {
            countElements.forEach(function(countElement){
                console.log(countElement);
            });
        }

Write to .txt file?

FILE *f = fopen("file.txt", "w");
if (f == NULL)
{
    printf("Error opening file!\n");
    exit(1);
}

/* print some text */
const char *text = "Write this to the file";
fprintf(f, "Some text: %s\n", text);

/* print integers and floats */
int i = 1;
float py = 3.1415927;
fprintf(f, "Integer: %d, float: %f\n", i, py);

/* printing single chatacters */
char c = 'A';
fprintf(f, "A character: %c\n", c);

fclose(f);

How do I disable "missing docstring" warnings at a file-level in Pylint?

I think the fix is relative easy without disabling this feature.

def kos_root():
    """Return the pathname of the KOS root directory."""
    global _kos_root
    if _kos_root: return _kos_root

All you need to do is add the triple double quotes string in every function.

How to add "required" attribute to mvc razor viewmodel text input editor

On your model class decorate that property with [Required] attribute. I.e.:

[Required]
public string ShortName {get; set;}

Download a div in a HTML page as pdf using javascript

You can do it using jsPDF

HTML:

<div id="content">
     <h3>Hello, this is a H3 tag</h3>

    <p>A paragraph</p>
</div>
<div id="editor"></div>
<button id="cmd">generate PDF</button>

JavaScript:

var doc = new jsPDF();
var specialElementHandlers = {
    '#editor': function (element, renderer) {
        return true;
    }
};

$('#cmd').click(function () {
    doc.fromHTML($('#content').html(), 15, 15, {
        'width': 170,
            'elementHandlers': specialElementHandlers
    });
    doc.save('sample-file.pdf');
});

Save matplotlib file to a directory

Here's the piece of code that saves plot to the selected directory. If the directory does not exist, it is created.

import os
import matplotlib.pyplot as plt

script_dir = os.path.dirname(__file__)
results_dir = os.path.join(script_dir, 'Results/')
sample_file_name = "sample"

if not os.path.isdir(results_dir):
    os.makedirs(results_dir)

plt.plot([1,2,3,4])
plt.ylabel('some numbers')
plt.savefig(results_dir + sample_file_name)

INFO: No Spring WebApplicationInitializer types detected on classpath

I also had the same problem. My maven had tomcat7 plugin but the JRE environment was 1.6. I changed my tomcat7 to tomcat6 and the error was gone.

How do I correctly upgrade angular 2 (npm) to the latest version?

Another nice package which I used for migrating form a beta version of Angular2 to Angular2 2.0.0 final is npm-check-updates

It shows the latest available version of all packages specified within your package.json. In contrast to npm outdated it is also capable to edit your package.json, enabling you to do a npm upgrade later.

Install

sudo npm install -g npm-check-updates

Usage

ncufor display

ncu -u for re-writing your package.json

How can I use interface as a C# generic type constraint?

I tried to do something similar and used a workaround solution: I thought about implicit and explicit operator on structure: The idea is to wrap the Type in a structure that can be converted into Type implicitly.

Here is such a structure:

public struct InterfaceType { private Type _type;

public InterfaceType(Type type)
{
    CheckType(type);
    _type = type;
}

public static explicit operator Type(InterfaceType value)
{
    return value._type;
}

public static implicit operator InterfaceType(Type type)
{
    return new InterfaceType(type);
}

private static void CheckType(Type type)
{
    if (type == null) throw new NullReferenceException("The type cannot be null");
    if (!type.IsInterface) throw new NotSupportedException(string.Format("The given type {0} is not an interface, thus is not supported", type.Name));
}

}

basic usage:

// OK
InterfaceType type1 = typeof(System.ComponentModel.INotifyPropertyChanged);

// Throws an exception
InterfaceType type2 = typeof(WeakReference);

You have to imagine your own mecanism around this, but an example could be a method taken a InterfaceType in parameter instead of a type

this.MyMethod(typeof(IMyType)) // works
this.MyMethod(typeof(MyType)) // throws exception

A method to override that should returns interface types:

public virtual IEnumerable<InterfaceType> GetInterfaces()

There are maybe things to do with generics also, but I didn't tried

Hope this can help or gives ideas :-)

How do I copy directories recursively with gulp?

If you want to copy the entire contents of a folder recursively into another folder, you can execute the following windows command from gulp:

xcopy /path/to/srcfolder /path/to/destfolder /s /e /y

The /y option at the end is to suppress the overwrite confirmation message.

In Linux, you can execute the following command from gulp:

cp -R /path/to/srcfolder /path/to/destfolder

you can use gulp-exec or gulp-run plugin to execute system commands from gulp.

Related Links:

  1. xcopy usage

  2. gulp-exec and gulp-run

Serialize Property as Xml Attribute in Element

Kind of, use the XmlAttribute instead of XmlElement, but it won't look like what you want. It will look like the following:

<SomeModel SomeStringElementName="testData"> 
</SomeModel> 

The only way I can think of to achieve what you want (natively) would be to have properties pointing to objects named SomeStringElementName and SomeInfoElementName where the class contained a single getter named "value". You could take this one step further and use DataContractSerializer so that the wrapper classes can be private. XmlSerializer won't read private properties.

// TODO: make the class generic so that an int or string can be used.
[Serializable]  
public class SerializationClass
{
    public SerializationClass(string value)
    {
        this.Value = value;
    }

    [XmlAttribute("value")]
    public string Value { get; }
}


[Serializable]                     
public class SomeModel                     
{                     
    [XmlIgnore]                     
    public string SomeString { get; set; }                     

    [XmlIgnore]                      
    public int SomeInfo { get; set; }  

    [XmlElement]
    public SerializationClass SomeStringElementName
    {
        get { return new SerializationClass(this.SomeString); }
    }               
}

Python function pointer

Why not store the function itself? myvar = mypackage.mymodule.myfunction is much cleaner.

Free easy way to draw graphs and charts in C++?

My favourite has always been gnuplot. It's very extensive, so it might be a bit too complex for your needs though. It is cross-platform and there is a C++ API.

How to customize listview using baseadapter

Create your own BaseAdapter class and use it as following.

 public class NotificationScreen extends Activity
{

@Override
protected void onCreate_Impl(Bundle savedInstanceState)
{
    setContentView(R.layout.notification_screen);

    ListView notificationList = (ListView) findViewById(R.id.notification_list);
    NotiFicationListAdapter notiFicationListAdapter = new NotiFicationListAdapter();
    notificationList.setAdapter(notiFicationListAdapter);

    homeButton = (Button) findViewById(R.id.home_button);

}

}

Make your own BaseAdapter class and its separate xml file.

public class NotiFicationListAdapter  extends BaseAdapter
{
private ArrayList<HashMap<String, String>> data;
private LayoutInflater inflater=null;


public NotiFicationListAdapter(ArrayList data)
{
this.data=data;        
    inflater =(LayoutInflater)baseActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}



public int getCount() 
{
 return data.size();
}



public Object getItem(int position) 
{
 return position;
}



public long getItemId(int position) 
{
    return position;
}



public View getView(int position, View convertView, ViewGroup parent) 
{
View vi=convertView;
    if(convertView==null)

    vi = inflater.inflate(R.layout.notification_list_item, null);

    ImageView compleatImageView=(ImageView)vi.findViewById(R.id.complet_image);
    TextView name = (TextView)vi.findViewById(R.id.game_name); // name
    TextView email_id = (TextView)vi.findViewById(R.id.e_mail_id); // email ID
    TextView notification_message = (TextView)vi.findViewById(R.id.notification_message); // notification message



    compleatImageView.setBackgroundResource(R.id.address_book);
    name.setText(data.getIndex(position));
    email_id.setText(data.getIndex(position));
    notification_message.setTextdata.getIndex(position));

    return vi;
}

  }

BaseAdapter xml file.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/inner_layout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
android:layout_marginLeft="10dp"
android:layout_weight="4"
android:background="@drawable/list_view_frame"
android:gravity="center_vertical"
android:padding="5dp" >

<TextView
    android:id="@+id/game_name"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Game name"
    android:textColor="#FFFFFF"
    android:textSize="15dip"
    android:textStyle="bold"
    android:typeface="sans" />

<TextView
    android:id="@+id/e_mail_id"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@id/game_name"
    android:layout_marginTop="1dip"
    android:text="E-Mail Id"
    android:textColor="#FFFFFF"
    android:textSize="10dip" />

<TextView
    android:id="@+id/notification_message"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@id/game_name"
    android:layout_toRightOf="@id/e_mail_id"
    android:paddingLeft="5dp"
    android:text="Notification message"
    android:textColor="#FFFFFF"
    android:textSize="10dip" />



<ImageView
    android:id="@+id/complet_image"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:layout_centerVertical="true"
    android:layout_marginBottom="30dp"
    android:layout_marginRight="10dp"
    android:src="@drawable/complete_tag"
    android:visibility="invisible" />

</RelativeLayout>

Change it accordingly and use.

How do I make an Android EditView 'Done' button and hide the keyboard when clicked?

Use These two lines to your EditText

android:imeActionLabel="Done"
android:singleLine="true"

or you can achieve it Programmatically by this line.

editText.setImeOptions(EditorInfo.IME_ACTION_DONE);

List of IP addresses/hostnames from local network in Python

I have done following code to get the IP of MAC known device. This can be modified accordingly to obtain all IPs with some string manipulation. Hope this will help you.

#running windows cmd line  statement and put output into a string
cmd_out = os.popen("arp -a").read()
line_arr = cmd_out.split('\n')
line_count = len(line_arr)


#search in all lines for ip
for i in range(0, line_count):
    y = line_arr[i]
    z = y.find(mac_address)

    #if mac address is found then get the ip using regex matching
    if z > 0:
        ip_out= re.search('[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+', y, re.M | re.I)

How do I change data-type of pandas data frame to string with a defined format?

I'm unable to reproduce your problem but have you tried converting it to an integer first?

image_name_data['id'] = image_name_data['id'].astype(int).astype('str')

Then, regarding your more general question you could use map (as in this answer). In your case:

image_name_data['id'] = image_name_data['id'].map('{:.0f}'.format)

MySQL export into outfile : CSV escaping chars

I think your statement should look like:

SELECT id, 
   client,
   project,
   task,
   description, 
   time,
   date  
  INTO OUTFILE '/path/to/file.csv'
  FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
  LINES TERMINATED BY '\n'
  FROM ts

Mainly without the FIELDS ESCAPED BY '""' option, OPTIONALLY ENCLOSED BY '"' will do the trick for description fields etc and your numbers will be treated as numbers in Excel (not strings comprising of numerics)

Also try calling:

SET NAMES utf8;

before your outfile select, that might help getting the character encodings inline (all UTF8)

Let us know how you get on.

Executing a batch file in a remote machine through PsExec

Here's my current solution to run any code remotely on a given machine or list of machines asynchronously with logging, too!

@echo off
:: by Ralph Buchfelder, thanks to Mark Russinovich and Rob van der Woude for their work!
:: requires PsExec.exe to be in the same directory (download from http://technet.microsoft.com/de-de/sysinternals/bb897553.aspx)
:: troubleshoot remote commands with PsExec arguments -i or -s if neccessary (see http://forum.sysinternals.com/pstools_forum8.html)
:: will run *in parallel* on a list of remote pcs (if given); to run serially please remove 'START "" CMD.EXE /C' from the psexec call


:: help
if '%1' =='-h' (
 echo.
 echo %~n0
 echo.
 echo Runs a command on one or many remote machines. If no input parameters
 echo are given you will be asked for a target remote machine.
 echo.
 echo You will be prompted for remote credentials with elevated privileges.
 echo.
 echo UNC paths and local paths can be supplied.
 echo Commands will be executed on the remote side just the way you typed
 echo them, so be sure to mind extensions and the path variable!
 echo.
 echo Please note that PsExec.exe must be allowed on remote machines, i.e.
 echo not blocked by firewall or antivirus solutions.
 echo.
 echo Syntax: %~n0 [^<inputfile^>]
 echo.
 echo     inputfile      = a plain text file ^(one hostname or ip address per line^)
 echo.
 echo.
 echo Example:
 echo %~n0 mylist.txt
 exit /b 0
)


:checkAdmin
>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system"
if '%errorlevel%' neq '0' (
 echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
 echo UAC.ShellExecute "%~s0", "", "", "runas", 1 >> "%temp%\getadmin.vbs"
 "%temp%\getadmin.vbs"
 del "%temp%\getadmin.vbs"
 exit /B
)
set ADMINTESTDIR=%WINDIR%\System32\Test_%RANDOM%
mkdir "%ADMINTESTDIR%" 2>NUL
if errorlevel 1 (
 cls
 echo ERROR: This script requires elevated privileges!
 echo.
 echo Launch by Right-Click / Run as Administrator ...
 pause
 exit /b 1
) else (
 rd /s /q "%ADMINTESTDIR%"
 echo Running with elevated privileges...
)
echo.


:checkRequirements
if not exist "%~dp0PsExec.exe" (
 echo PsExec.exe from Sysinternals/Microsoft not found 
 echo in %~dp0
 echo.
 echo Download from http://technet.microsoft.com/de-de/sysinternals/bb897553.aspx
 echo.
 pause
 exit /B
)


:environment
setlocal
echo.
echo %~n0
echo _____________________________
echo.
echo Working directory:  %cd%\
echo Script directory:   %~dp0
echo.
SET /P REMOTE_USER=Domain\Administrator : 
SET "psCommand=powershell -Command "$pword = read-host 'Kennwort' -AsSecureString ; ^
    $BSTR=[System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($pword); ^
        [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)""
for /f "usebackq delims=" %%p in (`%psCommand%`) do set REMOTE_PASS=%%p
if NOT DEFINED REMOTE_PASS SET /P REMOTE_PASS=Password             : 
echo.
if '%1' =='' goto menu
SET REMOTE_LIST=%1


:inputMultipleTargets
if not exist %REMOTE_LIST% (
 echo File %REMOTE_LIST% not found
 goto menu
)
type %REMOTE_LIST% >nul
if '%errorlevel%' neq '0' (
 echo Access denied %REMOTE_LIST%
 goto menu
)
set batchProcessing=true
echo Batch processing:   %REMOTE_LIST%   ...
ping -n 2 127.0.0.1 >nul
goto runOnce


:menu
if exist "%~dp0last.computer"  set /p LAST_COMPUTER=<"%~dp0last.computer"
if exist "%~dp0last.listing"   set /p LAST_LISTING=<"%~dp0last.listing"
if exist "%~dp0last.directory" set /p LAST_DIRECTORY=<"%~dp0last.directory"
if exist "%~dp0last.command"   set /p LAST_COMMAND=<"%~dp0last.command"
if exist "%~dp0last.timestamp" set /p LAST_TIMESTAMP=<"%~dp0last.timestamp"
echo.
echo.
echo                (1)  select target computer [default]
echo                (2)  select multiple computers
echo                     -----------------------------------
echo                     last target : %LAST_COMPUTER%
echo                     last listing: %LAST_LISTING%
echo                     last path   : %LAST_DIRECTORY%
echo                     last command: %LAST_COMMAND%
echo                     last run    : %LAST_TIMESTAMP%
echo                     -----------------------------------
echo                (0)  exit
echo.
echo ENTER your choice.
echo.
echo.
:mychoice
SET /P mychoice=(0, 1, ...): 
if NOT DEFINED mychoice  goto promptSingleTarget
if "%mychoice%"=="1"     goto promptSingleTarget
if "%mychoice%"=="2"     goto promptMultipleTargets
if "%mychoice%"=="0"     goto end
goto mychoice


:promptMultipleTargets
echo.
echo Please provide an input file
echo [one IP address or hostname per line]
SET /P REMOTE_LIST=Filename             : 
goto inputMultipleTargets


:promptSingleTarget
SET batchProcessing=
echo.
echo Please provide a hostname
SET /P REMOTE_COMPUTER=Target computer      : 
goto runOnce


:runOnce
cls
echo Note: Paths are mandatory for CMD-commands (e.g. dir,copy) to work!
echo       Paths are provided on the remote machine via PUSHD.
echo.
SET /P REMOTE_PATH=UNC-Path or folder : 
SET /P REMOTE_CMD=Command with params: 
SET REMOTE_TIMESTAMP=%DATE% %TIME:~0,8%
echo.
echo Remote command starting (%REMOTE_PATH%\%REMOTE_CMD%) on %REMOTE_TIMESTAMP%...
if not defined batchProcessing goto runOnceSingle


:runOnceMulti
REM do for each line; this circumvents PsExec's @file to have stdouts separately
SET REMOTE_LOG=%~dp0\log\%REMOTE_LIST%
if not exist %REMOTE_LOG% md %REMOTE_LOG%
for /F "tokens=*" %%A in (%REMOTE_LIST%) do (
 if "%REMOTE_PATH%" =="" START "" CMD.EXE /C ^(%~dp0PSEXEC -u %REMOTE_USER% -p %REMOTE_PASS% -h -accepteula \\%%A cmd /c "%REMOTE_CMD%" ^>"%REMOTE_LOG%\%%A.log" 2^>"%REMOTE_LOG%\%%A_debug.log" ^)
 if not "%REMOTE_PATH%" =="" START "" CMD.EXE /C ^(%~dp0PSEXEC -u %REMOTE_USER% -p %REMOTE_PASS% -h -accepteula \\%%A cmd /c "pushd %REMOTE_PATH% && %REMOTE_CMD% & popd" ^>"%REMOTE_LOG%\%%A.log" 2^>"%REMOTE_LOG%\%%A_debug.log" ^)
)
goto restart


:runOnceSingle
SET REMOTE_LOG=%~dp0\log
if not exist %REMOTE_LOG% md %REMOTE_LOG%
if "%REMOTE_PATH%" =="" %~dp0PSEXEC -u %REMOTE_USER% -p %REMOTE_PASS% -h -accepteula \\%REMOTE_COMPUTER% cmd /c "%REMOTE_CMD%" >"%REMOTE_LOG%\%REMOTE_COMPUTER%.log" 2>"%REMOTE_LOG%\%REMOTE_COMPUTER%_debug.log"
if not "%REMOTE_PATH%" =="" %~dp0PSEXEC -u %REMOTE_USER% -p %REMOTE_PASS% -h -accepteula \\%REMOTE_COMPUTER% cmd /c "pushd %REMOTE_PATH% && %REMOTE_CMD% & popd" >"%REMOTE_LOG%\%REMOTE_COMPUTER%.log" 2>"%REMOTE_LOG%\%REMOTE_COMPUTER%_debug.log"
goto restart


:restart
echo.
echo.
echo Batch completed. Finished with last errorlevel %errorlevel% .
echo All outputs have been saved to %~dp0log\%REMOTE_TIMESTAMP%\.
echo %REMOTE_PATH% >"%~dp0last.directory"
echo %REMOTE_CMD% >"%~dp0last.command"
echo %REMOTE_LIST% >"%~dp0last.listing"
echo %REMOTE_COMPUTER% >"%~dp0last.computer"
echo %REMOTE_TIMESTAMP% >"%~dp0last.timestamp"
SET REMOTE_PATH=
SET REMOTE_CMD=
SET REMOTE_LIST=
SET REMOTE_COMPUTER=
SET REMOTE_LOG=
SET REMOTE_TIMESTAMP=
ping -n 2 127.0.0.1 >nul
goto menu


:end
SET REMOTE_USER=
SET REMOTE_PASS=

How do I create a readable diff of two spreadsheets using git diff?

You can try this free online tool - www.cloudyexcel.com/compare-excel/

It gives a good visual output online, in terms of rows added,deleted, changed etc.

enter image description here

Plus you donot have to install anything.

How to load a resource from WEB-INF directory of a web archive

The problem I had accessing the sqlite db file I created in my java (jersey) server had solely to due with path. Some of the docs say the jdbc connect url should look like "jdbc:sqlite://path-to-file/sample.db". I thought the double-slash was part of a htt protocol-style path and would map properly when deployed, but in actuality, it's an absolute or relative path. So, when I placed the file at the root of the WebContent folder (tomcat project), a uri like this worked "jdbc:sqlite:sample.db".

The one thing that was throwing me was that when I was stepping through the debugger, I received a message that said "opening db: ... permission denied". I thought it was a matter of file system permissions or perhaps sql user permissions. After finding out that SQLite doesn't have the concept of roles/permissions like MySQL, etc, I did eventually change the file permissions before I came to what I believe was the correct solution, but I think it was just a bad message (i.e. permission denied, instead of File not found).

Hope this helps someone.

How to Cast Objects in PHP

I think that the best approach is to just create a new instance of a class and than assign the object. Here's what I would do:

public function ($someVO) {

     $someCastVO = new SomeVO();
     $someCastVO = $someVO;
     $someCastVO->SomePropertyInVO = "123";

}

Doing this will give you code hinting in most IDEs and help ensure you are using the correct properties.

Error:(23, 17) Failed to resolve: junit:junit:4.12

If none of these answers for you, try clearing the Android Studio cache/restart. That was the only thing that worked for me:

From the file menu option, I selected "invalidate caches/restart".

https://teamtreehouse.com/community/gradle-project-sync-failed-7

Is there a better jQuery solution to this.form.submit();?

this.form.submit();

This is probably your best bet. Especially if you are not already using jQuery in your project, there is no need to add it (or any other JS library) just for this purpose.

How to check View Source in Mobile Browsers (Both Android && Feature Phone)

This is an old post but still a problem within the Chrome dev tools. I find the best way to check mobile source locally is to open the site locally in Xcode's iOS Simulator. Then from there you open the Safari browser and enable dev tools, if you have not already done this (go to preferences -> advanced -> show develop menu in menu bar). Now you will see the develop option in the main menu and can go to develop -> iOS Simulator -> and the page you have open in Xcode's iOS Simulator will be there. Once you click on it, it will open the web inspector and you can edit as you would normally in the browser dev tools.

I'm afraid this solution will only work on a Mac though as it uses Xcode.

Does Python have an ordered set?

If you're using the ordered set to maintain a sorted order, consider using a sorted set implementation from PyPI. The sortedcontainers module provides a SortedSet for just this purpose. Some benefits: pure-Python, fast-as-C implementations, 100% unit test coverage, hours of stress testing.

Installing from PyPI is easy with pip:

pip install sortedcontainers

Note that if you can't pip install, simply pull down the sortedlist.py and sortedset.py files from the open-source repository.

Once installed you can simply:

from sortedcontainers import SortedSet
help(SortedSet)

The sortedcontainers module also maintains a performance comparison with several alternative implementations.

For the comment that asked about Python's bag data type, there's alternatively a SortedList data type which can be used to efficiently implement a bag.

How to get current time and date in Android

You can (but no longer should - see below!) use android.text.format.Time:

Time now = new Time();
now.setToNow();

From the reference linked above:

The Time class is a faster replacement for the java.util.Calendar and java.util.GregorianCalendar classes. An instance of the Time class represents a moment in time, specified with second precision.


NOTE 1: It's been several years since I wrote this answer, and it is about an old, Android-specific and now deprecated class. Google now says that "[t]his class has a number of issues and it is recommended that GregorianCalendar is used instead".


NOTE 2: Even though the Time class has a toMillis(ignoreDaylightSavings) method, this is merely a convenience to pass to methods that expect time in milliseconds. The time value is only precise to one second; the milliseconds portion is always 000. If in a loop you do

Time time = new Time();   time.setToNow();
Log.d("TIME TEST", Long.toString(time.toMillis(false)));
... do something that takes more than one millisecond, but less than one second ...

The resulting sequence will repeat the same value, such as 1410543204000, until the next second has started, at which time 1410543205000 will begin to repeat.

Why am I getting an error "Object literal may only specify known properties"?

As of TypeScript 1.6, properties in object literals that do not have a corresponding property in the type they're being assigned to are flagged as errors.

Usually this error means you have a bug (typically a typo) in your code, or in the definition file. The right fix in this case would be to fix the typo. In the question, the property callbackOnLoactionHash is incorrect and should have been callbackOnLocationHash (note the mis-spelling of "Location").

This change also required some updates in definition files, so you should get the latest version of the .d.ts for any libraries you're using.

Example:

interface TextOptions {
    alignment?: string;
    color?: string;
    padding?: number;
}
function drawText(opts: TextOptions) { ... }
drawText({ align: 'center' }); // Error, no property 'align' in 'TextOptions'

But I meant to do that

There are a few cases where you may have intended to have extra properties in your object. Depending on what you're doing, there are several appropriate fixes

Type-checking only some properties

Sometimes you want to make sure a few things are present and of the correct type, but intend to have extra properties for whatever reason. Type assertions (<T>v or v as T) do not check for extra properties, so you can use them in place of a type annotation:

interface Options {
    x?: string;
    y?: number;
}

// Error, no property 'z' in 'Options'
let q1: Options = { x: 'foo', y: 32, z: 100 };
// OK
let q2 = { x: 'foo', y: 32, z: 100 } as Options;
// Still an error (good):
let q3 = { x: 100, y: 32, z: 100 } as Options;

These properties and maybe more

Some APIs take an object and dynamically iterate over its keys, but have 'special' keys that need to be of a certain type. Adding a string indexer to the type will disable extra property checking

Before

interface Model {
  name: string;
}
function createModel(x: Model) { ... }

// Error
createModel({name: 'hello', length: 100});

After

interface Model {
  name: string;
  [others: string]: any;
}
function createModel(x: Model) { ... }

// OK
createModel({name: 'hello', length: 100});

This is a dog or a cat or a horse, not sure yet

interface Animal { move; }
interface Dog extends Animal { woof; }
interface Cat extends Animal { meow; }
interface Horse extends Animal { neigh; }

let x: Animal;
if(...) {
  x = { move: 'doggy paddle', woof: 'bark' };
} else if(...) {
  x = { move: 'catwalk', meow: 'mrar' };
} else {
  x = { move: 'gallop', neigh: 'wilbur' };
}

Two good solutions come to mind here

Specify a closed set for x

// Removes all errors
let x: Dog|Cat|Horse;

or Type assert each thing

// For each initialization
  x = { move: 'doggy paddle', woof: 'bark' } as Dog;

This type is sometimes open and sometimes not

A clean solution to the "data model" problem using intersection types:

interface DataModelOptions {
  name?: string;
  id?: number;
}
interface UserProperties {
  [key: string]: any;
}
function createDataModel(model: DataModelOptions & UserProperties) {
 /* ... */
}
// findDataModel can only look up by name or id
function findDataModel(model: DataModelOptions) {
 /* ... */
}
// OK
createDataModel({name: 'my model', favoriteAnimal: 'cat' });
// Error, 'ID' is not correct (should be 'id')
findDataModel({ ID: 32 });

See also https://github.com/Microsoft/TypeScript/issues/3755

PHP Parse error: syntax error, unexpected '?' in helpers.php 233

I had the same problem with the laravel initiation. The solution was as follows.

1st - I checked the version of my PHP. That it was 5.6 would soon give problem with the laravel.

2nd - I changed the version of my PHP to PHP 7.1.1. ATTENTION, in my case I changed my environment variable that was getting Xampp's PHP version 5.6 I changed to 7.1.1 for laragon.

3rd - I went to the terminal / console and navigated to my folder where my project was and typed the following command: php artisan serves. And it worked! In my case it started at the port: 8000 see example below.

C: \ laragon \ www \ first> php artisan serves Laravel development server started: http://127.0.0.1:8000

I hope I helped someone who has been through the same problem as me.

No templates in Visual Studio 2017

I found the path and wrote it in the options enter image description here

How to start up spring-boot application via command line?

One of the ways that you can run your spring-boot application from command line is as follows :

1) First go to your project directory in command line [where is your project located ?]

2) Then in the next step you have to create jar file for that, this can be done as

mvnw package [for WINDOWS OS ] or ./mvnw package [for MAC OS] , this will create jar file for our application.

3) jar file is created in the target sub-directory

4)Now go to target sub directory as jar was created inside of it , i.e cd target

5) Now run the jar file in there. Use command java -jar name.jar [ name is the name of your created jar file.]

and there you go , you are done . Now you can run project in browser,

 http://localhost:port_number

iOS start Background Thread

Well that's pretty easy actually with GCD. A typical workflow would be something like this:

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0ul);
    dispatch_async(queue, ^{
        // Perform async operation
        // Call your method/function here
        // Example:
        // NSString *result = [anObject calculateSomething];
                dispatch_sync(dispatch_get_main_queue(), ^{
                    // Update UI
                    // Example:
                    // self.myLabel.text = result;
                });
    });

For more on GCD you can take a look into Apple's documentation here

Chrome dev tools fails to show response even the content returned has header Content-Type:text/html; charset=UTF-8

One workaround is to use Postman with same request url, headers and payload.

It will give response for sure.

Check if an array contains any element of another array in JavaScript

Just one more solution

var a1 = [1, 2, 3, 4, 5]
var a2 = [2, 4]

Check if a1 contain all element of a2

var result = a1.filter(e => a2.indexOf(e) !== -1).length === a2.length
console.log(result)

Copy to Clipboard for all Browsers using javascript

This works on firefox 3.6.x and IE:

    function copyToClipboardCrossbrowser(s) {           
        s = document.getElementById(s).value;               

        if( window.clipboardData && clipboardData.setData )
        {
            clipboardData.setData("Text", s);
        }           
        else
        {
            // You have to sign the code to enable this or allow the action in about:config by changing
            //user_pref("signed.applets.codebase_principal_support", true);
            netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');

            var clip = Components.classes["@mozilla.org/widget/clipboard;1"].createInstance(Components.interfaces.nsIClipboard);
            if (!clip) return;

            // create a transferable

            var trans = Components.classes["@mozilla.org/widget/transferable;1"].createInstance(Components.interfaces.nsITransferable);
            if (!trans) return;

            // specify the data we wish to handle. Plaintext in this case.
            trans.addDataFlavor('text/unicode');

            // To get the data from the transferable we need two new objects
            var str = new Object();
            var len = new Object();

            var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);

            str.data= s;        

            trans.setTransferData("text/unicode",str, str.data.length * 2);

            var clipid=Components.interfaces.nsIClipboard;              
            if (!clip) return false;
            clip.setData(trans,null,clipid.kGlobalClipboard);      
        }
    }

compression and decompression of string data in java

The problem is this line:

    String outStr = obj.toString("UTF-8");

The byte array obj contains arbitrary binary data. You can't "decode" arbitrary binary data as if it was UTF-8. If you try you will get a String that cannot then be "encoded" back to bytes. Or at least, the bytes you get will be different to what you started with ... to the extent that they are no longer a valid GZIP stream.

The fix is to store or transmit the contents of the byte array as-is. Don't try to convert it into a String. It is binary data, not text.

How to check a string for specific characters?

user Jochen Ritzel said this in a comment to an answer to this question from user dappawit. It should work:

('1' in var) and ('2' in var) and ('3' in var) ...

'1', '2', etc. should be replaced with the characters you are looking for.

See this page in the Python 2.7 documentation for some information on strings, including about using the in operator for substring tests.

Update: This does the same job as my above suggestion with less repetition:

# When looking for single characters, this checks for any of the characters...
# ...since strings are collections of characters
any(i in '<string>' for i in '123')
# any(i in 'a' for i in '123') -> False
# any(i in 'b3' for i in '123') -> True

# And when looking for subsrings
any(i in '<string>' for i in ('11','22','33'))
# any(i in 'hello' for i in ('18','36','613')) -> False
# any(i in '613 mitzvahs' for i in ('18','36','613')) ->True

How to See the Contents of Windows library (*.lib)

DUMPBIN /EXPORTS Will get most of that information and hitting MSDN will get the rest.

Get one of the Visual Studio packages; C++

Declaring and using MySQL varchar variables

In Mysql, We can declare and use variables with set command like below

mysql> set @foo="manjeet";
mysql> select * from table where name = @foo;

gnuplot : plotting data from multiple input files in a single graph

You may find that gnuplot's for loops are useful in this case, if you adjust your filenames or graph titles appropriately.

e.g.

filenames = "first second third fourth fifth"
plot for [file in filenames] file."dat" using 1:2 with lines

and

filename(n) = sprintf("file_%d", n)
plot for [i=1:10] filename(i) using 1:2 with lines

Converting from Integer, to BigInteger

The method you want is BigInteger#valueOf(long val).

E.g.,

BigInteger bi = BigInteger.valueOf(myInteger.intValue());

Making a String first is unnecessary and undesired.

How to set selected value on select using selectpicker plugin from bootstrap

use this and it's gonna work:

 $('select[name=selValue]').selectpicker('val', 1);

Font.createFont(..) set color and size (java.awt.Font)

Font's don't have a color; only when using the font you can set the color of the component. For example, when using a JTextArea:

JTextArea txt = new JTextArea();
Font font = new Font("Verdana", Font.BOLD, 12);
txt.setFont(font);
txt.setForeground(Color.BLUE);

According to this link, the createFont() method creates a new Font object with a point size of 1 and style PLAIN. So, if you want to increase the size of the Font, you need to do this:

 Font font = Font.createFont(Font.TRUETYPE_FONT, new File("A.ttf"));
 return font.deriveFont(12f);

Add php variable inside echo statement as href link address?

You can use one and more echo statement inside href

<a href="profile.php?usr=<?php echo $_SESSION['firstname']."&email=". $_SESSION['email']; ?> ">Link</a>

link : "/profile.php?usr=firstname&email=email"

How to send FormData objects with Ajax-requests in jQuery?

JavaScript:

function submitForm() {
    var data1 = new FormData($('input[name^="file"]'));
    $.each($('input[name^="file"]')[0].files, function(i, file) {
        data1.append(i, file);
    });

    $.ajax({
        url: "<?php echo base_url() ?>employee/dashboard2/test2",
        type: "POST",
        data: data1,
        enctype: 'multipart/form-data',
        processData: false, // tell jQuery not to process the data
        contentType: false // tell jQuery not to set contentType
    }).done(function(data) {
        console.log("PHP Output:");
        console.log(data);
    });
    return false;
}

PHP:

public function upload_file() {
    foreach($_FILES as $key) {
        $name = time().$key['name'];
        $path = 'upload/'.$name;
        @move_uploaded_file($key['tmp_name'], $path);
    }
}

How to use SharedPreferences in Android to store, fetch and edit values

to save

PreferenceManager.getDefaultSharedPreferences(this).edit().putString("VarName","your value").apply();

to retreive :

String name = PreferenceManager.getDefaultSharedPreferences(this).getString("VarName","defaultValue");

default value is : Values to return if this preference does not exist.

you can change "this" with getActivity() or getApplicationContext() in some cases

What do $? $0 $1 $2 mean in shell script?

They are called the Positional Parameters.

3.4.1 Positional Parameters

A positional parameter is a parameter denoted by one or more digits, other than the single digit 0. Positional parameters are assigned from the shell’s arguments when it is invoked, and may be reassigned using the set builtin command. Positional parameter N may be referenced as ${N}, or as $N when N consists of a single digit. Positional parameters may not be assigned to with assignment statements. The set and shift builtins are used to set and unset them (see Shell Builtin Commands). The positional parameters are temporarily replaced when a shell function is executed (see Shell Functions).

When a positional parameter consisting of more than a single digit is expanded, it must be enclosed in braces.

Background service with location listener in android

Very easy no need create class extends LocationListener 1- Variable

private LocationManager mLocationManager;
private LocationListener mLocationListener;
private static double currentLat =0;
private static double currentLon =0;

2- onStartService()

@Override public void onStartService() {
    addListenerLocation();
}

3- Method addListenerLocation()

 private void addListenerLocation() {
    mLocationManager = (LocationManager)
            getSystemService(Context.LOCATION_SERVICE);
    mLocationListener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            currentLat = location.getLatitude();
            currentLon = location.getLongitude();

            Toast.makeText(getBaseContext(),currentLat+"-"+currentLon, Toast.LENGTH_SHORT).show();

        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
        }

        @Override
        public void onProviderEnabled(String provider) {
            Location lastKnownLocation = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
            if(lastKnownLocation!=null){
                currentLat = lastKnownLocation.getLatitude();
                currentLon = lastKnownLocation.getLongitude();
            }

        }

        @Override
        public void onProviderDisabled(String provider) {
        }
    };
    mLocationManager.requestLocationUpdates(
            LocationManager.GPS_PROVIDER, 500, 10, mLocationListener);
}

4- onDestroy()

@Override
public void onDestroy() {
    super.onDestroy();
    mLocationManager.removeUpdates(mLocationListener);
}

How to regex in a MySQL query

I think you can use REGEXP instead of LIKE

SELECT trecord FROM `tbl` WHERE (trecord REGEXP '^ALA[0-9]')

C++ deprecated conversion from string constant to 'char*'

For what its worth, I find this simple wrapper class to be helpful for converting C++ strings to char *:

class StringWrapper {
    std::vector<char> vec;
public:
    StringWrapper(const std::string &str) : vec(str.begin(), str.end()) {
    }

    char *getChars() {
        return &vec[0];
    }
};

Grep only the first match and stop

-m 1 means return the first match in any given file. But it will still continue to search in other files. Also, if there are two or more matched in the same line, all of them will be displayed.

You can use head -1 to solve this problem:

grep -o -a -m 1 -h -r "Pulsanti Operietur" /path/to/dir | head -1

explanation of each grep option:

-o, --only-matching, print only the matched part of the line (instead of the entire line)
-a, --text, process a binary file as if it were text
-m 1, --max-count, stop reading a file after 1 matching line
-h, --no-filename, suppress the prefixing of file names on output
-r, --recursive, read all files under a directory recursively

Is it possible to get a list of files under a directory of a website? How?

Yes, you can, but you need a few tools first. You need to know a little about basic coding, FTP clients, port scanners and brute force tools, if it has a .htaccess file.

If not just try tgp.linkurl.htm or html, ie default.html, www/home/siteurl/web/, or wap /index/ default /includes/ main/ files/ images/ pics/ vids/, could be possible file locations on the server, so try all of them so www/home/siteurl/web/includes/.htaccess or default.html. You'll hit a file after a few tries then work off that. Yahoo has a site file viewer too: you can try to scan sites file indexes.

Alternatively, try brutus aet, trin00, trinity.x, or whiteshark airtool to crack the site's FTP login (but it's illegal and I do not condone that).

select unique rows based on single distinct column

Since you don't care which id to return I stick with MAX id for each email to simplify SQL query, give it a try

;WITH ue(id)
 AS
 (
   SELECT MAX(id)
   FROM table
   GROUP BY email
 )
 SELECT * FROM table t
 INNER JOIN ue ON ue.id = t.id

Which rows are returned when using LIMIT with OFFSET in MySQL?

OFFSET is nothing but a keyword to indicate starting cursor in table

SELECT column FROM table LIMIT 18 OFFSET 8 -- fetch 18 records, begin with record 9 (OFFSET 8)

you would get the same result form

SELECT column FROM table LIMIT 8, 18

visual representation (R is one record in the table in some order)

 OFFSET        LIMIT          rest of the table
 __||__   _______||_______   __||__
/      \ /                \ /
RRRRRRRR RRRRRRRRRRRRRRRRRR RRRR...
         \________________/
                 ||
             your result

Removing Spaces from a String in C?

#include<stdio.h>
#include<string.h>
main()
{
  int i=0,n;
  int j=0;
  char str[]="        Nar ayan singh              ";
  char *ptr,*ptr1;
  printf("sizeof str:%ld\n",strlen(str));
  while(str[i]==' ')
   {
     memcpy (str,str+1,strlen(str)+1);
   }
  printf("sizeof str:%ld\n",strlen(str));
  n=strlen(str);
  while(str[n]==' ' || str[n]=='\0')
    n--;
  str[n+1]='\0';
  printf("str:%s ",str);
  printf("sizeof str:%ld\n",strlen(str));
}

Return JSON response from Flask view

As of version 1.1.0 Flask, if a view returns a dict it will be turned into a JSON response.

@app.route("/users", methods=['GET'])
def get_user():
    return {
        "user": "John Doe",
    }

Only variable references should be returned by reference - Codeigniter

this has been modified in codeigniter 2.2.1...usually not best practice to modify core files, I would always check for updates and 2.2.1 came out in Jan 2015

Importing a function from a class in another file?

You can use the below syntax -

from FolderName.FileName import Classname

How do I consume the JSON POST data in an Express application

I think you're conflating the use of the response object with that of the request.

The response object is for sending the HTTP response back to the calling client, whereas you are wanting to access the body of the request. See this answer which provides some guidance.

If you are using valid JSON and are POSTing it with Content-Type: application/json, then you can use the bodyParser middleware to parse the request body and place the result in request.body of your route.

For earlier versions of Express (< 4)

var express = require('express')
  , app = express.createServer();

app.use(express.bodyParser());

app.post('/', function(request, response){
  console.log(request.body);      // your JSON
  response.send(request.body);    // echo the result back
});

app.listen(3000);

Test along the lines of:

$ curl -d '{"MyKey":"My Value"}' -H "Content-Type: application/json" http://127.0.0.1:3000/
{"MyKey":"My Value"}

Updated for Express 4+

Body parser was split out into it's own npm package after v4, requires a separate install npm install body-parser

var express = require('express')
  , bodyParser = require('body-parser');

var app = express();

app.use(bodyParser.json());

app.post('/', function(request, response){
  console.log(request.body);      // your JSON
   response.send(request.body);    // echo the result back
});

app.listen(3000);

Update for Express 4.16+

Starting with release 4.16.0, a new express.json() middleware is available.

var express = require('express');

var app = express();

app.use(express.json());

app.post('/', function(request, response){
  console.log(request.body);      // your JSON
   response.send(request.body);    // echo the result back
});

app.listen(3000);

How to use in jQuery :not and hasClass() to get a specific element without a class

It's much easier to do like this:

if(!$('#foo').hasClass('bar')) { 
  ...
}

The ! in front of the criteria means false, works in most programming languages.

String parsing in Java with delimiter tab "\t" using split

I just had the same question and noticed the answer in some kind of tutorial. In general you need to use the second form of the split method, using the

split(regex, limit)

Here is the full tutorial http://www.rgagnon.com/javadetails/java-0438.html

If you set some negative number for the limit parameter you will get empty strings in the array where the actual values are missing. To use this your initial string should have two copies of the delimiter i.e. you should have \t\t where the values are missing.

Hope this helps :)

Where can I find the TypeScript version installed in Visual Studio?

The tsc -v command run technically reads the TypeScript compiler version within the SDK directory set within the Windows Path variable. This doesn't necessarily reflect the latest version installed as the Path variable is not updated with subsequent installations.

The version that VS.NET uses to compile the TypeScript is what's in the project's configuration:

<TypeScriptToolsVersion>1.5</TypeScriptToolsVersion>

To help explain this more in detail I created the following post which has the specifics on the TypeScript versions installed, and which version VS.NET uses to compile the TypeScript files.

Which Version of TypeScript is Installed and Which Version is Visual Studio Using?

I also added a feature request on Microsoft Connect to make viewing and switching the TypeScript targeted version in VS.NET easier. This isn't really a TypeScript feature request as much as it is a VS.NET IDE enhancement.

Allow switching TypeScript configured version from Project Properties IDE

Are nested try/except blocks in Python a good programming practice?

I don't think it's a matter of being Pythonic or elegant. It's a matter of preventing exceptions as much as you can. Exceptions are meant to handle errors that might occur in code or events you have no control over.

In this case, you have full control when checking if an item is an attribute or in a dictionary, so avoid nested exceptions and stick with your second attempt.

Should each and every table have a primary key?

I am in the role of maintaining application created by offshore development team. Now I am having all kinds of issues in the application because original database schema did not contain PRIMARY KEYS on some tables. So please dont let other people suffer because of your poor design. It is always good idea to have primary keys on tables.

Understanding The Modulus Operator %

As you say, the % sign is used to take the modulus (division remainder).

In w3schools' JavaScript Arithmetic page we can read in the Remainder section what I think to be a great explanation

In arithmetic, the division of two integers produces a quotient and a remainder.

In mathematics, the result of a modulo operation is the remainder of an arithmetic division.

So, in your specific case, when you try to divide 7 bananas into a group of 5 bananas, you're able to create 1 group of 5 (quotient) and you'll be left with 2 bananas (remainder).

If 5 bananas into a group of 7, you won't be able to and so you're left with again the 5 bananas (remainder).

What does the "yield" keyword do?

yield is just like return - it returns whatever you tell it to (as a generator). The difference is that the next time you call the generator, execution starts from the last call to the yield statement. Unlike return, the stack frame is not cleaned up when a yield occurs, however control is transferred back to the caller, so its state will resume the next time the function is called.

In the case of your code, the function get_child_candidates is acting like an iterator so that when you extend your list, it adds one element at a time to the new list.

list.extend calls an iterator until it's exhausted. In the case of the code sample you posted, it would be much clearer to just return a tuple and append that to the list.

How to add style from code behind?

:hover is a selector, and not a style. What you're doing in your example is adding inline styles to an element, and a selector equivalent for that obviously doesn't make much sense.

You can add a class to your link: hlRow.CssClass = 'abc'; And define your class as such:

a.abc:hover {
    ...
}

GROUP_CONCAT ORDER BY

In IMPALA, not having order in the GROUP_CONCAT can be problematic, over at Coders'Co. we have some sort of a workaround for that (we need it for Rax/Impala). If you need the GROUP_CONCAT result with an ORDER BY clause in IMPALA, take a look at this blog post: http://raxdb.com/blog/sorting-by-regex/

Generate sql insert script from excel worksheet

This query i have generated for inserting the Excel file data into database In this id and price are numeric values and date field as well. This query summarized all the type which I require It may useful to you as well

="insert into  product (product_id,name,date,price) values("&A1&",'" &B1& "','" &C1& "'," &D1& ");"


    Id    Name           Date           price 
    7   Product 7   2017-01-05 15:28:37 200
    8   Product 8   2017-01-05 15:28:37 40
    9   Product 9   2017-01-05 15:32:31 500
    10  Product 10  2017-01-05 15:32:31 30
    11  Product 11  2017-01-05 15:32:31 99
    12  Product 12  2017-01-05 15:32:31 25

Checking for the correct number of arguments

You can check the total number of arguments which are passed in command line with "$#" Say for Example my shell script name is hello.sh

sh hello.sh hello-world
# I am passing hello-world as argument in command line which will b considered as 1 argument 
if [ $# -eq 1 ] 
then
    echo $1
else
    echo "invalid argument please pass only one argument "
fi

Output will be hello-world

Android emulator: How to monitor network traffic?

You can use http://docs.mitmproxy.org/en/stable/install.html

Its easy to setup and won't require any extra tweaks.

I go through various tool but found it to be really good and easy.

MySQL error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near

MYSQL PROCEDURE steps:

  1. change delimiter from default ' ; ' to ' // '

DELIMITER //

  1. create PROCEDURE, you can refer syntax

    NOTE: Don't forget to end statement with ' ; '

create procedure ProG() 
begin 
SELECT * FROM hs_hr_employee_leave_quota;
end;//
  1. Change delimiter back to ' ; '

delimiter ;

  1. Now to execute:

call ProG();

What is default list styling (CSS)?

You cannot. Whenever there is any style sheet being applied that assigns a property to an element, there is no way to get to the browser defaults, for any instance of the element.

The (disputable) idea of reset.css is to get rid of browser defaults, so that you can start your own styling from a clean desk. No version of reset.css does that completely, but to the extent they do, the author using reset.css is supposed to completely define the rendering.

Selecting Folder Destination in Java?

You could try something like this (as shown here: Select a Directory with a JFileChooser):

import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.util.*;


public class DemoJFileChooser extends JPanel
   implements ActionListener {
   JButton go;

   JFileChooser chooser;
   String choosertitle;

  public DemoJFileChooser() {
    go = new JButton("Do it");
    go.addActionListener(this);
    add(go);
   }

  public void actionPerformed(ActionEvent e) {            
    chooser = new JFileChooser(); 
    chooser.setCurrentDirectory(new java.io.File("."));
    chooser.setDialogTitle(choosertitle);
    chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    //
    // disable the "All files" option.
    //
    chooser.setAcceptAllFileFilterUsed(false);
    //    
    if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) { 
      System.out.println("getCurrentDirectory(): " 
         +  chooser.getCurrentDirectory());
      System.out.println("getSelectedFile() : " 
         +  chooser.getSelectedFile());
      }
    else {
      System.out.println("No Selection ");
      }
     }

  public Dimension getPreferredSize(){
    return new Dimension(200, 200);
    }

  public static void main(String s[]) {
    JFrame frame = new JFrame("");
    DemoJFileChooser panel = new DemoJFileChooser();
    frame.addWindowListener(
      new WindowAdapter() {
        public void windowClosing(WindowEvent e) {
          System.exit(0);
          }
        }
      );
    frame.getContentPane().add(panel,"Center");
    frame.setSize(panel.getPreferredSize());
    frame.setVisible(true);
    }
}

GCC -fPIC option

I'll try to explain what has already been said in a simpler way.

Whenever a shared lib is loaded, the loader (the code on the OS which load any program you run) changes some addresses in the code depending on where the object was loaded to.

In the above example, the "111" in the non-PIC code is written by the loader the first time it was loaded.

For not shared objects, you may want it to be like that because the compiler can make some optimizations on that code.

For shared object, if another process will want to "link" to that code he must read it to the same virtual addresses or the "111" will make no sense. but that virtual-space may already be in use in the second process.

How to avoid reverse engineering of an APK file?

Agreed with @Muhammad Saqib here: https://stackoverflow.com/a/46183706/2496464

And @Mumair give a good starting steps: https://stackoverflow.com/a/35411378/474330

It is always safe to assume that everything you distribute to your user's device, belong to the user. Plain and simple. You may be able to use the latest tools and procedure to encrypt your intellectual properties but there is no way to prevent a determined person from 'studying' your system. And even if the current technology may make it difficult for them to gain unwanted access, there might be some easy way tomorrow, or even just the next hour!

Thus, here comes the equation:

When it comes to money, we always assume that client is untrusted.

Even in as simple as an in-game economy. (Especially in games! There are more 'sophisticated' users there and loopholes spread in seconds!)

How do we stay safe?

Most, if not all, of our key processing systems (and database of course) located on the server side. And between the client and server, lies encrypted communications, validations, etc. That is the idea of thin client.

Hiding a button in Javascript

//Your code to make the box goes here... call it box
box.id="foo";
//Your code to remove the box goes here
document.getElementById("foo").style.display="none";

of course if you are doing a lot of stuff like this, use jQuery

Java RegEx meta character (.) and ordinary dot?

Solutions proposed by the other members don't work for me.

But I found this :

to escape a dot in java regexp write [.]

How to undo last commit

Warning: Don't do this if you've already pushed

You want to do:

git reset HEAD~

If you don't want the changes and blow everything away:

git reset --hard HEAD~

Django check for any exists for a query

Use count():

sc=scorm.objects.filter(Header__id=qp.id)

if sc.count() > 0:
   ...

The advantage over e.g. len() is, that the QuerySet is not yet evaluated:

count() performs a SELECT COUNT(*) behind the scenes, so you should always use count() rather than loading all of the record into Python objects and calling len() on the result.

Having this in mind, When QuerySets are evaluated can be worth reading.


If you use get(), e.g. scorm.objects.get(pk=someid), and the object does not exists, an ObjectDoesNotExist exception is raised:

from django.core.exceptions import ObjectDoesNotExist
try:
    sc = scorm.objects.get(pk=someid)
except ObjectDoesNotExist:
    print ...

Update: it's also possible to use exists():

if scorm.objects.filter(Header__id=qp.id).exists():
    ....

Returns True if the QuerySet contains any results, and False if not. This tries to perform the query in the simplest and fastest way possible, but it does execute nearly the same query as a normal QuerySet query.

Jquery-How to grey out the background while showing the loading icon over it

Note: There is no magic to animating a gif: it is either an animated gif or it is not. If the gif is not visible, very likely the path to the gif is wrong - or, as in your case, the container (div/p/etc) is not large enough to display it. In your code sample, you did not specify height or width and that appeared to be problem.

If the gif is displayed but not animating, see reference links at very bottom of this answer.

Displaying the gif + overlay, however, is easier than you might think.

All you need are two absolute-position DIVs: an overlay div, and a div that contains your loading gif. Both have higher z-index than your page content, and the image has a higher z-index than the overlay - so they will display above the page when visible.

So, when the button is pressed, just unhide those two divs. That's it!

jsFiddle Demo

_x000D_
_x000D_
$("#button").click(function() {_x000D_
    $('#myOverlay').show();_x000D_
    $('#loadingGIF').show();_x000D_
    setTimeout(function(){_x000D_
   $('#myOverlay, #loadingGIF').fadeOut();_x000D_
    },2500);_x000D_
});_x000D_
/*  Or, remove overlay/image on click background... */_x000D_
$('#myOverlay').click(function(){_x000D_
 $('#myOverlay, #loadingGIF').fadeOut();_x000D_
});
_x000D_
body{font-family:Calibri, Helvetica, sans-serif;}_x000D_
#myOverlay{position:absolute;top:0;left:0;height:100%;width:100%;}_x000D_
#myOverlay{display:none;backdrop-filter:blur(4px);background:black;opacity:.4;z-index:2;}_x000D_
_x000D_
#loadingGIF{position:absolute;top:10%;left:35%;z-index:3;display:none;}_x000D_
_x000D_
button{margin:5px 30px;padding:10px 20px;}
_x000D_
<div id="myOverlay"></div>_x000D_
<div id="loadingGIF"><img src="http://placekitten.com/150/80" /></div>_x000D_
_x000D_
<div id="abunchoftext">_x000D_
Once upon a midnight dreary, while I pondered weak and weary, over many a quaint and curious routine of forgotten code... While I nodded, nearly napping, suddenly there came a tapping... as of someone gently rapping - rapping at my office door. 'Tis the team leader, I muttered, tapping at my office door - only this and nothing more. Ah, distinctly I remember it was in the bleak December and each separate React print-out lay there crumpled on the floor. Eagerly I wished the morrow; vainly I had sought to borrow from Stack-O surcease from sorrow - sorrow for my routine's core. For the brilliant but unworking code my angels seem to just ignore. I'll be tweaking code... forevermore! - <a href="http://www.online-literature.com/poe/335/" target="_blank">Apologies To Poe</a></div>_x000D_
<button id="button">Submit</button>_x000D_
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

Update:

You might enjoy playing with the new backdrop-filter:blur(_px) css property that gives a blur effect to the underlying content, as used in above demo... (As of April 2020: works in Chrome, Edge, Safari, Android, but not yet in Firefox)

References:

http://www.paulirish.com/2007/animated-gif-not-animating/

Animated GIF while loading page does not animate

https://wordpress.org/support/topic/animated-gif-not-working

http://forums.mozillazine.org/viewtopic.php?p=987829

How to update each dependency in package.json to the latest version?

I solved this by seeing the instructions from https://github.com/tjunnone/npm-check-updates

$ npm install -g npm-check-updates
$ ncu
$ ncu -u # to update all the dependencies to latest
$ ncu -u "specific module name"  #in case you want to update specific dependencies to latest

How can I get the last day of the month in C#?

public static class DateTimeExtensions
{
    public static DateTime LastDayOfMonth(this DateTime date)
    {
        return date.AddDays(1-(date.Day)).AddMonths(1).AddDays(-1);
    }
}

Convert list into a pandas data frame

You need convert list to numpy array and then reshape:

df = pd.DataFrame(np.array(my_list).reshape(3,3), columns = list("abc"))
print (df)
   a  b  c
0  1  2  3
1  4  5  6
2  7  8  9

How do I implement charts in Bootstrap?

You can use a 3rd party library like Shield UI for charting - that is tested and works well on all legacy and new web browsers and devices.

Docker - Cannot remove dead container

I got the same issue and both answers did not help.

What helped for me is just creating the directories that are missing and them remove them:

mkdir /var/lib/docker/devicemapper/mnt/656cfd09aee399c8ae8c8d3e735fe48d70be6672773616e15579c8de18e2a3b3
mkdir /var/lib/docker/devicemapper/mnt/656cfd09aee399c8ae8c8d3e735fe48d70be6672773616e15579c8de18e2a3b3-init
docker rm 656cfd09aee399c8ae8c8d3e735fe48d70be6672773616e15579c8de18e2a3b3

Formatting "yesterday's" date in python

Use datetime.timedelta()

>>> from datetime import date, timedelta
>>> yesterday = date.today() - timedelta(days=1)
>>> yesterday.strftime('%m%d%y')
'110909'

Counting how many times a certain char appears in a string before any other char appears

The simplest approach would be to use LINQ:

var count = text.TakeWhile(c => c == '$').Count();

There are certainly more efficient approaches, but that's probably the simplest.

Put byte array to JSON and vice versa

If your byte array may contain runs of ASCII characters that you'd like to be able to see, you might prefer BAIS (Byte Array In String) format instead of Base64. The nice thing about BAIS is that if all the bytes happen to be ASCII, they are converted 1-to-1 to a string (e.g. byte array {65,66,67} becomes simply "ABC") Also, BAIS often gives you a smaller file size than Base64 (this isn't guaranteed).

After converting the byte array to a BAIS string, write it to JSON like you would any other string.

Here is a Java class (ported from the original C#) that converts byte arrays to string and back.

import java.io.*;
import java.lang.*;
import java.util.*;

public class ByteArrayInString
{
  // Encodes a byte array to a string with BAIS encoding, which 
  // preserves runs of ASCII characters unchanged.
  //
  // For simplicity, this method's base-64 encoding always encodes groups of 
  // three bytes if possible (as four characters). This decision may 
  // unfortunately cut off the beginning of some ASCII runs.
  public static String convert(byte[] bytes) { return convert(bytes, true); }
  public static String convert(byte[] bytes, boolean allowControlChars)
  {
    StringBuilder sb = new StringBuilder();
    int i = 0;
    int b;
    while (i < bytes.length)
    {
      b = get(bytes,i++);
      if (isAscii(b, allowControlChars))
        sb.append((char)b);
      else {
        sb.append('\b');
        // Do binary encoding in groups of 3 bytes
        for (;; b = get(bytes,i++)) {
          int accum = b;
          System.out.println("i="+i);
          if (i < bytes.length) {
            b = get(bytes,i++);
            accum = (accum << 8) | b;
            if (i < bytes.length) {
              b = get(bytes,i++);
              accum = (accum << 8) | b;
              sb.append(encodeBase64Digit(accum >> 18));
              sb.append(encodeBase64Digit(accum >> 12));
              sb.append(encodeBase64Digit(accum >> 6));
              sb.append(encodeBase64Digit(accum));
              if (i >= bytes.length)
                break;
            } else {
              sb.append(encodeBase64Digit(accum >> 10));
              sb.append(encodeBase64Digit(accum >> 4));
              sb.append(encodeBase64Digit(accum << 2));
              break;
            }
          } else {
            sb.append(encodeBase64Digit(accum >> 2));
            sb.append(encodeBase64Digit(accum << 4));
            break;
          }
          if (isAscii(get(bytes,i), allowControlChars) &&
            (i+1 >= bytes.length || isAscii(get(bytes,i), allowControlChars)) &&
            (i+2 >= bytes.length || isAscii(get(bytes,i), allowControlChars))) {
            sb.append('!'); // return to ASCII mode
            break;
          }
        }
      }
    }
    return sb.toString();
  }

  // Decodes a BAIS string back to a byte array.
  public static byte[] convert(String s)
  {
    byte[] b;
    try {
      b = s.getBytes("UTF8");
    } catch(UnsupportedEncodingException e) { 
      throw new RuntimeException(e.getMessage());
    }
    for (int i = 0; i < b.length - 1; ++i) {
      if (b[i] == '\b') {
        int iOut = i++;

        for (;;) {
          int cur;
          if (i >= b.length || ((cur = get(b, i)) < 63 || cur > 126))
            throw new RuntimeException("String cannot be interpreted as a BAIS array");
          int digit = (cur - 64) & 63;
          int zeros = 16 - 6; // number of 0 bits on right side of accum
          int accum = digit << zeros;

          while (++i < b.length)
          {
            if ((cur = get(b, i)) < 63 || cur > 126)
              break;
            digit = (cur - 64) & 63;
            zeros -= 6;
            accum |= digit << zeros;
            if (zeros <= 8)
            {
              b[iOut++] = (byte)(accum >> 8);
              accum <<= 8;
              zeros += 8;
            }
          }

          if ((accum & 0xFF00) != 0 || (i < b.length && b[i] != '!'))
            throw new RuntimeException("String cannot be interpreted as BAIS array");
          i++;

          // Start taking bytes verbatim
          while (i < b.length && b[i] != '\b')
            b[iOut++] = b[i++];
          if (i >= b.length)
            return Arrays.copyOfRange(b, 0, iOut);
          i++;
        }
      }
    }
    return b;
  }

  static int get(byte[] bytes, int i) { return ((int)bytes[i]) & 0xFF; }

  public static int decodeBase64Digit(char digit)
    { return digit >= 63 && digit <= 126 ? (digit - 64) & 63 : -1; }
  public static char encodeBase64Digit(int digit)
    { return (char)((digit + 1 & 63) + 63); }
  static boolean isAscii(int b, boolean allowControlChars)
    { return b < 127 && (b >= 32 || (allowControlChars && b != '\b')); }
}

See also: C# unit tests.

Page loaded over HTTPS but requested an insecure XMLHttpRequest endpoint

What I can do to fix this (other than installing a real SSL certificate).

You can't.

On an https webpage you can only make AJAX request to https webpage (With a certificate trusted by the browser, if you use a self-signed one, it will not work for your visitors)

Putting a password to a user in PhpMyAdmin in Wamp

There is a file called config.inc.php in the phpmyadmin folder.

The file path is C:\wamp\apps\phpmyadmin4.0.4

Edit The auth_type 'cookie' to 'config' or 'http'

$cfg['Servers'][$i]['auth_type'] = 'cookie';

$cfg['Servers'][$i]['auth_type'] = 'config';

or

$cfg['Servers'][$i]['auth_type'] = 'http';

When you go to the phpmyadmin site then you will be asked for the username and password. This also secure external people from accessing your phpmyadmin application if you happen to have your web server exposed to outside connections.

how to calculate percentage in python

I guess you're learning how to Python. The other answers are right. But I am going to answer your main question: "how to calculate percentage in python"

Although it works the way you did it, it doesn´t look very pythonic. Also, what happens if you need to add a new subject? You'll have to add another variable, use another input, etc. I guess you want the average of all marks, so you will also have to modify the count of the subjects everytime you add a new one! Seems a mess...

I´ll throw a piece of code where the only thing you'll have to do is to add the name of the new subject in a list. If you try to understand this simple piece of code, your Python coding skills will experiment a little bump.

#!/usr/local/bin/python2.7

marks = {} #a dictionary, it's a list of (key : value) pairs (eg. "Maths" : 34)
subjects = ["Tamil","English","Maths","Science","Social"] # this is a list

#here we populate the dictionary with the marks for every subject
for subject in subjects:
   marks[subject] = input("Enter the " + subject + " marks: ")

#and finally the calculation of the total and the average
total = sum(marks.itervalues())
average = float(total) / len(marks)

print ("The total is " + str(total) + " and the average is " + str(average))

Here you can test the code and experiment with it.

How to execute UNION without sorting? (SQL)

Consider these tables (Standard SQL code, runs on SQL Server 2008):

WITH A 
     AS 
     (
      SELECT * 
        FROM (
              VALUES (1), 
                     (2), 
                     (3), 
                     (4), 
                     (5), 
                     (6) 
             ) AS T (col)
     ),
     B 
     AS 
     (
      SELECT * 
        FROM (
              VALUES (9), 
                     (8), 
                     (7), 
                     (6), 
                     (5), 
                     (4) 
             ) AS T (col)
     ), ...

The desired effect is this to sort table A by col ascending, sort table B by col descending then unioning the two, removing duplicates, retaining order before the union and leaving table A results on the "top" with table B on the "bottom" e.g. (pesudo code)

(
 SELECT *
   FROM A
  ORDER 
     BY col
)
UNION
(
 SELECT *
   FROM B
  ORDER 
     BY col DESC
);

Of course, this won't work in SQL because there can only be one ORDER BY clause and it can only be applied to the top level table expression (or whatever the output of a SELECT query is known as; I call it the "resultset").

The first thing to address is the intersection between the two tables, in this case the values 4, 5 and 6. How the intersection should be sorted needs to be specified in SQL code, therefore it is desirable that the designer specifies this too! (i.e. the person asking the question, in this case).

The implication in this case would seem to be that the intersection ("duplicates") should be sorted within the results for table A. Therefore, the sorted resultset should look like this:

      VALUES (1), -- A including intersection, ascending
             (2), -- A including intersection, ascending
             (3), -- A including intersection, ascending
             (4), -- A including intersection, ascending
             (5), -- A including intersection, ascending
             (6), -- A including intersection, ascending
             (9), -- B only, descending 
             (8), -- B only, descending  
             (7), -- B only, descending 

Note in SQL "top" and "bottom" has no inferent meaning and a table (other than a resultset) has no inherent ordering. Also (to cut a long story short) consider that UNION removes duplicate rows by implication and must be applied before ORDER BY. The conclusion has to be that each table's sort order must be explicitly defined by exposing a sort order column(s) before being unioned. For this we can use the ROW_NUMBER() windowed function e.g.

     ...
     A_ranked
     AS
     (
      SELECT col, 
             ROW_NUMBER() OVER (ORDER BY col) AS sort_order_1
        FROM A                      -- include the intersection
     ),
     B_ranked
     AS
     (
      SELECT *, 
             ROW_NUMBER() OVER (ORDER BY col DESC) AS sort_order_1
        FROM B
       WHERE NOT EXISTS (           -- exclude the intersection
                         SELECT * 
                           FROM A
                          WHERE A.col = B.col 
                        )
     )
SELECT *, 1 AS sort_order_0 
  FROM A_ranked
UNION
SELECT *, 2 AS sort_order_0 
  FROM B_ranked
ORDER BY sort_order_0, sort_order_1;

rails + MySQL on OSX: Library not loaded: libmysqlclient.18.dylib

This works for me:

ln -s /usr/local/Cellar/mysql/5.6.22/lib/libmysqlclient.18.dylib /usr/local/lib/libmysqlclient.18.dylib

How to add a line break in an Android TextView?

This worked for me, maybe someone will find out this helpful:

TextView textField = (TextView) findViewById(R.id.textview1);
textField.setText("First line of text" + System.getProperty("line.separator") + "Linija 2");

SQL multiple columns in IN clause

In Oracle you can do this:

SELECT * FROM table1 WHERE (col_a,col_b) IN (SELECT col_x,col_y FROM table2)

How can I nullify css property?

To get rid of the fixed height property you can set it to the default value:

height: auto;

Spring MVC - How to get all request params in a map in Spring controller?

While the other answers are correct it certainly is not the "Spring way" to use the HttpServletRequest object directly. The answer is actually quite simple and what you would expect if you're familiar with Spring MVC.

@RequestMapping(value = {"/search/", "/search"}, method = RequestMethod.GET)
public String search(
@RequestParam Map<String,String> allRequestParams, ModelMap model) {
   return "viewName";
}

Python int to binary string?

numpy.binary_repr(num, width=None)

Examples from the documentation link above:

>>> np.binary_repr(3)
'11'
>>> np.binary_repr(-3)
'-11'
>>> np.binary_repr(3, width=4)
'0011'

The two’s complement is returned when the input number is negative and width is specified:

>>> np.binary_repr(-3, width=3)
'101'
>>> np.binary_repr(-3, width=5)
'11101'

INSERT INTO @TABLE EXEC @query with SQL Server 2000

The documentation is misleading.
I have the following code running in production

DECLARE @table TABLE (UserID varchar(100))
DECLARE @sql varchar(1000)
SET @sql = 'spSelUserIDList'
/* Will also work
   SET @sql = 'SELECT UserID FROM UserTable'
*/

INSERT INTO @table
EXEC(@sql)

SELECT * FROM @table

Output an Image in PHP

Try this:

<?php
  header("Content-type: image/jpeg");
  readfile("/path/to/image.jpg");
  exit(0);
?>

Remove all items from RecyclerView

Avoid deleting your items in a for loop and calling notifyDataSetChanged in every iteration. Instead just call the clear method in your list myList.clear(); and then notify your adapter

public void clearData() {
    myList.clear(); // clear list
    mAdapter.notifyDataSetChanged(); // let your adapter know about the changes and reload view.
}

How to extract or unpack an .ab file (Android Backup file)

As per https://android.stackexchange.com/a/78183/239063 you can run a one line command in Linux to add in an appropriate tar header to extract it.

( printf "\x1f\x8b\x08\x00\x00\x00\x00\x00" ; tail -c +25 backup.ab ) | tar xfvz -

Replace backup.ab with the path to your file.

Working with TIFFs (import, export) in Python using numpy

First, I downloaded a test TIFF image from this page called a_image.tif. Then I opened with PIL like this:

>>> from PIL import Image
>>> im = Image.open('a_image.tif')
>>> im.show()

This showed the rainbow image. To convert to a numpy array, it's as simple as:

>>> import numpy
>>> imarray = numpy.array(im)

We can see that the size of the image and the shape of the array match up:

>>> imarray.shape
(44, 330)
>>> im.size
(330, 44)

And the array contains uint8 values:

>>> imarray
array([[  0,   1,   2, ..., 244, 245, 246],
       [  0,   1,   2, ..., 244, 245, 246],
       [  0,   1,   2, ..., 244, 245, 246],
       ..., 
       [  0,   1,   2, ..., 244, 245, 246],
       [  0,   1,   2, ..., 244, 245, 246],
       [  0,   1,   2, ..., 244, 245, 246]], dtype=uint8)

Once you're done modifying the array, you can turn it back into a PIL image like this:

>>> Image.fromarray(imarray)
<Image.Image image mode=L size=330x44 at 0x2786518>

Use Expect in a Bash script to provide a password to an SSH command

Another way that I found useful to use a small Expect script from a Bash script is as follows.

...
Bash script start
Bash commands
...
expect - <<EOF
spawn your-command-here
expect "some-pattern"
send "some-command"
...
...
EOF
...
More Bash commands
...

This works because ...If the string "-" is supplied as a filename, standard input is read instead...

Can "list_display" in a Django ModelAdmin display attributes of ForeignKey fields?

I prefer this:

class CoolAdmin(admin.ModelAdmin):
    list_display = ('pk', 'submodel__field')

    @staticmethod
    def submodel__field(obj):
        return obj.submodel.field

javascript functions to show and hide divs

I usually do this with classes, that seems to force the browsers to reassess all the styling.

.hiddendiv {display:none;}
.visiblediv {display:block;}

then use;

<script>  
function show() {  
    document.getElementById('benefits').className='visiblediv';  
}  
function close() {  
    document.getElementById('benefits').className='hiddendiv';  
}    
</script>

Note the casing of "className" that trips me up a lot

No Spring WebApplicationInitializer types detected on classpath

I also had the same problem. My maven had tomcat7 plugin but the JRE environment was 1.6. I changed my tomcat7 to tomcat6 and the error was gone.

What is default color for text in textview?

I found that android:textColor="@android:color/secondary_text_dark" provides a closer result to the default TextView color than android:textColor="@android:color/tab_indicator_text". I suppose you have to switch between secondary_text_dark/light depending on the Theme you are using

For div to extend full height

This might be of some help: http://www.webmasterworld.com/forum83/200.htm

A relevant quote:

Most attempts to accomplish this were made by assigning the property and value: div{height:100%} - this alone will not work. The reason is that without a parent defined height, the div{height:100%;} has nothing to factor 100% percent of, and will default to a value of div{height:auto;} - auto is an "as needed value" which is governed by the actual content, so that the div{height:100%} will a=only extend as far as the content demands.

The solution to the problem is found by assigning a height value to the parent container, in this case, the body element. Writing your body stlye to include height 100% supplies the needed value.

html, body { 
  margin:0; 
  padding:0; 
  height:100%; 
}

jQuery - Click event on <tr> elements with in a table and getting <td> element values

This work for me!

$(document).ready(function() {
    $(document).on("click", "#tableId tbody tr", function() {
        //some think
    });
});

How to set page content to the middle of screen?

I'm guessing you want to center the box both vertically and horizontally, regardless of browser window size. Since you have a fixed width and height for the box, this should work:

Markup:

<div></div>

CSS:

div {
    height: 200px;
    width: 400px;
    background: black;

    position: fixed;
    top: 50%;
    left: 50%;
    margin-top: -100px;
    margin-left: -200px;
}

The div should remain in the center of the screen even if you resize the browser. Just replace the margin-top and margin-left with half of the height and width of your table.

Edit: Credit goes to CSS-Tricks, where I got the original idea.

How to recognize swipe in all 4 directions

It can be done by simply declaring one function which will handle all your swipe UISwipeGestureRecognizer directions. Here is my code:

let swipeGestureRight = UISwipeGestureRecognizer(target: self, action:#selector(ViewController.respondToSwipeGesture(_:)) )
swipeGestureRight.direction = UISwipeGestureRecognizerDirection.right
self.view .addGestureRecognizer(swipeGestureRight)

let swipeGestureLeft = UISwipeGestureRecognizer(target: self, action: #selector(ViewController.respondToSwipeGesture(_:)))
swipeGestureLeft.direction = UISwipeGestureRecognizerDirection.left
self.view.addGestureRecognizer(swipeGestureLeft)

let swipeGestureUp = UISwipeGestureRecognizer(target: self, action: #selector(ViewController.respondToSwipeGesture(_:)))
swipeGestureUp.direction = UISwipeGestureRecognizerDirection.up
self.view.addGestureRecognizer(swipeGestureUp)

let swipeGestureDown = UISwipeGestureRecognizer(target: self, action: #selector(ViewController.respondToSwipeGesture(_:)))
swipeGestureDown.direction = UISwipeGestureRecognizerDirection.down
self.view.addGestureRecognizer(swipeGestureDown)

Here is the function which will hande the swipedirection functionality:

func respondToSwipeGesture(_ sender: UIGestureRecognizer) {
    if let swipeGesture = sender as? UISwipeGestureRecognizer {
        switch swipeGesture.direction {
            case UISwipeGestureRecognizerDirection.right:
                print("right swipe")
            case UISwipeGestureRecognizerDirection.left:
                print("leftSwipe")
            case UISwipeGestureRecognizerDirection.up:
                print("upSwipe")
            case UISwipeGestureRecognizerDirection.down:
                print("downSwipe")
            default:
                break
        }
    }
}

How do I calculate percentiles with python/numpy?

To calculate the percentile of a series, run:

from scipy.stats import rankdata
import numpy as np

def calc_percentile(a, method='min'):
    if isinstance(a, list):
        a = np.asarray(a)
    return rankdata(a, method=method) / float(len(a))

For example:

a = range(20)
print {val: round(percentile, 3) for val, percentile in zip(a, calc_percentile(a))}
>>> {0: 0.05, 1: 0.1, 2: 0.15, 3: 0.2, 4: 0.25, 5: 0.3, 6: 0.35, 7: 0.4, 8: 0.45, 9: 0.5, 10: 0.55, 11: 0.6, 12: 0.65, 13: 0.7, 14: 0.75, 15: 0.8, 16: 0.85, 17: 0.9, 18: 0.95, 19: 1.0}

How to prevent vim from creating (and leaving) temporary files?

I'd strongly recommend to keep working with swap files (in case Vim crashes).

You can set the directory where the swap files are stored, so they don't clutter your normal directories:

set swapfile
set dir=~/tmp

See also

:help swap-file

querySelector and querySelectorAll vs getElementsByClassName and getElementById in JavaScript

I would like to know what exactly is the difference between querySelector and querySelectorAll against getElementsByClassName and getElementById?

The syntax and the browser support.

querySelector is more useful when you want to use more complex selectors.

e.g. All list items descended from an element that is a member of the foo class: .foo li

document.querySelector("#view:_id1:inputText1") it doesn't work. But writing document.getElementById("view:_id1:inputText1") works. Any ideas why?

The : character has special meaning inside a selector. You have to escape it. (The selector escape character has special meaning in a JS string too, so you have to escape that too).

document.querySelector("#view\\:_id1\\:inputText1")

How to encrypt and decrypt file in Android?

Use a CipherOutputStream or CipherInputStream with a Cipher and your FileInputStream / FileOutputStream.

I would suggest something like Cipher.getInstance("AES/CBC/PKCS5Padding") for creating the Cipher class. CBC mode is secure and does not have the vulnerabilities of ECB mode for non-random plaintexts. It should be present in any generic cryptographic library, ensuring high compatibility.

Don't forget to use a Initialization Vector (IV) generated by a secure random generator if you want to encrypt multiple files with the same key. You can prefix the plain IV at the start of the ciphertext. It is always exactly one block (16 bytes) in size.

If you want to use a password, please make sure you do use a good key derivation mechanism (look up password based encryption or password based key derivation). PBKDF2 is the most commonly used Password Based Key Derivation scheme and it is present in most Java runtimes, including Android. Note that SHA-1 is a bit outdated hash function, but it should be fine in PBKDF2, and does currently present the most compatible option.

Always specify the character encoding when encoding/decoding strings, or you'll be in trouble when the platform encoding differs from the previous one. In other words, don't use String.getBytes() but use String.getBytes(StandardCharsets.UTF_8).

To make it more secure, please add cryptographic integrity and authenticity by adding a secure checksum (MAC or HMAC) over the ciphertext and IV, preferably using a different key. Without an authentication tag the ciphertext may be changed in such a way that the change cannot be detected.

Be warned that CipherInputStream may not report BadPaddingException, this includes BadPaddingException generated for authenticated ciphers such as GCM. This would make the streams incompatible and insecure for these kind of authenticated ciphers.

Dockerfile if else condition with external arguments

The accepted answer may solve the question, but if you want multiline if conditions in the dockerfile, you can do that placing \ at the end of each line (similar to how you would do in a shell script) and ending each command with ;. You can even define someting like set -eux as the 1st command.

Example:

RUN set -eux; \
  if [ -f /path/to/file ]; then \
    mv /path/to/file /dest; \
  fi; \
  if [ -d /path/to/dir ]; then \
    mv /path/to/dir /dest; \
  fi

In your case:

FROM centos:7
ARG arg
RUN if [ -z "$arg" ] ; then \
    echo Argument not provided; \
  else \
    echo Argument is $arg; \
  fi

Then build with:

docker build -t my_docker . --build-arg arg=42

In LINQ, select all values of property X where X != null

There is no way to skip a check if it exists.

Fatal error: Out of memory, but I do have plenty of memory (PHP)

Could be an issue with MySQL and the number of open connections, hence why it sorts itself out when you restart every few days. Are they auto closing on script shutdown?

How to find a whole word in a String in java

To Match "123woods" instead of "woods" , use atomic grouping in regular expresssion. One thing to be noted is that, in a string to match "123woods" alone , it will match the first "123woods" and exits instead of searching the same string further.

\b(?>123woods|woods)\b

it searches 123woods as primary search, once it got matched it exits the search.

CSS Change List Item Background Color with Class

This is an issue of selector specificity. (The selector .selected is less specific than ul.nav li.)

To fix, use as much specificity in the overriding rule as in the original:

ul.nav li {
 background-color:blue;
}
ul.nav li.selected {
 background-color:red;
}

You might also consider nixing the ul, unless there will be other .navs. So:

.nav li {
 background-color:blue;
}
.nav li.selected {
 background-color:red;
}

That's a bit cleaner, less typing, and fewer bits.

How to get < span > value?

<div id="test">
    <span>1</span>
    <span>2</span>
    <span>3</span>
    <span>4</span>
</div>
<div id="test2"></div>

<script type="text/javascript">
    var getDiv = document.getElementById('test');
    var getSpan = getDiv.getElementsByTagName('span');???
    var divDump = document.getElementById('test2');

    for (var i=0; i<getSpan.length; i++) {
        divDump.innerHTML = divDump.innerHTML + ' ' + getSpan[i].innerHTML;
    }
</script>

?

How to take column-slices of dataframe in pandas

Also, Given a DataFrame

data

as in your example, if you would like to extract column a and d only (e.i. the 1st and the 4th column), iloc mothod from the pandas dataframe is what you need and could be used very effectively. All you need to know is the index of the columns you would like to extract. For example:

>>> data.iloc[:,[0,3]]

will give you

          a         d
0  0.883283  0.100975
1  0.614313  0.221731
2  0.438963  0.224361
3  0.466078  0.703347
4  0.955285  0.114033
5  0.268443  0.416996
6  0.613241  0.327548
7  0.370784  0.359159
8  0.692708  0.659410
9  0.806624  0.875476

How to format column to number format in Excel sheet?

This will format column A as text, B as General, C as a number.

Sub formatColumns()
 Columns(1).NumberFormat = "@"
 Columns(2).NumberFormat = "General"
 Columns(3).NumberFormat = "0"
End Sub

How to Set Variables in a Laravel Blade Template

You Can Set Variables In The Blade Templating Engine The Following Ways:

1. General PHP Block
Setting Variable: <?php $hello = "Hello World!"; ?>
Output: {{$hello}}

2. Blade PHP Block
Setting Variable: @php $hello = "Hello World!"; @endphp
Output: {{$hello}}

Commit history on remote repository

I'm not sure when filtering was added but it's a way to exclude the object blobs if you only want to fetch the history/ref-logs:

git clone --filter=blob:none --no-checkout --single-branch --branch master git://some.repo.git .
git log

Update MySQL using HTML Form and PHP

Try it this way. Put the table name in quotes (``). beside put variable '".$xyz."'.

So your sql query will be like:

$sql = mysql_query("UPDATE `anstalld` SET mandag = "'.$mandag.'" WHERE namn =".$name)or die(mysql_error());

Monitor the Graphics card usage

From Unix.SE: A simple command-line utility called gpustat now exists: https://github.com/wookayin/gpustat.

It is free software (MIT license) and is packaged in pypi. It is a wrapper of nvidia-smi.

How to fix Python indentation

If you're using Vim, see :h retab.

                                                        *:ret* *:retab*
:[range]ret[ab][!] [new_tabstop]
                        Replace all sequences of white-space containing a
                        <Tab> with new strings of white-space using the new
                        tabstop value given.  If you do not specify a new
                        tabstop size or it is zero, Vim uses the current value
                        of 'tabstop'.
                        The current value of 'tabstop' is always used to
                        compute the width of existing tabs.
                        With !, Vim also replaces strings of only normal
                        spaces with tabs where appropriate.
                        With 'expandtab' on, Vim replaces all tabs with the
                        appropriate number of spaces.
                        This command sets 'tabstop' to the new value given,
                        and if performed on the whole file, which is default,
                        should not make any visible change.
                        Careful: This command modifies any <Tab> characters
                        inside of strings in a C program.  Use "\t" to avoid
                        this (that's a good habit anyway).
                        ":retab!" may also change a sequence of spaces by
                        <Tab> characters, which can mess up a printf().
                        {not in Vi}
                        Not available when |+ex_extra| feature was disabled at
                        compile time.

For example, if you simply type

:ret

all your tabs will be expanded into spaces.

You may want to

:se et  " shorthand for :set expandtab

to make sure that any new lines will not use literal tabs.


If you're not using Vim,

perl -i.bak -pe "s/\t/' 'x(8-pos()%8)/eg" file.py

will replace tabs with spaces, assuming tab stops every 8 characters, in file.py (with the original going to file.py.bak, just in case). Replace the 8s with 4s if your tab stops are every 4 spaces instead.

Nesting await in Parallel.ForEach

You can save effort with the new AsyncEnumerator NuGet Package, which didn't exist 4 years ago when the question was originally posted. It allows you to control the degree of parallelism:

using System.Collections.Async;
...

await ids.ParallelForEachAsync(async i =>
{
    ICustomerRepo repo = new CustomerRepo();
    var cust = await repo.GetCustomer(i);
    customers.Add(cust);
},
maxDegreeOfParallelism: 10);

Disclaimer: I'm the author of the AsyncEnumerator library, which is open source and licensed under MIT, and I'm posting this message just to help the community.

How to set default value to the input[type="date"]

$date=date("Y-m-d");
echo"$date";
echo"<br>SELECT DATE: <input type='date'  name='date'  id='datepicker' 
value='$date' required >";

Insert string at specified position

Use the stringInsert function rather than the putinplace function. I was using the later function to parse a mysql query. Although the output looked alright, the query resulted in a error which took me a while to track down. The following is my version of the stringInsert function requiring only one parameter.

function stringInsert($str,$insertstr,$pos)
{
    $str = substr($str, 0, $pos) . $insertstr . substr($str, $pos);
    return $str;
}  

PHP-FPM and Nginx: 502 Bad Gateway

For anyone else struggling to get to the bottom of this, I tried adjusting timeouts as suggested as I didn't want to stop using Unix sockets...after lots of troubleshooting and not much to go on I found that this issue was being caused by the APC extension that I'd enabled in php-fpm a few months back. Disabling this extension resolved the intermittent 502 errors, easiest way to do this was by commenting out the following line :

;extension = apc.so

This did the trick for me!

How to pass a parameter to routerLink that is somewhere inside the URL?

First configure in table:

const routes: Routes = [  
{
  path: 'class/:id/enrollment/:guid',
  component: ClassEnrollmentComponent
 }
];

now in type script code:

this.router.navigate([`class/${classId}/enrollment/${4545455}`]);

receive params in another component

 this.activatedRoute.params.subscribe(params => {
  let id = params['id'];
  let guid = params['guid'];

  console.log(`${id},${guid}`);
  });

Create, read, and erase cookies with jQuery

Use jquery cookie plugin, the link as working today: https://github.com/js-cookie/js-cookie

Why am I getting InputMismatchException?

Since you have the manual user input loop, after the scanner has read your first input it will pass the carriage/return into the next line which will also be read; of course, that is not what you wanted.

You can try this

try {
    // ...
} catch (InputMismatchException e) {
    reader.next(); 
}

or alternatively, you can consume that carriage return before reading your next double input by calling

reader.next()

Postgresql : Connection refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections

The error you quote has nothing to do with pg_hba.conf; it's failing to connect, not failing to authorize the connection.

Do what the error message says:

Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections

You haven't shown the command that produces the error. Assuming you're connecting on localhost port 5432 (the defaults for a standard PostgreSQL install), then either:

  • PostgreSQL isn't running

  • PostgreSQL isn't listening for TCP/IP connections (listen_addresses in postgresql.conf)

  • PostgreSQL is only listening on IPv4 (0.0.0.0 or 127.0.0.1) and you're connecting on IPv6 (::1) or vice versa. This seems to be an issue on some older Mac OS X versions that have weird IPv6 socket behaviour, and on some older Windows versions.

  • PostgreSQL is listening on a different port to the one you're connecting on

  • (unlikely) there's an iptables rule blocking loopback connections

(If you are not connecting on localhost, it may also be a network firewall that's blocking TCP/IP connections, but I'm guessing you're using the defaults since you didn't say).

So ... check those:

  • ps -f -u postgres should list postgres processes

  • sudo lsof -n -u postgres |grep LISTEN or sudo netstat -ltnp | grep postgres should show the TCP/IP addresses and ports PostgreSQL is listening on

BTW, I think you must be on an old version. On my 9.3 install, the error is rather more detailed:

$ psql -h localhost -p 12345
psql: could not connect to server: Connection refused
        Is the server running on host "localhost" (::1) and accepting
        TCP/IP connections on port 12345?

When should you use a class vs a struct in C++?

As others have pointed out

  • both are equivalent apart from default visibility
  • there may be reasons to be forced to use the one or the other for whatever reason

There's a clear recommendation about when to use which from Stroustrup/Sutter:

Use class if the class has an invariant; use struct if the data members can vary independently

However, keep in mind that it is not wise to forward declare sth. as a class (class X;) and define it as struct (struct X { ... }). It may work on some linkers (e.g., g++) and may fail on others (e.g., MSVC), so you will find yourself in developer hell.

jQuery Validate Plugin - Trigger validation of single field

in case u wanna do the validation for "some elements" (not all element) on your form.You can use this method:

$('input[name="element-one"], input[name="element-two"], input[name="element-three"]').valid();

Hope it help everybody :)

EDITED

How to enable multidexing with the new Android Multidex support library

just adding this snipped in the build.gradle also works fine

android {
   compileSdkVersion 22
   buildToolsVersion "23.0.0"

     defaultConfig {
         minSdkVersion 14 //lower than 14 doesn't support multidex
         targetSdkVersion 22

         **// Enabling multidex support.
         **multiDexEnabled true****
     }
}

One liner to check if element is in the list

Use Arrays.asList:

if( Arrays.asList("a","b","c").contains("a") )

Complex nesting of partials and templates

I too was struggling with nested views in Angular.

Once I got a hold of ui-router I knew I was never going back to angular default routing functionality.

Here is an example application that uses multiple levels of views nesting

app.config(function ($stateProvider, $urlRouterProvider,$httpProvider) {
// navigate to view1 view by default
$urlRouterProvider.otherwise("/view1");

$stateProvider
    .state('view1', {
        url: '/view1',
        templateUrl: 'partials/view1.html',
        controller: 'view1.MainController'
    })
    .state('view1.nestedViews', {
        url: '/view1',
        views: {
            'childView1': { templateUrl: 'partials/view1.childView1.html' , controller: 'childView1Ctrl'},
            'childView2': { templateUrl: 'partials/view1.childView2.html', controller: 'childView2Ctrl' },
            'childView3': { templateUrl: 'partials/view1.childView3.html', controller: 'childView3Ctrl' }
        }
    })

    .state('view2', {
        url: '/view2',
    })

    .state('view3', {
        url: '/view3',
    })

    .state('view4', {
        url: '/view4',
    });
});

As it can be seen there are 4 main views (view1,view2,view3,view4) and view1 has 3 child views.

How to convert datetime to integer in python

When converting datetime to integers one must keep in mind the tens, hundreds and thousands.... like "2018-11-03" must be like 20181103 in int for that you have to 2018*10000 + 100* 11 + 3

Similarly another example, "2018-11-03 10:02:05" must be like 20181103100205 in int

Explanatory Code

dt = datetime(2018,11,3,10,2,5)
print (dt)

#print (dt.timestamp()) # unix representation ... not useful when converting to int

print (dt.strftime("%Y-%m-%d"))
print (dt.year*10000 + dt.month* 100  + dt.day)
print (int(dt.strftime("%Y%m%d")))

print (dt.strftime("%Y-%m-%d %H:%M:%S"))
print (dt.year*10000000000 + dt.month* 100000000 +dt.day * 1000000 + dt.hour*10000  +  dt.minute*100 + dt.second)
print (int(dt.strftime("%Y%m%d%H%M%S")))

General Function

To avoid that doing manually use below function

def datetime_to_int(dt):
    return int(dt.strftime("%Y%m%d%H%M%S"))

OSX El Capitan: sudo pip install OSError: [Errno: 1] Operation not permitted

Used pip3 install <package> instead and solved the permission problem with pip.

in a "using" block is a SqlConnection closed on return or exception?

  1. Yes
  2. Yes.

Either way, when the using block is exited (either by successful completion or by error) it is closed.

Although I think it would be better to organize like this because it's a lot easier to see what is going to happen, even for the new maintenance programmer who will support it later:

using (SqlConnection connection = new SqlConnection(connectionString)) 
{    
    int employeeID = findEmployeeID();    
    try    
    {
        connection.Open();
        SqlCommand command = new SqlCommand("UpdateEmployeeTable", connection);
        command.CommandType = CommandType.StoredProcedure;
        command.Parameters.Add(new SqlParameter("@EmployeeID", employeeID));
        command.CommandTimeout = 5;

        command.ExecuteNonQuery();    
    } 
    catch (Exception) 
    { 
        /*Handle error*/ 
    }
}

Understanding the results of Execute Explain Plan in Oracle SQL Developer

The CBO builds a decision tree, estimating the costs of each possible execution path available per query. The costs are set by the CPU_cost or I/O_cost parameter set on the instance. And the CBO estimates the costs, as best it can with the existing statistics of the tables and indexes that the query will use. You should not tune your query based on cost alone. Cost allows you to understand WHY the optimizer is doing what it does. Without cost you could figure out why the optimizer chose the plan it did. Lower cost does not mean a faster query. There are cases where this is true and there will be cases where this is wrong. Cost is based on your table stats and if they are wrong the cost is going to be wrong.

When tuning your query, you should take a look at the cardinality and the number of rows of each step. Do they make sense? Is the cardinality the optimizer is assuming correct? Is the rows being return reasonable. If the information present is wrong then its very likely the optimizer doesn't have the proper information it needs to make the right decision. This could be due to stale or missing statistics on the table and index as well as cpu-stats. Its best to have stats updated when tuning a query to get the most out of the optimizer. Knowing your schema is also of great help when tuning. Knowing when the optimizer chose a really bad decision and pointing it in the correct path with a small hint can save a load of time.

Setting up Gradle for api 26 (Android)

you must add in your MODULE-LEVEL build.gradle file with:

//module-level build.gradle file
repositories {
    maven {
        url 'https://maven.google.com'

    }
}

see: Google's Maven repository

I have observed that when I use Android Studio 2.3.3 I MUST add repositories{maven{url 'https://maven.google.com'}} in MODULE-LEVEL build.gradle. In the case of Android Studio 3.0.0 there is no need for the addition in module-level build.gradle. It is enough the addition in project-level build.gradle which has been referred to in the other posts here, namely:

//project-level build.gradle file
allprojects {
 repositories {
    jcenter()
    maven {
        url 'https://maven.google.com/'
        name 'Google'
    }
  }
}

UPDATE 11-14-2017: The solution, that I present, was valid when I did the post. Since then, there have been various updates (even with respect to the site I refer to), and I do not know if now is valid. For one month I did my work depending on the solution above, until I upgraded to Android Studio 3.0.0

Angular routerLink does not navigate to the corresponding component

Try changing the links as below:

  <ul class="nav navbar-nav item">
    <li>
        <a [routerLink]="['/home']" routerLinkActive="active">Home</a>
    </li>
    <li>
        <a [routerLink]="['/about']" routerLinkActive="active">About this</a>
    </li>
  </ul>

Also, add the following in the header of index.html:

<base href="/">

When is TCP option SO_LINGER (0) required?

In servers, you may like to send RST instead of FIN when disconnecting misbehaving clients. That skips FIN-WAIT followed by TIME-WAIT socket states in the server, which prevents from depleting server resources, and, hence, protects from this kind of denial-of-service attack.

Filter items which array contains any of given values

There's also terms query which should save you some work. Here example from docs:

{
  "terms" : {
      "tags" : [ "blue", "pill" ],
      "minimum_should_match" : 1
  }
}

Under hood it constructs boolean should. So it's basically the same thing as above but shorter.

There's also a corresponding terms filter.

So to summarize your query could look like this:

{
  "filtered": {
    "query": {
      "match": { "title": "hello world" }
    },
    "filter": {
      "terms": {
        "tags": ["c", "d"]
      }
    }
  }
}

With greater number of tags this could make quite a difference in length.

How to display custom view in ActionBar?

I struggled with this myself, and tried Tomik's answer. However, this didn't made the layout to full available width on start, only when you add something to the view.

You'll need to set the LayoutParams.FILL_PARENT when adding the view:

//I'm using actionbarsherlock, but it's the same.
LayoutParams layout = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
getSupportActionBar().setCustomView(overlay, layout); 

This way it completely fills the available space. (You may need to use Tomik's solution too).

Date format Mapping to JSON Jackson

If anyone has problems with using a custom dateformat for java.sql.Date, this is the simplest solution:

ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addSerializer(java.sql.Date.class, new DateSerializer());
mapper.registerModule(module);

(This SO-answer saved me a lot of trouble: https://stackoverflow.com/a/35212795/3149048 )

Jackson uses the SqlDateSerializer by default for java.sql.Date, but currently, this serializer doesn't take the dateformat into account, see this issue: https://github.com/FasterXML/jackson-databind/issues/1407 . The workaround is to register a different serializer for java.sql.Date as shown in the code example.

How to deploy a war file in JBoss AS 7?

I built the following ant-task for deployment based on the jboss deployment docs:

<target name="deploy" depends="jboss.environment, buildwar">
    <!-- Build path for deployed war-file -->
    <property name="deployed.war" value="${jboss.home}/${jboss.deploy.dir}/${war.filename}" />

    <!-- remove current deployed war -->
    <delete file="${deployed.war}.deployed" failonerror="false" />
    <waitfor maxwait="10" maxwaitunit="second">
        <available file="${deployed.war}.undeployed" />
    </waitfor>
    <delete dir="${deployed.war}" />

    <!-- copy war-file -->
    <copy file="${war.filename}" todir="${jboss.home}/${jboss.deploy.dir}" />

    <!-- start deployment -->
    <echo>start deployment ...</echo>
    <touch file="${deployed.war}.dodeploy" />

    <!-- wait for deployment to complete -->
    <waitfor maxwait="10" maxwaitunit="second">
        <available file="${deployed.war}.deployed" />
    </waitfor>
    <echo>deployment ok!</echo>
</target>

${jboss.deploy.dir} is set to standalone/deployments

"Uncaught TypeError: undefined is not a function" - Beginner Backbone.js Application

Uncaught TypeError: undefined is not a function example_app.js:7

This error message tells the whole story. On this line, you are trying to execute a function. However, whatever is being executed is not a function! Instead, it's undefined.

So what's on example_app.js line 7? Looks like this:

var tasks = new ExampleApp.Collections.Tasks(data.tasks);

There is only one function being run on that line. We found the problem! ExampleApp.Collections.Tasks is undefined.

So lets look at where that is declared:

var Tasks = Backbone.Collection.extend({
    model: Task,
    url: '/tasks'
});

If that's all the code for this collection, then the root cause is right here. You assign the constructor to global variable, called Tasks. But you never add it to the ExampleApp.Collections object, a place you later expect it to be.

Change that to this, and I bet you'd be good.

ExampleApp.Collections.Tasks = Backbone.Collection.extend({
    model: Task,
    url: '/tasks'
});

See how important the proper names and line numbers are in figuring this out? Never ever regard errors as binary (it works or it doesn't). Instead read the error, in most cases the error message itself gives you the critical clues you need to trace through to find the real issue.


In Javascript, when you execute a function, it's evaluated like:

expression.that('returns').aFunctionObject(); // js
execute -> expression.that('returns').aFunctionObject // what the JS engine does

That expression can be complex. So when you see undefined is not a function it means that expression did not return a function object. So you have to figure out why what you are trying to execute isn't a function.

And in this case, it was because you didn't put something where you thought you did.

How to compile multiple java source files in command line

or you can use the following to compile the all java source files in current directory..

javac *.java

How do I create a new Git branch from an old commit?

git checkout -b NEW_BRANCH_NAME COMMIT_ID

This will create a new branch called 'NEW_BRANCH_NAME' and check it out.

("check out" means "to switch to the branch")

git branch NEW_BRANCH_NAME COMMIT_ID

This just creates the new branch without checking it out.


in the comments many people seem to prefer doing this in two steps. here's how to do so in two steps:

git checkout COMMIT_ID
# you are now in the "detached head" state
git checkout -b NEW_BRANCH_NAME

Send response to all clients except sender

I am using namespaces and rooms - I found

socket.broadcast.to('room1').emit('event', 'hi');

to work where

namespace.broadcast.to('room1').emit('event', 'hi');

did not

(should anyone else face that problem)

How to create a table from select query result in SQL Server 2008

Select [Column Name] into [New Table] from [Source Table]

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

Looping through list items with jquery

   <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
   <script>
      $(document).ready(function() {
      $("form").submit(function(e){
          e.preventDefault();
       var name = $("#name").val();
       var amount =$("#number").val();
       var gst=(amount)*(0.18);
           gst=Math.round(gst);

       var total=parseInt(amount)+parseInt(gst);
       $(".myTable tbody").append("<tr><td></td><td>"+name+"</td><td>"+amount+"</td><td>"+gst+"</td><td>"+total+"</td></tr>");
       $("#name").val('');
       $("#number").val('');

       $(".myTable").find("tbody").find("tr").each(function(i){
       $(this).closest('tr').find('td:first-child').text(i+1);

       });

       $("#formdata").on('submit', '.myTable', function () {

                   var sum = 0;

          $(".myTable tbody tr").each(function () {
                    var getvalue = $(this).val();
                    if ($.isNumeric(getvalue))
                     {
                        sum += parseFloat(getvalue);
                     }                  
                     });

                     $(".total").text(sum);
        });

    });
   });

   </script>

     <style>
           #formdata{
                      float:left;
                      width:400px;
                    }

     </style>
  </head>


  <body>  

       <form id="formdata">  

                           <span>Product Name</span>
                           <input type="text" id="name">
                            <br>

                           <span>Product Amount</span>
                           <input type="text" id="number">
                           <br>
                           <br>
                           <center><button type="submit" class="adddata">Add</button></center>
       </form>
       <br>
       <br>

      <table class="myTable" border="1px" width="300px">
      <thead><th>s.no</th><th>Name</th><th>Amount</th><th>Gst</th><th>NetTotal</th></thead>

      <tbody></tbody>

      <tfoot>
             <tr>
                 <td></td>
                 <td></td>
                 <td></td>
                 <td class="total"></td>
                 <td class="total"></td>
             </tr>

      </tfoot>
      </table>

   </body>

arranging div one below the other

The default behaviour of divs is to take the full width available in their parent container.
This is the same as if you'd give the inner divs a width of 100%.

By floating the divs, they ignore their default and size their width to fit the content. Everything behind it (in the HTML), is placed under the div (on the rendered page).
This is the reason that they align theirselves next to each other.

The float CSS property specifies that an element should be taken from the normal flow and placed along the left or right side of its container, where text and inline elements will wrap around it. A floating element is one where the computed value of float is not none.

Source: https://developer.mozilla.org/en-US/docs/Web/CSS/float

Get rid of the float, and the divs will be aligned under each other.
If this does not happen, you'll have some other css on divs or children of wrapper defining a floating behaviour or an inline display.

If you want to keep the float, for whatever reason, you can use clear on the 2nd div to reset the floating properties of elements before that element.
clear has 5 valid values: none | left | right | both | inherit. Clearing no floats (used to override inherited properties), left or right floats or both floats. Inherit means it'll inherit the behaviour of the parent element

Also, because of the default behaviour, you don't need to set the width and height on auto.
You only need this is you want to set a hardcoded height/width. E.g. 80% / 800px / 500em / ...

<div id="wrapper">
    <div id="inner1"></div>
    <div id="inner2"></div>
</div>

CSS is

#wrapper{
    margin-left:auto;
    margin-right:auto;
    height:auto; // this is not needed, as parent container, this div will size automaticly
    width:auto; // this is not needed, as parent container, this div will size automaticly
}

/*
You can get rid of the inner divs in the css, unless you want to style them.
If you want to style them identicly, you can use concatenation
*/
#inner1, #inner2 {
    border: 1px solid black;
}

require is not defined? Node.js

In the terminal, you are running the node application and it is running your script. That is a very different execution environment than directly running your script in the browser. While the Javascript language is largely the same (both V8 if you're running the Chrome browser), the rest of the execution environment such as libraries available are not the same.

node.js is a server-side Javascript execution environment that combines the V8 Javascript engine with a bunch of server-side libraries. require() is one such feature that node.js adds to the environment. So, when you run node in the terminal, you are running an environment that contains require().

require() is not a feature that is built into the browser. That is a specific feature of node.js, not of a browser. So, when you try to have the browser run your script, it does not have require().

There are ways to run some forms of node.js code in a browser (but not all). For example, you can get browser substitutes for require() that work similarly (though not identically).

But, you won't be running a web server in your browser as that is not something the browser has the capability to do.


You may be interested in browserify which lets you use node-style modules in a browser using require() statements.

"And" and "Or" troubles within an IF statement

I like assylias' answer, however I would refactor it as follows:

Sub test()

Dim origNum As String
Dim creditOrDebit As String

origNum = "30062600006"
creditOrDebit = "D"

If creditOrDebit = "D" Then
  If origNum = "006260006" Then
    MsgBox "OK"
  ElseIf origNum = "30062600006" Then
    MsgBox "OK"
  End If
End If

End Sub

This might save you some CPU cycles since if creditOrDebit is <> "D" there is no point in checking the value of origNum.

Update:

I used the following procedure to test my theory that my procedure is faster:

Public Declare Function timeGetTime Lib "winmm.dll" () As Long

Sub DoTests2()

  Dim startTime1 As Long
  Dim endTime1 As Long
  Dim startTime2 As Long
  Dim endTime2 As Long
  Dim i As Long
  Dim msg As String

  Const numberOfLoops As Long = 10000
  Const origNum As String = "006260006"
  Const creditOrDebit As String = "D"

  startTime1 = timeGetTime
  For i = 1 To numberOfLoops
    If creditOrDebit = "D" Then
      If origNum = "006260006" Then
        ' do something here
        Debug.Print "OK"
      ElseIf origNum = "30062600006" Then
        ' do something here
        Debug.Print "OK"
      End If
    End If
  Next i
  endTime1 = timeGetTime

  startTime2 = timeGetTime
  For i = 1 To numberOfLoops
    If (origNum = "006260006" Or origNum = "30062600006") And _
      creditOrDebit = "D" Then
      ' do something here
      Debug.Print "OK"
    End If
  Next i
  endTime2 = timeGetTime

  msg = "number of iterations: " & numberOfLoops & vbNewLine
  msg = msg & "JP proc: " & Format$((endTime1 - startTime1), "#,###") & _
       " ms" & vbNewLine
  msg = msg & "assylias proc: " & Format$((endTime2 - startTime2), "#,###") & _
       " ms"

  MsgBox msg

End Sub

I must have a slow computer because 1,000,000 iterations took nowhere near ~200 ms as with assylias' test. I had to limit the iterations to 10,000 -- hey, I have other things to do :)

After running the above procedure 10 times, my procedure is faster only 20% of the time. However, when it is slower it is only superficially slower. As assylias pointed out, however, when creditOrDebit is <>"D", my procedure is at least twice as fast. I was able to reasonably test it at 100 million iterations.

And that is why I refactored it - to short-circuit the logic so that origNum doesn't need to be evaluated when creditOrDebit <> "D".

At this point, the rest depends on the OP's spreadsheet. If creditOrDebit is likely to equal D, then use assylias' procedure, because it will usually run faster. But if creditOrDebit has a wide range of possible values, and D is not any more likely to be the target value, my procedure will leverage that to prevent needlessly evaluating the other variable.

Load content of a div on another page

You just need to add a jquery selector after the url.

See: http://api.jquery.com/load/

Example straight from the API:

$('#result').load('ajax/test.html #container');

So what that does is it loads the #container element from the specified url.

how to get current datetime in SQL?

I want my datetime, and I want it now()!

For MySQL, anyway.

Current time formatting with Javascript

There are many great libraries out there, for those interested

There really shouldn't be a need these days to invent your own formatting specifiers.

How to play a notification sound on websites?

How about the yahoo's media player Just embed yahoo's library

<script type="text/javascript" src="http://mediaplayer.yahoo.com/js"></script> 

And use it like

<a id="beep" href="song.mp3">Play Song</a>

To autostart

$(function() { $("#beep").click(); });

How to force two figures to stay on the same page in LaTeX?

You can put two figures inside one figure environment. For example:

\begin{figure}[p]
\centering
\includegraphics{fig1}
\caption{Caption 1}
\includegraphics{fig2}
\caption{Caption 2}
\end{figure}

Each caption will generate a separate figure number.

CodeIgniter - Correct way to link to another page in a view

<a href="<?php echo site_url('controller/function'); ?>Compose</a>

<a href="<?php echo site_url('controller/function'); ?>Inbox</a>

<a href="<?php echo site_url('controller/function'); ?>Outbox</a>

<a href="<?php echo site_url('controller/function'); ?>logout</a>

<a href="<?php echo site_url('controller/function'); ?>logout</a>

check / uncheck checkbox using jquery?

You can set the state of the checkbox based on the value:

$('#your-checkbox').prop('checked', value == 1);

How get total sum from input box values using Javascript?

Here's a simpler solution using what Akhil Sekharan has provided but with a little change.

var inputs = document.getElementsByTagName('input');

for (var i = 0; i < inputs.length; i += 1) {
if(parseInt(inputs[i].value)){
        inputs[i].value = '';
       }
    }????
document.getElementById('total').value = total;

regular expression to match exactly 5 digits

No need to care of whether before/after this digit having other type of words

To just match the pattern of 5 digits number anywhere in the string, no matter it is separated by space or not, use this regular expression (?<!\d)\d{5}(?!\d).

Sample JavaScript codes:

var regexp = new RegExp(/(?<!\d)\d{5}(?!\d)/g); 
    var matches = yourstring.match(regexp);
    if (matches && matches.length > 0) {
        for (var i = 0, len = matches.length; i < len; i++) {
            // ... ydo something with matches[i] ...
        } 
    }

Here's some quick results.

  • abc12345xyz (?)

  • 12345abcd (?)

  • abcd12345 (?)

  • 0000aaaa2 (?)

  • a1234a5 (?)

  • 12345 (?)

  • <space>12345<space>12345 (??)

Error 1053 the service did not respond to the start or control request in a timely fashion

In my case, I was publishing service while it was in debug mode.

Solution was:

  • Changing solution to release mode
  • Uninstall old service with command InstallUtil -u WindowsServiceName.exe
  • installing service again InstallUtil -i WindowsServiceName.exe

It worked perfectly after.

Python - A keyboard command to stop infinite loop?

Ctrl+C is what you need. If it didn't work, hit it harder. :-) Of course, you can also just close the shell window.

Edit: You didn't mention the circumstances. As a last resort, you could write a batch file that contains taskkill /im python.exe, and put it on your desktop, Start menu, etc. and run it when you need to kill a runaway script. Of course, it will kill all Python processes, so be careful.

Why can't I push to this bare repository?

Yes, the problem is that there are no commits in "bare". This is a problem with the first commit only, if you create the repos in the order (bare,alice). Try doing:

git push --set-upstream origin master

This would only be required the first time. Afterwards it should work normally.

As Chris Johnsen pointed out, you would not have this problem if your push.default was customized. I like upstream/tracking.

How to add an element to the beginning of an OrderedDict?

You have to make a new instance of OrderedDict. If your keys are unique:

d1=OrderedDict([("a",1),("b",2)])
d2=OrderedDict([("c",3),("d",99)])
both=OrderedDict(list(d2.items()) + list(d1.items()))
print(both)

#OrderedDict([('c', 3), ('d', 99), ('a', 1), ('b', 2)])

But if not, beware as this behavior may or may not be desired for you:

d1=OrderedDict([("a",1),("b",2)])
d2=OrderedDict([("c",3),("b",99)])
both=OrderedDict(list(d2.items()) + list(d1.items()))
print(both)

#OrderedDict([('c', 3), ('b', 2), ('a', 1)])

Runtime vs. Compile time

The major difference between run-time and compile time is:

  1. If there are any syntax errors and type checks in your code,then it throws compile time error, where-as run-time:it checks after executing the code. For example:

int a = 1 int b = a/0;

here first line doesn't have a semi-colon at the end---> compile time error after executing the program while performing operation b, result is infinite---> run-time error.

  1. Compile time doesn't look for output of functionality provided by your code, whereas run-time does.

Javascript to display the current date and time

<script>

    var today = new Date();
    var dd = today.getDate();
    var mm = today.getMonth() + 1; //January is 0!
    var yyyy = today.getFullYear();
    var h = today.getHours();
    var m = today.getMinutes();
    var s = today.getSeconds();


    if (dd < 10) {
        dd = '0' + dd
    }

    if (mm < 10) {
        mm = '0' + mm
    }
    if (h < 10) { h = '0' + h }
    if (m < 10) { m = '0' + m }
    if (s < 10) { s = '0' + s }

    var ctoday = dd + '/' + mm + '/' + yyyy+ '\t' +h+ ':' +m+ ':' +s;
    var d = new Date()
    var weekday = new Array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday")
    console.log("Today is " + weekday[d.getDay()])
    document.getElementById('time').innerHTML = '<span style="color:blue">' + weekday[d.getDay()] + ", " + ctoday + '</span>';
</script>
<div>
<span> Today is : <span id="time"> </span>
</div>

What are all the escape characters?

You can find the full list here.

  • \t Insert a tab in the text at this point.
  • \b Insert a backspace in the text at this point.
  • \n Insert a newline in the text at this point.
  • \r Insert a carriage return in the text at this point.
  • \f Insert a formfeed in the text at this point.
  • \' Insert a single quote character in the text at this point.
  • \" Insert a double quote character in the text at this point.
  • \\ Insert a backslash character in the text at this point.

Opening new window in HTML for target="_blank"

You can't influence neither type (tab/window) nor dimensions that way. You'll have to use JavaScript's window.open() for that.

Meaning of $? (dollar question mark) in shell scripts

Outputs the result of the last executed unix command

0 implies true
1 implies false

whitespaces in the path of windows filepath

There is no problem with whitespaces in the path since you're not using the "shell" to open the file. Here is a session from the windows console to prove the point. You're doing something else wrong

Python 2.7.2 (default, Jun 12 2011, 14:24:46) [MSC v.1500 64 bit (AMD64)] on wi
32
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>>
>>> os.makedirs("C:/ABC/SEM 2/testfiles")
>>> open("C:/ABC/SEM 2/testfiles/all.txt","w")
<open file 'C:/ABC/SEM 2/testfiles/all.txt', mode 'w' at 0x0000000001D95420>
>>> exit()

C:\Users\Gnibbler>dir "C:\ABC\SEM 2\testfiles"
 Volume in drive C has no label.
 Volume Serial Number is 46A0-BB64

 Directory of c:\ABC\SEM 2\testfiles

13/02/2013  10:20 PM    <DIR>          .
13/02/2013  10:20 PM    <DIR>          ..
13/02/2013  10:20 PM                 0 all.txt
               1 File(s)              0 bytes
               2 Dir(s)  78,929,309,696 bytes free

C:\Users\Gnibbler>

Resource files not found from JUnit test cases

Main classes should be under src/main/java
and
test classes should be under src/test/java

If all in the correct places and still main classes are not accessible then
Right click project => Maven => Update Project
Hope so this will resolve the issue

Android: Expand/collapse animation

I think the easiest solution is to set android:animateLayoutChanges="true" to your LinearLayout and then just show/hide view by seting its visibility. Works like a charm, but you have no controll on the animation duration

Change EditText hint color when using TextInputLayout

You must set hint color on TextInputLayout.