Programs & Examples On #Dispatcher

In WPF and Silverlight, Dispatcher is an object that is used to execute work on a specific thread. In another meaning, dispatcher defines an object that receives requests from the client and sends them to any resource (such as a servlet, HTML file, or JSP file) on the server.

No WebApplicationContext found: no ContextLoaderListener registered?

You'll have to have a ContextLoaderListener in your web.xml - It loads your configuration files.

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

You need to understand the difference between Web application context and root application context .

In the web MVC framework, each DispatcherServlet has its own WebApplicationContext, which inherits all the beans already defined in the root WebApplicationContext. These inherited beans defined can be overridden in the servlet-specific scope, and new scope-specific beans can be defined local to a given servlet instance.

The dispatcher servlet's application context is a web application context which is only applicable for the Web classes . You cannot use these for your middle tier layers . These need a global app context using ContextLoaderListener .

Read the spring reference here for spring mvc .

Change WPF controls from a non-main thread using Dispatcher.Invoke

japf has answer it correctly. Just in case if you are looking at multi-line actions, you can write as below.

Application.Current.Dispatcher.BeginInvoke(
  DispatcherPriority.Background,
  new Action(() => { 
    this.progressBar.Value = 50;
  }));

Information for other users who want to know about performance:

If your code NEED to be written for high performance, you can first check if the invoke is required by using CheckAccess flag.

if(Application.Current.Dispatcher.CheckAccess())
{
    this.progressBar.Value = 50;
}
else
{
    Application.Current.Dispatcher.BeginInvoke(
      DispatcherPriority.Background,
      new Action(() => { 
        this.progressBar.Value = 50;
      }));
}

Note that method CheckAccess() is hidden from Visual Studio 2015 so just write it without expecting intellisense to show it up. Note that CheckAccess has overhead on performance (overhead in few nanoseconds). It's only better when you want to save that microsecond required to perform the 'invoke' at any cost. Also, there is always option to create two methods (on with invoke, and other without) when calling method is sure if it's in UI Thread or not. It's only rarest of rare case when you should be looking at this aspect of dispatcher.

Event system in Python

PyPI packages

As of January 2021, these are the event-related packages available on PyPI, ordered by most recent release date.

There's more

That's a lot of libraries to choose from, using very different terminology (events, signals, handlers, method dispatch, hooks, ...).

I'm trying to keep an overview of the above packages, plus the techniques mentioned in the answers here.

First, some terminology...

Observer pattern

The most basic style of event system is the 'bag of handler methods', which is a simple implementation of the Observer pattern.

Basically, the handler methods (callables) are stored in an array and are each called when the event 'fires'.

Publish-Subscribe

The disadvantage of Observer event systems is that you can only register the handlers on the actual Event object (or handlers list). So at registration time the event already needs to exist.

That's why the second style of event systems exists: the publish-subscribe pattern. Here, the handlers don't register on an event object (or handler list), but on a central dispatcher. Also the notifiers only talk to the dispatcher. What to listen for, or what to publish is determined by 'signal', which is nothing more than a name (string).

Mediator pattern

Might be of interest as well: the Mediator pattern.

Hooks

A 'hook' system is usally used in the context of application plugins. The application contains fixed integration points (hooks), and each plugin may connect to that hook and perform certain actions.

Other 'events'

Note: threading.Event is not an 'event system' in the above sense. It's a thread synchronization system where one thread waits until another thread 'signals' the Event object.

Network messaging libraries often use the term 'events' too; sometimes these are similar in concept; sometimes not. They can of course traverse thread-, process- and computer boundaries. See e.g. pyzmq, pymq, Twisted, Tornado, gevent, eventlet.

Weak references

In Python, holding a reference to a method or object ensures that it won't get deleted by the garbage collector. This can be desirable, but it can also lead to memory leaks: the linked handlers are never cleaned up.

Some event systems use weak references instead of regular ones to solve this.

Some words about the various libraries

Observer-style event systems:

  • zope.event shows the bare bones of how this works (see Lennart's answer). Note: this example does not even support handler arguments.
  • LongPoke's 'callable list' implementation shows that such an event system can be implemented very minimalistically by subclassing list.
  • Felk's variation EventHook also ensures the signatures of callees and callers.
  • spassig's EventHook (Michael Foord's Event Pattern) is a straightforward implementation.
  • Josip's Valued Lessons Event class is basically the same, but uses a set instead of a list to store the bag, and implements __call__ which are both reasonable additions.
  • PyNotify is similar in concept and also provides additional concepts of variables and conditions ('variable changed event'). Homepage is not functional.
  • axel is basically a bag-of-handlers with more features related to threading, error handling, ...
  • python-dispatch requires the even source classes to derive from pydispatch.Dispatcher.
  • buslane is class-based, supports single- or multiple handlers and facilitates extensive type hints.
  • Pithikos' Observer/Event is a lightweight design.

Publish-subscribe libraries:

  • blinker has some nifty features such as automatic disconnection and filtering based on sender.
  • PyPubSub is a stable package, and promises "advanced features that facilitate debugging and maintaining topics and messages".
  • pymitter is a Python port of Node.js EventEmitter2 and offers namespaces, wildcards and TTL.
  • PyDispatcher seems to emphasize flexibility with regards to many-to-many publication etc. Supports weak references.
  • louie is a reworked PyDispatcher and should work "in a wide variety of contexts".
  • pypydispatcher is based on (you guessed it...) PyDispatcher and also works in PyPy.
  • django.dispatch is a rewritten PyDispatcher "with a more limited interface, but higher performance".
  • pyeventdispatcher is based on PHP's Symfony framework's event-dispatcher.
  • dispatcher was extracted from django.dispatch but is getting fairly old.
  • Cristian Garcia's EventManger is a really short implementation.

Others:

  • pluggy contains a hook system which is used by pytest plugins.
  • RxPy3 implements the Observable pattern and allows merging events, retry etc.
  • Qt's Signals and Slots are available from PyQt or PySide2. They work as callback when used in the same thread, or as events (using an event loop) between two different threads. Signals and Slots have the limitation that they only work in objects of classes that derive from QObject.

"Object doesn't support this property or method" error in IE11

We were also facing this issue when using IE version 11 to access our React app (create-react-app with react version 16.0.0 with jQuery v3.1.1) on the enterprise intranet. To solve it, i simply followed the directions at this url which are also listed below:

  1. Make sure to set the DOCTYPE to standards mode by making sure the first line of the master file is: <!DOCTYPE html>

  2. Force IE 11 to use the latest internal version by including the following meta tag in the head tag: <meta http-equiv="X-UA-Compatible" content="IE=edge;" />

NOTE: I did not face the problem when using IE to access the app in development mode on my local machine (localhost:3000). The problem occurred only when accessing the app deployed to the DEV server on the company Intranet, probably because of some company wide Windows OS policy settings and/or IE Internet Options.

How to create timer in angular2

Another solution is to use TimerObservable

TimerObservable is a subclass of Observable.

import {Component, OnInit, OnDestroy} from '@angular/core';
import {Subscription} from "rxjs";
import {TimerObservable} from "rxjs/observable/TimerObservable";

@Component({
  selector: 'app-component',
  template: '{{tick}}',
})
export class Component implements OnInit, OnDestroy {

  private tick: string;
  private subscription: Subscription;

  constructor() {
  }

  ngOnInit() {
    let timer = TimerObservable.create(2000, 1000);
    this.subscription = timer.subscribe(t => {
      this.tick = t;
    });
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }
}

P.S.: Don't forget to unsubsribe.

Insert a background image in CSS (Twitter Bootstrap)

And if you can't repeat the background image (for esthetic reasons), then this handy JQuery plugin will stretch the background image to fit the window.

Backstretch http://srobbin.com/jquery-plugins/backstretch/

Works great...

~Cheers!

MongoDB: update every document on one field

Regardless of the version, for your example, the <update> is:

{  $set: { lastLookedAt: Date.now() / 1000 }  }

However, depending on your version of MongoDB, the query will look different. Regardless of version, the key is that the empty condition {} will match any document. In the Mongo shell, or with any MongoDB client:

$version >= 3.2:

db.foo.updateMany( {}, <update> )
  • {} is the condition (the empty condition matches any document)

3.2 > $version >= 2.2:

db.foo.update( {}, <update>, { multi: true } )
  • {} is the condition (the empty condition matches any document)
  • {multi: true} is the "update multiple documents" option

$version < 2.2:

db.foo.update( {}, <update>, false, true )
  • {} is the condition (the empty condition matches any document)
  • false is for the "upsert" parameter
  • true is for the "multi" parameter (update multiple records)

How do you automatically resize columns in a DataGridView control AND allow the user to resize the columns on that same grid?

Well, I did this like this:

dgvReport.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None;
dgvReport.AutoResizeColumns();
dgvReport.AllowUserToResizeColumns = true;
dgvReport.AllowUserToOrderColumns = true;

in that particular order. Columns are resized (extended) AND the user can resize columns afterwards.

Java - Access is denied java.io.FileNotFoundException

You need to set permission for the user controls .

  1. Goto C:\Program Files\
  2. Right click java folder, click properties. Select the security tab.
  3. There, click on "Edit" button, which will pop up PERMISSIONS FOR JAVA window.
  4. Click on Add, which will pop up a new window. In that, in the "Enter object name" box, Enter your user account name, and click okay(if already exist, skip this step).
  5. Now in "PERMISSIONS OF JAVA" window, you will see several clickable options like CREATOR OWNER, SYSTEM, among them is your username. Click on it, and check mark the FULL CONTROL option in Permissions for sub window.
  6. Finally, Hit apply and okay.

CSV file written with Python has blank lines between each row

Note: It seems this is not the preferred solution because of how the extra line was being added on a Windows system. As stated in the python document:

If csvfile is a file object, it must be opened with the ‘b’ flag on platforms where that makes a difference.

Windows is one such platform where that makes a difference. While changing the line terminator as I described below may have fixed the problem, the problem could be avoided altogether by opening the file in binary mode. One might say this solution is more "elegent". "Fiddling" with the line terminator would have likely resulted in unportable code between systems in this case, where opening a file in binary mode on a unix system results in no effect. ie. it results in cross system compatible code.

From Python Docs:

On Windows, 'b' appended to the mode opens the file in binary mode, so there are also modes like 'rb', 'wb', and 'r+b'. Python on Windows makes a distinction between text and binary files; the end-of-line characters in text files are automatically altered slightly when data is read or written. This behind-the-scenes modification to file data is fine for ASCII text files, but it’ll corrupt binary data like that in JPEG or EXE files. Be very careful to use binary mode when reading and writing such files. On Unix, it doesn’t hurt to append a 'b' to the mode, so you can use it platform-independently for all binary files.

Original:

As part of optional paramaters for the csv.writer if you are getting extra blank lines you may have to change the lineterminator (info here). Example below adapated from the python page csv docs. Change it from '\n' to whatever it should be. As this is just a stab in the dark at the problem this may or may not work, but it's my best guess.

>>> import csv
>>> spamWriter = csv.writer(open('eggs.csv', 'w'), lineterminator='\n')
>>> spamWriter.writerow(['Spam'] * 5 + ['Baked Beans'])
>>> spamWriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])

How to compile Go program consisting of multiple files?

Since Go 1.11+, GOPATH is no longer recommended, the new way is using Go Modules.

Say you're writing a program called simple:

  1. Create a directory:

    mkdir simple
    cd simple
    
  2. Create a new module:

    go mod init github.com/username/simple
    # Here, the module name is: github.com/username/simple.
    # You're free to choose any module name.
    # It doesn't matter as long as it's unique.
    # It's better to be a URL: so it can be go-gettable.
    
  3. Put all your files in that directory.

  4. Finally, run:

    go run .
    
  5. Alternatively, you can create an executable program by building it:

    go build .
    
    # then:
    ./simple     # if you're on xnix
    
    # or, just:
    simple       # if you're on Windows
    

For more information, you may read this.

Go has included support for versioned modules as proposed here since 1.11. The initial prototype vgo was announced in February 2018. In July 2018, versioned modules landed in the main Go repository. In Go 1.14, module support is considered ready for production use, and all users are encouraged to migrate to modules from other dependency management systems.

How can I add additional PHP versions to MAMP

MAMP takes only two highest versions of the PHP in the following folder /Application/MAMP/bin/php

As you can see here highest versions are 7.0.10 and 5.6.25 MAMP php Versions 7.0.10 and 5.6.25

Now 7.0.10 version is removed and as you can see highest two versions are 5.6.25 and 5.5.38 as shown in preferencesphp versions 5.6.25 and 5.5.38

How do I get the last inserted ID of a MySQL table in PHP?

Use mysqli as mysql is depricating

<?php
$mysqli = new mysqli("localhost", "yourUsername", "yourPassword", "yourDB");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}
// Conside employee table with id,name,designation
$query = "INSERT INTO myCity VALUES (NULL, 'Ram', 'Developer')";
$mysqli->query($query);

printf ("New Record has id %d.\n", $mysqli->insert_id);

/* close connection */
$mysqli->close();
?>

Java 8 Stream API to find Unique Object matching a property value

findAny & orElse

By using findAny() and orElse():

Person matchingObject = objects.stream().
filter(p -> p.email().equals("testemail")).
findAny().orElse(null);

Stops looking after finding an occurrence.

findAny

Optional<T> findAny()

Returns an Optional describing some element of the stream, or an empty Optional if the stream is empty. This is a short-circuiting terminal operation. The behavior of this operation is explicitly nondeterministic; it is free to select any element in the stream. This is to allow for maximal performance in parallel operations; the cost is that multiple invocations on the same source may not return the same result. (If a stable result is desired, use findFirst() instead.)

Using Postman to access OAuth 2.0 Google APIs

The best way I found so far is to go to the Oauth playground here: https://developers.google.com/oauthplayground/

  1. Select the relevant google api category, and then select the scope inside that category in the UI.
  2. Get the authorization code by clicking "authorize API" blue button. Exchange authorization code for token by clicking the blue button.
  3. Store the OAuth2 token and use it as shown below.

In the HTTP header for the REST API request, add: "Authorization: Bearer ". Here, Authorization is the key, and "Bearer ". For example: "Authorization: Bearer za29.KluqA3vRtZChWfJDabcdefghijklmnopqrstuvwxyz6nAZ0y6ElzDT3yH3MT5"

Android Horizontal RecyclerView scroll Direction

Assuming you use LinearLayoutManager in your RecyclerView, then you can pass true as third argument in the LinearLayoutManager constructor.

For example:

mRecyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, true));

If you are using the StaggeredGridLayoutManager, then you can use the setReverseLayout method it provides.

NPM doesn't install module dependencies

OP may be true for an older version of node. However, I faced the same with node 4.4.1 as well.

It very well may be linked to the node version you are using. Try to upgrade to a latest version. Certain dependencies don't load transitively if they are incompatible with node version.

I found this by running npm update.

After upgrading to latest version (4.4 -> 5.9); this got fixed.

Reading settings from app.config or web.config in .NET

Please check the .NET version you are working on. It should be higher than 4. And you have to add the System.Configuration system library to your application.

How to import other Python files?

Just to import python file in another python file

lets say I have helper.py python file which has a display function like,

def display():
    print("I'm working sundar gsv")

Now in app.py, you can use the display function,

import helper
helper.display()

The output,

I'm working sundar gsv

NOTE: No need to specify the .py extension.

Is there any sizeof-like method in Java?

yes..in JAVA

System.out.println(Integer.SIZE/8);  //gives you 4.
System.out.println(Integer.SIZE);   //gives you 32.

//Similary for Byte,Long,Double....

Javascript callback when IFRAME is finished loading?

I have a similar code in my projects that works fine. Adapting my code to your function, a solution could be the following:

function xssRequest(url, callback)
{
    var iFrameObj = document.createElement('IFRAME');
    iFrameObj.id = 'myUniqueID';
    document.body.appendChild(iFrameObj);       
    iFrameObj.src = url;                        

    $(iFrameObj).load(function() 
    {
        callback(window['myUniqueID'].document.body.innerHTML);
        document.body.removeChild(iFrameObj);
    });
}

Maybe you have an empty innerHTML because (one or both causes): 1. you should use it against the body element 2. you have removed the iframe from the your page DOM

How I can filter a Datatable?

If you're using at least .NET 3.5, i would suggest to use Linq-To-DataTable instead since it's much more readable and powerful:

DataTable tblFiltered = table.AsEnumerable()
          .Where(row => row.Field<String>("Nachname") == username
                   &&   row.Field<String>("Ort") == location)
          .OrderByDescending(row => row.Field<String>("Nachname"))
          .CopyToDataTable();

Above code is just an example, actually you have many more methods available.

Remember to add using System.Linq; and for the AsEnumerable extension method a reference to the System.Data.DataSetExtensions dll (How).

Show Console in Windows Application?

In wind32, console-mode applications are a completely different beast from the usual message-queue-receiving applications. They are declared and compile differently. You might create an application which has both a console part and normal window and hide one or the other. But suspect you will find the whole thing a bit more work than you thought.

How do I horizontally center an absolute positioned element inside a 100% width div?

If you want to align center on left attribute.
The same thing is for top alignment, you could use margin-top: (width/2 of your div), the concept is the same of left attribute.
It's important to set header element to position:relative.
try this:

#logo {
    background:red;
    height:50px;
    position:absolute;
    width:50px;
    left:50%;
    margin-left:-25px;
}

DEMO

If you would like to not use calculations you can do this:

#logo {
  background:red;
  width:50px;
  height:50px;
  position:absolute;
  left: 0;
  right: 0;
  margin: 0 auto;
}

DEMO2

What are all the user accounts for IIS/ASP.NET and how do they differ?

This is a very good question and sadly many developers don't ask enough questions about IIS/ASP.NET security in the context of being a web developer and setting up IIS. So here goes....

To cover the identities listed:

IIS_IUSRS:

This is analogous to the old IIS6 IIS_WPG group. It's a built-in group with it's security configured such that any member of this group can act as an application pool identity.

IUSR:

This account is analogous to the old IUSR_<MACHINE_NAME> local account that was the default anonymous user for IIS5 and IIS6 websites (i.e. the one configured via the Directory Security tab of a site's properties).

For more information about IIS_IUSRS and IUSR see:

Understanding Built-In User and Group Accounts in IIS 7

DefaultAppPool:

If an application pool is configured to run using the Application Pool Identity feature then a "synthesised" account called IIS AppPool\<pool name> will be created on the fly to used as the pool identity. In this case there will be a synthesised account called IIS AppPool\DefaultAppPool created for the life time of the pool. If you delete the pool then this account will no longer exist. When applying permissions to files and folders these must be added using IIS AppPool\<pool name>. You also won't see these pool accounts in your computers User Manager. See the following for more information:

Application Pool Identities

ASP.NET v4.0: -

This will be the Application Pool Identity for the ASP.NET v4.0 Application Pool. See DefaultAppPool above.

NETWORK SERVICE: -

The NETWORK SERVICE account is a built-in identity introduced on Windows 2003. NETWORK SERVICE is a low privileged account under which you can run your application pools and websites. A website running in a Windows 2003 pool can still impersonate the site's anonymous account (IUSR_ or whatever you configured as the anonymous identity).

In ASP.NET prior to Windows 2008 you could have ASP.NET execute requests under the Application Pool account (usually NETWORK SERVICE). Alternatively you could configure ASP.NET to impersonate the site's anonymous account via the <identity impersonate="true" /> setting in web.config file locally (if that setting is locked then it would need to be done by an admin in the machine.config file).

Setting <identity impersonate="true"> is common in shared hosting environments where shared application pools are used (in conjunction with partial trust settings to prevent unwinding of the impersonated account).

In IIS7.x/ASP.NET impersonation control is now configured via the Authentication configuration feature of a site. So you can configure to run as the pool identity, IUSR or a specific custom anonymous account.

LOCAL SERVICE:

The LOCAL SERVICE account is a built-in account used by the service control manager. It has a minimum set of privileges on the local computer. It has a fairly limited scope of use:

LocalService Account

LOCAL SYSTEM:

You didn't ask about this one but I'm adding for completeness. This is a local built-in account. It has fairly extensive privileges and trust. You should never configure a website or application pool to run under this identity.

LocalSystem Account

In Practice:

In practice the preferred approach to securing a website (if the site gets its own application pool - which is the default for a new site in IIS7's MMC) is to run under Application Pool Identity. This means setting the site's Identity in its Application Pool's Advanced Settings to Application Pool Identity:

enter image description here

In the website you should then configure the Authentication feature:

enter image description here

Right click and edit the Anonymous Authentication entry:

enter image description here

Ensure that "Application pool identity" is selected:

enter image description here

When you come to apply file and folder permissions you grant the Application Pool identity whatever rights are required. For example if you are granting the application pool identity for the ASP.NET v4.0 pool permissions then you can either do this via Explorer:

enter image description here

Click the "Check Names" button:

enter image description here

Or you can do this using the ICACLS.EXE utility:

icacls c:\wwwroot\mysite /grant "IIS AppPool\ASP.NET v4.0":(CI)(OI)(M)

...or...if you site's application pool is called BobsCatPicBlogthen:

icacls c:\wwwroot\mysite /grant "IIS AppPool\BobsCatPicBlog":(CI)(OI)(M)

I hope this helps clear things up.

Update:

I just bumped into this excellent answer from 2009 which contains a bunch of useful information, well worth a read:

The difference between the 'Local System' account and the 'Network Service' account?

Read tab-separated file line into array

If you really want to split every word (bash meaning) into a different array index completely changing the array in every while loop iteration, @ruakh's answer is the correct approach. But you can use the read property to split every read word into different variables column1, column2, column3 like in this code snippet

while IFS=$'\t' read -r column1 column2 column3 ; do
  printf "%b\n" "column1<${column1}>"
  printf "%b\n" "column2<${column2}>"
  printf "%b\n" "column3<${column3}>"
done < "myfile"

to reach a similar result avoiding array index access and improving your code readability by using meaningful variable names (of course using columnN is not a good idea to do so).

Service Reference Error: Failed to generate code for the service reference

It would be extremely difficult to guess the problem since it is due to a an error in the WSDL and without examining the WSDL, I cannot comment much more. So if you can share your WSDL, please do so.

All I can say is that there seems to be a missing schema in the WSDL (with the target namespace 'http://service.ebms.edi.cecid.hku.hk/'). I know about issues and different handling of the schema when include instructions are ignored.

Generally I have found Microsoft's implementation of web services pretty good so I think the web service is sending back dodgy WSDL.

When to use HashMap over LinkedList or ArrayList and vice-versa

Lists and Maps are different data structures. Maps are used for when you want to associate a key with a value and Lists are an ordered collection.

Map is an interface in the Java Collection Framework and a HashMap is one implementation of the Map interface. HashMap are efficient for locating a value based on a key and inserting and deleting values based on a key. The entries of a HashMap are not ordered.

ArrayList and LinkedList are an implementation of the List interface. LinkedList provides sequential access and is generally more efficient at inserting and deleting elements in the list, however, it is it less efficient at accessing elements in a list. ArrayList provides random access and is more efficient at accessing elements but is generally slower at inserting and deleting elements.

How to handle anchor hash linking in AngularJS

This was my solution using a directive which seems more Angular-y because we're dealing with the DOM:

Plnkr over here

github

CODE

angular.module('app', [])
.directive('scrollTo', function ($location, $anchorScroll) {
  return function(scope, element, attrs) {

    element.bind('click', function(event) {
        event.stopPropagation();
        var off = scope.$on('$locationChangeStart', function(ev) {
            off();
            ev.preventDefault();
        });
        var location = attrs.scrollTo;
        $location.hash(location);
        $anchorScroll();
    });

  };
});

HTML

<ul>
  <li><a href="" scroll-to="section1">Section 1</a></li>
  <li><a href="" scroll-to="section2">Section 2</a></li>
</ul>

<h1 id="section1">Hi, I'm section 1</h1>
<p>
Zombie ipsum reversus ab viral inferno, nam rick grimes malum cerebro. De carne lumbering animata corpora quaeritis. 
 Summus brains sit??, morbo vel maleficia? De apocalypsi gorger omero undead survivor dictum mauris. 
Hi mindless mortuis soulless creaturas, imo evil stalking monstra adventus resi dentevil vultus comedat cerebella viventium. 
Nescio brains an Undead zombies. Sicut malus putrid voodoo horror. Nigh tofth eliv ingdead.
</p>

<h1 id="section2">I'm totally section 2</h1>
<p>
Zombie ipsum reversus ab viral inferno, nam rick grimes malum cerebro. De carne lumbering animata corpora quaeritis. 
 Summus brains sit??, morbo vel maleficia? De apocalypsi gorger omero undead survivor dictum mauris. 
Hi mindless mortuis soulless creaturas, imo evil stalking monstra adventus resi dentevil vultus comedat cerebella viventium. 
Nescio brains an Undead zombies. Sicut malus putrid voodoo horror. Nigh tofth eliv ingdead.
</p>

I used the $anchorScroll service. To counteract the page-refresh that goes along with the hash changing I went ahead and cancelled the locationChangeStart event. This worked for me because I had a help page hooked up to an ng-switch and the refreshes would esentially break the app.

How do I get DOUBLE_MAX?

Using double to store large integers is dubious; the largest integer that can be stored reliably in double is much smaller than DBL_MAX. You should use long long, and if that's not enough, you need your own arbitrary-precision code or an existing library.

Getting all names in an enum as a String[]

Try this:

public static String[] vratAtributy() {
    String[] atributy = new String[values().length];
    for(int index = 0; index < atributy.length; index++) {
        atributy[index] = values()[index].toString();
    }
    return atributy;
}

"python" not recognized as a command

Python comes with a small utility that fixes this. From the command line run:

c:\python27\tools\scripts\win_add2path.py

Make sure you close the command window (with exit or the close button) and open it again.

Make a URL-encoded POST request using `http.NewRequest(...)`

URL-encoded payload must be provided on the body parameter of the http.NewRequest(method, urlStr string, body io.Reader) method, as a type that implements io.Reader interface.

Based on the sample code:

package main

import (
    "fmt"
    "net/http"
    "net/url"
    "strconv"
    "strings"
)

func main() {
    apiUrl := "https://api.com"
    resource := "/user/"
    data := url.Values{}
    data.Set("name", "foo")
    data.Set("surname", "bar")

    u, _ := url.ParseRequestURI(apiUrl)
    u.Path = resource
    urlStr := u.String() // "https://api.com/user/"

    client := &http.Client{}
    r, _ := http.NewRequest(http.MethodPost, urlStr, strings.NewReader(data.Encode())) // URL-encoded payload
    r.Header.Add("Authorization", "auth_token=\"XXXXXXX\"")
    r.Header.Add("Content-Type", "application/x-www-form-urlencoded")
    r.Header.Add("Content-Length", strconv.Itoa(len(data.Encode())))

    resp, _ := client.Do(r)
    fmt.Println(resp.Status)
}

resp.Status is 200 OK this way.

Fullscreen Activity in Android?

For those using AppCompact... style.xml

 <style name="Xlogo" parent="Theme.AppCompat.DayNight.NoActionBar">
    <item name="android:windowNoTitle">true</item>
    <item name="android:windowFullscreen">true</item>
</style>

Then put the name in your manifest...

How do I enable --enable-soap in php on linux?

As far as your question goes: no, if activating from .ini is not enough and you can't upgrade PHP, there's not much you can do. Some modules, but not all, can be added without recompilation (zypper install php5-soap, yum install php-soap). If it is not enough, try installing some PEAR class for interpreted SOAP support (NuSOAP, etc.).

In general, the double-dash --switches are designed to be used when recompiling PHP from scratch.

You would download the PHP source package (as a compressed .tgz tarball, say), expand it somewhere and then, e.g. under Linux, run the configure script

./configure --prefix ...

The configure command used by your PHP may be shown with phpinfo(). Repeating it identical should give you an exact copy of the PHP you now have installed. Adding --enable-soap will then enable SOAP in addition to everything else.

That said, if you aren't familiar with PHP recompilation, don't do it. It also requires several ancillary libraries that you might, or might not, have available - freetype, gd, libjpeg, XML, expat, and so on and so forth (it's not enough they are installed; they must be a developer version, i.e. with headers and so on; in most distributions, having libjpeg installed might not be enough, and you might need libjpeg-dev also).

I have to keep a separate virtual machine with everything installed for my recompilation purposes.

What is the difference between instanceof and Class.isAssignableFrom(...)?

When using instanceof, you need to know the class of B at compile time. When using isAssignableFrom() it can be dynamic and change during runtime.

How to change the default charset of a MySQL table?

If you want to change the table default character set and all character columns to a new character set, use a statement like this:

ALTER TABLE tbl_name CONVERT TO CHARACTER SET charset_name;

So query will be:

ALTER TABLE etape_prospection CONVERT TO CHARACTER SET utf8;

How to check if a folder exists

We can check files and thire Folders.

import java.io.*;
public class fileCheck
{
    public static void main(String arg[])
    {
        File f = new File("C:/AMD");
        if (f.exists() && f.isDirectory()) {
        System.out.println("Exists");
        //if the file is present then it will show the msg  
        }
        else{
        System.out.println("NOT Exists");
        //if the file is Not present then it will show the msg      
        }
    }
}

"The underlying connection was closed: An unexpected error occurred on a send." With SSL Certificate

In my case the site that I'm connecting to has upgraded to TLS 1.2. As a result I had to install .net 4.5.2 on my web server in order to support it.

How to check existence of user-define table type in SQL Server 2008?

You can use also system table_types view

IF EXISTS (SELECT *
           FROM   [sys].[table_types]
           WHERE  user_type_id = Type_id(N'[dbo].[UdTableType]'))
  BEGIN
      PRINT 'EXISTS'
  END 

Can I stop 100% Width Text Boxes from extending beyond their containers?

If you can't use box-sizing:border-box you could try removing the width:100% and putting a very large size attribute in the <input> element, drawback is however you have to modify the html, and can't do it with CSS only:

<input size="1000"></input>

Encrypt and decrypt a password in Java

I recently used Spring Security 3.0 for this (combined with Wicket btw), and am quite happy with it. Here's a good thorough tutorial and documentation. Also take a look at this tutorial which gives a good explanation of the hashing/salting/decoding setup for Spring Security 2.

ValueError: could not broadcast input array from shape (224,224,3) into shape (224,224)

You can covert numpy.ndarray to object using astype(object)

This will work:

>>> a = [np.zeros((224,224,3)).astype(object), np.zeros((224,224,3)).astype(object), np.zeros((224,224,13)).astype(object)]

How to use regex with find command?

Judging from other answers, it seems this might be find's fault.

However you can do it this way instead:

find . * | grep -P "[a-f0-9\-]{36}\.jpg"

You might have to tweak the grep a bit and use different options depending on what you want but it works.

Warning: Null value is eliminated by an aggregate or other SET operation in Aqua Data Studio

You want to put the ISNULL inside of the COUNT function, not outside:

Not GOOD: ISNULL(COUNT(field), 0)

GOOD: COUNT(ISNULL(field, 0))

Default values and initialization in Java

Read your reference more carefully:

Default Values

It's not always necessary to assign a value when a field is declared. Fields that are declared but not initialized will be set to a reasonable default by the compiler. Generally speaking, this default will be zero or null, depending on the data type. Relying on such default values, however, is generally considered bad programming style.

The following chart summarizes the default values for the above data types.

. . .

Local variables are slightly different; the compiler never assigns a default value to an uninitialized local variable. If you cannot initialize your local variable where it is declared, make sure to assign it a value before you attempt to use it. Accessing an uninitialized local variable will result in a compile-time error.

make script execution to unlimited

As @Peter Cullen answer mention, your script will meet browser timeout first. So its good idea to provide some log output, then flush(), but connection have buffer and you'll not see anything unless much output provided. Here are code snippet what helps provide reliable log:

set_time_limit(0);
...
print "log message";
print "<!--"; print str_repeat (' ', 4000); print "-->"; flush();
print "log message";
print "<!--"; print str_repeat (' ', 4000); print "-->"; flush();

Custom UITableViewCell from nib in Swift

Simple take a xib with class UITableViewCell. Set the UI as per reuirement and assign IBOutlet. Use it in cellForRowAt() of table view like this:

//MARK: - table method

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return self.arrayFruit.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    var cell:simpleTableViewCell? = tableView.dequeueReusableCell(withIdentifier:"simpleTableViewCell") as? simpleTableViewCell
    if cell == nil{
        tableView.register(UINib.init(nibName: "simpleTableViewCell", bundle: nil), forCellReuseIdentifier: "simpleTableViewCell")
        let arrNib:Array = Bundle.main.loadNibNamed("simpleTableViewCell",owner: self, options: nil)!
        cell = arrNib.first as? simpleTableViewCell
    }

    cell?.labelName.text = self.arrayFruit[indexPath.row]
    cell?.imageViewFruit.image = UIImage (named: "fruit_img")

    return cell!

}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
{
 return 100.0
}

enter image description here

100% working without any issue (Tested)

Windows 7 SDK installation failure

Do you have access to a PC with Windows 7, or a PC with the SDK already installed?

If so, the easiest solution is to copy the C:\Program Files\Microsoft SDKs\Windows\v7.1 folder from the Windows 7 machine to the Windows 8 machine.

GCM with PHP (Google Cloud Messaging)

<?php
    // Replace with the real server API key from Google APIs
    $apiKey = "your api key";

    // Replace with the real client registration IDs
    $registrationIDs = array( "reg id1","reg id2");

    // Message to be sent
    $message = "hi Shailesh";

    // Set POST variables
    $url = 'https://android.googleapis.com/gcm/send';

    $fields = array(
        'registration_ids' => $registrationIDs,
        'data' => array( "message" => $message ),
    );
    $headers = array(
        'Authorization: key=' . $apiKey,
        'Content-Type: application/json'
    );

    // Open connection
    $ch = curl_init();

    // Set the URL, number of POST vars, POST data
    curl_setopt( $ch, CURLOPT_URL, $url);
    curl_setopt( $ch, CURLOPT_POST, true);
    curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true);
    //curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode( $fields));

    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    // curl_setopt($ch, CURLOPT_POST, true);
    // curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode( $fields));

    // Execute post
    $result = curl_exec($ch);

    // Close connection
    curl_close($ch);
    echo $result;
    //print_r($result);
    //var_dump($result);
?>

Android: How to rotate a bitmap on a center point

You can use something like following:


Matrix matrix = new Matrix();
matrix.setRotate(mRotation,source.getWidth()/2,source.getHeight()/2);
RectF rectF = new RectF(0, 0, source.getWidth(), source.getHeight());
matrix.mapRect(rectF);
Bitmap targetBitmap = Bitmap.createBitmap(rectF.width(), rectF.height(), config);
Canvas canvas = new Canvas(targetBitmap);
canvas.drawBitmap(source, matrix, new Paint());

Capture the screen shot using .NET

It's certainly possible to grab a screenshot using the .NET Framework. The simplest way is to create a new Bitmap object and draw into that using the Graphics.CopyFromScreen method.

Sample code:

using (Bitmap bmpScreenCapture = new Bitmap(Screen.PrimaryScreen.Bounds.Width, 
                                            Screen.PrimaryScreen.Bounds.Height))
using (Graphics g = Graphics.FromImage(bmpScreenCapture))
{
    g.CopyFromScreen(Screen.PrimaryScreen.Bounds.X,
                     Screen.PrimaryScreen.Bounds.Y,
                     0, 0,
                     bmpScreenCapture.Size,
                     CopyPixelOperation.SourceCopy);
}

Caveat: This method doesn't work properly for layered windows. Hans Passant's answer here explains the more complicated method required to get those in your screen shots.

Add characters to a string in Javascript

You can also keep adding strings to an existing string like so:

var myString = "Hello ";
myString += "World";
myString += "!";

the result would be -> Hello World!

How to convert string to long

String s = "1";

try {
   long l = Long.parseLong(s);       
} catch (NumberFormatException e) {
   System.out.println("NumberFormatException: " + e.getMessage());
}

Guid.NewGuid() vs. new Guid()

new Guid() makes an "empty" all-0 guid (00000000-0000-0000-0000-000000000000 is not very useful).

Guid.NewGuid() makes an actual guid with a unique value, what you probably want.

Adding and using header (HTTP) in nginx

To add a header just add the following code to the location block where you want to add the header:

location some-location {
  add_header X-my-header my-header-content;      
}

Obviously, replace the x-my-header and my-header-content with what you want to add. And that's all there is to it.

Java: notify() vs. notifyAll() all over again

Useful differences:

  • Use notify() if all your waiting threads are interchangeable (the order they wake up doesn't matter), or if you only ever have one waiting thread. A common example is a thread pool used to execute jobs from a queue--when a job is added, one of threads is notified to wake up, execute the next job and go back to sleep.

  • Use notifyAll() for other cases where the waiting threads may have different purposes and should be able to run concurrently. An example is a maintenance operation on a shared resource, where multiple threads are waiting for the operation to complete before accessing the resource.

Cannot ping AWS EC2 instance

Yes you need to open up access to the port. Look at Security Groups http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-network-security.html

Your EC2 instance needs to be attached to a security group that allows the access you require.

Laravel 5.1 API Enable Cors

For me i put this codes in public\index.php file. and it worked just fine for all CRUD operations.

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS, post, get');
header("Access-Control-Max-Age", "3600");
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token');
header("Access-Control-Allow-Credentials", "true");

How to change colour of blue highlight on select box dropdown

Just found this whilst looking for a solution. I've only tested it FF 32.0.3

box-shadow: 0 0 10px 100px #fff inset;

Dynamically Add Images React Webpack

If you are bundling your code at the server-side, then there is nothing stopping you from requiring assets directly from jsx:

<div>
  <h1>Image</h1>
  <img src={require('./assets/image.png')} />
</div>

Accessing a Dictionary.Keys Key through a numeric index

A dictionary may not be very intuitive for using index for reference but, you can have similar operations with an array of KeyValuePair:

ex. KeyValuePair<string, string>[] filters;

How to disable the ability to select in a DataGridView?

you have to create a custom DataGridView

`

namespace System.Windows.Forms
{
    class MyDataGridView : DataGridView
    {
        public bool PreventUserClick = false;

        public MyDataGridView()
        {

        }
        protected override void OnMouseDown(MouseEventArgs e)
        {
            if (PreventUserClick) return;

            base.OnMouseDown(e);
        }
    }
}

` note that you have to first compile the program once with the added class, before you can use the new control.

then go to The .Designer.cs and change the old DataGridView to the new one without having to mess up you previous code.

private System.Windows.Forms.DataGridView dgv; // found close to the bottom

private void InitializeComponent() {
    ...
    this.dgv = new System.Windows.Forms.DataGridView();
    ...
}

to (respective)

private System.Windows.Forms.MyDataGridView dgv;

this.dgv = new System.Windows.Forms.MyDataGridView();

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

Have a look at either Left or Substring if you need to chop it up even more.

Google and the MySQL docs are a good place to start - you'll usually not get such a warm response if you've not even tried to help yourself before asking a question.

Run a script in Dockerfile

In addition to the answers above:

If you created/edited your .sh script file in Windows, make sure it was saved with line ending in Unix format. By default many editors in Windows will convert Unix line endings to Windows format and Linux will not recognize shebang (#!/bin/sh) at the beginning of the file. So Linux will produce the error message like if there is no shebang.

Tips:

  • If you use Notepad++, you need to click "Edit/EOL Conversion/UNIX (LF)"
  • If you use Visual Studio, I would suggest installing "End Of Line" plugin. Then you can make line endings visible by pressing Ctrl-R, Ctrl-W. And to set Linux style endings you can press Ctrl-R, Ctrl-L. For Windows style, press Ctrl-R, Ctrl-C.

Writing image to local server

This thread is old but I wanted to do same things with the https://github.com/mikeal/request package.

Here a working example

var fs      = require('fs');
var request = require('request');
// Or with cookies
// var request = require('request').defaults({jar: true});

request.get({url: 'https://someurl/somefile.torrent', encoding: 'binary'}, function (err, response, body) {
  fs.writeFile("/tmp/test.torrent", body, 'binary', function(err) {
    if(err)
      console.log(err);
    else
      console.log("The file was saved!");
  }); 
});

Update and left outer join statements

In mysql the SET clause needs to come after the JOIN. Example:

UPDATE e
    LEFT JOIN a ON a.id = e.aid
    SET e.id = 2
    WHERE  
        e.type = 'user' AND
        a.country = 'US';

Update a table using JOIN in SQL Server?

You don't quite have SQL Server's proprietary UPDATE FROM syntax down. Also not sure why you needed to join on the CommonField and also filter on it afterward. Try this:

UPDATE t1
  SET t1.CalculatedColumn = t2.[Calculated Column]
  FROM dbo.Table1 AS t1
  INNER JOIN dbo.Table2 AS t2
  ON t1.CommonField = t2.[Common Field]
  WHERE t1.BatchNo = '110';

If you're doing something really silly - like constantly trying to set the value of one column to the aggregate of another column (which violates the principle of avoiding storing redundant data), you can use a CTE (common table expression) - see here and here for more details:

;WITH t2 AS
(
  SELECT [key], CalculatedColumn = SUM(some_column)
    FROM dbo.table2
    GROUP BY [key]
)
UPDATE t1
  SET t1.CalculatedColumn = t2.CalculatedColumn
  FROM dbo.table1 AS t1
  INNER JOIN t2
  ON t1.[key] = t2.[key];

The reason this is really silly, is that you're going to have to re-run this entire update every single time any row in table2 changes. A SUM is something you can always calculate at runtime and, in doing so, never have to worry that the result is stale.

ConvergenceWarning: Liblinear failed to converge, increase the number of iterations

Normally when an optimization algorithm does not converge, it is usually because the problem is not well-conditioned, perhaps due to a poor scaling of the decision variables. There are a few things you can try.

  1. Normalize your training data so that the problem hopefully becomes more well conditioned, which in turn can speed up convergence. One possibility is to scale your data to 0 mean, unit standard deviation using Scikit-Learn's StandardScaler for an example. Note that you have to apply the StandardScaler fitted on the training data to the test data.
  2. Related to 1), make sure the other arguments such as regularization weight, C, is set appropriately.
  3. Set max_iter to a larger value. The default is 1000.
  4. Set dual = True if number of features > number of examples and vice versa. This solves the SVM optimization problem using the dual formulation. Thanks @Nino van Hooff for pointing this out, and @JamesKo for spotting my mistake.
  5. Use a different solver, for e.g., the L-BFGS solver if you are using Logistic Regression. See @5ervant's answer.

Note: One should not ignore this warning.

This warning came about because

  1. Solving the linear SVM is just solving a quadratic optimization problem. The solver is typically an iterative algorithm that keeps a running estimate of the solution (i.e., the weight and bias for the SVM). It stops running when the solution corresponds to an objective value that is optimal for this convex optimization problem, or when it hits the maximum number of iterations set.

  2. If the algorithm does not converge, then the current estimate of the SVM's parameters are not guaranteed to be any good, hence the predictions can also be complete garbage.

Edit

In addition, consider the comment by @Nino van Hooff and @5ervant to use the dual formulation of the SVM. This is especially important if the number of features you have, D, is more than the number of training examples N. This is what the dual formulation of the SVM is particular designed for and helps with the conditioning of the optimization problem. Credit to @5ervant for noticing and pointing this out.

Furthermore, @5ervant also pointed out the possibility of changing the solver, in particular the use of the L-BFGS solver. Credit to him (i.e., upvote his answer, not mine).

I would like to provide a quick rough explanation for those who are interested (I am :)) why this matters in this case. Second-order methods, and in particular approximate second-order method like the L-BFGS solver, will help with ill-conditioned problems because it is approximating the Hessian at each iteration and using it to scale the gradient direction. This allows it to get better convergence rate but possibly at a higher compute cost per iteration. That is, it takes fewer iterations to finish but each iteration will be slower than a typical first-order method like gradient-descent or its variants.

For e.g., a typical first-order method might update the solution at each iteration like

x(k + 1) = x(k) - alpha(k) * gradient(f(x(k)))

where alpha(k), the step size at iteration k, depends on the particular choice of algorithm or learning rate schedule.

A second order method, for e.g., Newton, will have an update equation

x(k + 1) = x(k) - alpha(k) * Hessian(x(k))^(-1) * gradient(f(x(k)))

That is, it uses the information of the local curvature encoded in the Hessian to scale the gradient accordingly. If the problem is ill-conditioned, the gradient will be pointing in less than ideal directions and the inverse Hessian scaling will help correct this.

In particular, L-BFGS mentioned in @5ervant's answer is a way to approximate the inverse of the Hessian as computing it can be an expensive operation.

However, second-order methods might converge much faster (i.e., requires fewer iterations) than first-order methods like the usual gradient-descent based solvers, which as you guys know by now sometimes fail to even converge. This can compensate for the time spent at each iteration.

In summary, if you have a well-conditioned problem, or if you can make it well-conditioned through other means such as using regularization and/or feature scaling and/or making sure you have more examples than features, you probably don't have to use a second-order method. But these days with many models optimizing non-convex problems (e.g., those in DL models), second order methods such as L-BFGS methods plays a different role there and there are evidence to suggest they can sometimes find better solutions compared to first-order methods. But that is another story.

How to return value from Action()?

Use Func<T> rather than Action<T>.

Action<T> acts like a void method with parameter of type T, while Func<T> works like a function with no parameters and which returns an object of type T.

If you wish to give parameters to your function, use Func<TParameter1, TParameter2, ..., TReturn>.

Reading from a text file and storing in a String

These are the necersary imports:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

And this is a method that will allow you to read from a File by passing it the filename as a parameter like this: readFile("yourFile.txt");

String readFile(String fileName) throws IOException {
    BufferedReader br = new BufferedReader(new FileReader(fileName));
    try {
        StringBuilder sb = new StringBuilder();
        String line = br.readLine();

        while (line != null) {
            sb.append(line);
            sb.append("\n");
            line = br.readLine();
        }
        return sb.toString();
    } finally {
        br.close();
    }
}

Convert integer to string Jinja

The OP needed to cast as string outside the {% set ... %}. But if that not your case you can do:

{% set curYear = 2013 | string() %}

Note that you need the parenthesis on that jinja filter.

If you're concatenating 2 variables, you can also use the ~ custom operator.

How to center the text in PHPExcel merged cell

<?php
    /** Error reporting */
    error_reporting(E_ALL);
    ini_set('display_errors', TRUE);
    ini_set('display_startup_errors', TRUE);
    date_default_timezone_set('Europe/London');

    /** Include PHPExcel */
    require_once '../Classes/PHPExcel.php';

    $objPHPExcel = new PHPExcel();
    $sheet = $objPHPExcel->getActiveSheet();
    $sheet->setCellValueByColumnAndRow(0, 1, "test");
    $sheet->mergeCells('A1:B1');
    $sheet->getActiveSheet()->getStyle('A1:B1')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
    $objWriter->save("test.xlsx");
?>

How to change a single value in a NumPy array?

Is this what you are after? Just index the element and assign a new value.

A[2,1]=150

A
Out[345]: 
array([[ 1,  2,  3,  4],
       [ 5,  6,  7,  8],
       [ 9, 150, 11, 12],
       [13, 14, 15, 16]])

Python+OpenCV: cv2.imwrite

wtluo, great ! May I propose a slight modification of your code 2. ? Here it is:

for i, detected_box in enumerate(detect_boxes):
    box = detected_box["box"]
    face_img = img[ box[1]:box[1] + box[3], box[0]:box[0] + box[2] ]
    cv2.imwrite("face-{:03d}.jpg".format(i+1), face_img)

Monad in plain English? (For the OOP programmer with no FP background)

From wikipedia:

In functional programming, a monad is a kind of abstract data type used to represent computations (instead of data in the domain model). Monads allow the programmer to chain actions together to build a pipeline, in which each action is decorated with additional processing rules provided by the monad. Programs written in functional style can make use of monads to structure procedures that include sequenced operations,1[2] or to define arbitrary control flows (like handling concurrency, continuations, or exceptions).

Formally, a monad is constructed by defining two operations (bind and return) and a type constructor M that must fulfill several properties to allow the correct composition of monadic functions (i.e. functions that use values from the monad as their arguments). The return operation takes a value from a plain type and puts it into a monadic container of type M. The bind operation performs the reverse process, extracting the original value from the container and passing it to the associated next function in the pipeline.

A programmer will compose monadic functions to define a data-processing pipeline. The monad acts as a framework, as it's a reusable behavior that decides the order in which the specific monadic functions in the pipeline are called, and manages all the undercover work required by the computation.[3] The bind and return operators interleaved in the pipeline will be executed after each monadic function returns control, and will take care of the particular aspects handled by the monad.

I believe it explains it very well.

Is there a way to access the "previous row" value in a SELECT statement?

select t2.col from (
select col,MAX(ID) id from 
(
select ROW_NUMBER() over(PARTITION by col order by col) id ,col from testtab t1) as t1
group by col) as t2

Accessing Google Spreadsheets with C# using Google Data API

I'm pretty sure there'll be some C# SDKs / toolkits on Google Code for this. I found this one, but there may be others so it's worth having a browse around.

How can I debug git/git-shell related problems?

Have you tried adding the verbose (-v) operator when you clone?

git clone -v git://git.kernel.org/pub/scm/.../linux-2.6 my2.6

Why plt.imshow() doesn't display the image?

plt.imshow just finishes drawing a picture instead of printing it. If you want to print the picture, you just need to add plt.show.

What is the best way to measure execution time of a function?

I would definitely advise you to have a look at System.Diagnostics.Stopwatch

And when I looked around for more about Stopwatch I found this site;

Beware of the stopwatch

There mentioned another possibility

Process.TotalProcessorTime

How to print Two-Dimensional Array like table

Just for the records, Java 8 provides a better alternative.

int[][] table = new int[][]{{2,4,5},{6,34,7},{23,57,2}};

System.out.println(Stream.of(table)
    .map(rowParts -> Stream.of(rowParts
    .map(element -> ((Integer)element).toString())
        .collect(Collectors.joining("\t")))
    .collect(Collectors.joining("\n")));

How to reset or change the passphrase for a GitHub SSH key?

  1. Log in to your github account.
  2. Go to the "Settings" page (the "wrench and screwdriver" icon in the top right corner of the page).
  3. Go to "SSH keys" page.
  4. Generate a new SSH key (probably studying the links provided by github on that page).
  5. Add your new key using the "Add SSH key" link.
  6. Verify your new key works.
  7. Make gitub forget your old key by using the "Delete" link next to it in the list of known keys.

Why use @PostConstruct?

Also constructor based initialisation will not work as intended whenever some kind of proxying or remoting is involved.

The ct will get called whenever an EJB gets deserialized, and whenever a new proxy gets created for it...

Setting Timeout Value For .NET Web Service

Try setting the timeout value in your web service proxy class:

WebReference.ProxyClass myProxy = new WebReference.ProxyClass();
myProxy.Timeout = 100000; //in milliseconds, e.g. 100 seconds

Position absolute but relative to parent

#father {
   position: relative;
}

#son1 {
   position: absolute;
   top: 0;
}

#son2 {
   position: absolute;
   bottom: 0;
}

This works because position: absolute means something like "use top, right, bottom, left to position yourself in relation to the nearest ancestor who has position: absolute or position: relative."

So we make #father have position: relative, and the children have position: absolute, then use top and bottom to position the children.

Get current time as formatted string in Go?

Use the time.Now() function and the time.Format() method.

t := time.Now()
fmt.Println(t.Format("20060102150405"))

prints out 20110504111515, or at least it did a few minutes ago. (I'm on Eastern Daylight Time.) There are several pre-defined time formats in the constants defined in the time package.

You can use time.Now().UTC() if you'd rather have UTC than your local time zone.

How can I make a "color map" plot in matlab?

Note that both pcolor and "surf + view(2)" do not show the last row and the last column of your 2D data.

On the other hand, using imagesc, you have to be careful with the axes. The surf and the imagesc examples in gevang's answer only (almost -- apart from the last row and column) correspond to each other because the 2D sinc function is symmetric.

To illustrate these 2 points, I produced the figure below with the following code:

[x, y] = meshgrid(1:10,1:5);
z      = x.^3 + y.^3;

subplot(3,1,1)
imagesc(flipud(z)), axis equal tight, colorbar
set(gca, 'YTick', 1:5, 'YTickLabel', 5:-1:1);
title('imagesc')

subplot(3,1,2)
surf(x,y,z,'EdgeColor','None'), view(2), axis equal tight, colorbar
title('surf with view(2)')

subplot(3,1,3)
imagesc(flipud(z)), axis equal tight, colorbar
axis([0.5 9.5 1.5 5.5])
set(gca, 'YTick', 1:5, 'YTickLabel', 5:-1:1);
title('imagesc cropped')

colormap jet

surf vs imagesc

As you can see the 10th row and 5th column are missing in the surf plot. (You can also see this in images in the other answers.)

Note how you can use the "set(gca, 'YTick'..." (and Xtick) command to set the x and y tick labels properly if x and y are not 1:1:N.

Also note that imagesc only makes sense if your z data correspond to xs and ys are (each) equally spaced. If not you can use surf (and possibly duplicate the last column and row and one more "(end,end)" value -- although that's a kind of a dirty approach).

Is the ternary operator faster than an "if" condition in Java

Does it matter which I use?

Yes! The second is vastly more readable. You are trading one line which concisely expresses what you want against nine lines of effectively clutter.

Which is faster?

Neither.

Is it a better practice to use the shortest code whenever possible?

Not “whenever possible” but certainly whenever possible without detriment effects. Shorter code is at least potentially more readable since it focuses on the relevant part rather than on incidental effects (“boilerplate code”).

Converting user input string to regular expression

Use the JavaScript RegExp object constructor.

var re = new RegExp("\\w+");
re.test("hello");

You can pass flags as a second string argument to the constructor. See the documentation for details.

TypeError: only integer scalar arrays can be converted to a scalar index with 1D numpy indices array

Another case that could cause this error is

>>> np.ndindex(np.random.rand(60,60))
TypeError: only integer scalar arrays can be converted to a scalar index

Using the actual shape will fix it.

>>> np.ndindex(np.random.rand(60,60).shape)
<numpy.ndindex object at 0x000001B887A98880>

Removing index column in pandas when reading a csv

You can set one of the columns as an index in case it is an "id" for example. In this case the index column will be replaced by one of the columns you have chosen.

df.set_index('id', inplace=True)

How to recover corrupted Eclipse workspace?

deleting below file helped me solve my eclipse start up issue. Perforce plugin has always troubled me especially when my machine reboots, next time eclipse tries to recover workspace and craps out.

workspace/.metadata/.plugins/org.eclipse.core.resources/.snap

For your reference, Error I was getting: org.eclipse.core.runtime.CoreException: Plug-in com.perforce.team.ui was unable to load class com.perforce.team.ui.UITeamProvider.

Doctrine 2 ArrayCollection filter method

Doctrine now has Criteria which offers a single API for filtering collections with SQL and in PHP, depending on the context.

https://www.doctrine-project.org/projects/doctrine-orm/en/latest/reference/working-with-associations.html#filtering-collections

Update

This will achieve the result in the accepted answer, without getting everything from the database.

use Doctrine\Common\Collections\Criteria;

/**
 * @ORM\Entity
 */
class Member {
  // ...
  public function getCommentsFiltered($ids) {
    $criteria = Criteria::create()->where(Criteria::expr()->in("id", $ids));

    return $this->getComments()->matching($criteria); 
  }
}

macro run-time error '9': subscript out of range

"Subscript out of range" indicates that you've tried to access an element from a collection that doesn't exist. Is there a "Sheet1" in your workbook? If not, you'll need to change that to the name of the worksheet you want to protect.

Oracle DB: How can I write query ignoring case?

You can use either lower or upper function on both sides of the where condition

How do I style appcompat-v7 Toolbar like Theme.AppCompat.Light.DarkActionBar?

The cleanest way I found to do this is create a child of 'ThemeOverlay.AppCompat.Dark.ActionBar'. In the example, I set the Toolbar's background color to RED and text's color to BLUE.

<style name="MyToolbar" parent="ThemeOverlay.AppCompat.Dark.ActionBar">
    <item name="android:background">#FF0000</item>
    <item name="android:textColorPrimary">#0000FF</item>
</style>

You can then apply your theme to the toolbar:

<android.support.v7.widget.Toolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    app:theme="@style/MyToolbar"
    android:minHeight="?attr/actionBarSize"/>

How to draw a standard normal distribution in R

I am pretty sure this is a duplicate. Anyway, have a look at the following piece of code

x <- seq(5, 15, length=1000)
y <- dnorm(x, mean=10, sd=3)
plot(x, y, type="l", lwd=1)

I'm sure you can work the rest out yourself, for the title you might want to look for something called main= and y-axis labels are also up to you.

If you want to see more of the tails of the distribution, why don't you try playing with the seq(5, 15, ) section? Finally, if you want to know more about what dnorm is doing I suggest you look here

How to leave a message for a github.com user

Besides the removal of the github messaging service, usage was often not necessary due to many githubbers communicating with- and advocating twitter.

The advantage is that there is:

  • full transparency
  • better coverage
  • better search features for tweets
  • better archiving, for instance by the US Library of Congress

It is probably no coincidence that stackoverflow doesn't allow private messaging either, to ensure full transparency. The entire messaging issue is thoroughly discussed on meta-stackoverflow here.

Use jquery to set value of div tag

try this function $('div.total-title').text('test');

How to list all dates between two dates

Use this,

DECLARE @start_date DATETIME = '2015-02-12 00:00:00.000';
DECLARE @end_date DATETIME = '2015-02-13 00:00:00.000';

WITH    AllDays
          AS ( SELECT   @start_date AS [Date], 1 AS [level]
               UNION ALL
               SELECT   DATEADD(DAY, 1, [Date]), [level] + 1
               FROM     AllDays
               WHERE    [Date] < @end_date )
     SELECT [Date], [level]
     FROM   AllDays OPTION (MAXRECURSION 0)

pass the @start_date and @end_date as SP parameters.

Result:

Date                    level
----------------------- -----------
2015-02-12 00:00:00.000 1
2015-02-13 00:00:00.000 2

(2 row(s) affected)

Error in installation a R package

The solution indicated by Guannan Shen has one drawback that usually goes unnoticed.

When you run sudo R in order to run install.packages() as superuser, the directories in which you install the library end up belonging to root user, a.k.a., the superuser.

So, next time you need to update your libraries, you will not remember that you ran sudo, therefore leaving root as the owner of the files and directories; that eventually causes the error when trying to move files, because no one can overwrite root but themself.

That can be averted by running

sudo chown -R yourusername:yourusername *

in the directory lib that contains your local libraries, replacing yourusername by the adequated value in your installation. Then you try installing once again.

curl usage to get header

You need to add the -i flag to the first command, to include the HTTP header in the output. This is required to print headers.

curl -X HEAD -i http://www.google.com

More here: https://serverfault.com/questions/140149/difference-between-curl-i-and-curl-x-head

Rename multiple files in a directory in Python

The following code should work. It takes every filename in the current directory, if the filename contains the pattern CHEESE_CHEESE_ then it is renamed. If not nothing is done to the filename.

import os
for fileName in os.listdir("."):
    os.rename(fileName, fileName.replace("CHEESE_CHEESE_", "CHEESE_"))

How do I define global variables in CoffeeScript?

Since coffee script has no var statement it automatically inserts it for all variables in the coffee-script, that way it prevents the compiled JavaScript version from leaking everything into the global namespace.

So since there's no way to make something "leak" into the global namespace from the coffee-script side of things on purpose, you need to define your global variables as properties of the global object.

attach them as properties on window

This means you need to do something like window.foo = 'baz';, which handles the browser case, since there the global object is the window.

Node.js

In Node.js there's no window object, instead there's the exports object that gets passed into the wrapper that wraps the Node.js module (See: https://github.com/ry/node/blob/master/src/node.js#L321 ), so in Node.js what you would need to do is exports.foo = 'baz';.

Now let us take a look at what it states in your quote from the docs:

...targeting both CommonJS and the browser: root = exports ? this

This is obviously coffee-script, so let's take a look into what this actually compiles to:

var root;
root = (typeof exports !== "undefined" && exports !== null) ? exports : this;

First it will check whether exports is defined, since trying to reference a non existent variable in JavaScript would otherwise yield an SyntaxError (except when it's used with typeof)

So if exports exists, which is the case in Node.js (or in a badly written WebSite...) root will point to exports, otherwise to this. So what's this?

(function() {...}).call(this);

Using .call on a function will bind the this inside the function to the first parameter passed, in case of the browser this would now be the window object, in case of Node.js it would be the global context which is also available as the global object.

But since you have the require function in Node.js, there's no need to assign something to the global object in Node.js, instead you assign to the exports object which then gets returned by the require function.

Coffee-Script

After all that explanation, here's what you need to do:

root = exports ? this
root.foo = -> 'Hello World'

This will declare our function foo in the global namespace (whatever that happens to be).
That's all :)

Can I force a page break in HTML printing?

Try this (its work in Chrome, Firefox and IE):

... content in page 1 ...
<p style="page-break-after: always;">&nbsp;</p>
<p style="page-break-before: always;">&nbsp;</p>
... content in page 2 ...

Google Maps API OVER QUERY LIMIT per second limit

The geocoder has quota and rate limits. From experience, you can geocode ~10 locations without hitting the query limit (the actual number probably depends on server loading). The best solution is to delay when you get OVER_QUERY_LIMIT errors, then retry. See these similar posts:

How do I print colored output to the terminal in Python?

I suggest sty. It's similar to colorama, but less verbose and it supports 8bit and 24bit colors. You can also extend the color register with your own colors.

Examples:

from sty import fg, bg, ef, rs

foo = fg.red + 'This is red text!' + fg.rs
bar = bg.blue + 'This has a blue background!' + bg.rs
baz = ef.italic + 'This is italic text' + rs.italic
qux = fg(201) + 'This is pink text using 8bit colors' + fg.rs
qui = fg(255, 10, 10) + 'This is red text using 24bit colors.' + fg.rs

# Add custom colors:

from sty import Style, RgbFg

fg.orange = Style(RgbFg(255, 150, 50))

buf = fg.orange + 'Yay, Im orange.' + fg.rs

print(foo, bar, baz, qux, qui, buf, sep='\n')

enter image description here

Demo:

enter image description here

LabelEncoder: TypeError: '>' not supported between instances of 'float' and 'str'

This is due to the series df[cat] containing elements that have varying data types e.g.(strings and/or floats). This could be due to the way the data is read, i.e. numbers are read as float and text as strings or the datatype was float and changed after the fillna operation.

In other words

pandas data type 'Object' indicates mixed types rather than str type

so using the following line:

df[cat] = le.fit_transform(df[cat].astype(str))


should help

Upgrade version of Pandas

Add your C:\WinPython-64bit-3.4.4.1\python_***\Scripts folder to your system PATH variable by doing the following:

  1. Select Start, select Control Panel. double click System, and select the Advanced tab.
  2. Click Environment Variables. ...

  3. In the Edit System Variable (or New System Variable) window, specify the value of the PATH environment variable. ...

  4. Reopen Command prompt window

How to convert int to date in SQL Server 2008

You most likely want to examine the documentation for T-SQL's CAST and CONVERT functions, located in the documentation here: http://msdn.microsoft.com/en-US/library/ms187928(v=SQL.90).aspx

You will then use one of those functions in your T-SQL query to convert the [idate] column from the database into the datetime format of your liking in the output.

Viewing unpushed Git commits

There is tool named unpushed that scans all Git, Mercurial and Subversion repos in specified working directory and shows list of ucommited files and unpushed commits. Installation is simple under Linux:

$ easy_install --user unpushed

or

$ sudo easy_install unpushed

to install system-wide.

Usage is simple too:

$ unpushed ~/workspace
* /home/nailgun/workspace/unpushed uncommitted (Git)
* /home/nailgun/workspace/unpushed:master unpushed (Git)
* /home/nailgun/workspace/python:new-syntax unpushed (Git)

See unpushed --help or official description for more information. It also has a cronjob script unpushed-notify for on-screen notification of uncommited and unpushed changes.

Java - get index of key in HashMap?

The HashMap has no defined ordering of keys.

port forwarding in windows

I've solved it, it can be done executing:

netsh interface portproxy add v4tov4 listenport=4422 listenaddress=192.168.1.111 connectport=80 connectaddress=192.168.0.33

To remove forwarding:

netsh interface portproxy delete v4tov4 listenport=4422 listenaddress=192.168.1.111

Official docs

adb connection over tcp not working now

ADb used to work fine for me for a week. But now suddenly today it says the machine actively refused connection.

fix:

step 1: go check you phone's IP Adress once again, it keeps changing.
step 2: If it changed. Just use that new IP to connect.

Hope it helped someone :)

How to select rows with no matching entry in another table?

Here's a simple query:

SELECT t1.ID
FROM Table1 t1
    LEFT JOIN Table2 t2 ON t1.ID = t2.ID
WHERE t2.ID IS NULL

The key points are:

  1. LEFT JOIN is used; this will return ALL rows from Table1, regardless of whether or not there is a matching row in Table2.

  2. The WHERE t2.ID IS NULL clause; this will restrict the results returned to only those rows where the ID returned from Table2 is null - in other words there is NO record in Table2 for that particular ID from Table1. Table2.ID will be returned as NULL for all records from Table1 where the ID is not matched in Table2.

How do I find the parent directory in C#?

Since nothing else I have found helps to solve this in a truly normalized way, here is another answer.

Note that some answers to similar questions try to use the Uri type, but that struggles with trailing slashes vs. no trailing slashes too.

My other answer on this page works for operations that put the file system to work, but if we want to have the resolved path right now (such as for comparison reasons), without going through the file system, C:/Temp/.. and C:/ would be considered different. Without going through the file system, navigating in that manner does not provide us with a normalized, properly comparable path.

What can we do?

We will build on the following discovery:

Path.GetDirectoryName(path + "/") ?? "" will reliably give us a directory path without a trailing slash.

  • Adding a slash (as string, not as char) will treat a null path the same as it treats "".
  • GetDirectoryName will refrain from discarding the last path component thanks to the added slash.
  • GetDirectoryName will normalize slashes and navigational dots.
  • This includes the removal of any trailing slashes.
  • This includes collapsing .. by navigating up.
  • GetDirectoryName will return null for an empty path, which we coalesce to "".

How do we use this?

First, normalize the input path:

dirPath = Path.GetDirectoryName(dirPath + "/") ?? "";

Then, we can get the parent directory, and we can repeat this operation any number of times to navigate further up:

// This is reliable if path results from this or the previous operation
path = Path.GetDirectoryName(path);

Note that we have never touched the file system. No part of the path needs to exist, as it would if we had used DirectoryInfo.

Clone contents of a GitHub repository (without the folder itself)

to clone git repo into the current and empty folder (no git init) and if you do not use ssh:

git clone https://github.com/accountName/repoName.git .

How do I use DateTime.TryParse with a Nullable<DateTime>?

Here is a slightly concised edition of what Jason suggested:

DateTime? d; DateTime dt;
d = DateTime.TryParse(DateTime.Now.ToString(), out dt)? dt : (DateTime?)null;

SQL Server Express CREATE DATABASE permission denied in database 'master'

After I performed the following instructions in SSMS, everything works fine:

create login [IIS APPPOOL\MyWebAPP] from windows;

exec sp_addsrvrolemember N'IIS APPPOOL\MyWebAPP', sysadmin

How To Convert A Number To an ASCII Character?

you can simply cast it.

char c = (char)100;

javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found

Fix for Android N & above: I had similar issue and mange to solve it by following steps described in https://developer.android.com/training/articles/security-config

But the config changes, without any complicated code logic, would only work on Android version 24 & above.

Fix for all version, including version < N: So for android lower then N (version 24) the solution is to via code changes as mentioned above. If you are using OkHttp, then follow the customTrust: https://github.com/square/okhttp/blob/master/samples/guide/src/main/java/okhttp3/recipes/CustomTrust.java

How to limit the maximum value of a numeric field in a Django model?

I had this very same problem; here was my solution:

SCORE_CHOICES = zip( range(1,n), range(1,n) )
score = models.IntegerField(choices=SCORE_CHOICES, blank=True)

remove objects from array by object property

findIndex works for modern browsers:

var myArr = [{id:'a'},{id:'myid'},{id:'c'}];
var index = myArr.findIndex(function(o){
  return o.id === 'myid';
})
if (index !== -1) myArr.splice(index, 1);

Including JavaScript class definition from another file in Node.js

Using ES6, you can have user.js:

export default class User {
  constructor() {
    ...
  }
}

And then use it in server.js

const User = require('./user.js').default;
const user = new User();

How to escape regular expression special characters using javascript?

Use the backslash to escape a character. For example:

/\\d/

This will match \d instead of a numeric character

Can I obtain method parameter name using Java reflection?

Parameter names are only useful to the compiler. When the compiler generates a class file, the parameter names are not included - a method's argument list only consists of the number and types of its arguments. So it would be impossible to retrieve the parameter name using reflection (as tagged in your question) - it doesn't exist anywhere.

However, if the use of reflection is not a hard requirement, you can retrieve this information directly from the source code (assuming you have it).

How can I check the size of a file in a Windows batch script?

After a few "try and test" iterations I've found a way (still not present here) to get size of file in cycle variable (not a command line parameter):

for %%i in (*.txt) do (
    echo %%~z%i
)

How to parse XML using jQuery?

I went the way of jQuery's .parseXML() however found that the XML path syntax of 'Page[Name="test"] > controls > test' wouldn't work (if anyone knows why please shout out!).

Instead I chained together the individual .find() results into something that looked like this:

$xmlDoc.find('Page[Name="test"]')
       .find('contols')
       .find('test')

The result achieves the same as what I would expect the one shot find.

How to remove leading zeros using C#

It really depends on how long the NVARCHAR is, as a few of the above (especially the ones that convert through IntXX) methods will not work for:

String s = "005780327584329067506780657065786378061754654532164953264952469215462934562914562194562149516249516294563219437859043758430587066748932647329814687194673219673294677438907385032758065763278963247982360675680570678407806473296472036454612945621946";

Something like this would

String s ="0000058757843950000120465875468465874567456745674000004000".TrimStart(new Char[] { '0' } );
// s = "58757843950000120465875468465874567456745674000004000"

Could not create work tree dir 'example.com'.: Permission denied

Change ownership and permissions folder

sudo chown -R username.www-data /var/www

sudo chmod -R +rwx /var/www

How to compare dates in Java?

Update for Java 8 and later

These methods exists in LocalDate, LocalTime, and LocalDateTime classes.

Those classes are built into Java 8 and later. Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP (see How to use…).

Django: multiple models in one template using forms

I just was in about the same situation a day ago, and here are my 2 cents:

1) I found arguably the shortest and most concise demonstration of multiple model entry in single form here: http://collingrady.wordpress.com/2008/02/18/editing-multiple-objects-in-django-with-newforms/ .

In a nutshell: Make a form for each model, submit them both to template in a single <form>, using prefix keyarg and have the view handle validation. If there is dependency, just make sure you save the "parent" model before dependant, and use parent's ID for foreign key before commiting save of "child" model. The link has the demo.

2) Maybe formsets can be beaten into doing this, but as far as I delved in, formsets are primarily for entering multiples of the same model, which may be optionally tied to another model/models by foreign keys. However, there seem to be no default option for entering more than one model's data and that's not what formset seems to be meant for.

how to make password textbox value visible when hover an icon

In one line of code as below :

_x000D_
_x000D_
<p> cursor on text field shows text .if not password will be shown</p>_x000D_
<input type="password" name="txt_password" onmouseover="this.type='text'"_x000D_
       onmouseout="this.type='password'" placeholder="password" />
_x000D_
_x000D_
_x000D_

How do I vertically align text in a div?

HTML :

<div class="col-md-2 ml-2 align-middle">
    <label for="option2" id="time-label">Time</label>
</div>

CSS :

.align-middle {
    margin-top: auto;
    margin-bottom: auto;
}

Changing Tint / Background color of UITabBar

if ([tabBar respondsToSelector:@selector(setBackgroundImage:)]) {
    // ios 5 code here
    [tabBar setBackgroundImage:[UIImage imageNamed:@"image.png"]];
} 
else {
    // ios 4 code here
    CGRect frame = CGRectMake(0, 0, 480, 49);
    UIView *tabbg_view = [[UIView alloc] initWithFrame:frame];
    UIImage *tabbag_image = [UIImage imageNamed:@"image.png"];
    UIColor *tabbg_color = [[UIColor alloc] initWithPatternImage:tabbag_image];
    tabbg_view.backgroundColor = tabbg_color;
    [tabBar insertSubview:tabbg_view atIndex:0];
}

How can I regenerate ios folder in React Native project?

This is too late, but for anyone who is still having same issue and have a detached react native app, what i did for me I just run exp detach over my detached app and it created ios folder!

How to execute function in SQL Server 2008

It looks like there's something else called Afisho_rankimin in your DB so the function is not being created. Try calling your function something else. E.g.

CREATE FUNCTION dbo.Afisho_rankimin1(@emri_rest int)
RETURNS int
AS
   BEGIN
       Declare @rankimi int
       Select @rankimi=dbo.RESTORANTET.Rankimi
       From RESTORANTET
       Where  dbo.RESTORANTET.ID_Rest=@emri_rest
       RETURN @rankimi
  END
  GO

Note that you need to call this only once, not every time you call the function. After that try calling

SELECT dbo.Afisho_rankimin1(5) AS Rankimi 

How to get a random value from dictionary?

Try this (using random.choice from items)

import random

a={ "str" : "sda" , "number" : 123, 55 : "num"}
random.choice(list(a.items()))
#  ('str', 'sda')
random.choice(list(a.items()))[1] # getting a value
#  'num'

Setting the default active profile in Spring-boot

The neat way to do this without changing your source code each time is to use the OS environment variable SPRING_PROFILES_ACTIVE:

export SPRING_PROFILES_ACTIVE=production

how-to-set-active-spring-profiles

How do I create an Excel chart that pulls data from multiple sheets?

2007 is more powerful with ribbon..:=) To add new series in chart do: Select Chart, then click Design in Chart Tools on the ribbon, On the Design ribbon, select "Select Data" in Data Group, Then you will see the button for Add to add new series.

Hope that will help.

Set Colorbar Range in matplotlib

Use the CLIM function (equivalent to CAXIS function in MATLAB):

plt.pcolor(X, Y, v, cmap=cm)
plt.clim(-4,4)  # identical to caxis([-4,4]) in MATLAB
plt.show()

A method to count occurrences in a list

var wordCount =
    from word in words
    group word by word into g
    select new { g.Key, Count = g.Count() };    

This is taken from one of the examples in the linqpad

C# Dictionary get item by index

You can take keys or values per index:

int value = _dict.Values.ElementAt(5);//ElementAt value should be <= _dict.Count - 1
string key = _dict.Keys.ElementAt(5);//ElementAt value should be  < =_dict.Count - 1

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().

Check if a variable is between two numbers with Java

Assuming you are programming in Java, this works:

if (90 >= angle  &&  angle <= 180 )  {

(don't you mean 90 is less than angle? If so: 90 <= angle)

Handle JSON Decode Error when nothing returned

There is a rule in Python programming called "it is Easier to Ask for Forgiveness than for Permission" (in short: EAFP). It means that you should catch exceptions instead of checking values for validity.

Thus, try the following:

try:
    qByUser = byUsrUrlObj.read()
    qUserData = json.loads(qByUser).decode('utf-8')
    questionSubjs = qUserData["all"]["questions"]
except ValueError:  # includes simplejson.decoder.JSONDecodeError
    print 'Decoding JSON has failed'

EDIT: Since simplejson.decoder.JSONDecodeError actually inherits from ValueError (proof here), I simplified the catch statement by just using ValueError.

How to embed image or picture in jupyter notebook, either from a local machine or from a web resource?

In addition to the other answers using HTML (either in Markdown or using the %%HTML magic:

If you need to specify the image height, this will not work:

<img src="image.png" height=50> <-- will not work

That is because the CSS styling in Jupyter uses height: auto per default for the img tags, which overrides the HTML height attribute. You need need to overwrite the CSS height attribute instead:

<img src="image.png" style="height:50px"> <-- works

How to output to the console and file?

I came up with this [untested]

import sys

class Tee(object):
    def __init__(self, *files):
        self.files = files
    def write(self, obj):
        for f in self.files:
            f.write(obj)
            f.flush() # If you want the output to be visible immediately
    def flush(self) :
        for f in self.files:
            f.flush()

f = open('out.txt', 'w')
original = sys.stdout
sys.stdout = Tee(sys.stdout, f)
print "test"  # This will go to stdout and the file out.txt

#use the original
sys.stdout = original
print "This won't appear on file"  # Only on stdout
f.close()

print>>xyz in python will expect a write() function in xyz. You could use your own custom object which has this. Or else, you could also have sys.stdout refer to your object, in which case it will be tee-ed even without >>xyz.

Pandas groupby month and year

There are different ways to do that.

  • I created the data frame to showcase the different techniques to filter your data.
df = pd.DataFrame({'Date':['01-Jun-13','03-Jun-13', '15-Aug-13', '20-Jan-14', '21-Feb-14'],

'abc':[100,-20,40,25,60],'xyz':[200,50,-5,15,80] })

  • I separated months/year/day and seperated month-year as you explained.
def getMonth(s):
  return s.split("-")[1]

def getDay(s):
  return s.split("-")[0]

def getYear(s):
  return s.split("-")[2]

def getYearMonth(s):
  return s.split("-")[1]+"-"+s.split("-")[2]
  • I created new columns: year, month, day and 'yearMonth'. In your case, you need one of both. You can group using two columns 'year','month' or using one column yearMonth
df['year']= df['Date'].apply(lambda x: getYear(x))
df['month']= df['Date'].apply(lambda x: getMonth(x))
df['day']= df['Date'].apply(lambda x: getDay(x))
df['YearMonth']= df['Date'].apply(lambda x: getYearMonth(x))

Output:

        Date  abc  xyz year month day YearMonth
0  01-Jun-13  100  200   13   Jun  01    Jun-13
1  03-Jun-13  -20   50   13   Jun  03    Jun-13
2  15-Aug-13   40   -5   13   Aug  15    Aug-13
3  20-Jan-14   25   15   14   Jan  20    Jan-14
4  21-Feb-14   60   80   14   Feb  21    Feb-14
  • You can go through the different groups in groupby(..) items.

In this case, we are grouping by two columns:

for key,g in df.groupby(['year','month']):
    print key,g

Output:

('13', 'Jun')         Date  abc  xyz year month day YearMonth
0  01-Jun-13  100  200   13   Jun  01    Jun-13
1  03-Jun-13  -20   50   13   Jun  03    Jun-13
('13', 'Aug')         Date  abc  xyz year month day YearMonth
2  15-Aug-13   40   -5   13   Aug  15    Aug-13
('14', 'Jan')         Date  abc  xyz year month day YearMonth
3  20-Jan-14   25   15   14   Jan  20    Jan-14
('14', 'Feb')         Date  abc  xyz year month day YearMonth

In this case, we are grouping by one column:

for key,g in df.groupby(['YearMonth']):
    print key,g

Output:

Jun-13         Date  abc  xyz year month day YearMonth
0  01-Jun-13  100  200   13   Jun  01    Jun-13
1  03-Jun-13  -20   50   13   Jun  03    Jun-13
Aug-13         Date  abc  xyz year month day YearMonth
2  15-Aug-13   40   -5   13   Aug  15    Aug-13
Jan-14         Date  abc  xyz year month day YearMonth
3  20-Jan-14   25   15   14   Jan  20    Jan-14
Feb-14         Date  abc  xyz year month day YearMonth
4  21-Feb-14   60   80   14   Feb  21    Feb-14
  • In case you wanna access to specific item, you can use get_group

print df.groupby(['YearMonth']).get_group('Jun-13')

Output:

        Date  abc  xyz year month day YearMonth
0  01-Jun-13  100  200   13   Jun  01    Jun-13
1  03-Jun-13  -20   50   13   Jun  03    Jun-13
  • Similar to get_group. This hack would help to filter values and get the grouped values.

This also would give the same result.

print df[df['YearMonth']=='Jun-13'] 

Output:

        Date  abc  xyz year month day YearMonth
0  01-Jun-13  100  200   13   Jun  01    Jun-13
1  03-Jun-13  -20   50   13   Jun  03    Jun-13

You can select list of abc or xyz values during Jun-13

print df[df['YearMonth']=='Jun-13'].abc.values
print df[df['YearMonth']=='Jun-13'].xyz.values

Output:

[100 -20]  #abc values
[200  50]  #xyz values

You can use this to go through the dates that you have classified as "year-month" and apply cretiria on it to get related data.

for x in set(df.YearMonth): 
    print df[df['YearMonth']==x].abc.values
    print df[df['YearMonth']==x].xyz.values

I recommend also to check this answer as well.

Explanation of "ClassCastException" in Java

It's really pretty simple: if you are trying to typecast an object of class A into an object of class B, and they aren't compatible, you get a class cast exception.

Let's think of a collection of classes.

class A {...}
class B extends A {...}
class C extends A {...}
  1. You can cast any of these things to Object, because all Java classes inherit from Object.
  2. You can cast either B or C to A, because they're both "kinds of" A
  3. You can cast a reference to an A object to B only if the real object is a B.
  4. You can't cast a B to a C even though they're both A's.

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

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

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

Find JavaScript function definition in Chrome

You can print the function by evaluating the name of it in the console, like so

> unknownFunc
function unknownFunc(unknown) {
    alert('unknown seems to be ' + unknown);
}

this won't work for built-in functions, they will only display [native code] instead of the source code.

EDIT: this implies that the function has been defined within the current scope.

Paste Excel range in Outlook

Often this question is asked in the context of Ron de Bruin's RangeToHTML function, which creates an HTML PublishObject from an Excel.Range, extracts that via FSO, and inserts the resulting stream HTML in to the email's HTMLBody. In doing so, this removes the default signature (the RangeToHTML function has a helper function GetBoiler which attempts to insert the default signature).

Unfortunately, the poorly-documented Application.CommandBars method is not available via Outlook:

wdDoc.Application.CommandBars.ExecuteMso "PasteExcelTableSourceFormatting"

It will raise a runtime 6158:

enter image description here

But we can still leverage the Word.Document which is accessible via the MailItem.GetInspector method, we can do something like this to copy & paste the selection from Excel to the Outlook email body, preserving your default signature (if there is one).

Dim rng as Range
Set rng = Range("A1:F10") 'Modify as needed

With OutMail
    .To = "[email protected]"
    .BCC = ""
    .Subject = "Subject"
    .Display
    Dim wdDoc As Object     '## Word.Document
    Dim wdRange As Object   '## Word.Range
    Set wdDoc = OutMail.GetInspector.WordEditor
    Set wdRange = wdDoc.Range(0, 0)
    wdRange.InsertAfter vbCrLf & vbCrLf
    'Copy the range in-place
    rng.Copy
    wdRange.Paste
End With

Note that in some cases this may not perfectly preserve the column widths or in some instances the row heights, and while it will also copy shapes and other objects in the Excel range, this may also cause some funky alignment issues, but for simple tables and Excel ranges, it is very good:

enter image description here

Difference between & and && in Java?

&& == logical AND

& = bitwise AND

Laravel Pagination links not including other GET parameters

Be aware of the Input::all() , it will Include the previous ?page= values again and again in each page you open !
for example if you are in ?page=1 and you open the next page, it will open ?page=1&page=2
So the last value page takes will be the page you see ! not the page you want to see

Solution : use Input::except(array('page'))

How to get equal width of input and select fields

Updated answer

Here is how to change the box model used by the input/textarea/select elements so that they all behave the same way. You need to use the box-sizing property which is implemented with a prefix for each browser

-ms-box-sizing:content-box;
-moz-box-sizing:content-box;
-webkit-box-sizing:content-box; 
box-sizing:content-box;

This means that the 2px difference we mentioned earlier does not exist..

example at http://www.jsfiddle.net/gaby/WaxTS/5/

note: On IE it works from version 8 and upwards..


Original

if you reset their borders then the select element will always be 2 pixels less than the input elements..

example: http://www.jsfiddle.net/gaby/WaxTS/2/

Unresolved Import Issues with PyDev and Eclipse

project-->properties-->pydev-pythonpath-->external libraries --> add source folder, add the PARENT FOLDER of the project. Then restart eclipse.

sql: check if entry in table A exists in table B

SELECT *
FROM   B
WHERE  NOT EXISTS (SELECT 1 
                   FROM   A 
                   WHERE  A.ID = B.ID)

How to count items in JSON object using command line?

The shortest expression is

curl 'http://…' | jq length

400 BAD request HTTP error code meaning?

A 400 means that the request was malformed. In other words, the data stream sent by the client to the server didn't follow the rules.

In the case of a REST API with a JSON payload, 400's are typically, and correctly I would say, used to indicate that the JSON is invalid in some way according to the API specification for the service.

By that logic, both the scenarios you provided should be 400s.

Imagine instead this were XML rather than JSON. In both cases, the XML would never pass schema validation--either because of an undefined element or an improper element value. That would be a bad request. Same deal here.

How to define Singleton in TypeScript

i think maybe use generics be batter

class Singleton<T>{
    public static Instance<T>(c: {new(): T; }) : T{
        if (this._instance == null){
            this._instance = new c();
        }
        return this._instance;
    }

    private static _instance = null;
}

how to use

step1

class MapManager extends Singleton<MapManager>{
     //do something
     public init():void{ //do }
}

step2

    MapManager.Instance(MapManager).init();

Ruby on Rails. How do I use the Active Record .build method in a :belongs to relationship?

@article = user.articles.build(:title => "MainTitle")
@article.save

How to implode array with key and value without foreach in PHP

You could use http_build_query, like this:

<?php
  $a=array("item1"=>"object1", "item2"=>"object2");
  echo http_build_query($a,'',', ');
?>

Output:

item1=object1, item2=object2 

Demo

"element.dispatchEvent is not a function" js error caught in firebug of FF3.0

Change the following line

$(document).ready(function() {

To

jQuery.noConflict();
jQuery(document).ready(function($) {

How can I hide/show a div when a button is clicked?

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Show and hide div with JavaScript</title>
<script>

    var button_beg = '<button id="button" onclick="showhide()">', button_end = '</button>';
    var show_button = 'Show', hide_button = 'Hide';
    function showhide() {
        var div = document.getElementById( "hide_show" );
        var showhide = document.getElementById( "showhide" );
        if ( div.style.display !== "none" ) {
            div.style.display = "none";
            button = show_button;
            showhide.innerHTML = button_beg + button + button_end;
        } else {
            div.style.display = "block";
            button = hide_button;
            showhide.innerHTML = button_beg + button + button_end;
        }
    }
    function setup_button( status ) {
        if ( status == 'show' ) {
            button = hide_button;
        } else {
            button = show_button;
        }
        var showhide = document.getElementById( "showhide" );
        showhide.innerHTML = button_beg + button + button_end;
    }
    window.onload = function () {
        setup_button( 'hide' );
        showhide(); // if setup_button is set to 'show' comment this line
    }
</script>
</head>
<body>
    <div id="showhide"></div>
    <div id="hide_show">
        <p>This div will be show and hide on button click</p>
    </div>
</body>
</html>

How can I change column types in Spark SQL's DataFrame?

You can use selectExpr to make it a little cleaner:

df.selectExpr("cast(year as int) as year", "upper(make) as make",
    "model", "comment", "blank")

Regex allow digits and a single dot

My try is combined solution.

string = string.replace(',', '.').replace(/[^\d\.]/g, "").replace(/\./, "x").replace(/\./g, "").replace(/x/, ".");
string = Math.round( parseFloat(string) * 100) / 100;

First line solution from here: regex replacing multiple periods in floating number . It replaces comma "," with dot "." ; Replaces first comma with x; Removes all dots and replaces x back to dot.

Second line cleans numbers after dot.

Read binary file as string in Ruby

how about some open/close safety.

string = File.open('file.txt', 'rb') { |file| file.read }

How do I choose the URL for my Spring Boot webapp?

You need to set the property server.contextPath to /myWebApp.

Check out this part of the documentation

The easiest way to set that property would be in the properties file you are using (most likely application.properties) but Spring Boot provides a whole lot of different way to set properties. Check out this part of the documentation

EDIT

As has been mentioned by @AbdullahKhan, as of Spring Boot 2.x the property has been deprecated and should be replaced with server.servlet.contextPath as has been correctly mentioned in this answer.

How to clean up R memory (without the need to restart my PC)?

I came under the same problem with R. I dig a bit and come with a solution, that we need to restart R session to fully clean the memory/RAM. For this, you can use a simple code after removing everything from your workspace. the code is as follows :

rm(list = ls())

.rs.restartR()

Python timedelta in years

First off, at the most detailed level, the problem can't be solved exactly. Years vary in length, and there isn't a clear "right choice" for year length.

That said, get the difference in whatever units are "natural" (probably seconds) and divide by the ratio between that and years. E.g.

delta_in_days / (365.25)
delta_in_seconds / (365.25*24*60*60)

...or whatever. Stay away from months, since they are even less well defined than years.

push() a two-dimensional array

You have some errors in your code:

  1. Use myArray[i].push( 0 ); to add a new column. Your code (myArray[i][j].push(0);) would work in a 3-dimensional array as it tries to add another element to an array at position [i][j].
  2. You only expand (col-d)-many columns in all rows, even in those, which haven't been initialized yet and thus have no entries so far.

One correct, although kind of verbose version, would be the following:

var r = 3; //start from rows 3

var rows = 8;
var cols = 7;

// expand to have the correct amount or rows
for( var i=r; i<rows; i++ ) {
  myArray.push( [] );
}

// expand all rows to have the correct amount of cols
for (var i = 0; i < rows; i++)
{
    for (var j =  myArray[i].length; j < cols; j++)
    {
        myArray[i].push(0);
    }
}

Why would we call cin.clear() and cin.ignore() after reading input?

The cin.clear() clears the error flag on cin (so that future I/O operations will work correctly), and then cin.ignore(10000, '\n') skips to the next newline (to ignore anything else on the same line as the non-number so that it does not cause another parse failure). It will only skip up to 10000 characters, so the code is assuming the user will not put in a very long, invalid line.

What's a good hex editor/viewer for the Mac?

  1. Open file with Xcode and press Command + Shift + J
  2. Right click file name in left pane
  3. Open as -> Hex

Maximum number of threads in a .NET app?

There is no inherent limit. The maximum number of threads is determined by the amount of physical resources available. See this article by Raymond Chen for specifics.

If you need to ask what the maximum number of threads is, you are probably doing something wrong.

[Update: Just out of interest: .NET Thread Pool default numbers of threads:

  • 1023 in Framework 4.0 (32-bit environment)
  • 32767 in Framework 4.0 (64-bit environment)
  • 250 per core in Framework 3.5
  • 25 per core in Framework 2.0

(These numbers may vary depending upon the hardware and OS)]

Removing ul indentation with CSS

-webkit-padding-start: 0;

will remove padding added by webkit engine

Get remote registry value

For remote registry you have to use .NET with powershell 2.0

$w32reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine',$computer1)
$keypath = 'SOFTWARE\Veritas\NetBackup\CurrentVersion'
$netbackup = $w32reg.OpenSubKey($keypath)
$NetbackupVersion1 = $netbackup.GetValue('PackageVersion')

Changing tab bar item image and text color iOS

Swift 3

This worked for me (referring to set tabBarItems image colors):

UITabBar.appearance().tintColor = ThemeColor.Blue

if let items = tabBarController.tabBar.items {
        let tabBarImages = getTabBarImages() // tabBarImages: [UIImage]
        for i in 0..<items.count {
            let tabBarItem = items[i]
            let tabBarImage = tabBarImages[i]
            tabBarItem.image = tabBarImage.withRenderingMode(.alwaysOriginal)
            tabBarItem.selectedImage = tabBarImage
        }
    }

I have noticed that if you set image with rendering mode = .alwaysOriginal, the UITabBar.tintColor doesn't have any effect.

Auto margins don't center image in page

Under some circumstances (such as earlier versions of IE, Gecko, Webkit) and inheritance, elements with position:relative; will prevent margin:0 auto; from working, even if top, right, bottom, and left aren't set.

Setting the element to position:static; (the default) may fix it under these circumstances. Generally, block level elements with a specified width will respect margin:0 auto; using either relative or static positioning.

Semaphore vs. Monitors - what's the difference?

A Monitor is an object designed to be accessed from multiple threads. The member functions or methods of a monitor object will enforce mutual exclusion, so only one thread may be performing any action on the object at a given time. If one thread is currently executing a member function of the object then any other thread that tries to call a member function of that object will have to wait until the first has finished.

A Semaphore is a lower-level object. You might well use a semaphore to implement a monitor. A semaphore essentially is just a counter. When the counter is positive, if a thread tries to acquire the semaphore then it is allowed, and the counter is decremented. When a thread is done then it releases the semaphore, and increments the counter.

If the counter is already zero when a thread tries to acquire the semaphore then it has to wait until another thread releases the semaphore. If multiple threads are waiting when a thread releases a semaphore then one of them gets it. The thread that releases a semaphore need not be the same thread that acquired it.

A monitor is like a public toilet. Only one person can enter at a time. They lock the door to prevent anyone else coming in, do their stuff, and then unlock it when they leave.

A semaphore is like a bike hire place. They have a certain number of bikes. If you try and hire a bike and they have one free then you can take it, otherwise you must wait. When someone returns their bike then someone else can take it. If you have a bike then you can give it to someone else to return --- the bike hire place doesn't care who returns it, as long as they get their bike back.

How can I add a PHP page to WordPress?

If you're like me, sometimes you want to be able to reference WordPress functions in a page which does not exist in the CMS. This way, it remains backend-specific and cannot be accidentally deleted by the client.

This is actually simple to do just by including the wp-blog-header.php file using a PHP require().

Here's an example that uses a query string to generate Facebook Open Graph (OG) data for any post.

Take the example of a link like http://example.com/yourfilename.php?1 where 1 is the ID of a post we want to generate OG data for:

Now in the contents of yourfilename.php which, for our convenience, is located in the root WordPress directory:

<?php
    require( dirname( __FILE__ ) . '/wp-blog-header.php' );

    $uri = $_SERVER['REQUEST_URI'];
    $pieces = explode("?", $uri);
    $post_id = intval( $pieces[1] );

    // og:title
    $title = get_the_title($post_id);

    // og:description
    $post = get_post($post_id);
    $descr = $post->post_excerpt;

    // og:image
    $img_data_array = get_attached_media('image', $post_id);
    $img_src = null;
    $img_count = 0;

    foreach ( $img_data_array as $img_data ) {
        if ( $img_count > 0 ) {
            break;
        } else {
            ++$img_count;
            $img_src = $img_data->guid;
        }
    } // end og:image

?>
<!DOCTYPE HTML>
<html>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, user-scalable=yes" />
<meta property="og:title" content="<?php echo $title; ?>" />
<meta property="og:description" content="<?php echo $descr; ?>" />
<meta property="og:locale" content="en_US" />
<meta property="og:type" content="website" />
<meta property="og:url" content="<?php echo site_url().'/your_redirect_path'.$post_id; ?>" />
<meta property="og:image" content="<?php echo $img_src; ?>" />
<meta property="og:site_name" content="Your Title" />
</html>

There you have it: generated sharing models for any post using the post's actual image, excerpt and title!

We could have created a special template and edited the permalink structure to do this, but since it's only needed for one page and because we don't want the client to delete it from within the CMS, this seemed like the cleaner option.


EDIT 2017: Please note that this approach is now deprecated

For WordPress installations from 2016+ please see How can I add a PHP page to WordPress? for extra parameters to include before outputting your page data to the browser.

Java regex capturing groups indexes

Capturing and grouping

Capturing group (pattern) creates a group that has capturing property.

A related one that you might often see (and use) is (?:pattern), which creates a group without capturing property, hence named non-capturing group.

A group is usually used when you need to repeat a sequence of patterns, e.g. (\.\w+)+, or to specify where alternation should take effect, e.g. ^(0*1|1*0)$ (^, then 0*1 or 1*0, then $) versus ^0*1|1*0$ (^0*1 or 1*0$).

A capturing group, apart from grouping, will also record the text matched by the pattern inside the capturing group (pattern). Using your example, (.*):, .* matches ABC and : matches :, and since .* is inside capturing group (.*), the text ABC is recorded for the capturing group 1.

Group number

The whole pattern is defined to be group number 0.

Any capturing group in the pattern start indexing from 1. The indices are defined by the order of the opening parentheses of the capturing groups. As an example, here are all 5 capturing groups in the below pattern:

(group)(?:non-capturing-group)(g(?:ro|u)p( (nested)inside)(another)group)(?=assertion)
|     |                       |          | |      |      ||       |     |
1-----1                       |          | 4------4      |5-------5     |
                              |          3---------------3              |
                              2-----------------------------------------2

The group numbers are used in back-reference \n in pattern and $n in replacement string.

In other regex flavors (PCRE, Perl), they can also be used in sub-routine calls.

You can access the text matched by certain group with Matcher.group(int group). The group numbers can be identified with the rule stated above.

In some regex flavors (PCRE, Perl), there is a branch reset feature which allows you to use the same number for capturing groups in different branches of alternation.

Group name

From Java 7, you can define a named capturing group (?<name>pattern), and you can access the content matched with Matcher.group(String name). The regex is longer, but the code is more meaningful, since it indicates what you are trying to match or extract with the regex.

The group names are used in back-reference \k<name> in pattern and ${name} in replacement string.

Named capturing groups are still numbered with the same numbering scheme, so they can also be accessed via Matcher.group(int group).

Internally, Java's implementation just maps from the name to the group number. Therefore, you cannot use the same name for 2 different capturing groups.

Remove HTML Tags from an NSString on the iPhone

Take a look at NSXMLParser. It's a SAX-style parser. You should be able to use it to detect tags or other unwanted elements in the XML document and ignore them, capturing only pure text.

Uploading into folder in FTP?

The folder is part of the URL you set when you create request: "ftp://www.contoso.com/test.htm". If you use "ftp://www.contoso.com/wibble/test.htm" then the file will be uploaded to a folder named wibble.

You may need to first use a request with Method = WebRequestMethods.Ftp.MakeDirectory to make the wibble folder if it doesn't already exist.

FULL OUTER JOIN vs. FULL JOIN

Actually they are the same. LEFT OUTER JOIN is same as LEFT JOIN and RIGHT OUTER JOIN is same as RIGHT JOIN. It is more informative way to compare from INNER Join.

See this Wikipedia article for details.

How to run Rake tasks from within Rake tasks?

task :build_all do
  [ :debug, :release ].each do |t|
    $build_type = t
    Rake::Task["build"].execute
  end
end

How to place div in top right hand corner of page

You can use css float

<div style='float: left;'><a href="login.php">Log in</a></div>

<div style='float: right;'><a href="home.php">Back to Home</a></div>

Have a look at this CSS Positioning

Getting list of lists into pandas DataFrame

With approach explained by EdChum above, the values in the list are shown as rows. To show the values of lists as columns in DataFrame instead, simply use transpose() as following:

table = [[1 , 2], [3, 4]]
df = pd.DataFrame(table)
df = df.transpose()
df.columns = ['Heading1', 'Heading2']

The output then is:

      Heading1  Heading2
0         1        3
1         2        4

git commit error: pathspec 'commit' did not match any file(s) known to git

In my case, the problem was I used wrong alias for git commit -m. I used gcalias which dit not meant git commit -m

Delete rows with blank values in one particular column

An elegant solution with dplyr would be:

df %>%
  # recode empty strings "" by NAs
  na_if("") %>%
  # remove NAs
  na.omit

Encoding URL query parameters in Java

String param="2019-07-18 19:29:37";
param="%27"+param.trim().replace(" ", "%20")+"%27";

I observed in case of Datetime (Timestamp) URLEncoder.encode(param,"UTF-8") does not work.

How to use OUTPUT parameter in Stored Procedure

The SQL in your SP is wrong. You probably want

Select @code = RecItemCode from Receipt where RecTransaction = @id

In your statement, you are not setting @code, you are trying to use it for the value of RecItemCode. This would explain your NullReferenceException when you try to use the output parameter, because a value is never assigned to it and you're getting a default null.

The other issue is that your SQL statement if rewritten as

Select @code = RecItemCode, RecUsername from Receipt where RecTransaction = @id

It is mixing variable assignment and data retrieval. This highlights a couple of points. If you need the data that is driving @code in addition to other parts of the data, forget the output parameter and just select the data.

Select RecItemCode, RecUsername from Receipt where RecTransaction = @id

If you just need the code, use the first SQL statement I showed you. On the offhand chance you actually need the output and the data, use two different statements

Select @code = RecItemCode from Receipt where RecTransaction = @id
Select RecItemCode, RecUsername from Receipt where RecTransaction = @id

This should assign your value to the output parameter as well as return two columns of data in a row. However, this strikes me as terribly redundant.

If you write your SP as I have shown at the very top, simply invoke cmd.ExecuteNonQuery(); and then read the output parameter value.


Another issue with your SP and code. In your SP, you have declared @code as varchar. In your code, you specify the parameter type as Int. Either change your SP or your code to make the types consistent.


Also note: If all you are doing is returning a single value, there's another way to do it that does not involve output parameters at all. You could write

 Select RecItemCode from Receipt where RecTransaction = @id

And then use object obj = cmd.ExecuteScalar(); to get the result, no need for an output parameter in the SP or in your code.

Different font size of strings in the same TextView

I have written my own function which takes 2 strings and 1 int (text size)

The full text and the part of the text you want to change the size of it.

It returns a SpannableStringBuilder which you can use it in text view.

  public static SpannableStringBuilder setSectionOfTextSize(String text, String textToChangeSize, int size){

        SpannableStringBuilder builder=new SpannableStringBuilder();

        if(textToChangeSize.length() > 0 && !textToChangeSize.trim().equals("")){

            //for counting start/end indexes
            String testText = text.toLowerCase(Locale.US);
            String testTextToBold = textToChangeSize.toLowerCase(Locale.US);
            int startingIndex = testText.indexOf(testTextToBold);
            int endingIndex = startingIndex + testTextToBold.length();
            //for counting start/end indexes

            if(startingIndex < 0 || endingIndex <0){
                return builder.append(text);
            }
            else if(startingIndex >= 0 && endingIndex >=0){

                builder.append(text);
                builder.setSpan(new AbsoluteSizeSpan(size, true), startingIndex, endingIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }else{
            return builder.append(text);
        }

        return builder;
    }

How to access to a child method from the parent in vue.js

To communicate a child component with another child component I've made a method in parent which calls a method in a child with:

this.$refs.childMethod()

And from the another child I've called the root method:

this.$root.theRootMethod()

It worked for me.

How to exit a 'git status' list in a terminal?

Type 'q' and it will do the job.

Whenever you are at the terminal and have a similar predicament keep in mind also to try and type 'quit', 'exit' as well as the abort key combination 'Ctrl + C'.

How to make shadow on border-bottom?

Try:

_x000D_
_x000D_
div{_x000D_
-webkit-box-shadow:0px 1px 1px #de1dde;_x000D_
 -moz-box-shadow:0px 1px 1px #de1dde;_x000D_
 box-shadow:0px 1px 1px #de1dde;_x000D_
  }
_x000D_
<div>wefwefwef</div>
_x000D_
_x000D_
_x000D_

It generally adds a 1px blurred shadow 1px from the bottom of the box

box-shadow: [horizontal offset] [vertical offset] [blur radius] [color];

I keep getting this error for my simple python program: "TypeError: 'float' object cannot be interpreted as an integer"

Also possible is to fix this with np.arange() instead of range which works for float numbers:

import numpy as np
for i in np.arange(c/10):