Programs & Examples On #Xilinx

Xilinx is a major brand of Field Programmable Gate Arrays (FPGA) and CPLDs (Complex Programmable Logic Devices)

Adding Http Headers to HttpClient

Create a HttpRequestMessage, set the Method to GET, set your headers and then use SendAsync instead of GetAsync.

var client = new HttpClient();
var request = new HttpRequestMessage() {
    RequestUri = new Uri("http://www.someURI.com"),
    Method = HttpMethod.Get,
};
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("text/plain"));
var task = client.SendAsync(request)
    .ContinueWith((taskwithmsg) =>
    {
        var response = taskwithmsg.Result;

        var jsonTask = response.Content.ReadAsAsync<JsonObject>();
        jsonTask.Wait();
        var jsonObject = jsonTask.Result;
    });
task.Wait();

Iterate all files in a directory using a 'for' loop

try this:

::Example directory
set SetupDir=C:\Users

::Loop in the folder with "/r" to search in recursive folders, %%f being a loop ::variable 
for /r "%SetupDir%" %%f in (*.msi *.exe) do set /a counter+=1

echo there are %counter% files in your folder

it counts .msi and .exe files in your directory (and in the sub directory). So it also makes the difference between folders and files as executables.

Just add an extension (.pptx .docx ..) if you need to filter other files in the loop

Why can't I call a public method in another class?

You have to create a variable of the type of the class, and set it equal to a new instance of the object first.

GradeBook myGradeBook = new GradeBook();

Then call the method on the obect you just created.

myGradeBook.[method you want called]

Convert string into integer in bash script - "Leading Zero" number error

You could also use bc

hour=8
result=$(echo "$hour + 1" | bc)
echo $result
9

XML Error: Extra content at the end of the document

You need a root node

<?xml version="1.0" encoding="ISO-8859-1"?>    
<documents>
    <document>
        <name>Sample Document</name>
        <type>document</type>
        <url>http://nsc-component.webs.com/Office/Editor/new-doc.html?docname=New+Document&amp;titletype=Title&amp;fontsize=9&amp;fontface=Arial&amp;spacing=1.0&amp;text=&amp;wordcount3=0</url>
    </document>

    <document>
        <name>Sample</name>
        <type>document</type>
        <url>http://nsc-component.webs.com/Office/Editor/new-doc.html?docname=New+Document&amp;titletype=Title&amp;fontsize=9&amp;fontface=Arial&amp;spacing=1.0&amp;text=&amp;</url>
    </document>
</documents>

How can I emulate a get request exactly like a web browser?

i'll make an example, first decide what browser you want to emulate, in this case i chose Firefox 60.6.1esr (64-bit), and check what GET request it issues, this can be obtained with a simple netcat server (MacOS bundles netcat, most linux distributions bunles netcat, and Windows users can get netcat from.. Cygwin.org , among other places),

setting up the netcat server to listen on port 9999: nc -l 9999

now hitting http://127.0.0.1:9999 in firefox, i get:

$ nc -l 9999
GET / HTTP/1.1
Host: 127.0.0.1:9999
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive
Upgrade-Insecure-Requests: 1

now let us compare that with this simple script:

<?php
$ch=curl_init("http://127.0.0.1:9999");
curl_exec($ch);

i get:

$ nc -l 9999
GET / HTTP/1.1
Host: 127.0.0.1:9999
Accept: */*

there are several missing headers here, they can all be added with the CURLOPT_HTTPHEADER option of curl_setopt, but the User-Agent specifically should be set with CURLOPT_USERAGENT instead (it will be persistent across multiple calls to curl_exec() and if you use CURLOPT_FOLLOWLOCATION then it will persist across http redirections as well), and the Accept-Encoding header should be set with CURLOPT_ENCODING instead (if they're set with CURLOPT_ENCODING then curl will automatically decompress the response if the server choose to compress it, but if you set it via CURLOPT_HTTPHEADER then you must manually detect and decompress the content yourself, which is a pain in the ass and completely unnecessary, generally speaking) so adding those we get:

<?php
$ch=curl_init("http://127.0.0.1:9999");
curl_setopt_array($ch,array(
        CURLOPT_USERAGENT=>'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0',
        CURLOPT_ENCODING=>'gzip, deflate',
        CURLOPT_HTTPHEADER=>array(
                'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
                'Accept-Language: en-US,en;q=0.5',
                'Connection: keep-alive',
                'Upgrade-Insecure-Requests: 1',
        ),
));
curl_exec($ch);

now running that code, our netcat server gets:

$ nc -l 9999
GET / HTTP/1.1
Host: 127.0.0.1:9999
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0
Accept-Encoding: gzip, deflate
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Connection: keep-alive
Upgrade-Insecure-Requests: 1

and voila! our php-emulated browser GET request should now be indistinguishable from the real firefox GET request :)

this next part is just nitpicking, but if you look very closely, you'll see that the headers are stacked in the wrong order, firefox put the Accept-Encoding header in line 6, and our emulated GET request puts it in line 3.. to fix this, we can manually put the Accept-Encoding header in the right line,

<?php
$ch=curl_init("http://127.0.0.1:9999");
curl_setopt_array($ch,array(
        CURLOPT_USERAGENT=>'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0',
        CURLOPT_ENCODING=>'gzip, deflate',
        CURLOPT_HTTPHEADER=>array(
                'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
                'Accept-Language: en-US,en;q=0.5',
                'Accept-Encoding: gzip, deflate',
                'Connection: keep-alive',
                'Upgrade-Insecure-Requests: 1',
        ),
));
curl_exec($ch);

running that, our netcat server gets:

$ nc -l 9999
GET / HTTP/1.1
Host: 127.0.0.1:9999
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive
Upgrade-Insecure-Requests: 1

problem solved, now the headers is even in the correct order, and the request seems to be COMPLETELY INDISTINGUISHABLE from the real firefox request :) (i don't actually recommend this last step, it's a maintenance burden to keep CURLOPT_ENCODING in sync with the custom Accept-Encoding header, and i've never experienced a situation where the order of the headers are significant)

Check whether number is even or odd

I would recommend

Java Puzzlers: Traps, Pitfalls, and Corner Cases Book by Joshua Bloch and Neal Gafter

There is a briefly explanation how to check if number is odd. First try is something similar what @AseemYadav tried:

public static boolean isOdd(int i) {
     return i % 2 == 1;
}

but as was mentioned in book:

when the remainder operation returns a nonzero result, it has the same sign as its left operand

so generally when we have negative odd number then instead of 1 we'll get -1 as result of i%2. So we can use @Camilo solution or just do:

public static boolean isOdd(int i) {
     return i % 2 != 0;
}

but generally the fastest solution is using AND operator like @lucasmo write above:

public static boolean isOdd(int i) {
     return (i & 1) != 0;
}

@Edit It also worth to point Math.floorMod(int x, int y); which deals good with negative the dividend but also can return -1 if the divisor is negative

HTML-Tooltip position relative to mouse pointer

We can achieve the same using "Directive" in Angularjs.

            //Bind mousemove event to the element which will show tooltip
            $("#tooltip").mousemove(function(e) {
                //find X & Y coodrinates
                x = e.clientX,
                y = e.clientY;

                //Set tooltip position according to mouse position
                tooltipSpan.style.top = (y + 20) + 'px';
                tooltipSpan.style.left = (x + 20) + 'px';
            });

You can check this post for further details. http://www.ufthelp.com/2014/12/Tooltip-Directive-AngularJS.html

How do you update Xcode on OSX to the latest version?

  1. Open up App Store

    enter image description here

  2. Look in the top right for the updates section (may also be in lefthand column "Updates"..)

    enter image description here

  3. Find Xcode & click Update enter image description here

How can I find my Apple Developer Team id and Team Agent Apple ID?

Apple has changed the interface.

The team ID could be found via this link: https://developer.apple.com/account/#/membership

How can I sort a dictionary by key?

Here I found some simplest solution to sort the python dict by key using pprint. eg.

>>> x = {'a': 10, 'cd': 20, 'b': 30, 'az': 99} 
>>> print x
{'a': 10, 'b': 30, 'az': 99, 'cd': 20}

but while using pprint it will return sorted dict

>>> import pprint 
>>> pprint.pprint(x)
{'a': 10, 'az': 99, 'b': 30, 'cd': 20}

Load a WPF BitmapImage from a System.Drawing.Bitmap

Thanks to Hallgrim, here is the code I ended up with:

ScreenCapture = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
   bmp.GetHbitmap(), 
   IntPtr.Zero, 
   System.Windows.Int32Rect.Empty, 
   BitmapSizeOptions.FromWidthAndHeight(width, height));

I also ended up binding to a BitmapSource instead of a BitmapImage as in my original question

JavaScript set object key by variable

In ES6, you can do like this.

var key = "name";
var person = {[key]:"John"}; // same as var person = {"name" : "John"}
console.log(person); // should print  Object { name="John"}

_x000D_
_x000D_
    var key = "name";_x000D_
    var person = {[key]:"John"};_x000D_
    console.log(person); // should print  Object { name="John"}
_x000D_
_x000D_
_x000D_

Its called Computed Property Names, its implemented using bracket notation( square brackets) []

Example: { [variableName] : someValue }

Starting with ECMAScript 2015, the object initializer syntax also supports computed property names. That allows you to put an expression in brackets [], that will be computed and used as the property name.

For ES5, try something like this

var yourObject = {};

yourObject[yourKey] = "yourValue";

console.log(yourObject );

example:

var person = {};
var key = "name";

person[key] /* this is same as person.name */ = "John";

console.log(person); // should print  Object { name="John"}

_x000D_
_x000D_
    var person = {};_x000D_
    var key = "name";_x000D_
    _x000D_
    person[key] /* this is same as person.name */ = "John";_x000D_
    _x000D_
    console.log(person); // should print  Object { name="John"}
_x000D_
_x000D_
_x000D_

How find out which process is using a file in Linux?

You can use the fuser command, like:

fuser file_name

You will receive a list of processes using the file.

You can use different flags with it, in order to receive a more detailed output.

You can find more info in the fuser's Wikipedia article, or in the man pages.

How to remove pip package after deleting it manually

I met the same issue while experimenting with my own Python library and what I've found out is that pip freeze will show you the library as installed if your current directory contains lib.egg-info folder. And pip uninstall <lib> will give you the same error message.

  1. Make sure your current directory doesn't have any egg-info folders
  2. Check pip show <lib-name> to see the details about the location of the library, so you can remove files manually.

How to make flutter app responsive according to different screen size?

I've been knocking other people's (@datayeah & Vithani Ravi) solutions a bit hard here, so I thought I'd share my own attempt[s] at solving this variable screen density scaling problem or shut up. So I approach this problem from a solid/fixed foundation: I base all my scaling off a fixed (immutable) ratio of 2:1 (height:width). I have a helper class "McGyver" that does all the heavy lifting (and useful code finessing) across my app. This "McGyver" class contains only static methods and static constant class members.

RATIO SCALING METHOD: I scale both width & height independently based on the 2:1 Aspect Ratio. I take width & height input values and divide each by the width & height constants and finally compute an adjustment factor by which to scale the respective width & height input values. The actual code looks as follows:

import 'dart:math';
import 'package:flutter/material.dart';

class McGyver {

  static const double _fixedWidth = 410;    // Set to an Aspect Ratio of 2:1 (height:width)
  static const double _fixedHeight = 820;   // Set to an Aspect Ratio of 2:1 (height:width) 

  // Useful rounding method (@andyw solution -> https://stackoverflow.com/questions/28419255/how-do-you-round-a-double-in-dart-to-a-given-degree-of-precision-after-the-decim/53500405#53500405)
  static double roundToDecimals(double val, int decimalPlaces){
    double mod = pow(10.0, decimalPlaces);
    return ((val * mod).round().toDouble() / mod);
  }

  // The 'Ratio-Scaled' Widget method (takes any generic widget and returns a "Ratio-Scaled Widget" - "rsWidget")
  static Widget rsWidget(BuildContext ctx, Widget inWidget, double percWidth, double percHeight) {

    // ---------------------------------------------------------------------------------------------- //
    // INFO: Ratio-Scaled "SizedBox" Widget - Scaling based on device's height & width at 2:1 ratio.  //
    // ---------------------------------------------------------------------------------------------- //

    final int _decPlaces = 5;
    final double _fixedWidth = McGyver._fixedWidth;
    final double _fixedHeight = McGyver._fixedHeight;

    Size _scrnSize = MediaQuery.of(ctx).size;                // Extracts Device Screen Parameters.
    double _scrnWidth = _scrnSize.width.floorToDouble();     // Extracts Device Screen maximum width.
    double _scrnHeight = _scrnSize.height.floorToDouble();   // Extracts Device Screen maximum height.

    double _rsWidth = 0;
    if (_scrnWidth == _fixedWidth) {   // If input width matches fixedWidth then do normal scaling.
      _rsWidth = McGyver.roundToDecimals((_scrnWidth * (percWidth / 100)), _decPlaces);
    } else {   // If input width !match fixedWidth then do adjustment factor scaling.
      double _scaleRatioWidth = McGyver.roundToDecimals((_scrnWidth / _fixedWidth), _decPlaces);
      double _scalerWidth = ((percWidth + log(percWidth + 1)) * pow(1, _scaleRatioWidth)) / 100;
      _rsWidth = McGyver.roundToDecimals((_scrnWidth * _scalerWidth), _decPlaces);
    }

    double _rsHeight = 0;
    if (_scrnHeight == _fixedHeight) {   // If input height matches fixedHeight then do normal scaling.
      _rsHeight = McGyver.roundToDecimals((_scrnHeight * (percHeight / 100)), _decPlaces);
    } else {   // If input height !match fixedHeight then do adjustment factor scaling.
      double _scaleRatioHeight = McGyver.roundToDecimals((_scrnHeight / _fixedHeight), _decPlaces);
      double _scalerHeight = ((percHeight + log(percHeight + 1)) * pow(1, _scaleRatioHeight)) / 100;
      _rsHeight = McGyver.roundToDecimals((_scrnHeight * _scalerHeight), _decPlaces);
    }

    // Finally, hand over Ratio-Scaled "SizedBox" widget to method call.
    return SizedBox(
      width: _rsWidth,
      height: _rsHeight,
      child: inWidget,
    );
  }

}

... ... ...

Then you would individually scale your widgets (which for my perfectionist disease is ALL of my UI) with a simple static call to the "rsWidget()" method as follows:

  // Step 1: Define your widget however you like (this widget will be supplied as the "inWidget" arg to the "rsWidget" method in Step 2)...
  Widget _btnLogin = RaisedButton(color: Colors.blue, elevation: 9.0, 
                                  shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(McGyver.rsDouble(context, ScaleType.width, 2.5))),
                                  child: McGyver.rsText(context, "LOGIN", percFontSize: EzdFonts.button2_5, textColor: Colors.white, fWeight: FontWeight.bold),
                                  onPressed: () { _onTapBtnLogin(_tecUsrId.text, _tecUsrPass.text); }, );

  // Step 2: Scale your widget by calling the static "rsWidget" method...
  McGyver.rsWidget(context, _btnLogin, 34.5, 10.0)   // ...and Bob's your uncle!!

The cool thing is that the "rsWidget()" method returns a widget!! So you can either assign the scaled widget to another variable like _rsBtnLogin for use all over the place - or you could simply use the full McGyver.rsWidget() method call in-place inside your build() method (exactly how you need it to be positioned in the widget tree) and it will work perfectly as it should.

For those more astute coders: you will have noticed that I used two additional ratio-scaled methods McGyver.rsText() and McGyver.rsDouble() (not defined in the code above) in my RaisedButton() - so I basically go crazy with this scaling stuff...because I demand my apps to be absolutely pixel perfect at any scale or screen density!! I ratio-scale my ints, doubles, padding, text (everything that requires UI consistency across devices). I scale my texts based on width only, but specify which axis to use for all other scaling (as was done with the ScaleType.width enum used for the McGyver.rsDouble() call in the code example above).

I know this is crazy - and is a lot of work to do on the main thread - but I am hoping somebody will see my attempt here and help me find a better (more light-weight) solution to my screen density 1:1 scaling nightmares.

How do I check if an object has a key in JavaScript?

You should use hasOwnProperty. For example:

myObj.hasOwnProperty('myKey');

Note: If you are using ESLint, the above may give you an error for violating the no-prototype-builtins rule, in that case the workaround is as below:

Object.prototype.hasOwnProperty.call(myObj, 'myKey');

JS: iterating over result of getElementsByClassName using Array.forEach

Here is a test I created on jsperf: https://jsperf.com/vanillajs-loop-through-elements-of-class

The most perfomant version in Chrome and Firefox is the good old for loop in combination with document.getElementsByClassName:

var elements = document.getElementsByClassName('testClass'), elLength = elements.length;
for (var i = 0; i < elLength; i++) {
    elements.item(i).textContent = 'Tested';
};

In Safari this variant is the winner:

var elements = document.querySelectorAll('.testClass');
elements.forEach((element) => {
    element.textContent = 'Tested';
});

If you want the most perfomant variant for all browsers it might be this one:

var elements = document.getElementsByClassName('testClass');
Array.from(elements).map(
    (element) => {
        return element.textContent = 'Tested';
    }
);

You should not use <Link> outside a <Router>

I kinda come up with this code :

import React from 'react';
import { render } from 'react-dom';

// import componentns
import Main from './components/Main';
import PhotoGrid from './components/PhotoGrid';
import Single from './components/Single';

// import react router
import { Router, Route, IndexRoute, BrowserRouter, browserHistory} from 'react-router-dom'

class MainComponent extends React.Component {
  render() {
    return (
      <div>
        <BrowserRouter history={browserHistory}>
          <Route path="/" component={Main} >
            <IndexRoute component={PhotoGrid}></IndexRoute>
            <Route path="/view/:postId" component={Single}></Route>
          </Route>
        </BrowserRouter>
      </div>
    );
  }
}

render(<MainComponent />, document.getElementById('root'));

I think the error was because you were rendering the Main component, and the Main component didn't know anything about Router, so you have to render its father component.

How can I get the IP address from NIC in Python?

If you only need to work on Unix, you can use a system call (ref. Stack Overflow question Parse ifconfig to get only my IP address using Bash):

import os
f = os.popen('ifconfig eth0 | grep "inet\ addr" | cut -d: -f2 | cut -d" " -f1')
your_ip=f.read()

Is calling destructor manually always a sign of bad design?

No, you shouldn't call it explicitly because it would be called twice. Once for the manual call and another time when the scope in which the object is declared ends.

Eg.

{
  Class c;
  c.~Class();
}

If you really need to perform the same operations you should have a separate method.

There is a specific situation in which you may want to call a destructor on a dynamically allocated object with a placement new but it doesn't sound something you will ever need.

Measuring execution time of a function in C++

#include <iostream>
#include <chrono>

void function()
{
    // code here;
}

int main()
{
    auto t1 = std::chrono::high_resolution_clock::now();
    function();
    auto t2 = std::chrono::high_resolution_clock::now();

    auto duration = std::chrono::duration_cast<std::chrono::microseconds>( t2 - t1 ).count();

    std::cout << duration<<"/n";
    return 0;
}

This Worked for me.


Note:

The high_resolution_clock is not implemented consistently across different standard library implementations, and its use should be avoided. It is often just an alias for std::chrono::steady_clock or std::chrono::system_clock, but which one it is depends on the library or configuration. When it is a system_clock, it is not monotonic (e.g., the time can go backwards).

For example, for gcc's libstdc++ it is system_clock, for MSVC it is steady_clock, and for clang's libc++ it depends on configuration.

Generally one should just use std::chrono::steady_clock or std::chrono::system_clock directly instead of std::chrono::high_resolution_clock: use steady_clock for duration measurements, and system_clock for wall-clock time.

"Cannot evaluate expression because the code of the current method is optimized" in Visual Studio 2010

For me it was happening in VS2017 and VS2019. It stopped happening after I selected the option "Suppressed JIT optimization on module load".

enter image description here

How do I comment out a block of tags in XML?

Syntax for XML : <!--Your comment-->

eg.

   <?xml version = "1.0" encoding = "UTF-8" ?>
   <!--here is your comment :) -->
   <class_list>   
   <student>
   <name></name>
   <grade>A</grade>
   </student>
   </class_list>

XML Comments Rules

Comments cannot appear before XML declaration.
Comments may appear anywhere in a document.
Comments must not appear within attribute values.
Comments cannot be nested inside the other comments.

Get the year from specified date php

You can achieve your goal by using php date() & explode() functions:

$date = date("2068-06-15");

$date_arr = explode("-", $date);

$yr = $date_arr[0];

echo $yr;

That is it. Happy coding :)

Of Countries and their Cities

https://code.google.com/p/worlddb/downloads/list

Open World Database alpha

This database has multi languages country names, region names, city names and they's latitude and longitude number and country's alpha2 code .

Global Events in Angular

There is no equivalent to $scope.emit() or $scope.broadcast() from AngularJS. EventEmitter inside of a component comes close, but as you mentioned, it will only emit an event to the immediate parent component.

In Angular, there are other alternatives which I'll try to explain below.

@Input() bindings allows the application model to be connected in a directed object graph (root to leaves). The default behavior of a component's change detector strategy is to propagate all changes to an application model for all bindings from any connected component.

Aside: There are two types of models: View Models and Application Models. An application model is connected through @Input() bindings. A view model is a just a component property (not decorated with @Input()) which is bound in the component's template.

To answer your questions:

What if I need to communicate between sibling components?

  1. Shared Application Model: Siblings can communicate through a shared application model (just like angular 1). For example, when one sibling makes a change to a model, the other sibling that has bindings to the same model is automatically updated.

  2. Component Events: Child components can emit an event to the parent component using @Output() bindings. The parent component can handle the event, and manipulate the application model or it's own view model. Changes to the Application Model are automatically propagated to all components that directly or indirectly bind to the same model.

  3. Service Events: Components can subscribe to service events. For example, two sibling components can subscribe to the same service event and respond by modifying their respective models. More on this below.

How can I communicate between a Root component and a component nested several levels deep?

  1. Shared Application Model: The application model can be passed from the Root component down to deeply nested sub-components through @Input() bindings. Changes to a model from any component will automatically propagate to all components that share the same model.
  2. Service Events: You can also move the EventEmitter to a shared service, which allows any component to inject the service and subscribe to the event. That way, a Root component can call a service method (typically mutating the model), which in turn emits an event. Several layers down, a grand-child component which has also injected the service and subscribed to the same event, can handle it. Any event handler that changes a shared Application Model, will automatically propagate to all components that depend on it. This is probably the closest equivalent to $scope.broadcast() from Angular 1. The next section describes this idea in more detail.

Example of an Observable Service that uses Service Events to Propagate Changes

Here is an example of an observable service that uses service events to propagate changes. When a TodoItem is added, the service emits an event notifying its component subscribers.

export class TodoItem {
    constructor(public name: string, public done: boolean) {
    }
}
export class TodoService {
    public itemAdded$: EventEmitter<TodoItem>;
    private todoList: TodoItem[] = [];

    constructor() {
        this.itemAdded$ = new EventEmitter();
    }

    public list(): TodoItem[] {
        return this.todoList;
    }

    public add(item: TodoItem): void {
        this.todoList.push(item);
        this.itemAdded$.emit(item);
    }
}

Here is how a root component would subscribe to the event:

export class RootComponent {
    private addedItem: TodoItem;
    constructor(todoService: TodoService) {
        todoService.itemAdded$.subscribe(item => this.onItemAdded(item));
    }

    private onItemAdded(item: TodoItem): void {
        // do something with added item
        this.addedItem = item;
    }
}

A child component nested several levels deep would subscribe to the event in the same way:

export class GrandChildComponent {
    private addedItem: TodoItem;
    constructor(todoService: TodoService) {
        todoService.itemAdded$.subscribe(item => this.onItemAdded(item));
    }

    private onItemAdded(item: TodoItem): void {
        // do something with added item
        this.addedItem = item;
    }
}

Here is the component that calls the service to trigger the event (it can reside anywhere in the component tree):

@Component({
    selector: 'todo-list',
    template: `
         <ul>
            <li *ngFor="#item of model"> {{ item.name }}
            </li>
         </ul>
        <br />
        Add Item <input type="text" #txt /> <button (click)="add(txt.value); txt.value='';">Add</button>
    `
})
export class TriggeringComponent{
    private model: TodoItem[];

    constructor(private todoService: TodoService) {
        this.model = todoService.list();
    }

    add(value: string) {
        this.todoService.add(new TodoItem(value, false));
    }
}

Reference: Change Detection in Angular

How to compile a c++ program in Linux?

Try this:

g++ -o hi hi.cpp

gcc is only for C

Passing parameters from jsp to Spring Controller method

Use the @RequestParam to pass a parameter to the controller handler method. In the jsp your form should have an input field with name = "id" like the following:

<input type="text" name="id" />
<input type="submit" />

Then in your controller, your handler method should be like the following:

@RequestMapping("listNotes")
public String listNotes(@RequestParam("id") int id) {
    Person person = personService.getCurrentlyAuthenticatedUser();
    model.addAttribute("person", new Person());
    model.addAttribute("listPersons", this.personService.listPersons());
    model.addAttribute("listNotes", this.notesService.listNotesBySectionId(id, person));
    return "note";
}

Please also refer to these answers and tutorial:

Angular2: custom pipe could not be found

A really dumb answer (I'll vote myself down in a minute), but this worked for me:

After adding your pipe, if you're still getting the errors and are running your Angular site using "ng serve", stop it... then start it up again.

For me, none of the other suggestions worked, but simply stopping, then restarting "ng serve" was enough to make the error go away.

Strange.

Where can I find the assembly System.Web.Extensions dll?

I had this issue when converting an older project to use a new version of Visual Studio. Upon conversion, the project target framework was set to 2.0

I was able to solve this issue by changing the target framework to be 3.5.

Parsing arguments to a Java command line program

Simple code for command line in java:

class CMDLineArgument
{
    public static void main(String args[])
    {
        String name=args[0];
        System.out.println(name);
    }
}

What is an idiomatic way of representing enums in Go?

There is a way with struct namespace.

The benefit is all enum variables are under a specific namespace to avoid pollution. The issue is that we could only use var not const

type OrderStatusType string

var OrderStatus = struct {
    APPROVED         OrderStatusType
    APPROVAL_PENDING OrderStatusType
    REJECTED         OrderStatusType
    REVISION_PENDING OrderStatusType
}{
    APPROVED:         "approved",
    APPROVAL_PENDING: "approval pending",
    REJECTED:         "rejected",
    REVISION_PENDING: "revision pending",
}

jQuery UI 1.10: dialog and zIndex option

Add zIndex property to dialog object:

$(elm).dialog(
 zIndex: 10000
);

How to restore the dump into your running mongodb

To restore a single database:

1. Backup the 'users' database
$ mongodump --db users

2. Restore the 'users' database to a new database called 'users2'
$ mongorestore --db users2 dump/users

To restore all databases:

1. Backup all databases
$ mongodump

2. Restore all databases
$ mongorestore dump

Open files always in a new tab

enabling using GUI

go to Code -> Preferences -> Settings -> User -> Window -> New Window

here Open Files In New Window under drop down list select "on" that's it.

my VS Code version 1.38.1

Validate form field only on submit or user input

If you want to show error messages on form submission, you can use condition form.$submitted to check if an attempt was made to submit the form. Check following example.

<form name="myForm" novalidate ng-submit="myForm.$valid && createUser()">
  <input type="text" name="name" ng-model="user.name" placeholder="Enter name of user" required>
  <div ng-messages="myForm.name.$error" ng-if="myForm.$submitted">
    <div ng-message="required">Please enter user name.</div>
  </div>

  <input type="text" name="address" ng-model="user.address" placeholder="Enter Address" required ng-maxlength="30">
  <div ng-messages="myForm.name.$error" ng-if="myForm.$submitted">
    <div ng-message="required">Please enter user address.</div>
    <div ng-message="maxlength">Should be less than 30 chars</div>
  </div>

  <button type="submit">
    Create user
  </button>
</form>

Find indices of elements equal to zero in a NumPy array

You can use numpy.nonzero to find zero.

>>> import numpy as np
>>> x = np.array([1,0,2,0,3,0,0,4,0,5,0,6]).reshape(4, 3)
>>> np.nonzero(x==0)  # this is what you want
(array([0, 1, 1, 2, 2, 3]), array([1, 0, 2, 0, 2, 1]))
>>> np.nonzero(x)
(array([0, 0, 1, 2, 3, 3]), array([0, 2, 1, 1, 0, 2]))

Why doesn't document.addEventListener('load', function) work in a greasemonkey script?

Apparently, document.addEventListener() is unreliable, and hence, my error. Use window.addEventListener() with the same parameters, instead.

Setting focus to iframe contents

i had a similar problem where i was trying to focus on a txt area in an iframe loaded from another page. in most cases it work. There was an issue where it would fire in FF when the iFrame was loaded but before it was visible. so the focus never seemed to be set correctly.

i worked around this with a simular solution to cheeming's answer above

    var iframeID = document.getElementById("modalIFrame"); 
//focus the IFRAME element 
$(iframeID).focus(); 
//use JQuery to find the control in the IFRAME and set focus 
$(iframeID).contents().find("#emailTxt").focus(); 

TokenMismatchException in VerifyCsrfToken.php Line 67

I got this error when uploading large files (videos). Form worked fine, no mismatch error, but as soon as someone attached a large video file it would throw this token error. Adjusting the maximum allowable file size and increasing the processing time solved this problem for me. Not sure why Laravel throws this error in this case, but here's one more potential solution for you.

Here's a StackOverflow answer that goes into more detail about how to go about solving the large file upload issue.

PHP change the maximum upload file size

Create an array of integers property in Objective-C

This works

@interface RGBComponents : NSObject {

    float components[8];

}

@property(readonly) float * components;

- (float *) components {
    return components;
}

update columns values with column of another table based on condition

Something like this should do it :

UPDATE table1 
   SET table1.Price = table2.price 
   FROM table1  INNER JOIN  table2 ON table1.id = table2.id

You can also try this:

UPDATE table1 
   SET price=(SELECT price FROM table2 WHERE table1.id=table2.id);

how to use the Box-Cox power transformation in R

Box and Cox (1964) suggested a family of transformations designed to reduce nonnormality of the errors in a linear model. In turns out that in doing this, it often reduces non-linearity as well.

Here is a nice summary of the original work and all the work that's been done since: http://www.ime.usp.br/~abe/lista/pdfm9cJKUmFZp.pdf

You will notice, however, that the log-likelihood function governing the selection of the lambda power transform is dependent on the residual sum of squares of an underlying model (no LaTeX on SO -- see the reference), so no transformation can be applied without a model.

A typical application is as follows:

library(MASS)

# generate some data
set.seed(1)
n <- 100
x <- runif(n, 1, 5)
y <- x^3 + rnorm(n)

# run a linear model
m <- lm(y ~ x)

# run the box-cox transformation
bc <- boxcox(y ~ x)

enter image description here

(lambda <- bc$x[which.max(bc$y)])
[1] 0.4242424

powerTransform <- function(y, lambda1, lambda2 = NULL, method = "boxcox") {

  boxcoxTrans <- function(x, lam1, lam2 = NULL) {

    # if we set lambda2 to zero, it becomes the one parameter transformation
    lam2 <- ifelse(is.null(lam2), 0, lam2)

    if (lam1 == 0L) {
      log(y + lam2)
    } else {
      (((y + lam2)^lam1) - 1) / lam1
    }
  }

  switch(method
         , boxcox = boxcoxTrans(y, lambda1, lambda2)
         , tukey = y^lambda1
  )
}


# re-run with transformation
mnew <- lm(powerTransform(y, lambda) ~ x)

# QQ-plot
op <- par(pty = "s", mfrow = c(1, 2))
qqnorm(m$residuals); qqline(m$residuals)
qqnorm(mnew$residuals); qqline(mnew$residuals)
par(op)

enter image description here

As you can see this is no magic bullet -- only some data can be effectively transformed (usually a lambda less than -2 or greater than 2 is a sign you should not be using the method). As with any statistical method, use with caution before implementing.

To use the two parameter Box-Cox transformation, use the geoR package to find the lambdas:

library("geoR")
bc2 <- boxcoxfit(x, y, lambda2 = TRUE)

lambda1 <- bc2$lambda[1]
lambda2 <- bc2$lambda[2]

EDITS: Conflation of Tukey and Box-Cox implementation as pointed out by @Yui-Shiuan fixed.

Fatal error: [] operator not supported for strings

I had similar situation:

$foo = array();
$foo[] = 'test'; // error    
$foo[] = "test"; // working fine

Find all stored procedures that reference a specific column in some table

One option is to create a script file.

Right click on the database -> Tasks -> Generate Scripts

Then you can select all the stored procedures and generate the script with all the sps. So you can find the reference from there.

Or

-- Search in All Objects
SELECT OBJECT_NAME(OBJECT_ID),
definition
FROM sys.sql_modules
WHERE definition LIKE '%' + 'CreatedDate' + '%'
GO

-- Search in Stored Procedure Only
SELECT DISTINCT OBJECT_NAME(OBJECT_ID),
object_definition(OBJECT_ID)
FROM sys.Procedures
WHERE object_definition(OBJECT_ID) LIKE '%' + 'CreatedDate' + '%'
GO

Source SQL SERVER – Find Column Used in Stored Procedure – Search Stored Procedure for Column Name

Expression must be a modifiable lvalue

In C, you will also experience the same error if you declare a:

char array[size];

and than try to assign a value without specifying an index position:

array = '\0'; 

By doing:

array[index] = '0\';

You're specifying the accessible/modifiable address previously declared.

How can I enter latitude and longitude in Google Maps?

You don't need to convert to decimal; you can also enter 46 23S, 115 22E. You can add seconds after the minutes, also separated by a space.

Raise error in a Bash script

There are a couple more ways with which you can approach this problem. Assuming one of your requirement is to run a shell script/function containing a few shell commands and check if the script ran successfully and throw errors in case of failures.

The shell commands in generally rely on exit-codes returned to let the shell know if it was successful or failed due to some unexpected events.

So what you want to do falls upon these two categories

  • exit on error
  • exit and clean-up on error

Depending on which one you want to do, there are shell options available to use. For the first case, the shell provides an option with set -e and for the second you could do a trap on EXIT

Should I use exit in my script/function?

Using exit generally enhances readability In certain routines, once you know the answer, you want to exit to the calling routine immediately. If the routine is defined in such a way that it doesn’t require any further cleanup once it detects an error, not exiting immediately means that you have to write more code.

So in cases if you need to do clean-up actions on script to make the termination of the script clean, it is preferred to not to use exit.

Should I use set -e for error on exit?

No!

set -e was an attempt to add "automatic error detection" to the shell. Its goal was to cause the shell to abort any time an error occurred, but it comes with a lot of potential pitfalls for example,

  • The commands that are part of an if test are immune. In the example, if you expect it to break on the test check on the non-existing directory, it wouldn't, it goes through to the else condition

    set -e
    f() { test -d nosuchdir && echo no dir; }
    f
    echo survived
    
  • Commands in a pipeline other than the last one, are immune. In the example below, because the most recently executed (rightmost) command's exit code is considered ( cat) and it was successful. This could be avoided by setting by the set -o pipefail option but its still a caveat.

    set -e
    somecommand that fails | cat -
    echo survived 
    

Recommended for use - trap on exit

The verdict is if you want to be able to handle an error instead of blindly exiting, instead of using set -e, use a trap on the ERR pseudo signal.

The ERR trap is not to run code when the shell itself exits with a non-zero error code, but when any command run by that shell that is not part of a condition (like in if cmd, or cmd ||) exits with a non-zero exit status.

The general practice is we define an trap handler to provide additional debug information on which line and what cause the exit. Remember the exit code of the last command that caused the ERR signal would still be available at this point.

cleanup() {
    exitcode=$?
    printf 'error condition hit\n' 1>&2
    printf 'exit code returned: %s\n' "$exitcode"
    printf 'the command executing at the time of the error was: %s\n' "$BASH_COMMAND"
    printf 'command present on line: %d' "${BASH_LINENO[0]}"
    # Some more clean up code can be added here before exiting
    exit $exitcode
}

and we just use this handler as below on top of the script that is failing

trap cleanup ERR

Putting this together on a simple script that contained false on line 15, the information you would be getting as

error condition hit
exit code returned: 1
the command executing at the time of the error was: false
command present on line: 15

The trap also provides options irrespective of the error to just run the cleanup on shell completion (e.g. your shell script exits), on signal EXIT. You could also trap on multiple signals at the same time. The list of supported signals to trap on can be found on the trap.1p - Linux manual page

Another thing to notice would be to understand that none of the provided methods work if you are dealing with sub-shells are involved in which case, you might need to add your own error handling.

  • On a sub-shell with set -e wouldn't work. The false is restricted to the sub-shell and never gets propagated to the parent shell. To do the error handling here, add your own logic to do (false) || false

    set -e
    (false)
    echo survived
    
  • The same happens with trap also. The logic below wouldn't work for the reasons mentioned above.

    trap 'echo error' ERR
    (false)
    

CodeIgniter - return only one row?

This is better way as it gives you result in a single line:

$this->db->query("Your query")->row()->campaign_id;

Insert line at middle of file with Python?

A simple but not efficient way is to read the whole content, change it and then rewrite it:

line_index = 3
lines = None
with open('file.txt', 'r') as file_handler:
    lines = file_handler.readlines()

lines.insert(line_index, 'Charlie')

with open('file.txt', 'w') as file_handler:
    file_handler.writelines(lines)

How can I read input from the console using the Scanner class in Java?

You can use the Scanner class in Java

Scanner scan = new Scanner(System.in);
String s = scan.nextLine();
System.out.println("String: " + s);

Waiting for HOME ('android.process.acore') to be launched

I solved this issue by creating a new virtual device and launching it from the AVD manager. The device takes a few minutes to start, you just have to wait. Then you can run your application on the already started device.

How do I find out my python path using python?

import sys
for a in sys.path:
    a.replace('\\\\','\\')
    print(a)

It will give all the paths ready for place in the Windows.

How to resolve Unneccessary Stubbing exception

If you're using this style instead:

@Rule
public MockitoRule rule = MockitoJUnit.rule().strictness(Strictness.STRICT_STUBS);

replace it with:

@Rule
public MockitoRule rule = MockitoJUnit.rule().silent();

Add values to app.config and retrieve them

sorry for late answer but may be my code may help u.

I placed 3 buttons on the winform surface. button1 & 2 will set different value and button3 will retrieve current value. so when run my code first add the reference System.configuration

and click on first button and then click on 3rd button to see what value has been set. next time again click on second & 3rd button to see again what value has been set after change.

so here is the code.

using System.Configuration;

 private void button1_Click(object sender, EventArgs e)
{
    Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
    config.AppSettings.Settings.Remove("DBServerName");
    config.AppSettings.Settings.Add("DBServerName", "FirstAddedValue1");
    config.Save(ConfigurationSaveMode.Modified);
}

private void button2_Click(object sender, EventArgs e)
{
    Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
    config.AppSettings.Settings.Remove("DBServerName");
    config.AppSettings.Settings.Add("DBServerName", "SecondAddedValue1");
    config.Save(ConfigurationSaveMode.Modified);
}

private void button3_Click(object sender, EventArgs e)
{
    Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
          MessageBox.Show(config.AppSettings.Settings["DBServerName"].Value);
}

Bash mkdir and subfolders

To create multiple sub-folders

mkdir -p parentfolder/{subfolder1,subfolder2,subfolder3}

Cannot import keras after installation

Ran to the same issue, Assuming your using anaconda3 and your using a venv with >= python=3.6:

python -m pip install keras
sudo python -m pip install --user tensorflow

Why can't Python parse this JSON data?

data = []
with codecs.open('d:\output.txt','rU','utf-8') as f:
    for line in f:
       data.append(json.loads(line))

What is unexpected T_VARIABLE in PHP?

There might be a semicolon or bracket missing a line before your pasted line.

It seems fine to me; every string is allowed as an array index.

Windows shell command to get the full path to the current directory?

As one of the possible codes

    echo off
    for /f "usebackq tokens=* delims= " %%x in (`chdir`) do set var=%var% %%x
    echo The current directory is: "%var:~1%"

HTML: How to center align a form

<center><form></form></center>    

does work in most cases like The Wobbuffet mentioned above...

How to log a method's execution time exactly in milliseconds?

I use this:

clock_t start, end;
double elapsed;
start = clock();

//Start code to time

//End code to time

end = clock();
elapsed = ((double) (end - start)) / CLOCKS_PER_SEC;
NSLog(@"Time: %f",elapsed);

But I'm not sure about CLOCKS_PER_SEC on the iPhone. You might want to leave it off.

Fire event on enter key press for a textbox

my jQuery powered solution is below :)

Text Element:

<asp:TextBox ID="txtTextBox" ClientIDMode="Static" onkeypress="return EnterEvent(event);" runat="server"></asp:TextBox>
<asp:Button ID="btnSubmitButton" ClientIDMode="Static" OnClick="btnSubmitButton_Click" runat="server" Text="Submit Form" />

Javascript behind:

<script type="text/javascript" language="javascript">
    function fnCheckValue() {
        var myVal = $("#txtTextBox").val();
        if (myVal == "") {
            alert("Blank message");
            return false;
        }
        else {
            return true;
        }
    }

    function EnterEvent(e) {
        if (e.keyCode == 13) {
            if (fnCheckValue()) {
                $("#btnSubmitButton").trigger("click");
            } else {
                return false;
            }
        }
    }

    $("#btnSubmitButton").click(function () {
        return fnCheckValue();
    });
</script>

How to cut an entire line in vim and paste it?

  1. Go to the line, and first press esc, and then Shift + v.

(This would have highlighted the line)

  1. press d

(The line is now deleted)

  1. Go to the location, where you wanted to paste the line, and hit p.

In a nutshell,

Esc -> Shift + v -> d -> p

What is the use of the @ symbol in PHP?

The @ symbol is the error control operator (aka the "silence" or "shut-up" operator). It makes PHP suppress any error messages (notice, warning, fatal, etc) generated by the associated expression. It works just like a unary operator, for example, it has a precedence and associativity. Below are some examples:

@echo 1 / 0;
// generates "Parse error: syntax error, unexpected T_ECHO" since 
// echo is not an expression

echo @(1 / 0);
// suppressed "Warning: Division by zero"

@$i / 0;
// suppressed "Notice: Undefined variable: i"
// displayed "Warning: Division by zero"

@($i / 0);
// suppressed "Notice: Undefined variable: i"
// suppressed "Warning: Division by zero"

$c = @$_POST["a"] + @$_POST["b"];
// suppressed "Notice: Undefined index: a"
// suppressed "Notice: Undefined index: b"

$c = @foobar();
echo "Script was not terminated";
// suppressed "Fatal error: Call to undefined function foobar()"
// however, PHP did not "ignore" the error and terminated the
// script because the error was "fatal"

What exactly happens if you use a custom error handler instead of the standard PHP error handler:

If you have set a custom error handler function with set_error_handler() then it will still get called, but this custom error handler can (and should) call error_reporting() which will return 0 when the call that triggered the error was preceded by an @.

This is illustrated in the following code example:

function bad_error_handler($errno, $errstr, $errfile, $errline, $errcontext) {
    echo "[bad_error_handler]: $errstr";
    return true;
}
set_error_handler("bad_error_handler");
echo @(1 / 0);
// prints "[bad_error_handler]: Division by zero"

The error handler did not check if @ symbol was in effect. The manual suggests the following:

function better_error_handler($errno, $errstr, $errfile, $errline, $errcontext) {
    if(error_reporting() !== 0) {
        echo "[better_error_handler]: $errstr";
    }
    // take appropriate action
    return true;
}

Set disable attribute based on a condition for Html.TextBoxFor

If you don't use html helpers you may use simple ternary expression like this:

<input name="Field"
       value="@Model.Field" tabindex="0"
       @(Model.IsDisabledField ? "disabled=\"disabled\"" : "")>

Getting list of files in documents folder

Apple states about NSSearchPathForDirectoriesInDomains(_:_:_:):

You should consider using the FileManager methods urls(for:in:) and url(for:in:appropriateFor:create:) which return URLs, which are the preferred format.


With Swift 5, FileManager has a method called contentsOfDirectory(at:includingPropertiesForKeys:options:). contentsOfDirectory(at:includingPropertiesForKeys:options:) has the following declaration:

Performs a shallow search of the specified directory and returns URLs for the contained items.

func contentsOfDirectory(at url: URL, includingPropertiesForKeys keys: [URLResourceKey]?, options mask: FileManager.DirectoryEnumerationOptions = []) throws -> [URL]

Therefore, in order to retrieve the urls of the files contained in documents directory, you can use the following code snippet that uses FileManager's urls(for:in:) and contentsOfDirectory(at:includingPropertiesForKeys:options:) methods:

guard let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return }

do {
    let directoryContents = try FileManager.default.contentsOfDirectory(at: documentsDirectory, includingPropertiesForKeys: nil, options: [])

    // Print the urls of the files contained in the documents directory
    print(directoryContents)
} catch {
    print("Could not search for urls of files in documents directory: \(error)")
}

As an example, the UIViewController implementation below shows how to save a file from app bundle to documents directory and how to get the urls of the files saved in documents directory:

import UIKit

class ViewController: UIViewController {

    @IBAction func copyFile(_ sender: UIButton) {
        // Get file url
        guard let fileUrl = Bundle.main.url(forResource: "Movie", withExtension: "mov") else { return }

        // Create a destination url in document directory for file
        guard let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return }
        let documentDirectoryFileUrl = documentsDirectory.appendingPathComponent("Movie.mov")

        // Copy file to document directory
        if !FileManager.default.fileExists(atPath: documentDirectoryFileUrl.path) {
            do {
                try FileManager.default.copyItem(at: fileUrl, to: documentDirectoryFileUrl)
                print("Copy item succeeded")
            } catch {
                print("Could not copy file: \(error)")
            }
        }
    }

    @IBAction func displayUrls(_ sender: UIButton) {
        guard let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return }

        do {
            let directoryContents = try FileManager.default.contentsOfDirectory(at: documentsDirectory, includingPropertiesForKeys: nil, options: [])

            // Print the urls of the files contained in the documents directory
            print(directoryContents) // may print [] or [file:///private/var/mobile/Containers/Data/Application/.../Documents/Movie.mov]
        } catch {
            print("Could not search for urls of files in documents directory: \(error)")
        }
    }

}

href="tel:" and mobile numbers

The BlackBerry browser and Safari for iOS (iPhone/iPod/iPad) automatically detect phone numbers and email addresses and convert them to links. If you don’t want this feature, you should use the following meta tags.

For Safari:

<meta name="format-detection" content="telephone=no">

For BlackBerry:

<meta http-equiv="x-rim-auto-match" content="none">

Source: mobilexweb.com

Common Header / Footer with static HTML

The most practical way is to use Server Side Include. It's very easy to implement and saves tons of work when you have more than a couple pages.

Displaying standard DataTables in MVC

Here is the answer in Razor syntax

 <table border="1" cellpadding="5">
    <thead>
       <tr>
          @foreach (System.Data.DataColumn col in Model.Columns)
          {
             <th>@col.Caption</th>
          }
       </tr>
    </thead>
    <tbody>
    @foreach(System.Data.DataRow row in Model.Rows)
    {
       <tr>
          @foreach (var cell in row.ItemArray)
          {
             <td>@cell.ToString()</td>
          }
       </tr>
    }      
    </tbody>
</table>

How do I use a third-party DLL file in Visual Studio C++?

In order to use Qt with dynamic linking you have to specify the lib files (usually qtmaind.lib, QtCored4.lib and QtGuid4.lib for the "Debug" configration) in
Properties » Linker » Input » Additional Dependencies.

You also have to specify the path where the libs are, namely in
Properties » Linker » General » Additional Library Directories.

And you need to make the corresponding .dlls are accessible at runtime, by either storing them in the same folder as your .exe or in a folder that is on your path.

Create Word Document using PHP in Linux

real Word documents

If you need to produce "real" Word documents you need a Windows-based web server and COM automation. I highly recommend Joel's article on this subject.

fake HTTP headers for tricking Word into opening raw HTML

A rather common (but unreliable) alternative is:

header("Content-type: application/vnd.ms-word");
header("Content-Disposition: attachment; filename=document_name.doc");

echo "<html>";
echo "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=Windows-1252\">";
echo "<body>";
echo "<b>Fake word document</b>";
echo "</body>";
echo "</html>"

Make sure you don't use external stylesheets. Everything should be in the same file.

Note that this does not send an actual Word document. It merely tricks browsers into offering it as download and defaulting to a .doc file extension. Older versions of Word may often open this without any warning/security message, and just import the raw HTML into Word. PHP sending sending that misleading Content-Type header along does not constitute a real file format conversion.

How to specify different Debug/Release output directories in QMake .pro file

I have a more compact approach:

release: DESTDIR = build/release
debug:   DESTDIR = build/debug

OBJECTS_DIR = $$DESTDIR/.obj
MOC_DIR = $$DESTDIR/.moc
RCC_DIR = $$DESTDIR/.qrc
UI_DIR = $$DESTDIR/.ui

How do I URL encode a string

In my case where the last component was Arabic letters I did the following in Swift 2.2:

extension String {

 func encodeUTF8() -> String? {

    //If I can create an NSURL out of the string nothing is wrong with it
    if let _ = NSURL(string: self) {

        return self
    }

    //Get the last component from the string this will return subSequence
    let optionalLastComponent = self.characters.split { $0 == "/" }.last


    if let lastComponent = optionalLastComponent {

        //Get the string from the sub sequence by mapping the characters to [String] then reduce the array to String
        let lastComponentAsString = lastComponent.map { String($0) }.reduce("", combine: +)


        //Get the range of the last component
        if let rangeOfLastComponent = self.rangeOfString(lastComponentAsString) {
            //Get the string without its last component
            let stringWithoutLastComponent = self.substringToIndex(rangeOfLastComponent.startIndex)


            //Encode the last component
            if let lastComponentEncoded = lastComponentAsString.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.alphanumericCharacterSet()) {


            //Finally append the original string (without its last component) to the encoded part (encoded last component)
            let encodedString = stringWithoutLastComponent + lastComponentEncoded

                //Return the string (original string/encoded string)
                return encodedString
            }
        }
    }

    return nil;
}
}

usage:

let stringURL = "http://xxx.dev.com/endpoint/nonLatinCharacters"

if let encodedStringURL = stringURL.encodeUTF8() {

    if let url = NSURL(string: encodedStringURL) {

      ...
    }

} 

AcquireConnection method call to the connection manager <Excel Connection Manager> failed with error code 0xC0202009

Hi This can be solved by changing the prorperty of the project in the solution explorer then give false to 64bit runtime option

How can I make a div not larger than its contents?

Tampering around with Firebug I found the property value -moz-fit-content which exactly does what the OP wanted and could be used as follow:

width: -moz-fit-content;

Although it only works on Firefox, I couldn't find any equivalent for other browsers such as Chrome.

dynamically add and remove view to viewpager

I find a good solution for this issue, this solution can make it work and no need to recreate Fragments.
My key point is:

  1. setup ViewPager every time you delete or add Tab(Fragment).
  2. Override the getItemId method, return a specific id rather than position.

Source Code

package com.zq.testviewpager;

import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;

import android.widget.TextView;

import java.util.ArrayList;
import java.util.Arrays;
/**
 * Created by [email protected] on 2017/5/31.
 * Implement dynamic delete or add tab(TAB_C in this test code).
 */
public class MainActivity extends AppCompatActivity {

    private static final int TAB_A = 1001;
    private static final int TAB_B = 1002;
    private static final int TAB_C = 1003;
    private static final int TAB_D = 1004;
    private static final int TAB_E = 1005;
    private Tab[] tabsArray = new Tab[]{new Tab(TAB_A, "A"),new Tab(TAB_B, "B"),new Tab(TAB_C, "C"),new Tab(TAB_D, "D"),new Tab(TAB_E, "E")};

    private ArrayList<Tab> mTabs = new ArrayList<>(Arrays.asList(tabsArray));

    private Tab[] tabsArray2 = new Tab[]{new Tab(TAB_A, "A"),new Tab(TAB_B, "B"),new Tab(TAB_D, "D"),new Tab(TAB_E, "E")};

    private ArrayList<Tab> mTabs2 = new ArrayList<>(Arrays.asList(tabsArray2));

    /**
     * The {@link android.support.v4.view.PagerAdapter} that will provide
     * fragments for each of the sections. We use a
     * {@link FragmentPagerAdapter} derivative, which will keep every
     * loaded fragment in memory. If this becomes too memory intensive, it
     * may be best to switch to a
     * {@link android.support.v4.app.FragmentStatePagerAdapter}.
     */
    private SectionsPagerAdapter mSectionsPagerAdapter;

    /**
     * The {@link ViewPager} that will host the section contents.
     */
    private ViewPager mViewPager;
    private TabLayout tabLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        // Create the adapter that will return a fragment for each of the three
        // primary sections of the activity.
        mSectionsPagerAdapter = new SectionsPagerAdapter(mTabs, getSupportFragmentManager());

        // Set up the ViewPager with the sections adapter.
        mViewPager = (ViewPager) findViewById(R.id.container);
        mViewPager.setAdapter(mSectionsPagerAdapter);

        tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(mViewPager);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }else if (id == R.id.action_delete) {
            int currentItemPosition = mViewPager.getCurrentItem();
            Tab currentTab = mTabs.get(currentItemPosition);

            if(currentTab.id == TAB_C){
                currentTab = mTabs.get(currentItemPosition == 0 ? currentItemPosition +1 : currentItemPosition - 1);
            }

            mSectionsPagerAdapter = new SectionsPagerAdapter(mTabs2, getSupportFragmentManager());
            mViewPager.setAdapter(mSectionsPagerAdapter);
            tabLayout.setupWithViewPager(mViewPager);


            mViewPager.setCurrentItem(mTabs2.indexOf(currentTab), false);
            return true;
        }else if (id == R.id.action_add) {

            int currentItemPosition = mViewPager.getCurrentItem();
            Tab currentTab = mTabs2.get(currentItemPosition);

            mSectionsPagerAdapter = new SectionsPagerAdapter(mTabs, getSupportFragmentManager());
            mViewPager.setAdapter(mSectionsPagerAdapter);
            tabLayout.setupWithViewPager(mViewPager);

            mViewPager.setCurrentItem(mTabs.indexOf(currentTab), false);
            return true;
        }else

        return super.onOptionsItemSelected(item);
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {
        /**
         * The fragment argument representing the section number for this
         * fragment.
         */
        private static final String ARG_SECTION_NUMBER = "section_number";

        public PlaceholderFragment() {
        }

        /**
         * Returns a new instance of this fragment for the given section
         * number.
         */
        public static PlaceholderFragment newInstance(int sectionNumber) {
            PlaceholderFragment fragment = new PlaceholderFragment();
            Bundle args = new Bundle();
            args.putInt(ARG_SECTION_NUMBER, sectionNumber);
            fragment.setArguments(args);
            return fragment;
        }

        @Override
        public void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            Log.e("TestViewPager", "onCreate"+getArguments().getInt(ARG_SECTION_NUMBER));
        }

        @Override
        public void onDestroy() {
            super.onDestroy();
            Log.e("TestViewPager", "onDestroy"+getArguments().getInt(ARG_SECTION_NUMBER));
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_main, container, false);
            TextView textView = (TextView) rootView.findViewById(R.id.section_label);
            textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
            return rootView;
        }
    }

    /**
     * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
     * one of the sections/tabs/pages.
     */
    public class SectionsPagerAdapter extends FragmentPagerAdapter {
        ArrayList<Tab> tabs;

        public SectionsPagerAdapter(ArrayList<Tab> tabs, FragmentManager fm) {
            super(fm);
            this.tabs = tabs;
        }

        @Override
        public Fragment getItem(int position) {
            // getItem is called to instantiate the fragment for the given page.
            // Return a PlaceholderFragment (defined as a static inner class below).
            return PlaceholderFragment.newInstance(tabs.get(position).id);
        }

        @Override
        public int getCount() {
            return tabs.size();
        }

        @Override
        public long getItemId(int position) {
            return tabs.get(position).id;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return tabs.get(position).title;
        }
    }

    private static class Tab {
        String title;
        public int id;

        Tab(int id, String title){
            this.id = id;
            this.title = title;
        }

        @Override
        public boolean equals(Object obj) {
            if(obj instanceof Tab){
                return ((Tab)obj).id == id;
            }else{
                return false;
            }
        }
    }
}

Code is at my Github Gist.

ES6 modules in the browser: Uncaught SyntaxError: Unexpected token import

Many modern browsers now support ES6 modules. As long as you import your scripts (including the entrypoint to your application) using <script type="module" src="..."> it will work.

Take a look at caniuse.com for more details: https://caniuse.com/#feat=es6-module

Describe table structure

Sql server

DECLARE @tableName nvarchar(100)
SET @tableName = N'members' -- change with table name
SELECT
    [column].*,
    COLUMNPROPERTY(object_id([column].[TABLE_NAME]), [column].[COLUMN_NAME], 'IsIdentity') AS [identity]
FROM 
    INFORMATION_SCHEMA.COLUMNS [column] 
WHERE
    [column].[Table_Name] = @tableName

How to use onSavedInstanceState example please

One major note that all new Android developers should know is that any information in Widgets (TextView, Buttons, etc.) will be persisted automatically by Android as long as you assign an ID to them. So that means most of the UI state is taken care of without issue. Only when you need to store other data does this become an issue.

From Android Docs:

The only work required by you is to provide a unique ID (with the android:id attribute) for each widget you want to save its state. If a widget does not have an ID, then it cannot save its state

Javascript | Set all values of an array

It's 2019 and you should be using this:

let arr = [...Array(20)].fill(10)

So basically 20 is the length or a new instantiated Array.

Excel: Searching for multiple terms in a cell

Try using COUNT function like this

=IF(COUNT(SEARCH({"Romney","Obama","Gingrich"},C1)),1,"")

Note that you don't need the wildcards (as teylyn says) and unless there's a specific reason "1" doesn't need quotes (in fact that makes it a text value)

Why is Spring's ApplicationContext.getBean considered bad?

There is another time when using getBean makes sense. If you're reconfiguring a system that already exists, where the dependencies are not explicitly called out in spring context files. You can start the process by putting in calls to getBean, so that you don't have to wire it all up at once. This way you can slowly build up your spring configuration putting each piece in place over time and getting the bits lined up properly. The calls to getBean will eventually be replaced, but as you understand the structure of the code, or lack there of, you can start the process of wiring more and more beans and using fewer and fewer calls to getBean.

Radio/checkbox alignment in HTML/CSS

There are several ways to implement it:

  1. For ASP.NET Standard CheckBox:

    .tdInputCheckBox
    { 
    position:relative;
    top:-2px;
    }
    <table>
            <tr>
                <td class="tdInputCheckBox">                  
                    <asp:CheckBox ID="chkMale" runat="server" Text="Male" />
                    <asp:CheckBox ID="chkFemale" runat="server" Text="Female" />
                </td>
            </tr>
    </table>
    
  2. For DevExpress CheckBox:

    <dx:ASPxCheckBox ID="chkAccept" runat="server" Text="Yes" Layout="Flow"/>
    <dx:ASPxCheckBox ID="chkAccept" runat="server" Text="No" Layout="Flow"/>
    
  3. For RadioButtonList:

    <asp:RadioButtonList ID="rdoAccept" runat="server" RepeatDirection="Horizontal">
       <asp:ListItem>Yes</asp:ListItem>
       <asp:ListItem>No</asp:ListItem>
    </asp:RadioButtonList>
    
  4. For Required Field Validators:

    <asp:TextBox ID="txtEmailId" runat="server"></asp:TextBox>
    <asp:RequiredFieldValidator ID="reqEmailId" runat="server" ErrorMessage="Email id is required." Display="Dynamic" ControlToValidate="txtEmailId"></asp:RequiredFieldValidator>
    <asp:RegularExpressionValidator ID="regexEmailId" runat="server" ErrorMessage="Invalid Email Id." ControlToValidate="txtEmailId" Text="*"></asp:RegularExpressionValidator>`
    

Parse JSON String into a Particular Object Prototype in JavaScript

The currently accepted answer wasn't working for me. You need to use Object.assign() properly:

class Person {
    constructor(name, age){
        this.name = name;
        this.age = age;
    }

    greet(){
        return `hello my name is ${ this.name } and i am ${ this.age } years old`;
    }
}

You create objects of this class normally:

let matt = new Person('matt', 12);
console.log(matt.greet()); // prints "hello my name is matt and i am 12 years old"

If you have a json string you need to parse into the Person class, do it like so:

let str = '{"name": "john", "age": 15}';
let john = JSON.parse(str); // parses string into normal Object type

console.log(john.greet()); // error!!

john = Object.assign(Person.prototype, john); // now john is a Person type
console.log(john.greet()); // now this works

ADB not recognising Nexus 4 under Windows 7

I had a similar problem, and none of the previous solutions worked for me, and I've just solved it by myself (after a few hours of frustration), so I'm going to share my solution.

My computer suddenly stopped recognizing any Android device I've plugged in after it installed Android Composite ADB Interface for my Nexus 4. I was not able to uninstall the driver, because any attempt to do so by Device Manager was unsuccessful (Device Manager stopped responding every time).

So I've solved it this way:

  1. Switch Windows into safe mode
  2. Uninstall Android Composite ADB Interface
  3. Install old SAMSUNG Android ADB Interface
  4. Switch Windows into normal mode
  5. Plug-in Android device (Nexus 4 in my case)
  6. Windows recognized the device as Nexus 4
  7. Install driver from android-sdk/extras/google folder
  8. Everything works again! :)

How to round an average to 2 decimal places in PostgreSQL?

you can use the function below

 SELECT TRUNC(14.568,2);

the result will show :

14.56

you can also cast your variable to the desire type :

 SELECT TRUNC(YOUR_VAR::numeric,2)

Best way to format integer as string with leading zeros?

For Python 3 and beyond: str.zfill() is still the most readable option

But it is a good idea to look into the new and powerful str.format(), what if you want to pad something that is not 0?

    # if we want to pad 22 with zeros in front, to be 5 digits in length:
    str_output = '{:0>5}'.format(22)
    print(str_output)
    # >>> 00022
    # {:0>5} meaning: ":0" means: pad with 0, ">" means move 22 to right most, "5" means the total length is 5

    # another example for comparision
    str_output = '{:#<4}'.format(11)
    print(str_output)
    # >>> 11##

    # to put it in a less hard-coded format:
    int_inputArg = 22
    int_desiredLength = 5
    str_output = '{str_0:0>{str_1}}'.format(str_0=int_inputArg, str_1=int_desiredLength)
    print(str_output)
    # >>> 00022

this is error ORA-12154: TNS:could not resolve the connect identifier specified?

ORA-12154: TNS:could not resolve the connect identifier specified?

In case the TNS is not defined you can also try this one:

If you are using C#.net 2010 or other version of VS and oracle 10g express edition or lower version, and you make a connection string like this:

static string constr = @"Data Source=(DESCRIPTION=
    (ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=yourhostname )(PORT=1521)))
    (CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=XE)));
    User Id=system ;Password=yourpasswrd"; 

After that you get error message ORA-12154: TNS:could not resolve the connect identifier specified then first you have to do restart your system and run your project.

And if Your windows is 64 bit then you need to install oracle 11g 32 bit and if you installed 11g 64 bit then you need to Install Oracle 11g Oracle Data Access Components (ODAC) with Oracle Developer Tools for Visual Studio version 11.2.0.1.2 or later from OTN and check it in Oracle Universal Installer Please be sure that the following are checked:

Oracle Data Provider for .NET 2.0

Oracle Providers for ASP.NET

Oracle Developer Tools for Visual Studio

Oracle Instant Client 

And then restart your Visual Studio and then run your project .... NOTE:- SYSTEM RESTART IS necessary TO SOLVE THIS TYPES OF ERROR.......

How to compress a String in Java?

You don't see any compression happening for your String, As you atleast require couple of hundred bytes to have real compression using GZIPOutputStream or ZIPOutputStream. Your String is too small.(I don't understand why you require compression for same)

Check Conclusion from this article:

The article also shows how to compress and decompress data on the fly in order to reduce network traffic and improve the performance of your client/server applications. Compressing data on the fly, however, improves the performance of client/server applications only when the objects being compressed are more than a couple of hundred bytes. You would not be able to observe improvement in performance if the objects being compressed and transferred are simple String objects, for example.

Ripple effect on Android Lollipop CardView

Ripple event for android Cardview control:

<android.support.v7.widget.CardView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:foreground="?android:attr/selectableItemBackground"
    android:clickable="true"
    android:layout_marginBottom="4dp"
    android:layout_marginTop="4dp" />

How to save SELECT sql query results in an array in C# Asp.net

    public void ChargingArraySelect()
    {
        int loop = 0;
        int registros = 0;

        OdbcConnection conn = WebApiConfig.conn();
        OdbcCommand query = conn.CreateCommand();

        query.CommandText = "select dataA, DataB, dataC, DataD FROM table  where dataA = 'xpto'";

        try
        {
            conn.Open();
            OdbcDataReader dr = query.ExecuteReader();

            //take the number the registers, to use into next step
            registros = dr.RecordsAffected;

            //calls an array to be populated
            Global.arrayTest = new string[registros, 4];

            while (dr.Read())
            {
                if (loop < registros)
                {
                    Global.arrayTest[i, 0] = Convert.ToString(dr["dataA"]);
                    Global.arrayTest[i, 1] = Convert.ToString(dr["dataB"]);
                    Global.arrayTest[i, 2] = Convert.ToString(dr["dataC"]);
                    Global.arrayTest[i, 3] = Convert.ToString(dr["dataD"]);
                }
                loop++;
            }
        }
    }


    //Declaration the Globais Array in Global Classs
    private static string[] uso_internoArray1;
    public static string[] arrayTest
    {
        get { return uso_internoArray1; }
        set { uso_internoArray1 = value; }
    }

Cannot make a static reference to the non-static method fxn(int) from the type Two

Since the main method is static and the fxn() method is not, you can't call the method without first creating a Two object. So either you change the method to:

public static int fxn(int y) {
    y = 5;
    return y;
}

or change the code in main to:

Two two = new Two();
x = two.fxn(x);

Read more on static here in the Java Tutorials.

Why is my CSS bundling not working with a bin deployed MVC4 app?

Omitting runAllManagedModulesForAllRequests="true" also worked for me. Add the following configuration in web.config:

<modules>
  <remove name="BundleModule" />
  <add name="BundleModule" type="System.Web.Optimization.BundleModule" />
</modules>

runAllManagedModulesForAllRequests will impose a performance hit on your website if not used appropriately. Check out this article.

jquery remove "selected" attribute of option?

The question is asked in a misleading manner. "Removing the selected attribute" and "deselecting all options" are entirely different things.

To deselect all options in a documented, cross-browser manner use either

$("select").val([]);

or

// Note the use of .prop instead of .attr
$("select option").prop("selected", false);

Is there any method to get the URL without query string?

Here are two methods:

<script type="text/javascript">
    var s="http://localhost/dms/mduserSecurity/UIL/index.php?menu=true&submenu
                                =true&pcode=1235";

    var st=s.substring(0, s.indexOf("?"));

    alert(st);

    alert(s.replace(/\?.*/,''));
</script>

How to create XML file with specific structure in Java

Use JAXB: http://www.mkyong.com/java/jaxb-hello-world-example/

package com.mkyong.core;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Customer {

    String name;
    int age;
    int id;

    public String getName() {
        return name;
    }

    @XmlElement
    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    @XmlElement
    public void setAge(int age) {
        this.age = age;
    }

    public int getId() {
        return id;
    }

    @XmlAttribute
    public void setId(int id) {
        this.id = id;
    }

}
package com.mkyong.core;

import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

public class JAXBExample {
    public static void main(String[] args) {

      Customer customer = new Customer();
      customer.setId(100);
      customer.setName("mkyong");
      customer.setAge(29);

      try {

        File file = new File("C:\\file.xml");
        JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

        // output pretty printed
        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        jaxbMarshaller.marshal(customer, file);
        jaxbMarshaller.marshal(customer, System.out);

      } catch (JAXBException e) {
        e.printStackTrace();
      }

    }
}

How to wait for 2 seconds?

As mentioned in other answers, all of the following will work for the standard string-based syntax.

WAITFOR DELAY '02:00' --Two hours
WAITFOR DELAY '00:02' --Two minutes
WAITFOR DELAY '00:00:02' --Two seconds
WAITFOR DELAY '00:00:00.200' --Two tenths of a seconds

There is also an alternative method of passing it a DATETIME value. You might think I'm confusing this with WAITFOR TIME, but it also works for WAITFOR DELAY.

Considerations for passing DATETIME:

  • It must be passed as a variable, so it isn't a nice one-liner anymore.
  • The delay is measured as the time since the Epoch ('1900-01-01').
  • For situations that require a variable amount of delay, it is much easier to manipulate a DATETIME than to properly format a VARCHAR.

How to wait for 2 seconds:

--Example 1
DECLARE @Delay1 DATETIME
SELECT @Delay1 = '1900-01-01 00:00:02.000'
WAITFOR DELAY @Delay1

--Example 2
DECLARE @Delay2 DATETIME
SELECT @Delay2 = dateadd(SECOND, 2, convert(DATETIME, 0))
WAITFOR DELAY @Delay2

A note on waiting for TIME vs DELAY:

Have you ever noticed that if you accidentally pass WAITFOR TIME a date that already passed, even by just a second, it will never return? Check it out:

--Example 3
DECLARE @Time1 DATETIME
SELECT @Time1 = getdate()
WAITFOR DELAY '00:00:01'
WAITFOR TIME @Time1 --WILL HANG FOREVER

Unfortunately, WAITFOR DELAY will do the same thing if you pass it a negative DATETIME value (yes, that's a thing).

--Example 4
DECLARE @Delay3 DATETIME
SELECT @Delay3 = dateadd(SECOND, -1, convert(DATETIME, 0))
WAITFOR DELAY @Delay3 --WILL HANG FOREVER

However, I would still recommend using WAITFOR DELAY over a static time because you can always confirm your delay is positive and it will stay that way for however long it takes your code to reach the WAITFOR statement.

The controller for path was not found or does not implement IController

If appropriate to your design, you can make sure the access modifier on your controller class is 'public', not something that could limit access like 'internal' or 'private'.

MySQL: can't access root account

There is a section in the MySQL manual on how to reset the root password which will solve your problem.

argparse module How to add option without any argument?

As @Felix Kling suggested use action='store_true':

>>> from argparse import ArgumentParser
>>> p = ArgumentParser()
>>> _ = p.add_argument('-f', '--foo', action='store_true')
>>> args = p.parse_args()
>>> args.foo
False
>>> args = p.parse_args(['-f'])
>>> args.foo
True

How to call a asp:Button OnClick event using JavaScript?

If you're open to using jQuery:

<script type="text/javascript">
 function fncsave()
 {
    $('#<%= savebtn.ClientID %>').click();
 }
</script>

Also, if you are using .NET 4 or better you can make the ClientIDMode == static and simplify the code:

<script type="text/javascript">
 function fncsave()
 {
    $("#savebtn").click();
 }
</script>

Reference: MSDN Article for Control.ClientIDMode

com.google.android.gms:play-services-measurement-base is being requested by various other libraries

I was having an error The library com.google.android.gms:play-services-measurement-base is being requested by various other libraries at [[16.0.2,16.0.2]], but resolves to 16.0.0. Disable the plugin and check your dependencies tree using ./gradlew :app:dependencies.

Running ./gradlew :app:dependencies will reveal what dependencies are requiring wrong dependencies (the ones in the square bracket). For me the problem was coming from firebase-core:16.0.3 as shown below. I fixed it by downgrading firebase-core to 16.0.1

+--- com.google.firebase:firebase-core:16.0.3
|    +--- com.google.firebase:firebase-analytics:16.0.3
|    |    +--- com.google.android.gms:play-services-basement:15.0.1
|    |    |    \--- com.android.support:support-v4:26.1.0 (*)
|    |    +--- com.google.android.gms:play-services-measurement-api:[16.0.1] -> 16.0.1
|    |    |    +--- com.google.android.gms:play-services-ads-identifier:15.0.1
|    |    |    |    \--- com.google.android.gms:play-services-basement:[15.0.1,16.0.0) -> 15.0.1 (*)
|    |    |    +--- com.google.android.gms:play-services-basement:15.0.1 (*)
|    |    |    +--- com.google.android.gms:play-services-measurement-base:[16.0.2] -> 16.0.2

Error : getaddrinfo ENOTFOUND registry.npmjs.org registry.npmjs.org:443

I had the same issue. The reason was the corporate proxy issue. Solution was to set the proxy setting as @rsp says.

npm config set proxy http://example.com:8080
npm config set https-proxy http://example.com:8080

But later I face the same issue. This time reason was my password contains a special character.

In this command you can’t provide a password with special character

. So solution is to provide percentage encoded special character in the password.

For example # has to provide as %23

https://www.w3schools.com/tags/ref_urlencode.asp

Jquery UI Datepicker not displaying

If you are using the scripts of metro UI css (excellent free metro UI set from http://metroui.org.ua/) , that can clash too. In my case, this was the problem recently.

So, removed the scripts reference of metro UI (as I was not using its components), datepicker is showing.

But you cant get metro look for datepicker of jQuery-ui

But in most cases, as others mentioned, its clash with duplicate versions of jQuery-UI javascripts.

How to "crop" a rectangular image into a square with CSS?

I actually came across this same problem recently and ended up with a slightly different approach (I wasn't able to use background images). It does require a tiny bit of jQuery though to determine the orientation of the images (I' sure you could use plain JS instead though).

I wrote a blog post about it if you are interested in more explaination but the code is pretty simple:

HTML:

<ul class="cropped-images">
  <li><img src="http://fredparke.com/sites/default/files/cat-portrait.jpg" /></li>
  <li><img src="http://fredparke.com/sites/default/files/cat-landscape.jpg" /></li>
</ul>

CSS:

li {
  width: 150px; // Or whatever you want.
  height: 150px; // Or whatever you want.
  overflow: hidden;
  margin: 10px;
  display: inline-block;
  vertical-align: top;
}
li img {
  max-width: 100%;
  height: auto;
  width: auto;
}
li img.landscape {
  max-width: none;
  max-height: 100%;
}

jQuery:

$( document ).ready(function() {

    $('.cropped-images img').each(function() {
      if ($(this).width() > $(this).height()) {
        $(this).addClass('landscape');        
      }
    });

});

Sites not accepting wget user agent header

I created a ~/.wgetrc file with the following content (obtained from askapache.com but with a newer user agent, because otherwise it didn’t work always):

header = Accept-Language: en-us,en;q=0.5
header = Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
header = Connection: keep-alive
user_agent = Mozilla/5.0 (X11; Fedora; Linux x86_64; rv:40.0) Gecko/20100101 Firefox/40.0
referer = /
robots = off

Now I’m able to download from most (all?) file-sharing (streaming video) sites.

Get user's non-truncated Active Directory groups from command line

A little stale post, but I figured what the heck. Does "whoami" meet your needs?

I just found out about it today (from the same Google search that brought me here, in fact). Windows has had a whoami tool since XP (part of an add on toolkit) and has been built-in since Vista.

whoami /groups

Lists all the AD groups for the currently logged-on user. I believe it does require you to be logged on AS that user, though, so this won't help if your use case requires the ability to run the command to look at another user.

Group names only:

whoami /groups /fo list |findstr /c:"Group Name:"

Pass in an array of Deferreds to $.when()

I want to propose other one with using $.each:

  1. We may to declare ajax function like:

    function ajaxFn(someData) {
        this.someData = someData;
        var that = this;
        return function () {
            var promise = $.Deferred();
            $.ajax({
                method: "POST",
                url: "url",
                data: that.someData,
                success: function(data) {
                    promise.resolve(data);
                },
                error: function(data) {
                    promise.reject(data);
                }
            })
            return promise;
        }
    }
    
  2. Part of code where we creating array of functions with ajax to send:

    var arrayOfFn = [];
    for (var i = 0; i < someDataArray.length; i++) {
        var ajaxFnForArray = new ajaxFn(someDataArray[i]);
        arrayOfFn.push(ajaxFnForArray);
    }
    
  3. And calling functions with sending ajax:

    $.when(
        $.each(arrayOfFn, function(index, value) {
            value.call()
        })
    ).then(function() {
            alert("Cheer!");
        }
    )
    

How to get the day of week and the month of the year?

Yes, you'll need arrays.

var days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
var months = ['January','February','March','April','May','June','July','August','September','October','November','December'];

var day = days[ now.getDay() ];
var month = months[ now.getMonth() ];

Or you can use the date.js library.


EDIT:

If you're going to use these frequently, you may want to extend Date.prototype for accessibility.

(function() {
    var days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];

    var months = ['January','February','March','April','May','June','July','August','September','October','November','December'];

    Date.prototype.getMonthName = function() {
        return months[ this.getMonth() ];
    };
    Date.prototype.getDayName = function() {
        return days[ this.getDay() ];
    };
})();

var now = new Date();

var day = now.getDayName();
var month = now.getMonthName();

rename the columns name after cbind the data

You can also name columns directly in the cbind call, e.g.

cbind(date=c(0,1), high=c(2,3))

Output:

     date high
[1,]    0    2
[2,]    1    3

hibernate could not get next sequence value

I would also like to add a few notes about a MySQL-to-PostgreSQL migration:

  1. In your DDL, in the object naming prefer the use of '_' (underscore) character for word separation to the camel case convention. The latter works fine in MySQL but brings a lot of issues in PostgreSQL.
  2. The IDENTITY strategy for @GeneratedValue annotation in your model class-identity fields works fine for PostgreSQLDialect in hibernate 3.2 and superior. Also, The AUTO strategy is the typical setting for MySQLDialect.
  3. If you annotate your model classes with @Table and set a literal value to these equal to the table name, make sure you did create the tables to be stored under public schema.

That's as far as I remember now, hope these tips can spare you a few minutes of trial and error fiddling!

Website screenshots

It's in Python, but going over the documentation and code you can see exactly how this is done. If you can run python, then it's a ready-made solution for you:

http://browsershots.org/

Note that everything can run on one machine for one platform, or one machine with virtual machines running the other platforms.

Free, open source, scroll to bottom of page for links to documentation, source code, and other information.

Testing web application on Mac/Safari when I don't own a Mac

The best site to test website and see them realtime on MAC Safari is by using

Browserstack

They have like 25 free minutes of first time testing and then 10 free mins each day..You can even test your pages from your local PC by using their WEB TUNNEL Feature

I tested 7 to 8 pages in browserstack...And I think they have some java debugging tool in the upper right corner that is great help

What is the best way to conditionally apply attributes in AngularJS?

<h1 ng-attr-contenteditable="{{isTrue || undefined }}">{{content.title}}</h1>

will produce when isTrue=true : <h1 contenteditable="true">{{content.title}}</h1>

and when isTrue=false : <h1>{{content.title}}</h1>

Why is it bad practice to call System.gc()?

Yes, calling System.gc() doesn't guarantee that it will run, it's a request to the JVM that may be ignored. From the docs:

Calling the gc method suggests that the Java Virtual Machine expend effort toward recycling unused objects

It's almost always a bad idea to call it because the automatic memory management usually knows better than you when to gc. It will do so when its internal pool of free memory is low, or if the OS requests some memory be handed back.

It might be acceptable to call System.gc() if you know that it helps. By that I mean you've thoroughly tested and measured the behaviour of both scenarios on the deployment platform, and you can show it helps. Be aware though that the gc isn't easily predictable - it may help on one run and hurt on another.

How to convert an ASCII character into an int in C

Are you searching for this:

int c = some_ascii_character;

Or just converting without assignment:

(int)some_aschii_character;

IN vs OR in the SQL WHERE Clause

I did a SQL query in a large number of OR (350). Postgres do it 437.80ms.

Use OR

Now use IN:

Use IN

23.18ms

How do I set the selenium webdriver get timeout?

The timeouts() methods are not implemented in some drivers and are very unreliable in general.
I use a separate thread for the timeouts (passing the url to access as the thread name):

Thread t = new Thread(new Runnable() {
    public void run() {
        driver.get(Thread.currentThread().getName());
    }
}, url);
t.start();
try {
    t.join(YOUR_TIMEOUT_HERE_IN_MS);
} catch (InterruptedException e) { // ignore
}
if (t.isAlive()) { // Thread still alive, we need to abort
    logger.warning("Timeout on loading page " + url);
    t.interrupt();
}

This seems to work most of the time, however it might happen that the driver is really stuck and any subsequent call to driver will be blocked (I experience that with Chrome driver on Windows). Even something as innocuous as a driver.findElements() call could end up being blocked. Unfortunately I have no solutions for blocked drivers.

Can't connect to MySQL server on 'localhost' (10061)

Another possibility:

There are two ways the MySQL client can connect to the server: over TCP/IP, or using sockets. It's possible you have your MySQL server configured to support socket connections, but not network connections.

SecurityError: Blocked a frame with origin from accessing a cross-origin frame

If you have control over the content of the iframe - that is, if it is merely loaded in a cross-origin setup such as on Amazon Mechanical Turk - you can circumvent this problem with the <body onload='my_func(my_arg)'> attribute for the inner html.

For example, for the inner html, use the this html parameter (yes - this is defined and it refers to the parent window of the inner body element):

<body onload='changeForm(this)'>

In the inner html :

    function changeForm(window) {
        console.log('inner window loaded: do whatever you want with the inner html');
        window.document.getElementById('mturk_form').style.display = 'none';
    </script>

How to Load an Assembly to AppDomain with all references recursively?

http://support.microsoft.com/kb/837908/en-us

C# version:

Create a moderator class and inherit it from MarshalByRefObject:

class ProxyDomain : MarshalByRefObject
{
    public Assembly GetAssembly(string assemblyPath)
    {
        try
        {
            return Assembly.LoadFrom(assemblyPath);
        }
        catch (Exception ex)
        {
            throw new InvalidOperationException(ex.Message);
        }
    }
}

call from client site

ProxyDomain pd = new ProxyDomain();
Assembly assembly = pd.GetAssembly(assemblyFilePath);

MSSQL Select statement with incremental integer column... not from a table

It is ugly and performs badly, but technically this works on any table with at least one unique field AND works in SQL 2000.

SELECT (SELECT COUNT(*) FROM myTable T1 WHERE T1.UniqueField<=T2.UniqueField) as RowNum, T2.OtherField
FROM myTable T2
ORDER By T2.UniqueField

Note: If you use this approach and add a WHERE clause to the outer SELECT, you have to added it to the inner SELECT also if you want the numbers to be continuous.

file_put_contents(meta/services.json): failed to open stream: Permission denied

Suggest the correct permission, if for Apache,

sudo chown -R apache:apache apppath/app/storage

Android Room - simple select query - Cannot access database on the main thread

You cannot run it on main thread instead use handlers, async or working threads . A sample code is available here and read article over room library here : Android's Room Library

/**
 *  Insert and get data using Database Async way
 */
AsyncTask.execute(new Runnable() {
    @Override
    public void run() {
        // Insert Data
        AppDatabase.getInstance(context).userDao().insert(new User(1,"James","Mathew"));

        // Get Data
        AppDatabase.getInstance(context).userDao().getAllUsers();
    }
});

If you want to run it on main thread which is not preferred way .

You can use this method to achieve on main thread Room.inMemoryDatabaseBuilder()

How to generate graphs and charts from mysql database in php

I use highcharts. They are very interactive (and very fancy I might add). You do have to get a little creative to access data from MySQL database, but if you have a general understanding of JavaScript and PHP, you should have no problems.

Tkinter module not found on Ubuntu

The answer to your question is that Tkinter is renamed to tkinter in python3

that is with lowercase t

How to convert std::chrono::time_point to calendar datetime string with fractional seconds?

In my case I use chrono and c function localtime_r which is thread-safe (in opposition to std::localtime).

#include <iostream>
#include <chrono>
#include <ctime>
#include <time.h>
#include <iomanip>


int main() {
  std::chrono::system_clock::time_point now = std::chrono::system_clock::now();
  std::time_t currentTime = std::chrono::system_clock::to_time_t(now);
  std::chrono::milliseconds now2 = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch());
  struct tm currentLocalTime;
  localtime_r(&currentTime, &currentLocalTime);
  char timeBuffer[80];
  std::size_t charCount { std::strftime( timeBuffer, 80,
                                         "%b %d %T",
                                          &currentLocalTime)
                         };

  if (charCount == 0) return -1;

  std::cout << timeBuffer << "." << std::setfill('0') << std::setw(3) << now2.count() % 1000 << std::endl;
  return 0;
}

Oracle Not Equals Operator

They are the same, but i've heard people say that Developers use != while BA's use <>

Simple way to measure cell execution time in ipython notebook

import time
start = time.time()
"the code you want to test stays here"
end = time.time()
print(end - start)

Find and replace with a newline in Visual Studio Code

with v1.31.1 in RegEx mode the Replace All functionality is broken. clicking that button replaces only one instance

How to fix broken paste clipboard in VNC on Windows

I use Remote login with vnc-ltsp-config with GNOME Desktop Environment on CentOS 5.9. From experimenting today, I managed to get cut and paste working for the session and the login prompt (because I'm lazy and would rather copy and paste difficult passwords).

  1. I created a file vncconfig.desktop in the /etc/xdg/autostart directory which enabled cut and paste during the session after login. The vncconfig process is run as the logged in user.

    [Desktop Entry]
    Name=No name
    Encoding=UTF-8
    Version=1.0
    Exec=vncconfig -nowin
    X-GNOME-Autostart-enabled=true

  2. Added vncconfig -nowin & to the bottom of the file /etc/gdm/Init/Desktop which enabled cut and paste in the session during login but terminates after login. The vncconfig process is run as root.

  3. Adding vncconfig -nowin & to the bottom of the file /etc/gdm/PostLogin/Desktop also enabled cut and paste during the session after login. The vncconfig process is run as root however.

How to insert data into elasticsearch

If you are using KIBANA with elasticsearch then you can use below RESt request to create and put in the index.

CREATING INDEX:

http://localhost:9200/company
PUT company
{
  "settings": {
    "index": {
      "number_of_shards": 1,
      "number_of_replicas": 1
    },
    "analysis": {
      "analyzer": {
        "analyzer-name": {
          "type": "custom",
          "tokenizer": "keyword",
          "filter": "lowercase"
        }
      }
    }
  },
  "mappings": {
    "employee": {
      "properties": {
        "age": {
          "type": "long"
        },
        "experience": {
          "type": "long"
        },
        "name": {
          "type": "text",
          "analyzer": "analyzer-name"
        }
      }
    }
  }
}

CREATING DOCUMENT:

POST http://localhost:9200/company/employee/2/_create
{
"name": "Hemani",
"age" : 23,
"experienceInYears" : 2
}

How to choose between Hudson and Jenkins?

Jenkins is the new Hudson. It really is more like a rename, not a fork, since the whole development community moved to Jenkins. (Oracle is left sitting in a corner holding their old ball "Hudson", but it's just a soul-less project now.)

C.f. Ethereal -> WireShark

Default interface methods are only supported starting with Android N

You should use Java 8 to solve this, based on the Android documentation you can do this by

clicking File > Project Structure

and change Source Compatibility and Target Compatibility.

enter image description here

and you can also configure it directly in the app-level build.gradle file:

android {
  ...
  // Configure only for each module that uses Java 8
  // language features (either in its source code or
  // through dependencies).
  compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
  }
}

How many times a substring occurs

def count_substring(string, sub_string):
    inc = 0
    for i in range(0, len(string)):
        slice_object = slice(i,len(sub_string)+i)
        count = len(string[slice_object])
        if(count == len(sub_string)):
            if(sub_string == string[slice_object]):
                inc = inc + 1
    return inc

if __name__ == '__main__':
    string = input().strip()
    sub_string = input().strip()

    count = count_substring(string, sub_string)
    print(count)

"Debug certificate expired" error in Eclipse Android plugins

On a Mac, open the Terminal (current user's directory should open), cd ".android" ("ls" to validate debug.keystore is there). Finally "rm debug.keystore" to remove the file.

Shorter syntax for casting from a List<X> to a List<Y>?

dynamic data = List<x> val;  
List<y> val2 = ((IEnumerable)data).Cast<y>().ToList();

Binary search (bisection) in Python

This code works with integer lists in a recursive way. Looks for the simplest case scenario, which is: list length less than 2. It means the answer is already there and a test is performed to check for the correct answer. If not, a middle value is set and tested to be the correct, if not bisection is performed by calling again the function, but setting middle value as the upper or lower limit, by shifting it to the left or right

def binary_search(intList, intValue, lowValue, highValue):
    if(highValue - lowValue) < 2:
        return intList[lowValue] == intValue or intList[highValue] == intValue
    middleValue = lowValue + ((highValue - lowValue)/2)
    if intList[middleValue] == intValue:
        return True
    if intList[middleValue] > intValue:
        return binary_search(intList, intValue, lowValue, middleValue - 1)
   return binary_search(intList, intValue, middleValue + 1, highValue)

Android Crop Center of Bitmap

Probably the easiest solution so far:

public static Bitmap cropCenter(Bitmap bmp) {
    int dimension = Math.min(bmp.getWidth(), bmp.getHeight());
    return ThumbnailUtils.extractThumbnail(bmp, dimension, dimension);
}

imports:

import android.media.ThumbnailUtils;
import java.lang.Math;
import android.graphics.Bitmap;

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

I have the same problem too, after upgrading win7 to win10. then I check services.msc and found "World Wide Web Publishing Service" was running automatically by default. So then I disabled it, and running the Apache service again.

Large Numbers in Java

You can use the BigInteger class for integers and BigDecimal for numbers with decimal digits. Both classes are defined in java.math package.

Example:

BigInteger reallyBig = new BigInteger("1234567890123456890");
BigInteger notSoBig = new BigInteger("2743561234");
reallyBig = reallyBig.add(notSoBig);

This app won't run unless you update Google Play Services (via Bazaar)

After updating to ADT 22.0.1, due to Android private libraries, the Google Maps service was giving some error and the app crashed. So I found the solution finally and it worked for me.

Just install the Google Play service library and then go to google-play-service/libproject/google-play-services_lib from https://www.dropbox.com/sh/2ok76ep7lmav0qf/9XVlv61D2b. Import that into your workspace. Clean your project where you want to use gogole-play-services-lib and then build it again and go to the Project -> Properties -> Java BuildPath -> select "Android Private Libraries, Android Dependencies, google-play-service"

In Properties itself, go to Android and then choose any of the versions and then choose add and select google-play-service-lib and then press apply and finally OK.

At last, go to the Project -> Android Tools -> Android Support Libraries. Accept the license and after installing then run your project.

It will work fine.

How to fix 'Unchecked runtime.lastError: The message port closed before a response was received' chrome issue?

Post is rather old and not closely related to Chrome extensions development, but let it be here.

I had same problem when responding on message in callback. The solution is to return true in background message listener.

Here is simple example of background.js. It responses to any message from popup.js.

chrome.runtime.onMessage.addListener(function(rq, sender, sendResponse) {
    // setTimeout to simulate any callback (even from storage.sync)
    setTimeout(function() {
        sendResponse({status: true});
    }, 1);
    // return true;  // uncomment this line to fix error
});

Here is popup.js, which sends message on popup. You'll get exceptions until you un-comment "return true" line in background.js file.

document.addEventListener("DOMContentLoaded", () => {
    chrome.extension.sendMessage({action: "ping"}, function(resp) {
        console.log(JSON.stringify(resp));
    });
});

manifest.json, just in case :) Pay attention on alarm permissions section!

{
  "name": "TestMessages",
  "version": "0.1.0",
  "manifest_version": 2,
  "browser_action": {
    "default_popup": "src/popup.html"
  },
  "background": {
    "scripts": ["src/background.js"],
    "persistent": false
  },
  "permissions": [
    "alarms"
  ]
}

Missing artifact com.sun:tools:jar

I got this problem and it turns out that JBossDevStudio 9.1 on Windows is a 32-bit program. Eclipse, and thus the JBossDevStudio, does not work with the wrong type of JVM. 64-bit eclipse needs a 64-bit JVM, 32-bit eclipse needs a 32-bit JVM. Thus configuring Eclipse to run with my installed 64-bit JDK did not work.

Installing a 32 bit JDK and running Eclipse from that solved the problem.

At least for one of my projects, an other where I had tried to configure a runtime JDK in the Eclipse project properties is still broken.

I have Python on my Ubuntu system, but gcc can't find Python.h

On ubuntu you can just type sudo apt-get install python-dev -y in terminal to install the python-dev package.

Jquery how to find an Object by attribute in an Array

I have created a util service for my angular application. It have two function which use very often.

For example you have object.

First getting value from object recursively without throwing undefined error.

{prop: { nestedProp1: {nestedProp2: somevalue}}}; get nestedProp2 2 without undefined checks.

Second filter array on basis

[{prop: { nestedProp1: {nestedProp2: somevalue1}}}, {prop: { nestedProp1: {nestedProp2: somevalue2}}}];

Find object from array with nestedProp2=somevalue2

app.service('UtilService', function(httpService) {
this.mapStringKeyVal = function(map, field) {
    var lastIdentifiedVal = null;
    var parentVal = map;
    field.split('.').forEach(function(val){
        if(parentVal[val]){
            lastIdentifiedVal = parentVal[val]; 
            parentVal = parentVal[val]; 
        }
    });
    return lastIdentifiedVal;
}


this.arrayPropFilter = function(array, field,value) {
    var lastIdentifiedVal = null;
    var mapStringKeyVal = this.mapStringKeyVal;
    array.forEach(function(arrayItem){
        var valueFound = mapStringKeyVal(arrayItem,field);
        if(!lastIdentifiedVal  && valueFound && valueFound==value){
            lastIdentifiedVal = arrayItem;
        }
    });
    return lastIdentifiedVal;
}});

For solution for current question. inject UtilService and call,

UtilService.arrayPropFilter(purposeArray,'purpose','daily');

Or more advanced

UtilService.arrayPropFilter(purposeArray,'purpose.nestedProp1.nestedProp2','daily');

log4net hierarchy and logging levels

Try like this, it worked for me

<root>
  <!--<level value="ALL" />-->
  <level value="ERROR" />
  <level value="INFO" />
  <level value="WARN" />     
</root>

This logs 3 types of errors - error, info, and warning

Set cursor position on contentEditable <div>

After playing around I've modified eyelidlessness' answer above and made it a jQuery plugin so you can just do one of these:

var html = "The quick brown fox";
$div.html(html);

// Select at the text "quick":
$div.setContentEditableSelection(4, 5);

// Select at the beginning of the contenteditable div:
$div.setContentEditableSelection(0);

// Select at the end of the contenteditable div:
$div.setContentEditableSelection(html.length);

Excuse the long code post, but it may help someone:

$.fn.setContentEditableSelection = function(position, length) {
    if (typeof(length) == "undefined") {
        length = 0;
    }

    return this.each(function() {
        var $this = $(this);
        var editable = this;
        var selection;
        var range;

        var html = $this.html();
        html = html.substring(0, position) +
            '<a id="cursorStart"></a>' +
            html.substring(position, position + length) +
            '<a id="cursorEnd"></a>' +
            html.substring(position + length, html.length);
        console.log(html);
        $this.html(html);

        // Populates selection and range variables
        var captureSelection = function(e) {
            // Don't capture selection outside editable region
            var isOrContainsAnchor = false,
                isOrContainsFocus = false,
                sel = window.getSelection(),
                parentAnchor = sel.anchorNode,
                parentFocus = sel.focusNode;

            while (parentAnchor && parentAnchor != document.documentElement) {
                if (parentAnchor == editable) {
                    isOrContainsAnchor = true;
                }
                parentAnchor = parentAnchor.parentNode;
            }

            while (parentFocus && parentFocus != document.documentElement) {
                if (parentFocus == editable) {
                    isOrContainsFocus = true;
                }
                parentFocus = parentFocus.parentNode;
            }

            if (!isOrContainsAnchor || !isOrContainsFocus) {
                return;
            }

            selection = window.getSelection();

            // Get range (standards)
            if (selection.getRangeAt !== undefined) {
                range = selection.getRangeAt(0);

                // Get range (Safari 2)
            } else if (
                document.createRange &&
                selection.anchorNode &&
                selection.anchorOffset &&
                selection.focusNode &&
                selection.focusOffset
            ) {
                range = document.createRange();
                range.setStart(selection.anchorNode, selection.anchorOffset);
                range.setEnd(selection.focusNode, selection.focusOffset);
            } else {
                // Failure here, not handled by the rest of the script.
                // Probably IE or some older browser
            }
        };

        // Slight delay will avoid the initial selection
        // (at start or of contents depending on browser) being mistaken
        setTimeout(function() {
            var cursorStart = document.getElementById('cursorStart');
            var cursorEnd = document.getElementById('cursorEnd');

            // Don't do anything if user is creating a new selection
            if (editable.className.match(/\sselecting(\s|$)/)) {
                if (cursorStart) {
                    cursorStart.parentNode.removeChild(cursorStart);
                }
                if (cursorEnd) {
                    cursorEnd.parentNode.removeChild(cursorEnd);
                }
            } else if (cursorStart) {
                captureSelection();
                range = document.createRange();

                if (cursorEnd) {
                    range.setStartAfter(cursorStart);
                    range.setEndBefore(cursorEnd);

                    // Delete cursor markers
                    cursorStart.parentNode.removeChild(cursorStart);
                    cursorEnd.parentNode.removeChild(cursorEnd);

                    // Select range
                    selection.removeAllRanges();
                    selection.addRange(range);
                } else {
                    range.selectNode(cursorStart);

                    // Select range
                    selection.removeAllRanges();
                    selection.addRange(range);

                    // Delete cursor marker
                    document.execCommand('delete', false, null);
                }
            }

            // Register selection again
            captureSelection();
        }, 10);
    });
};

JavaScript private methods

Old question but this is a rather simple task that can be solved properly with core JS... without the Class abstraction of ES6. In fact as far as i can tell, the Class abstraction do not even solve this problem.

We can do this job both with the good old constructor function or even better with Object.create(). Lets go with the constructor first. This will essentially be a similar solution to georgebrock's answer which is criticised because all restaurants created by the Restaurant constructor will have the same private methods. I will try to overcome that limitation.

_x000D_
_x000D_
function restaurantFactory(name,menu){

  function Restaurant(name){
    this.name = name;
  }

  function prototypeFactory(menu){
    // This is a private function
    function calculateBill(item){
      return menu[item] || 0;
    }
    // This is the prototype to be
    return { constructor: Restaurant
           , askBill    : function(...items){
                            var cost = items.reduce((total,item) => total + calculateBill(item) ,0)
                            return "Thank you for dining at " + this.name + ". Total is: " + cost + "\n"
                          }
           , callWaiter : function(){
                            return "I have just called the waiter at " + this.name + "\n";
                          }
           }
  }

  Restaurant.prototype = prototypeFactory(menu);

  return new Restaurant(name,menu);
}

var menu = { water: 1
           , coke : 2
           , beer : 3
           , beef : 15
           , rice : 2
           },
    name = "Silver Scooop",
    rest = restaurantFactory(name,menu);

console.log(rest.callWaiter());
console.log(rest.askBill("beer", "beef"));
_x000D_
_x000D_
_x000D_

Now obviously we can not access menu from outside but we may easily rename the name property of a restaurant.

This can also be done with Object.create() in which case we skip the constructor function and simply do like var rest = Object.create(prototypeFactory(menu)) and add the name property to the rest object afterwards like rest.name = name.

Display calendar to pick a date in java

The LGoodDatePicker library includes a (swing) DatePicker component, which allows the user to choose dates from a calendar. (By default, the users can also type dates from the keyboard, but keyboard entry can be disabled if desired). The DatePicker has automatic data validation, which means (among other things) that any date that the user enters will always be converted to your desired date format.

Fair disclosure: I'm the primary developer.

Since the DatePicker is a swing component, you can add it to any other swing container including (in your scenario) the cells of a JTable.

The most commonly used date formats are automatically supported, and additional date formats can be added if desired.

To enforce your desired date format, you would most likely want to set your chosen format to be the default "display format" for the DatePicker. Formats can be specified by using the Java 8 DateTimeFormatter Patterns. No matter what the user types (or clicks), the date will always be converted to the specified format as soon as the user is done.

Besides the DatePicker, the library also has the TimePicker and DateTimePicker components. I pasted screenshots of all the components (and the demo program) below.

The library can be installed into your Java project from the project release page.

The project home page is on Github at:
https://github.com/LGoodDatePicker/LGoodDatePicker .


DateTimePicker screenshot


DateTimePicker examples


Demo screenshot

How should I unit test multithreaded code?

You may use EasyMock.makeThreadSafe to make testing instance threadsafe

Multiple WHERE clause in Linq

@Theo

The LINQ translator is smart enough to execute:

.Where(r => r.UserName !="XXXX" && r.UsernName !="YYYY")

I've test this in LinqPad ==> YES, Linq translator is smart enough :))

Subtracting Number of Days from a Date in PL/SQL

Use sysdate-1 to subtract one day from system date.

select sysdate, sysdate -1 from dual;

Output:

SYSDATE  SYSDATE-1
-------- ---------
22-10-13 21-10-13 

Crop image in PHP

$image = imagecreatefromjpeg($_GET['src']);

Needs to be replaced with this:

$image = imagecreatefromjpeg('images/thumbnails/myimage.jpg');

Because imagecreatefromjpeg() is expecting a string.
This worked for me.

ref:
http://php.net/manual/en/function.imagecreatefromjpeg.php

How to make readonly all inputs in some div in Angular2?

All inputs should be replaced with custom directive that reads a single global variable to toggle readonly status.

// template
<your-input [readonly]="!childmessage"></your-input>

// component value
childmessage = false;

Not equal string

With Equals() you can also use a Yoda condition:

if ( ! "-1".Equals(myString) )

Count how many files in directory PHP

  simple code add for file .php then your folder which number of file to count its      

    $directory = "images/icons";
    $files = scandir($directory);
    for($i = 0 ; $i < count($files) ; $i++){
        if($files[$i] !='.' && $files[$i] !='..')
        { echo $files[$i]; echo "<br>";
            $file_new[] = $files[$i];
        }
    }
    echo $num_files = count($file_new);

simple add its done ....

Invalid length for a Base-64 char array

My guess is that you simply need to URL-encode your Base64 string when you include it in the querystring.

Base64 encoding uses some characters which must be encoded if they're part of a querystring (namely + and /, and maybe = too). If the string isn't correctly encoded then you won't be able to decode it successfully at the other end, hence the errors.

You can use the HttpUtility.UrlEncode method to encode your Base64 string:

string msg = "Please click on the link below or paste it into a browser "
             + "to verify your email account.<br /><br /><a href=\""
             + _configuration.RootURL + "Accounts/VerifyEmail.aspx?a="
             + HttpUtility.UrlEncode(userName.Encrypt("verify")) + "\">"
             + _configuration.RootURL + "Accounts/VerifyEmail.aspx?a="
             + HttpUtility.UrlEncode(userName.Encrypt("verify")) + "</a>";

Python unittest - opposite of assertRaises?

If you pass an Exception class to assertRaises(), a context manager is provided. This can improve the readability of your tests:

# raise exception if Application created with bad data
with self.assertRaises(pySourceAidExceptions.PathIsNotAValidOne):
    application = Application("abcdef", "")

This allows you to test error cases in your code.

In this case, you are testing the PathIsNotAValidOne is raised when you pass invalid parameters to the Application constructor.

How to move an element down a litte bit in html

<div class="row-2">
 <ul>
     <li><a href="index.html" class="active"><p style="margin-top: 10px;">Buy</p></a></li>
 </ul>

Play with it

How do I change the android actionbar title and icon

You just need to add these 3 lines of code. Replace the icon with your own icon. If you want to generate icons use this

getSupportActionBar().setHomeAsUpIndicator(R.drawable.icon_back_arrow);
getActionBar().setHomeButtonEnabled(true);
getActionBar().setDisplayHomeAsUpEnabled(true);

Setting a minimum/maximum character count for any character using a regular expression

If you also want to match newlines, then you might want to use "^[\s\S]{1,35}$" (depending on the regex engine). Otherwise, as others have said, you should used "^.{1,35}$"

How to get the current working directory in Java?

generally, as a File object:

File getCwd() {
  return new File("").getAbsoluteFile();
}

you may want to have full qualified string like "D:/a/b/c" doing:

getCwd().getAbsolutePath()

How to create a button programmatically?

How to do this using Swift 3.0.

func createButton() {
    let button = UIButton(type: .system)
    button.frame = CGRect(x: 100.0, y: 100.0, width: 100.0, height: 100.0)
    button.setTitle(NSLocalizedString("Button", comment: "Button"), for: .normal)
    button.backgroundColor = .green
    button.addTarget(self, action: #selector(buttonAction(sender:)), for: .touchUpInside)
    view.addSubview(button)
}

@objc func buttonAction(sender: UIButton) {
    print("Button pushed")
}

how to implement Pagination in reactJs

I have implemented pagination + search in ReactJs, see the output: Pagination in React

View complete code on GitHub: https://github.com/navanathjadhav/generic-pagination

Also visit this article for step by step implementation of pagination: https://everblogs.com/react/3-simple-steps-to-add-pagination-in-react/

How to force 'cp' to overwrite directory instead of creating another one inside?

Very similar to @Jonathan Wheeler:

If you do not want to remember, but not rewrite bar:

rm -r bar/
cp -r foo/ !$

!$ displays the last argument of your previous command.

How to declare an array of objects in C#

The issue here is that you've initialized your array, but not its elements; they are all null. So if you try to reference houses[0], it will be null.

Here's a great little helper method you could write for yourself:

T[] InitializeArray<T>(int length) where T : new()
{
    T[] array = new T[length];
    for (int i = 0; i < length; ++i)
    {
        array[i] = new T();
    }

    return array;
}

Then you could initialize your houses array as:

GameObject[] houses = InitializeArray<GameObject>(200);

symbol(s) not found for architecture i386

I had used a CLGeocoder without adding a Core.Location Framework. Basically this error can mean multiple things. I hope this helps someone else.

OpenCV with Network Cameras

I just do it like this:

CvCapture *capture = cvCreateFileCapture("rtsp://camera-address");

Also make sure this dll is available at runtime else cvCreateFileCapture will return NULL

opencv_ffmpeg200d.dll

The camera needs to allow unauthenticated access too, usually set via its web interface. MJPEG format worked via rtsp but MPEG4 didn't.

hth

Si

Easy way to dismiss keyboard?

@Nicholas Riley & @Kendall Helmstetter Geln & @cannyboy:

Absolutely brilliant!

Thank you.

Considering your advice and the advice of others in this thread, this is what I've done:

What it looks like when used:

[[self appDelegate] dismissKeyboard]; (note: I added appDelegate as an addition to NSObject so I can use anywhere on anything)

What it looks like under the hood:

- (void)dismissKeyboard 
{
    UITextField *tempTextField = [[[UITextField alloc] initWithFrame:CGRectZero] autorelease];
    tempTextField.enabled = NO;
    [myRootViewController.view addSubview:tempTextField];
    [tempTextField becomeFirstResponder];
    [tempTextField resignFirstResponder];
    [tempTextField removeFromSuperview];
}

EDIT

Amendment to my answer to included tempTextField.enabled = NO;. Disabling the text field will prevent UIKeyboardWillShowNotification and UIKeyboardWillHideNotification keyboard notifications from being sent should you rely on these notifications throughout your app.

using jQuery .animate to animate a div from right to left?

This worked for me

$("div").css({"left":"2000px"}).animate({"left":"0px"}, "slow");

Using ListView : How to add a header view?

I found out that inflating the header view as:

inflater.inflate(R.layout.listheader, container, false);

being container the Fragment's ViewGroup, inflates the headerview with a LayoutParam that extends from FragmentLayout but ListView expect it to be a AbsListView.LayoutParams instead.

So, my problem was solved solved by inflating the header view passing the list as container:

ListView list = fragmentview.findViewById(R.id.listview);
View headerView = inflater.inflate(R.layout.listheader, list, false);

then

list.addHeaderView(headerView, null, false);

Kinda late answer but I hope this can help someone

How to add line breaks to an HTML textarea?

You need to use \n for linebreaks inside textarea

String comparison using '==' vs. 'strcmp()'

Well..according to this php bug report , you can even get 0wned.

<?php 
    $pass = isset($_GET['pass']) ? $_GET['pass'] : '';
    // Query /?pass[]= will authorize user
    //strcmp and strcasecmp both are prone to this hack
    if ( strcasecmp( $pass, '123456' ) == 0 ){
      echo 'You successfully logged in.';
    }
 ?>

It gives you a warning , but still bypass the comparison.
You should be doing === as @postfuturist suggested.

Does Python have a toString() equivalent, and can I convert a db.Model element to String?

str() is the equivalent.

However you should be filtering your query. At the moment your query is all() Todo's.

todos = Todo.all().filter('author = ', users.get_current_user().nickname()) 

or

todos = Todo.all().filter('author = ', users.get_current_user())

depending on what you are defining author as in the Todo model. A StringProperty or UserProperty.

Note nickname is a method. You are passing the method and not the result in template values.

sqlite database default time value 'now'

It's just a syntax error, you need parenthesis: (DATETIME('now'))

If you look at the documentation, you'll note the parenthesis that is added around the 'expr' option in the syntax.

html button to send email

 <form action="mailto:[email protected]" method="post"               enctype="text/plain">
 Name:<br>
<input type="text" name="name"><br>
 E-mail:<br>
<input type="text" name="mail"><br>
Comment:<br>
<input type="text" name="comment" size="50"><br><br>
<input type="submit" value="Send">
<input type="reset" value="Reset">

mysql_config not found when installing mysqldb python interface

Step1:-Install Python3 & Python3-dev Both

sudo apt-get install python3 python3-dev

Step2:- Install Python & Mysql Connector

sudo apt-get install libmysqlclient-dev

step3:- Install python mysql client

sudo apt-get install mysqlclient

This will Solve your Problem

./configure : /bin/sh^M : bad interpreter

If you are using TextMate or a similar programme, do save as, and then in encodings choose LF instead of CRLF.

Scanner doesn't read whole sentence - difference between next() and nextLine() of scanner class

You can do this:

class MyStudentDetails{
    public static void main (String args[]){
         Scanner s = new Scanner(System.in);
         System.out.println("Enter Your Name: ");
         String name = s.nextLine();
         System.out.println("Enter Your Age: ");
         String age = s.nextLine();
         System.out.println("Enter Your E-mail: ");
         String email = s.nextLine();
         System.out.println("Enter Your Address: ");
         String address = s.nextLine();


         System.out.println("Name: "+name);
         System.out.println("Age: "+age);
         System.out.println("E-mail: "+email);
         System.out.println("Address: "+address);

    }
}

How to get a tab character?

put it in between <pre></pre> tags then use this characters &#9;

it would not work without the <pre></pre> tags

How to handle notification when app in background in Firebase

Remove notification payload completely from your server request. Send only data and handle it in onMessageReceived(), otherwise your onMessageReceived will not be triggered when the app is in background or killed.

Here is what I am sending from server:

{
  "data":{
    "id": 1,
    "missedRequests": 5
    "addAnyDataHere": 123
  },
  "to": "fhiT7evmZk8:APA91bFJq7Tkly4BtLRXdYvqHno2vHCRkzpJT8QZy0TlIGs......"
}

So you can receive your data in onMessageReceived(RemoteMessage message) like this: (let's say I have to get the id)

Object obj = message.getData().get("id");
        if (obj != null) {
            int id = Integer.valueOf(obj.toString());
        }

And similarly you can get any data which you have sent from server within onMessageReceived().

Declare a constant array

As others have mentioned, there is no official Go construct for this. The closest I can imagine would be a function that returns a slice. In this way, you can guarantee that no one will manipulate the elements of the original slice (as it is "hard-coded" into the array).

I have shortened your slice to make it...shorter...:

func GetLetterGoodness() []float32 {
    return []float32 { .0817,.0149,.0278,.0425,.1270,.0223 }
}

Bootstrap close responsive menu "on click"

Just to spell out user1040259's solution, add this code to your $(document).ready(function() {});

    $('.nav').click( function() {
        $('.btn-navbar').addClass('collapsed');
        $('.nav-collapse').removeClass('in').css('height', '0');
    });

As they mention, this doesn't animate the move... but it does close the nav bar on item selection

What should be the package name of android app?

Package name is the reversed domain name, it is a unique name for each application on Playstore. You can't upload two apps with the same package name. You can check package name of the app from playstore url

https://play.google.com/store/apps/details?id=package_name

so you can easily check on playstore that this package name is in used by some other app or not before uploading it.

How do I get the current time only in JavaScript

Assign to variables and display it.

time = new Date();

var hh = time.getHours();
var mm = time.getMinutes();
var ss = time.getSeconds() 

document.getElementById("time").value = hh + ":" + mm + ":" + ss;

How can I install packages using pip according to the requirements.txt file from a local directory?

For virtualenv to install all files in the requirements.txt file.

  1. cd to the directory where requirements.txt is located
  2. activate your virtualenv
  3. run: pip install -r requirements.txt in your shell

Output ("echo") a variable to a text file

The simplest Hello World example...

$hello = "Hello World"
$hello | Out-File c:\debug.txt

SQL Server 2005 Setting a variable to the result of a select query

This will work for original question asked:

DECLARE @Result INT;
SELECT @Result = COUNT(*)
FROM  TableName
WHERE Condition

How to align an indented line in a span that wraps into multiple lines?

<!DOCTYPE html>
<html>
<body>

<span style="white-space:pre-wrap;">
Line no one
Line no two
And many more line.
This is Manik
End of Line
</span>

</body>
</html>

How to run code after some delay in Flutter?

Future.delayed(Duration(seconds: 3) , your_function)

Python: How to convert datetime format?

>>> import datetime
>>> d = datetime.datetime.strptime('2011-06-09', '%Y-%m-%d')
>>> d.strftime('%b %d,%Y')
'Jun 09,2011'

In pre-2.5 Python, you can replace datetime.strptime with time.strptime, like so (untested): datetime.datetime(*(time.strptime('2011-06-09', '%Y-%m-%d')[0:6]))

Rotate label text in seaborn factorplot

Aman is correct that you can use normal matplotlib commands, but this is also built into the FacetGrid:

import seaborn as sns
planets = sns.load_dataset("planets")
g = sns.factorplot("year", data=planets, aspect=1.5, kind="count", color="b")
g.set_xticklabels(rotation=30)

enter image description here

There are some comments and another answer claiming this "doesn't work", however, anyone can run the code as written here and see that it does work. The other answer does not provide a reproducible example of what isn't working, making it very difficult to address, but my guess is that people are trying to apply this solution to the output of functions that return an Axes object instead of a Facet Grid. These are different things, and the Axes.set_xticklabels() method does indeed require a list of labels and cannot simply change the properties of the existing labels on the Axes. The lesson is that it's important to pay attention to what kind of objects you are working with.