text:
from __future__ import print_function
from builtins import zip
from builtins import range
from builtins import object
## interp_coverage.py

# The usable interface to this will probably be part of field.py

from functools import reduce

import shapely.geometry

try:
    from . import constrained_delaunay
    import CGAL
except ImportError:
    # print "interp_coverage is not available"
    CGAL = None

# Read a shapefile with overlapping polygons and interpolate in the intersecting regions

# The direct application is merging bathymetry datasets - define a set of polygons that
# cover the domain where each polygon is linked to a dataset.
# For a point that lies in exactly one of these polygons, the corresponding dataset
# determines the value at the point.
# For a point that lies in more than one polygon, it's value is weighted linearly between
# each of the polygons, depending on which border it is closest to.

# Algorithm:
#   Compute a constrained Delaunay triangulation of all edges making up the polygons.
#   Special care must be taken at the intersections
#   Each vertex is given a vector defining its membership in the boundaries of the polygons.
#   Most vertices then have a vector with exactly one nonzero entry.
#   Vertices that define the intersection of polygon boundaries will have nonzero entries
#   for each of the boundaries.

# hmm - may have a problem here - really we want the distance from a given point to each of
#  the boundaries that define the intersection.  But with just a straight DT there's no
#  guarantee that we'll be a in a triangle that touches both polygon boundaries.

# So we need a point-polygon distance.  Does shapely or CGAL help us out?
# This would mean that the DT would tell us which polygons to consult, and the distance
# function would give the weightings.
# Shapely gives a distance function for min. distance between arbitrary geometries.

# Handling an intersection of more than two regions is a little tricky -
# Is it too slow to do an all-combinations intersection?  basically want to enumerate every
#  part of the Venn diagram
# Maybe look at each region in order
# compare it against all subsequent regions
# If there is an intersection, split the region into the non-intersecting portion, and the
# intersecting portion.  Each region, whether original or after being carved up, maintains
# a list of the regions that were intersected to get this region.
#

# Now we have the plane sliced up into pieces, where each polygon defines the intersection
# of N regions.

# Given some point, we find the polygon it lives in - this tells us which regions are going
# to have nonzero weights.

# How to assign weights within a polygon?
#  Definitely require that on a boundary with another region whose src vector has one nonzero
#  we have to be equal to that value.
# For each participating region, find the distance from a point to the edge of that region.
# This is probably done by taking the LinearRing for each regiong and finding the min. distance
# to it.  This gives us a distance for each region.  Then weights can be applied, probably linearly?

import numpy as np

import shapely.wkb
import shapely.geometry

from collections import OrderedDict

# from osgeo import ogr
from stompy.spatial import wkb2shp
from stompy.plot import plot_wkb

class Region(object):
    def __init__(self,feat):
        self.items=OrderedDict()

        for fld in feat.dtype.names:
            self.items[fld]=feat[fld]

        self.geom=feat['geom']
        self.boundary=self.geom.boundary
        self.items['boundary'] = self.boundary

    def plot(self):
        plot_wkb.plot_multipolygon(self.geom)

    def distance_to_boundary(self,pnt):
        return self.boundary.distance(pnt)

    def identifier(self):
        return ":".join([str(self.items[f])[:20]
                         for f in self.items
                         if f not in ['geom','boundary'] ])

class InterpCoverage(object):
    boneyard = []

    def __init__(self,regions_shp=None,regions_data=None,subset=None):
        if regions_shp is not None:
            self.regions_shp = regions_shp
            self.regions_data=None
        else:
            assert regions_data is not None
            self.regions_data=regions_data
            self.regions_shp=None

        self.load_shp(subset=subset)
        self.find_intersections()

    def load_shp(self,subset=None):
        if self.regions_shp is not None:
            self.shp_data=wkb2shp.shp2geom(self.regions_shp)
        else:
            self.shp_data=self.regions_data

        if subset is not None:
            self.shp_data=self.shp_data[subset]

        self.regions = [ Region(rec) for rec in self.shp_data]

    def find_intersections(self):
        geoms = [r.geom for r in self.regions]
        ii = np.arange(len(geoms))
        srcs = [ (ii==i) for i in range(len(geoms))]

        # DBG
        fns = [r.identifier() for r in self.regions]

        coverage = list(zip( geoms,srcs ))

        # iterate through the geoms, expanding coverage by however
        # each geom cuts it up

        total_coverage = None
        for i in range(len(geoms)):
            #print "processing geom for ",fns[i]

            g = geoms[i]

            # at the same time, we compute the union of all regions to speed up
            # out-of-bounds queries later on.
            if total_coverage is None:
                total_coverage = g
            else:
                total_coverage = total_coverage.union(g)

            new_coverage = []

            # take a possibly multipart geometry, and the source vector to go with it,
            # and append to new_coverage
            def add_new_geoms(new_geom,new_src):
                # geom_in_g may be multipart:
                if new_geom.type == 'Polygon':
                    new_coverage.append( (new_geom,new_src) )
                elif new_geom.type == 'MultiPolygon' or new_geom.type == 'GeometryCollection':
                    # Avoid memory related seg faults by not freeing these geometries
                    self.boneyard.append(new_geom)
                    for g in new_geom.geoms:
                        if g.type == 'Polygon':
                            new_coverage.append( (g,new_src) )
                        else:
                            print("Skipping sub-geometry of type %s"%g.type)
                            print(g.wkt)

            for gcover,src in coverage:
                if src[i]:
                    #print "Comparing %d with src %s"%(i,src)
                    # This coverage is already known to be a subset of g
                    new_coverage.append( (gcover,src) )
                else:
                    geom_in_g = gcover.intersection( g )
                    if geom_in_g.area > 0.0:
                        src_in_g = src.copy()
                        src_in_g[i] = 1

                        add_new_geoms(geom_in_g,src_in_g)

                        # And check for the remainder:
                        geom_not_in_g = gcover.difference( g )
                        if geom_not_in_g.area > 0.0:
                            add_new_geoms( geom_not_in_g,src )
                    else:
                        # they don't overlap at all - coverage doesn't change
                        new_coverage.append( (gcover,src) )
            coverage = new_coverage

        self.intersect_srcs  = [src for gcover,src in coverage]
        self.intersect_geoms = [gcover for gcover,src in coverage]
        self.total_coverage = total_coverage.convex_hull

    def plot_regions(self):
        for r in self.regions:
            r.plot()

    def plot_intersections(self):
        for ig in self.intersect_geoms:
            plot_wkb.plot_multipolygon(ig)

    tri_to_geom_src = None
    def prepare_point_to_intersection(self,tol=1e-3):
        """ build up a DT that will speed up queries to the regions
        """
        if CGAL is None:
            print("No CGAL.")
            return

        # get the raw vertices from the polygons
        all_rings = []
        for g in self.intersect_geoms:
            all_rings.append( np.array(g.exterior.coords) )
            for r in g.interiors: # probably no interiors, but just to be safe
                all_rings.append( np.array(r.coords) )

        all_vertices = np.concatenate(all_rings)

        # find the unique ones - ConstrainedDelaunay isn't quite ready to do all
        # of this.
        v_hash = {}
        uniq_vertices = []
        for a,b in all_vertices:
            k = (a,b)
            if k not in v_hash:
                # search to see if maybe we are close enough to somebody else.
                v_hash[k] = len(uniq_vertices)
                uniq_vertices.append( k )

        vertices = np.array(uniq_vertices)

        # Go over the rings and create unique edges
        e_hash = {}
        for r in all_rings:
            # find indices for each of the points
            ri =[v_hash[ (a,b) ] for a,b in r]
            for i in range(len(ri)):
                c,d = (ri[i],ri[(i+1)%len(ri)])
                if c==d:
                    continue
                elif c > d: # canonicalize edge naming
                    e_hash[(d,c)] = 1
                else:
                    e_hash[(c,d)] = 1

        edges = np.array( list(e_hash.keys()) )

        cdf = constrained_delaunay.ConstrainedXYZField(X=vertices,F=np.zeros(len(vertices),np.int32),
                                                       edges=edges)
        cdf.fix_duplicates(tol=tol)

        # now for each of the triangles figure out which region it goes with.
        t = cdf.tri()

        ## So how do we actually use the triangulation?
        #  ultimately, probably worth it to use this for the distance queries, too.

        #  what can this thing do quickly?
        #  if we feed it to a linear interper, can it interpolate whole vectors? or just
        #  scalars? just scalars.
        #  so we could have an interper for each region
        #  but I'm not sure that we should go straight for the distance queries
        #  for now, just go with the membership.  So each triangle can be associated with exactly one
        #  intersect_geom.  So what we need is a quick way to find the index of the right intersect_geom
        #  for all points in a grid.

        # can we go through the faces and associate an intersect_geom index with each?
        # the DT will give us a quick CGAL way to find a face given a point.  Then we'd have to hash that
        # face
        # we can identify each face by its vertex indices - these should stay the same.

        DT = cdf.DT
        tri_to_geom_src = [None]*DT.number_of_faces() # maps a DT triangle to its (intersect_geom,source)
        face_to_tri_index = {} # maps tuple of vertex indices to a triangle index

        # Find centers of each triangle
        tri_centers = np.mean(cdf.X[ cdf.tri().triangle_nodes ],axis=1)

        # put together a map from (v1,v2,v3) to triangle index - this is required to identify
        # faces coming back from CGAL
        i = 0

        # this is a bit slow - maybe 30s
        print("Associating each triangle with its intersection polygon")
        t = cdf.tri()
        for i in range(len(tri_centers)):
            vvv = tuple(t.triangle_nodes[i])
            face_to_tri_index[ vvv ] = i
            # and go ahead and figure out what intersect_geom it goes to
            if i>0: # try the last hit...
                pnt = shapely.geometry.Point( tri_centers[i] )
                if tri_to_geom_src[i-1][0] and tri_to_geom_src[i-1][0].contains(pnt):
                    tri_to_geom_src[i] = tri_to_geom_src[i-1]
                    continue
            tri_to_geom_src[i] = self.point_to_intersection( tri_centers[i] )

        # And save the results:
        self.tri_to_geom_src = tri_to_geom_src
        self.face_to_tri_index = face_to_tri_index
        self.DT = DT
        self.cdf = cdf

    last_face = None
    def point_to_intersection(self,pnt):
        """ Given a shapely point, find the region it should live in """
        # Find the intersecting region that the point lives in -
        # this would be sped up considerably by a DT and keeping queries locally
        # correlated

        if self.tri_to_geom_src is not None:
            p = CGAL.Point_2(pnt[0],pnt[1])
            if self.last_face is not None:
                f = self.DT.locate(p,self.last_face)
            else:
                f = self.DT.locate(p)
            if f is not None:
                self.last_face = f

            # possible that we hit an infinite face of the triangulation -
            # give up in that case.
            if f is None or self.DT.is_infinite(f):
                return None,None

            k = (f.vertex(0).info(),f.vertex(1).info(),f.vertex(2).info())
            try:
                i = self.face_to_tri_index[k]
            except KeyError:
                print("ERROR: Failed to find a triangle from the vertices.  This *could* be because there are some colinear edges")
                print("and the code is not smart enough to sort that out")
                print("Check around these vertices:")
                for i in k:
                    if i is not None:
                        print("vertex: %d (%f,%f)"%(i,self.cdf.X[i,0],self.cdf.X[i,1]))
                raise
            return self.tri_to_geom_src[i]
        else:
            pnt = shapely.geometry.Point(pnt)
            for g,src in zip(self.intersect_geoms,self.intersect_srcs):
                if g.contains(pnt):
                    return g,src

        #print "Point wasn't found in any region!"
        return None,None

    last_hit = (None,None)
    def calc_weights(self,parray):
        """ For the nonzero entries in src, compute the min. distance from the point
        to the boundary of that region
        Given a point or points as (...,2) size array, return the vector of weights to apply
        """
        plist = parray.reshape( (-1,2) )
        # Shapely doesn't do well with integer data
        plist = plist.astype(np.float64)

        Npnts = len(plist)

        pnts = [shapely.geometry.Point(p) for p in plist]

        weights = np.zeros( (Npnts,len(self.regions)), np.float64)

        for i in range(Npnts):
            if i>500 and i%5000==0:
                print("calc_weights: %.2f%%"%(100.0*i/Npnts))
            # This is the slowest step, and the one that can be sped up the most by
            # the DT.
            # exploiting spatial correlation may speed it up, though.
            # still, in the test case the majority of points fall outside all regions, and as
            # such we end up testing them against every region.
            # if (self.last_hit[0] is not None) and (self.last_hit[0].contains(pnts[i])):
            #     g,src = self.last_hit
            # elif (self.last_hit[0] is None) and not self.total_coverage.contains(pnts[i]):
            #     # out of bounds queries - tests that the point isn't in anybody.
            #     g,src = None,None
            # else:

            g,src = self.point_to_intersection(plist[i])

            self.last_hit = g,src

            if src is None:
                continue

            # first calculate the weights:
            for j in np.nonzero(src)[0]:
                weights[i,j] = self.regions[j].distance_to_boundary(pnts[i])

            # normalize - for now assume linear.
            weights[i,:] /= weights[i,:].sum()

        new_shape = parray.shape[:-1] + (len(self.regions),)
        return weights.reshape( new_shape )

if __name__ == '__main__':
    # Testing:

    ic = InterpCoverage('/home/rusty/classes/research/suntans/bathy_interp/test_input1.shp')

    # Sample plot (depends on there being exactly 3 regions)
    # First find the envelope of everyone:
    total = reduce(lambda x,y: x.union(y), [r.geom.envelope for r in ic.regions])
    minx,miny,maxx,maxy = total.bounds

    x = linspace(minx,maxx,300)
    y = linspace(miny,maxy,300)

    X,Y = meshgrid(x,y)

    pnts = concatenate( (X[...,newaxis],Y[...,newaxis]), axis=2)

    C = ic.calc_weights(pnts)

    cla()
    imshow(C,extent=(minx,maxx,miny,maxy),origin='bottom',interpolation='nearest')

    # it's a little slow, but probably bearable -
    #  a quick profiling run shows that for calc_weights, the time is spent...
    # 27s / 38s in point_to_intersection


text:
from django.shortcuts import render, get_object_or_404, redirect
# from django.http import HttpResponseRedirect,
# from django.template import loader
from .models import (Question,
                     Choice,
                     UserProfile,
                     Recruitment,
                     RecruitmentForm,
                     Round,
                     Questionnaire,
                     PublishedEvent,
                     RegisterEvent,
                     )

from django.http import HttpResponse, HttpResponseRedirect
from django.urls import reverse
from django.views import generic
from    django.utils import timezone
from django.contrib.auth.models import User
from .form import (
    RegisterForm,
    EditProfileForm,
    RecruitmentDataForm,
    Answer,
    AuthorForm,
    EventRegister
)
from    django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.forms import PasswordChangeForm
from django.contrib.auth import update_session_auth_hash
from django.forms import (inlineformset_factory,
                          modelformset_factory,)

class IndexView(generic.ListView):

    template_name = 'polls/index.html'
    context_object_name = 'latest_question_list'

    def get_queryset(self):
        """Return the last five published questions."""
        # return Question.objects.order_by('-pub_date')[:5]
        return Question.objects.filter(pub_date__lte=timezone.now()).order_by(
            '-pub_date'
        )[:5]

class DetailView(generic.DetailView):
    # question = get_object_or_404(Question, pk=question_id)
    # return render(request, 'polls/detail.html', {'question': question})
    model = Question
    template_name = 'polls/detail.html'

    def get_queryset(self):
        """
        Excludes any questions that aren't published yet.
        """
        return Question.objects.filter(pub_date__lte=timezone.now())

class ResultsView(generic.DetailView):
    # question = get_object_or_404(Question, pk = question_id)
    # return render(request,'polls/results.html',{'question':question})
    model = Question
    template_name = 'polls/results.html'

    def get_queryset(self):
        """
        Excludes any questions that aren't published yet.
        """
        return Question.objects.filter(pub_date__lte=timezone.now())

def vote(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    try:
        selected_choice = question.choice_set.get(pk=request.POST['choice'])
    except (KeyError, Choice.DoesNotExist):
        # Redisplay the question voting form.
        return render(request, 'polls/detail.html', {
            'question': question,
            'error_message': "You didn't select a choice.",
        })
    else:
        selected_choice.votes += 1
        selected_choice.save()
        # Always return an HttpResponseRedirect after successfully dealing
        # with POST data. This prevents data from being posted twice if a
        # user hits the Back button.
        return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))

        # create views login

def register(request):
    if request.method =='POST':
        form = RegisterForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('/polls')
    else:
        form = RegisterForm()

        args = {'form':form}
        return render(request, 'polls/register.html', args)

def profile(request):
    args = {'user':request.user}
    return render(request, 'polls/profile.html',args)

def edit_profile(request):
    formcombine = inlineformset_factory(User,UserProfile, fields=('city',
                                                                  'university',
                                                                  'image',))
    if request.method == 'POST':

        form1 = EditProfileForm(request.POST, instance=request.user)
        form = formcombine(request.POST, request.FILES, instance=request.user)
        if form.is_valid() and form1.is_valid():
            #handle_uploaded_file(request.FILES['file'])
            #save_image = UserProfile(image=request.FILES['image'])
            #save_image.save()
            form.save()
            form1.save()
            return redirect('/polls/profile')
    else:
        form =  formcombine(instance=request.user)
        form1 = EditProfileForm(instance=request.user)
        args = {'form':form,
                'form1':form1}
        return render(request, 'polls/edit_profile.html', args)

def change_password(request):
    if request.method == 'POST':
        form = PasswordChangeForm(data=request.POST, user=request.user)
        if form.is_valid():
            form.save()
            update_session_auth_hash(request, form.user) #keep session after change password
            return redirect('/polls/profile')
        else:
            return redirect('/profile/change_password')
    else:
        form =  PasswordChangeForm(user=request.user)
        args = {'form':form}
        return render(request, 'polls/change_password.html', args)

class testTemplate(generic.ListView):
    template_name = 'polls/testTemplate.html'
    context_object_name = 'recruitment'

    def get_queryset(self):
        return Recruitment.objects.all()

'''Student register recruitment compain'''
def DetailForm(request, pk):
    if request.method =='POST':
        form = RecruitmentDataForm(request.POST)
        if form.is_valid():

            post = form.save(commit=False)
            post.user_id = request.user

            post.recruiment_id_id = pk
            post.save()
            return redirect('polls:test')
    else:
        form = RecruitmentDataForm()
        check_user_register = RecruitmentForm.objects.filter(user_id = request.user, pk = pk)
        args = {'form':form}
        if check_user_register:
            return HttpResponse("You already register")
        else:
            return render(request, 'polls/detailform.html', args)

class RegisterFormList(generic.ListView):
    template_name = 'polls/listform.html'
    context_object_name = 'listform'

    def get_queryset(self):
        """Return the last five published questions."""
        # return Question.objects.order_by('-pub_date')[:5]
        #a =  Recruitment.objects.all()
        return RecruitmentForm.objects.all()

class QuestionForm(generic.DetailView):
    model = RecruitmentForm
    template_name = 'polls/question.html'

'''def AnswerForm(request,pk):
    a = Questionnaire.objects.filter(recruitment_form=pk)

    formalist = modelformset_factory(Questionnaire, fields=('answer',))

    if request.method == 'POST':
        formset = formalist(request.POST,
                            queryset = a)
        if formset.is_valid():
            formset.save()

            return redirect('polls:listform')
    else:
        formset = formalist(queryset = a)

        args = {'formset':formset}
        return render(request, 'polls/question.html', args)'''

def AnswerForm(request, pk):
    AuthorFormSet = modelformset_factory(Questionnaire, extra=0, form=AuthorForm)

    if request.method == "POST":
        formset = AuthorFormSet(
            request.POST,
            queryset=Questionnaire.objects.filter(recruitment_form=pk),
        )
        if formset.is_valid():

            formset.save()
            # Do something.
    else:

        formset = AuthorFormSet(queryset=Questionnaire.objects.filter(recruitment_form=pk))
    return render(request, 'polls/question.html', {'formset': formset,})

'''List of Event'''
class Event(generic.ListView):
    template_name = 'polls/event.html'
    context_object_name = 'event_list'

    def get_queryset(self):
        '''Return List of event available'''
        return PublishedEvent.objects.filter(
                                                pub_date__lte = timezone.now()).order(
                                                '-pub_date'
                                            )

'''Detail of Event'''
class DetailEvent(generic.DetailView):
    model = PublishedEvent
    template_name = 'polls/detailevent.html'

    def get_queryset(self):
        """Return detail event"""
        return PublishedEvent.objects.filter(
                                             pub_date__lte=timezone.now())

def UserEvent(request, event_id):
    if  request.method == "POST":
        form = EventRegister(request.POST)
        if form.is_valid():
            post = form.save(commit=False)
            post.customer = request.user
            post.event = event_id
            post.save()
        return redirect('polls:event')
    else:
        form = EventRegister()
        check_user_register = RegisterEvent.objects.filter(
            customer = request.user, pk = event_id)
        args = {'form': form}
        if check_user_register:
            return HttpResponse("You already registered")
        else:
            return render(request, 'polls/registerevent.html', args)

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace deluxcms\slideshow;

/**
 * menu module definition class
 */
class Slideshow extends \yii\base\Module
{
    /**
     * @inheritdoc
     */
    public $controllerNamespace = 'deluxcms\slideshow\controllers';

    /**
     * @inheritdoc
     */
    public function init()
    {
        parent::init();

        // custom initialization code goes here
    }
}


text:
Description

AirAware is an application that crowdsources data about pollution and respiratory illnesses from people, organizations as well as from various online sources(medical forums, google trends etc.). This data is then aggregated and processed to provide user-friendly visualizations which raise awareness about pollution and it's effects on our health. The data is also mined in order to obtain valuable insights and provide useful clues to researchers and decision makers.

Resources used

* http://www.ncdc.noaa.gov/cdo-web/datasets
* https://earthdata.nasa.gov/about/science-system-description/eosdis-components/global-imagery-browse-services-gibs
* https://www.google.ro/trends/explore#q=nasal%20obstruction
* https://www.google.ro/trends/explore#q=itchy%20eyes
* https://www.google.ro/trends/explore#q=cough
* https://www.google.ro/trends/explore#q=shortness%20of%20breath
* https://www.google.ro/trends/explore#q=wheezing
* https://www.google.ro/trends/explore#q=sneezing
* http://www.medhelp.org/forums/Allergy/show/67
* https://www.lovethegarden.com/community/fun-facts/nasa-guide-air-filtering-houseplants
* http://waqi.info/


text:
using System;
using System.Threading.Tasks;
using Windows.Devices.Bluetooth.GenericAttributeProfile;

namespace Plugin.BluetoothLE.Server
{
    public interface IUwpGattCharacteristic : IGattCharacteristic
    {
        Task Init(GattLocalService gatt);
    }
}


text:
     Advanced search

<form action="<?=base_url('product/search')?>" method="GET" id="sidebar_search" class="hidden-xs hidden-sm">

        By vendor
        <select type="text" name="intvendor" class="form-control">
            <option value="0">All vendor</option>
            <?php
            foreach ($vendors as $vendor):
                $select = $vendor['id'] == set_value('intvendor') ? 'selected' : '';
                echo "<option value='$vendor[id]' $select>$vendor[vendor_name]</option>";
            endforeach;
            ?>
        </select>
        <?= form_error("intvendor"); ?>

        By name
        <input type="text" name="txtname" class="form-control" value="<?= set_value('txtname') ?>"
               placeholder="Product name">
        <?= form_error("txtname"); ?>

        By price
        <input type="text" name="intprice_min" class="form-control" value="<?= set_value('intprice_min') ?>"
               placeholder="Min price">
        <?= form_error("intprice_min"); ?>
        <input type="text" name="intprice_max" class="form-control" value="<?= set_value('intprice_max') ?>"
               placeholder="Max price">
        <?= form_error("intprice_max"); ?>

    <?php

    foreach ($specs as $spec):
        $temp_spec = set_value("spec[]");
        $presets = explode(';', $spec['spec_presetvalue']);
        ?>

            By <?= $spec['spec_name'] ?>
            <select name="spec[<?= $spec['id'] ?>]" class="form-control">
                <option value="0">---</option>
                <?php
                foreach ($presets as $preset):
                    $select1 = $preset == $temp_spec ? 'selected' : '';
                    echo "<option value='$preset' $select1>$preset $spec[spec_unit]</option>";
                endforeach
                ?>
            </select>
            <?= form_error('spec['.$spec['id'].']'); ?>

        <?php
    endforeach;
    ?>

        <button class="btn btn-primary" type="submit" value="" class="form-control">Search</button>
        <button class="btn btn-danger" type="reset" value="" class="form-control">Reset</button>

</form>


text:
package im.AfriChat.core.entity.content.internal;

public class ContentLocalContainer extends AbsContentContainer {
    private AbsLocalContent content;

    public ContentLocalContainer(AbsLocalContent content) {
        this.content = content;
    }

    public AbsLocalContent getContent() {
        return content;
    }
}


text:
var title;
chrome.runtime.onMessage.addListener(function(message,sender,sendResponse){
	//title = "Blacklight";
	console.log(message);
	if(message.method === 'setOutput'){
		title = message.output;
		console.log(title);
	}
	else if(message.method === 'getOutput') {
		sendResponse({title:title});
		console.log(title);
	}
});


text:
import numpy
import cv2

img=cv2.imread("/home/udayan/Downloads/messi.jpg", 0)    #read image, 0=read as grayscale, -1=read as color
template=cv2.imread("/home/udayan/Downloads/messi_face.jpg", 0)    #read image, 0=read as grayscale, -1=read as color

h, w=template.shape

result=cv2.matchTemplate(img, template, cv2.TM_CCOEFF_NORMED)     #template matching, can also use cv2.TM_CCOEFF, cv2.TM_CCORR, 'cv2.TM_CCORR_NORMED', cv2.TM_SQDIFF, cv2.TM_SQDIFF_NORMED

min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)        #get coordinates and intensity values of pixels with max. & min. intensities in the result, max. value indicates best match here; min. value indicates best match for cv2.TM_SQDIFF & cv2.TM_SQDIFF_NORMED

#mark recognized area
top_left=max_loc
bottom_right=(top_left[0]+w, top_left[1]+h)
cv2.rectangle(img, top_left, bottom_right, 255, 3)   #draw a rectangle on the image, 1st argument=image variable, 2nd & 3rd arguments=coordinates of top-left & bottom right corners of rectangle, 4th argument=color (intensity here) of rectangle edge, 5th argument=pixel width of rectangle edge

cv2.imshow('image',img)   #show image in a window named "image"

cv2.imshow('result',result)   #show image in a window named "result"

cv2.waitKey(0)     #waits for a specified time in milliseconds or till a key is pressed, 0=wait indefinitely or till a key is pressed

cv2.destroyAllWindows()   #delete all created windows


text:
layout: post
title: "Quantitative Ecotoxicology, Page 85, Example 3.2, Nonlinear Regression"
date: 2012-12-01 23:04
author: Eduard Szöcs
published: true
status: publish
draft: false
tags: QETXR
---

<img src="http://vg03.met.vgwort.de/na/3acdf4ad5951451b8e6a4489d7ee47c5" width="1" height="1" alt="">

Get the data from [here](https://raw.github.com/EDiLD/r-ed/master/quantitative_ecotoxicology/data/p85.csv) and read it into R:

{% highlight r %}
OYSTERZN <- read.table("p85.csv", header = TRUE, sep = ";")
head(OYSTERZN)
{% endhighlight %}

{% highlight r %}
##   DAY ZINC
## 1   1  700
## 2   1  695
## 3   1  675
## 4   1  630
## 5   1  606
## 6   1  540
{% endhighlight %}

{% highlight r %}
plot(ZINC ~ DAY, data = OYSTERZN)
{% endhighlight %}

![plot of chunk p85_raw](/figures/p85_raw.jpeg)

First we fit a **nonlinear Regression without weighting**.

{% highlight r %}
mod_noweight <- nls(ZINC ~ INITACT * exp((-(KE + 0.00283)) * DAY), data = OYSTERZN,
    start = list(KE = 0.004, INITACT = 500))
{% endhighlight %}

So we fit the model

$$C_t = C_0 e^{-(k_{e1} + k_{e2}) \cdot t}$$

to our data.

In the R formula **ZINC** corresponds to $C_t$,
**INITACT** to $$C_0$$,
**KE** to $$k_{e1}$$,
**0.00283** is the decay rate constant for 65-Zn $k_{e2}$,
and **DAY** to $t$.

Were are going to estimate **KE** and **INITACT** and also supplied some start-values for the algorithm.

We can look a the summary to get the estimates and standard error:

{% highlight r %}
summary(mod_noweight)
{% endhighlight %}

{% highlight r %}
##
## Formula: ZINC ~ INITACT * exp((-(KE + 0.00283)) * DAY)
##
## Parameters:
##         Estimate Std. Error t value Pr(>|t|)
## KE      2.68e-03   6.68e-04    4.01  0.00015 ***
## INITACT 4.65e+02   2.04e+01   22.86  < 2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 98.8 on 71 degrees of freedom
##
## Number of iterations to convergence: 3
## Achieved convergence tolerance: 5.57e-06
{% endhighlight %}

The resulting estimates of $$k_{e1}$$ and $$C_0$$ are $$0.00268 \pm 0.00067$$ and $$465 \pm 20$$.

We can investigate the residuals, which show a clear pattern:

{% highlight r %}
res_mod_noweight <- resid(mod_noweight)
plot(OYSTERZN$DAY, res_mod_noweight)
abline(h = 0)
{% endhighlight %}

![plot of chunk p85_residuals_nls](/figures/p85_residuals_nls.jpeg)

Secondly, we run a **nonlinear regression with day-squared weighting**:

We use day^2 as weights and add there a column to our data:

{% highlight r %}
OYSTERZN$WNLIN <- OYSTERZN$DAY^2
{% endhighlight %}

We run again nls, but now we supply this new column as weights:

{% highlight r %}
mod_weight <- nls(ZINC ~ INITACT * exp((-(KE + 0.00283)) * DAY), data = OYSTERZN,
    weights = OYSTERZN$WNLIN, start = list(KE = 0.004, INITACT = 500))
summary(mod_weight)
{% endhighlight %}

{% highlight r %}
##
## Formula: ZINC ~ INITACT * exp((-(KE + 0.00283)) * DAY)
##
## Parameters:
##         Estimate Std. Error t value Pr(>|t|)
## KE      2.44e-03   3.47e-04    7.03  1.1e-09 ***
## INITACT 4.55e+02   3.82e+01   11.89  < 2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 7550 on 71 degrees of freedom
##
## Number of iterations to convergence: 4
## Achieved convergence tolerance: 5.42e-07
{% endhighlight %}

The estimates $$0.00244 \pm 0.00035$$ and  $$455 \pm 38$$ are quite similar to the non-weighted regression.

We could plot the two models and the data:

{% highlight r %}
# extract the fitted values
fit_mod_noweight <- fitted(mod_noweight)
fit_mod_weight <- fitted(mod_weight)
# plot data
plot(ZINC ~ DAY, data = OYSTERZN)
# add fitted values
lines(OYSTERZN$DAY, fit_mod_noweight)
lines(OYSTERZN$DAY, fit_mod_weight, lty = "dashed")
# add legend
legend("topright", legend = c("nonweighted", "weighted"), lty = c("solid", "dashed"))
{% endhighlight %}

![plot of chunk p85_nls_fitted](/figures/p85_nls_fitted.jpeg)

Finally we can also fit a **linear model** to the transformed Zinc-Concentrations:

First we ln-transform the concentrations:

{% highlight r %}
OYSTERZN$LZINC <- log(OYSTERZN$ZINC)
{% endhighlight %}

We see that the data has now linear trend:

{% highlight r %}
plot(LZINC ~ DAY, OYSTERZN)
{% endhighlight %}

![plot of chunk p85_raw2](/figures/p85_raw2.jpeg)

And fit a linear regression:

{% highlight r %}
mod_lm <- lm(LZINC ~ DAY, data = OYSTERZN)
sum_lm <- summary(mod_lm)
sum_lm
{% endhighlight %}

{% highlight r %}
##
## Call:
## lm(formula = LZINC ~ DAY, data = OYSTERZN)
##
## Residuals:
##     Min      1Q  Median      3Q     Max
## -0.8974 -0.2448 -0.0709  0.2958  0.5715
##
## Coefficients:
##              Estimate Std. Error t value Pr(>|t|)
## (Intercept)  6.073833   0.056834   106.9   <2e-16 ***
## DAY         -0.005314   0.000243   -21.9   <2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 0.354 on 71 degrees of freedom
## Multiple R-squared: 0.871,  Adjusted R-squared: 0.869
## F-statistic:  478 on 1 and 71 DF,  p-value: <2e-16
{% endhighlight %}

which is fitting the model
$$ln(Zn) = a \cdot day + intercept$$,
with a = `-0.0053` and intercept = `6.07`

Now plot data and model, as well as the residuals:

{% highlight r %}
# fitted values
fit_mod_lm <- fitted(mod_lm)

# data + fitted
plot(LZINC ~ DAY, OYSTERZN)
lines(OYSTERZN$DAY, fit_mod_lm)
{% endhighlight %}

![plot of chunk p85_lm_fitted](/figures/p85_lm_fitted1.jpeg)

{% highlight r %}

# residuals
plot(mod_lm, which = 1)
{% endhighlight %}

![plot of chunk p85_lm_fitted](/figures/p85_lm_fitted2.jpeg)

The mean square error can be calculated from the summary:

{% highlight r %}
# MSE
sum_lm$sigma^2
{% endhighlight %}

{% highlight r %}
## [1] 0.12516
{% endhighlight %}

From which we can get an unbiased estimate of $$C_0$$:

{% highlight r %}
# unbiased estimate for C_0: exp(MSE/2) * exp(Intercept)
exp(sum_lm$sigma^2/2) * exp(sum_lm$coefficients[1, 1])
{% endhighlight %}

{% highlight r %}
## [1] 462.39
{% endhighlight %}

where

{% highlight r %}
sum_lm$coefficients[1, 1]
{% endhighlight %}

extracts the intercept from the summary.

The estimated $$k$$ in the summary output is $$-0.00531 \pm 0.00024$$, and
$$k_e = k - decayrate = 0.00531 - 0.00283 = 0.00248$$

This result is similar to the weighted and non weighted nonlinear regression.
Again we have the same results as with SAS :) [Small deviations may be due to rounding error]

Code and data are available at my [github-repo](https://github.com/EDiLD/r-ed/tree/master/quantitative_ecotoxicology) under file name 'p85'.


text:
import { FC, HTMLAttributes } from 'react';
interface IProps {
    width: number;
    height: number;
    padding?: number;
    description?: string;
}
declare const Base: FC<IProps & HTMLAttributes<SVGElement>>;
export default Base;


text:
class SignalWatcherPrivate;

class SignalWatcher : public QObject {
	Q_OBJECT
public:
	static SignalWatcher* instance(void);
	virtual ~SignalWatcher(void);
	bool watch(int sig);
	bool unwatch(int sig);
	bool watch(int sig, bool watch);

	static const char* backend(void);

Q_SIGNALS:
	void unixSignal(int);

private:
	SignalWatcher(void);
	Q_DISABLE_COPY(SignalWatcher)

#if defined(Q_OS_UNIX) && !defined(Q_OS_SYMBIAN)
	Q_DECLARE_PRIVATE(SignalWatcher)
#if QT_VERSION >= 0x040600
	QScopedPointer<SignalWatcherPrivate> d_ptr;
#else
	SignalWatcherPrivate* d_ptr;
#endif
	Q_PRIVATE_SLOT(d_func(), void _q_handleSignal(void))
#endif
};

#endif // SIGNALWATCHER_H


text:
class AddCounterCacheToUsers < ActiveRecord::Migration
  def change
    add_column :users, :photographs_count, :integer
    User.find_each do |user|
      User.reset_counters(user.id, :photographs)
    end
  end
end


text:
<?php

global $smarty;
$smarty->debugging = false;
$smarty->debugging_ctrl = 'NONE';

// Let user choose to force compilation
$smarty->force_compile = (Configuration::get('PS_SMARTY_FORCE_COMPILE') == _PS_SMARTY_FORCE_COMPILE_) ? true : false;
// But force compile_check since the performance impact is small and it is better for debugging
$smarty->compile_check = true;

function smartyTranslate($params, &$smarty)
{
	$htmlentities = !isset($params['js']);
	$pdf = isset($params['pdf']);
	$addslashes = (isset($params['slashes']) || isset($params['js']));
	$sprintf = isset($params['sprintf']) ? $params['sprintf'] : null;

	if ($pdf)
		return Translate::smartyPostProcessTranslation(Translate::getPdfTranslation($params['s']), $params);

	$filename = ((!isset($smarty->compiler_object) || !is_object($smarty->compiler_object->template)) ? $smarty->template_resource : $smarty->compiler_object->template->getTemplateFilepath());

	// If the template is part of a module
	if (!empty($params['mod']))
		return Translate::smartyPostProcessTranslation(Translate::getModuleTranslation($params['mod'], $params['s'], basename($filename, '.tpl'), $sprintf, isset($params['js'])), $params);

	// If the tpl is at the root of the template folder
	if (dirname($filename) == '.')
		$class = 'index';

	// If the tpl is used by a Helper
	if (strpos($filename, 'helpers') === 0)
		$class = 'Helper';
	// If the tpl is used by a Controller
	else
	{
		if (!empty(Context::getContext()->override_controller_name_for_translations))
			$class = Context::getContext()->override_controller_name_for_translations;
		elseif (isset(Context::getContext()->controller))
		{
			$class_name = get_class(Context::getContext()->controller);
			$class = substr($class_name, 0, strpos(Tools::strtolower($class_name), 'controller'));
		}
		else
		{
		// Split by \ and / to get the folder tree for the file
		$folder_tree = preg_split('#[/\\\]#', $filename);
		$key = array_search('controllers', $folder_tree);

		// If there was a match, construct the class name using the child folder name
		// Eg. xxx/controllers/customers/xxx => AdminCustomers
		if ($key !== false)
			$class = 'Admin'.Tools::toCamelCase($folder_tree[$key + 1], true);
		elseif (isset($folder_tree[0]))
			$class = 'Admin'.Tools::toCamelCase($folder_tree[0], true);
		}
	}

	return Translate::smartyPostProcessTranslation(Translate::getAdminTranslation($params['s'], $class, $addslashes, $htmlentities, $sprintf), $params);
}


text:
    ©<?php echo date('Y'); ?> Codologic.com
    - Terms & Conditions


text:
using Microsoft.Xna.Framework;
using Xen2D;
using XenGameBase;

namespace Demo_BasicScene
{
    public class MoveXBehavior : BehaviorBase<MoveXBehavior>
    {
        private Vector2 _destination;
        private float _velocity;
        private IRenderable2D _target;

        public void Reset( Vector2 destination, float velocity, IRenderable2D target )
        {
            _destination = destination;
            _velocity = velocity;
            _target = target;
        }

        protected override void UpdateInternal( GameTime gameTime )
        {
            base.UpdateInternal( gameTime );
            Vector2 deltaFromTarget = _destination - _target.RenderingExtent.Anchor;
            deltaFromTarget.Normalize();

            float secondsElapsed = (float)gameTime.ElapsedGameTime.Milliseconds / (float)1000;
            float xDisplace = _velocity * secondsElapsed;

            _target.RenderingExtent.Anchor += new Vector2( xDisplace, 0 );
        }
    }
}


text:
package io.noties.markwon.html.tag;

import android.text.style.UnderlineSpan;

import androidx.annotation.NonNull;

import java.util.Arrays;
import java.util.Collection;

import io.noties.markwon.MarkwonVisitor;
import io.noties.markwon.SpannableBuilder;
import io.noties.markwon.html.HtmlTag;
import io.noties.markwon.html.MarkwonHtmlRenderer;
import io.noties.markwon.html.TagHandler;

public class UnderlineHandler extends TagHandler {

    @Override
    public void handle(
            @NonNull MarkwonVisitor visitor,
            @NonNull MarkwonHtmlRenderer renderer,
            @NonNull HtmlTag tag) {

        // as parser doesn't treat U tag as an inline one,
        // thus doesn't allow children, we must visit them first

        if (tag.isBlock()) {
            visitChildren(visitor, renderer, tag.getAsBlock());
        }

        SpannableBuilder.setSpans(
                visitor.builder(),
                new UnderlineSpan(),
                tag.start(),
                tag.end()
        );
    }

    @NonNull
    @Override
    public Collection<String> supportedTags() {
        return Arrays.asList("u", "ins");
    }
}


text:
package org.apache.commons.dbcp.datasources;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.sql.DataSource;

import junit.framework.Test;
import junit.framework.TestSuite;

import org.apache.commons.dbcp.TestConnectionPool;
import org.apache.commons.dbcp.TesterDriver;
import org.apache.commons.dbcp.cpdsadapter.DriverAdapterCPDS;

/**
 * @author John McNally
 * @author Dirk Verbeeck
 * @version $Revision$ $Date$
 */
public class TestPerUserPoolDataSource extends TestConnectionPool {
    public TestPerUserPoolDataSource(String testName) {
        super(testName);
    }

    public static Test suite() {
        return new TestSuite(TestPerUserPoolDataSource.class);
    }

    protected Connection getConnection() throws SQLException {
        return ds.getConnection("foo","bar");
    }

    private DataSource ds;

    public void setUp() throws Exception {
        super.setUp();
        DriverAdapterCPDS pcds = new DriverAdapterCPDS();
        pcds.setDriver("org.apache.commons.dbcp.TesterDriver");
        pcds.setUrl("jdbc:apache:commons:testdriver");
        pcds.setUser("foo");
        pcds.setPassword("bar");
        pcds.setAccessToUnderlyingConnectionAllowed(true);

        PerUserPoolDataSource tds = new PerUserPoolDataSource();
        tds.setConnectionPoolDataSource(pcds);
        tds.setDefaultMaxActive(getMaxActive());
        tds.setDefaultMaxWait((int)(getMaxWait()));
        tds.setPerUserMaxActive("foo",new Integer(getMaxActive()));
        tds.setPerUserMaxWait("foo",new Integer((int)(getMaxWait())));
        tds.setDefaultTransactionIsolation(
            Connection.TRANSACTION_READ_COMMITTED);

        ds = tds;
    }

    public void testBackPointers() throws Exception {
        // todo disabled until a wrapping issuen in PerUserPoolDataSource are resolved
    }

    /**
     * Switching 'u1 -> 'u2' and 'p1' -> 'p2' will
     * exhibit the bug detailed in
     * http://issues.apache.org/bugzilla/show_bug.cgi?id=18905
     */
    public void testIncorrectPassword() throws Exception
    {
        try {
            // Use bad password
            ds.getConnection("u1", "zlsafjk");
            fail("Able to retrieve connection with incorrect password");
        } catch (SQLException e1) {
            // should fail

        }

        // Use good password
        ds.getConnection("u1", "p1").close();
        try
        {
            ds.getConnection("u1", "x");
            fail("Able to retrieve connection with incorrect password");
        }
        catch (SQLException e)
        {
            if (!e.getMessage().startsWith("Given password did not match"))
            {
                throw e;
            }
            // else the exception was expected
        }

        // Make sure we can still use our good password.
        ds.getConnection("u1", "p1").close();

        // Try related users and passwords
        ds.getConnection("foo", "bar").close();
        try {
            ds.getConnection("foob", "ar");
            fail("Should have caused an SQLException");
        } catch (SQLException expected) {
        }
        try {
            ds.getConnection("foo", "baz");
            fail("Should have generated SQLException");
        } catch (SQLException expected) {
        }
    }

    public void testSimple() throws Exception
    {
        Connection conn = ds.getConnection();
        assertNotNull(conn);
        PreparedStatement stmt = conn.prepareStatement("select * from dual");
        assertNotNull(stmt);
        ResultSet rset = stmt.executeQuery();
        assertNotNull(rset);
        assertTrue(rset.next());
        rset.close();
        stmt.close();
        conn.close();
    }

    public void testSimpleWithUsername() throws Exception
    {
        Connection conn = ds.getConnection("u1", "p1");
        assertNotNull(conn);
        PreparedStatement stmt = conn.prepareStatement("select * from dual");
        assertNotNull(stmt);
        ResultSet rset = stmt.executeQuery();
        assertNotNull(rset);
        assertTrue(rset.next());
        rset.close();
        stmt.close();
        conn.close();
    }

    public void testClosingWithUserName()
        throws Exception
    {
        Connection[] c = new Connection[getMaxActive()];
        // open the maximum connections
        for (int i=0; i<c.length; i++)
        {
            c[i] = ds.getConnection("u1", "p1");
        }

        // close one of the connections
        c[0].close();
        assertTrue(c[0].isClosed());
        // get a new connection
        c[0] = ds.getConnection("u1", "p1");

        for (int i=0; i<c.length; i++)
        {
            c[i].close();
        }

        // open the maximum connections
        for (int i=0; i<c.length; i++)
        {
            c[i] = ds.getConnection("u1", "p1");
        }
        for (int i=0; i<c.length; i++)
        {
            c[i].close();
        }
    }

    public void testSimple2()
        throws Exception
    {
        Connection conn = ds.getConnection();
        assertNotNull(conn);

        PreparedStatement stmt =
            conn.prepareStatement("select * from dual");
        assertNotNull(stmt);
        ResultSet rset = stmt.executeQuery();
        assertNotNull(rset);
        assertTrue(rset.next());
        rset.close();
        stmt.close();

        stmt = conn.prepareStatement("select * from dual");
        assertNotNull(stmt);
        rset = stmt.executeQuery();
        assertNotNull(rset);
        assertTrue(rset.next());
        rset.close();
        stmt.close();

        conn.close();
        try
        {
            conn.createStatement();
            fail("Can't use closed connections");
        }
        catch(SQLException e)
        {
            // expected
        }

        conn = ds.getConnection();
        assertNotNull(conn);

        stmt = conn.prepareStatement("select * from dual");
        assertNotNull(stmt);
        rset = stmt.executeQuery();
        assertNotNull(rset);
        assertTrue(rset.next());
        rset.close();
        stmt.close();

        stmt = conn.prepareStatement("select * from dual");
        assertNotNull(stmt);
        rset = stmt.executeQuery();
        assertNotNull(rset);
        assertTrue(rset.next());
        rset.close();
        stmt.close();

        conn.close();
        conn = null;
    }

    public void testOpening()
        throws Exception
    {
        Connection[] c = new Connection[getMaxActive()];
        // test that opening new connections is not closing previous
        for (int i=0; i<c.length; i++)
        {
            c[i] = ds.getConnection();
            assertTrue(c[i] != null);
            for (int j=0; j<=i; j++)
            {
                assertTrue(!c[j].isClosed());
            }
        }

        for (int i=0; i<c.length; i++)
        {
            c[i].close();
        }
    }

    public void testClosing()
        throws Exception
    {
        Connection[] c = new Connection[getMaxActive()];
        // open the maximum connections
        for (int i=0; i<c.length; i++)
        {
            c[i] = ds.getConnection();
        }

        // close one of the connections
        c[0].close();
        assertTrue(c[0].isClosed());

        // get a new connection
        c[0] = ds.getConnection();

        for (int i=0; i<c.length; i++)
        {
            c[i].close();
        }
    }

    public void testMaxActive()
        throws Exception
    {
        Connection[] c = new Connection[getMaxActive()];
        for (int i=0; i<c.length; i++)
        {
            c[i] = ds.getConnection();
            assertTrue(c[i] != null);
        }

        try
        {
            ds.getConnection();
            fail("Allowed to open more than DefaultMaxActive connections.");
        }
        catch(java.sql.SQLException e)
        {
            // should only be able to open 10 connections, so this test should
            // throw an exception
        }

        for (int i=0; i<c.length; i++)
        {
            c[i].close();
        }
    }

    /**
     * Verify that defaultMaxWait = 0 means immediate failure when
     * pool is exhausted.
     */
    public void testMaxWaitZero() throws Exception {
        PerUserPoolDataSource tds = (PerUserPoolDataSource) ds;
        tds.setDefaultMaxWait(0);
        tds.setPerUserMaxActive("u1", new Integer(1));
        Connection conn = tds.getConnection("u1", "p1");
        try {
            tds.getConnection("u1", "p1");
            fail("Expecting Pool Exhausted exception");
        } catch (SQLException ex) {
            // expected
        }
        conn.close();
    }

    public void testPerUserMethods() throws Exception {
        PerUserPoolDataSource tds = (PerUserPoolDataSource) ds;

        // you need to set maxActive otherwise there is no accounting
        tds.setPerUserMaxActive("u1", new Integer(5));
        tds.setPerUserMaxActive("u2", new Integer(5));

        assertEquals(0, tds.getNumActive());
        assertEquals(0, tds.getNumActive("u1", "p1"));
        assertEquals(0, tds.getNumActive("u2", "p2"));
        assertEquals(0, tds.getNumIdle());
        assertEquals(0, tds.getNumIdle("u1", "p1"));
        assertEquals(0, tds.getNumIdle("u2", "p2"));

        Connection conn = tds.getConnection();
        assertNotNull(conn);
        assertEquals(1, tds.getNumActive());
        assertEquals(0, tds.getNumActive("u1", "p1"));
        assertEquals(0, tds.getNumActive("u2", "p2"));
        assertEquals(0, tds.getNumIdle());
        assertEquals(0, tds.getNumIdle("u1", "p1"));
        assertEquals(0, tds.getNumIdle("u2", "p2"));

        conn.close();
        assertEquals(0, tds.getNumActive());
        assertEquals(0, tds.getNumActive("u1", "p1"));
        assertEquals(0, tds.getNumActive("u2", "p2"));
        assertEquals(1, tds.getNumIdle());
        assertEquals(0, tds.getNumIdle("u1", "p1"));
        assertEquals(0, tds.getNumIdle("u2", "p2"));

        conn = tds.getConnection("u1", "p1");
        assertNotNull(conn);
        assertEquals(0, tds.getNumActive());
        assertEquals(1, tds.getNumActive("u1", "p1"));
        assertEquals(0, tds.getNumActive("u2", "p2"));
        assertEquals(1, tds.getNumIdle());
        assertEquals(0, tds.getNumIdle("u1", "p1"));
        assertEquals(0, tds.getNumIdle("u2", "p2"));

        conn.close();
        assertEquals(0, tds.getNumActive());
        assertEquals(0, tds.getNumActive("u1", "p1"));
        assertEquals(0, tds.getNumActive("u2", "p2"));
        assertEquals(1, tds.getNumIdle());
        assertEquals(1, tds.getNumIdle("u1", "p1"));
        assertEquals(0, tds.getNumIdle("u2", "p2"));
    }

    public void testMultipleThreads1() throws Exception {
        // Override wait time in order to allow for Thread.sleep(1) sometimes taking a lot longer on
        // some JVMs, e.g. Windows.
        final int defaultMaxWait = 430;
        ((PerUserPoolDataSource) ds).setDefaultMaxWait(defaultMaxWait);
        ((PerUserPoolDataSource) ds).setPerUserMaxWait("foo",new Integer(defaultMaxWait));
        multipleThreads(1, false, false, defaultMaxWait);
    }

    public void testMultipleThreads2() throws Exception {
        final int defaultMaxWait = 500;
        ((PerUserPoolDataSource) ds).setDefaultMaxWait(defaultMaxWait);
        ((PerUserPoolDataSource) ds).setPerUserMaxWait("foo",new Integer(defaultMaxWait));
        multipleThreads(2 * defaultMaxWait, true, true, defaultMaxWait);
    }

    public void testTransactionIsolationBehavior() throws Exception {
        Connection conn = getConnection();
        assertNotNull(conn);
        assertEquals(Connection.TRANSACTION_READ_COMMITTED,
                     conn.getTransactionIsolation());
        conn.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
        conn.close();

        Connection conn2 = getConnection();
        assertEquals(Connection.TRANSACTION_READ_COMMITTED,
                     conn2.getTransactionIsolation());

        Connection conn3 = getConnection();
        assertEquals(Connection.TRANSACTION_READ_COMMITTED,
                     conn3.getTransactionIsolation());
        conn2.close();
        conn3.close();
    }

    public void testSerialization() throws Exception {
        // make sure the pool has initialized
        Connection conn = ds.getConnection();
        conn.close();

        // serialize
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream out = new ObjectOutputStream(baos);
        out.writeObject(ds);
        byte[] b = baos.toByteArray();
        out.close();

        ByteArrayInputStream bais = new ByteArrayInputStream(b);
        ObjectInputStream in = new ObjectInputStream(bais);
        Object obj = in.readObject();
        in.close();

        assertEquals( 1, ((PerUserPoolDataSource)obj).getNumIdle() );
    }

    // see issue http://issues.apache.org/bugzilla/show_bug.cgi?id=23843
    // unregistered user is in the same pool as without username
    public void testUnregisteredUser() throws Exception {
        PerUserPoolDataSource tds = (PerUserPoolDataSource) ds;

        assertEquals(0, tds.getNumActive());
        assertEquals(0, tds.getNumIdle());

        Connection conn = tds.getConnection();
        assertNotNull(conn);
        assertEquals(1, tds.getNumActive());
        assertEquals(0, tds.getNumIdle());

        conn.close();
        assertEquals(0, tds.getNumActive());
        assertEquals(1, tds.getNumIdle());

        conn = tds.getConnection("u1", "p1");
        assertNotNull(conn);
        assertEquals(0, tds.getNumActive());
        assertEquals(1, tds.getNumIdle());
        assertEquals(1, tds.getNumActive("u1", "p1"));
        assertEquals(0, tds.getNumIdle("u1", "p1"));

        conn.close();
        assertEquals(0, tds.getNumActive());
        assertEquals(1, tds.getNumIdle());
        assertEquals(0, tds.getNumActive("u1", "p1"));
        assertEquals(1, tds.getNumIdle("u1", "p1"));
    }

    // see issue http://issues.apache.org/bugzilla/show_bug.cgi?id=23843
    public void testDefaultUser1() throws Exception {
        TesterDriver.addUser("mkh", "password");
        TesterDriver.addUser("hanafey", "password");
        TesterDriver.addUser("jsmith", "password");

        PerUserPoolDataSource puds = (PerUserPoolDataSource) ds;
        puds.setPerUserMaxActive("jsmith", new Integer(2));
        String[] users = {"mkh", "hanafey", "jsmith"};
        String password = "password";
        Connection[] c = new Connection[users.length];
        for (int i = 0; i < users.length; i++) {
            c[i] = puds.getConnection(users[i], password);
            assertEquals(users[i], getUsername(c[i]));
        }
        for (int i = 0; i < users.length; i++) {
            c[i].close();
        }
    }

    // see issue http://issues.apache.org/bugzilla/show_bug.cgi?id=23843
    public void testDefaultUser2() throws Exception {
        TesterDriver.addUser("mkh", "password");
        TesterDriver.addUser("hanafey", "password");
        TesterDriver.addUser("jsmith", "password");

        PerUserPoolDataSource puds = (PerUserPoolDataSource) ds;
        puds.setPerUserMaxActive("jsmith", new Integer(2));
        String[] users = {"jsmith", "hanafey", "mkh"};
        String password = "password";
        Connection[] c = new Connection[users.length];
        for (int i = 0; i < users.length; i++) {
            c[i] = puds.getConnection(users[i], password);
            assertEquals(users[i], getUsername(c[i]));
        }
        for (int i = 0; i < users.length; i++) {
            c[i].close();
        }
    }

    // See DBCP-8
    public void testChangePassword() throws Exception {
        try {
            ds.getConnection("foo", "bay");
            fail("Should have generated SQLException");
        } catch (SQLException expected) {
        }
        Connection con1 = ds.getConnection("foo", "bar");
        Connection con2 = ds.getConnection("foo", "bar");
        Connection con3 = ds.getConnection("foo", "bar");
        con1.close();
        con2.close();
        TesterDriver.addUser("foo","bay"); // change the user/password setting
        try {
            Connection con4 = ds.getConnection("foo", "bay"); // new password
            // Idle instances with old password should have been cleared
            assertEquals("Should be no idle connections in the pool",
                    0, ((PerUserPoolDataSource) ds).getNumIdle("foo", "bar"));
            con4.close();
            // Should be one idle instance with new pwd
            assertEquals("Should be one idle connection in the pool",
                    1, ((PerUserPoolDataSource) ds).getNumIdle("foo", "bay"));
            try {
                ds.getConnection("foo", "bar"); // old password
                fail("Should have generated SQLException");
            } catch (SQLException expected) {
            }
            Connection con5 = ds.getConnection("foo", "bay"); // take the idle one
            con3.close(); // Return a connection with the old password
            ds.getConnection("foo", "bay").close();  // will try bad returned connection and destroy it
            assertEquals("Should be one idle connection in the pool",
                    1, ((PerUserPoolDataSource) ds).getNumIdle("foo", "bar"));
            con5.close();
        } finally {
            TesterDriver.addUser("foo","bar");
        }
    }
}


text:
package org.toobsframework.pres.component.dataprovider.api;

import java.util.Map;

import org.toobsframework.util.IRequest;

/**
 * @author stewari
 *
 * Interface to a data source.
 */
public interface IDataProvider {

  public Object dispatchAction(String action, String dao, String objectType,
      String returnObjectType, String guidParam, String permissionContext, String indexParam, String namespace, Map<String, Object> params, Map<String, Object> outParams) throws Exception;

  public Object dispatchActionEx(IRequest request, String action, String dao, String objectType,
	      String returnObjectType, String guidParam, String permissionContext, String indexParam, String namespace, Map<String, Object> params, Map<String, Object> outParams) throws Exception;

}


text:
IziViews is an Android library that simplifies and enhances the creation and initialization process of a Project.

Extended Activities, Fragments and Views, enhanced lifecycle Delegates, automations and new features to remove Android hassle debloat code.

I have been developing and using this library for quite some time and decided to upload it, for anyone who might benefit from it and anyone willing to contribute to optimizing and expanding it.

## Features
 - [x] Extended Activities, Fragments and Views, with enhanced lifecycle delegates
 - [x] Automated View initialization, you won't have to do any findViewById
 - [x] Automatically saved instance state, simplified and enriched restoration
 - [x] Easily retain properties and control their behaviour throughout their lifecycle
 - [x] Simplified Tab Fragments and optimized Fragment Pager Adapter

# Usage
## Activity
```java
public class SampleActivity extends IziActivity {
    private Button sampleButton;
    private TextView sampleTextView;

    @Override
    protected int getContentResource() {
        return R.layout.activity_sample;
    }

    @Override
    protected int getFragmentContainerId() {
        return R.id.sample_fragment_container;
    }

    @Override
    public void onCreation() {
        sampleButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(view.getContext(),
                        "This is the creation delegate, execute on every configuration change",
                        Toast.LENGTH_LONG).show();

                // Add a new fragment
                addFragment(new SampleFragment());
            }
        });
    }

    @Override
    public void onInitialization() {
        sampleTextView.setText("This is the initialization delegate, executed only once.");
    }

    @Override
    public void onRestoration(@NonNull IziActivity savedInstance) {
        // Here is where we restore properties
    }

    @Override
    public void postShown() {
        // Executed just after the activity becomes visible
    }

    @Override
    public void postConcealed() {
        // Executed just after the activity becomes invisible
    }
}
```
## Fragment
```java
public class SampleFragment extends IziFragment {
    private Button sampleButton2;

    @Override
    protected int getContentResource() {
        return R.layout.fragment_sample;
    }

    @Override
    public void onCreation() {
        sampleButton2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // Add a new fragment to the Activity
                getParent().addFragment(new AnotherFragment());
            }
        });
    }

    @Override
    public void onInitialization() { }

    @Override
    public void onRestoration(@NonNull IziFragment savedInstance) { }

    @Override
    public void postShown() { }

    @Override
    public void postConcealed() { }
}
```
### Restoring a property's state

Views and other Objects can be saved and restored from the onRestoration delegate, which provides a dummy instance of the Activity or Fragment containing the saved properties.

 - [x] Set the property to be saved, by tagging it with SaveForInstanceRestoration.
```java
@SaveForInstanceRestoration
private TextView sampleTextView;
```
 - [x] Handle the restoration process on the onRestoration delegate.

```java
@Override
public void onRestoration(@NonNull IziActivity savedInstance) {
    SampleActivity mSavedInstance = (SampleActivity) savedInstance;
    sampleTextView.setText(mSavedInstance.sampleTextView.getText());
}
```

Views in the savedInstance object do not have a Context, to avoid leaking. Thus, you should not assign them directly, just get the desired data.

The restoration process is identical for Fragments.

### Retaining complex components, like Asyncs and Sockets

Use the Retainable class, with it's PersistenceDelegates interface.

 - [x] Declare the Retainable object as a class property, adapting it to the desired type.
```java
private Retainable<AsyncTask<Void, Void, Void>> asyncContainer;
```
 - [x] Initialize the component and the Retainable container.
```java
AsyncTask<Void, Void, Void> async = new AsyncTask<Void, Void, Void>() { ... };

asyncContainer = new Retainable<AsyncTask<Void, Void, Void>>() {
    @Override
    public void preSubmerged(AsyncTask<Void, Void, Void> value) {
        // Do something, like removing the ui of the task
    }

    @Override
    public void postSurfaced(AsyncTask<Void, Void, Void> value) {
        // Do something, like restoring the ui of the task
        if (value.getStatus().equals(AsyncTask.Status.RUNNING)) {
            // restore the ui
        }
    }
};
```
 - [x] Assign the component to the Retainable container.
```java
asyncContainer.setValue(async);
```
### How are Views initialized

Views are loaded with reflection, using a String format to define the id naming convention. The parts of the String format are:

(1) the name of the Class, (2) the name of the View, (3) the name of the View's type.

By default the String format is "%1$s_%2$s", meaning that a Button property, named myButton, inside an Activity named MyActivity, will look to be initialized with the id R.id.myactivity_mybutton.

You can override the String format and rearrange the parts, by Overriding the getViewNameFormat function.

```java
@Override
protected String getViewNameFormat() {
    // With this override, the ID of the button should be R.id.mybutton_button
    return "%2$s_%3$s";
}
```
### Control backstack for Fragments

Override the isStackable function of the IziFragment.

```java
@Override
public boolean isStackable() {
    return false;
}
```
# License
IziViews is released under the Apache 2.0 license. See LICENSE for details.


text:
PROJECT="neurobench"
SHORTNAME=NB
BASEDIR="${HOME}/${PROJECT}"
SOURCEDIR="${BASEDIR}/matlab"
JOBSCRIPT="${BASEDIR}/scripts/myjob.sh"

#Job parameters
RUN=${1}
INPUTFILE="${SCRATCH}/${PROJECT}/joblist-${1}.txt"
MAXID=$(sed -n $= ${INPUTFILE})
RUNTIME=23:00:00
MAXRT=NaN
VERBOSE=0
USEPRIOR=1
TOLFUN="1e-3"
STOPSUCCRUNS=1;
MAXFUNMULT="2.5";

NODES="1"
PPN="1"
MEM="3GB"
RESOURCES="nodes=${NODES}:ppn=${PPN},mem=${MEM},walltime=${RUNTIME}"

#if [[ -z ${1} ]]; then
        JOBLIST="1-$MAXID"
        NEWJOB=1
#else
#        JOB=${1}
#        NEWJOB=0
#        echo "JOB=${JOB}" >> ${BASEDIR}/reruns.log
#fi

#Convert from commas to spaces
JOBLIST=${JOBLIST//,/ }
echo JOBS $JOBLIST

WORKDIR="${SCRATCH}/${PROJECT}/run${RUN}"
mkdir ${WORKDIR}
cd ${WORKDIR}

JOBNAME=${SHORTNAME}${RUN}

if [ ${CLUSTER} = "Prince" ]; then
        # running on Prince
        sbatch --error=slurm-%A_%a.err --verbose --array=${JOBLIST} --mail-type=FAIL --mail-user=${USER}@nyu.edu --mem=${MEM} --time=${RUNTIME} --nodes=${NODES} --ntasks-per-node=${PPN} --export=PROJECT=${PROJECT},RUN=${RUN},MAXID=$MAXID,WORKDIR=$WORKDIR,USER=$USER,MAXRT=$MAXRT,INPUTFILE=${INPUTFILE},VERBOSE=${VERBOSE},USEPRIOR=${USEPRIOR},TOLFUN=${TOLFUN},MAXFUNMULT=${MAXFUNMULT},STOPSUCCRUNS=${STOPSUCCRUNS} --job-name=${JOBNAME} ${JOBSCRIPT}
else
	qsub -t ${JOBLIST} -q normal -v PROJECT=${PROJECT},RUN=${RUN},MAXID=$MAXID,WORKDIR=$WORKDIR,USER=$USER,MAXRT=$MAXRT,INPUTFILE=${INPUTFILE},VERBOSE=${VERBOSE},USEPRIOR=${USEPRIOR},TOLFUN=${TOLFUN},MAXFUNMULT=${MAXFUNMULT},STOPSUCCRUNS=${STOPSUCCRUNS} -l ${RESOURCES} -M ${USER}@nyu.edu -N ${JOBNAME} ${JOBSCRIPT}
fi


text:
<?php

namespace itaw\BackendBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use itaw\DataBundle\Entity\Incident;

/**
 * @author Florian Weber <florian.weber.dd@icloud.com>
 */
class IncidentController extends AbstractBackendController
{
    public function collectionAction()
    {
        $incidents = $this->getDoctrine()->getRepository('itawDataBundle:Incident')->findAll();

        return $this->render('itawBackendBundle:Incident:collection.html.twig', array(
                    'incidents' => $incidents,
        ));
    }

    public function objectAction($incidentId)
    {
        $incident = $this->getDoctrine()->getRepository('itawDataBundle:Incident')->findOneById($incidentId);

        return $this->render('itawBackendBundle:Incident:object.html.twig', array(
                    'incident' => $incident,
        ));
    }

    public function createAction(Request $request)
    {
        $endpoints = $this->getDoctrine()->getRepository('itawDataBundle:Endpoint')->findAll();

        if ($request->get('sent', 0) == 1) {
            $endpoint = $this->getDoctrine()->getRepository('itawDataBundle:Endpoint')->findOneBySlug($request->get('endpoint'));

            if (!$endpoint) {
                $this->addError(sprintf('An Endpoint with the Slug %s is not defined!', $request->get('endpoint')));

                return $this->render('itawBackendBundle:Incident:create.html.twig', array(
                            'endpoints' => $endpoints,
                ));
            }

            $incident = new Incident();
            $incident->setTitle($request->get('title'))
                    ->setDescription($request->get('description'))
                    ->setOccurrence(new \DateTime('now'))
                    ->setEndpoint($endpoint)
            ;

            //validate
            $validator = $this->get('validator');
            $errors = $validator->validate($incident);

            if (count($errors) > 0) {
                foreach ($errors as $error) {
                    $this->addError($error);
                }

                return $this->render('itawBackendBundle:Incident:create.html.twig', array(
                            'endpoints' => $endpoints,
                ));
            }

            $em = $this->getDoctrine()->getManager();
            $em->persist($incident);
            $em->flush();

            return $this->redirectToRoute('backend_incidents_collection');
        }

        return $this->render('itawBackendBundle:Incident:create.html.twig', array(
                    'endpoints' => $endpoints,
        ));
    }

    public function updateAction(Request $request, $incidentId)
    {
        $incident = $this->getDoctrine()->getRepository('itawDataBundle:Incident')->findOneById($incidentId);

        if ($request->get('sent', 0) == 1) {
            $incident->setTitle($request->get('title'))
                    ->setDescription($request->get('description'))
            ;

            //validate
            $validator = $this->get('validator');
            $errors = $validator->validate($incident);

            if (count($errors) > 0) {
                foreach ($errors as $error) {
                    $this->addError($error);
                }

                return $this->render('itawBackendBundle:Incident:update.html.twig', array(
                            'incident' => $incident,
                ));
            }

            $em = $this->getDoctrine()->getManager();
            $em->flush();

            return $this->redirectToRoute('backend_incidents_collection');
        }

        return $this->render('itawBackendBundle:Incident:update.html.twig', array(
                    'incident' => $incident,
        ));
    }

    public function deleteAction(Request $request, $incidentId)
    {
        $incident = $this->getDoctrine()->getRepository('itawDataBundle:Incident')->findOneById($incidentId);

        if ($request->get('sent', 0) == 1) {
            $em = $this->getDoctrine()->getManager();
            $em->remove($incident);
            $em->flush();

            return $this->redirectToRoute('backend_incidents_collection');
        }

        return $this->render('itawBackendBundle:Incident:delete.html.twig', array(
                    'incident' => $incident,
        ));
    }
}


text:
package com.hiklas.mucking.around;

import com.hiklas.mucking.around.api.CatalogueAPI;
import com.hiklas.mucking.around.api.LocationID;
import com.hiklas.mucking.around.api.Product;

import java.util.*;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author Fiona Bianchi
 * @since 11/10/2017.
 */
public class CatalogueService implements CatalogueAPI {

    // TODO: Maybe move to a constants class
    public static final LocationID NATIONAL = new LocationID("UK");

    private static final LocationID LONDON = new LocationID("London");
    private static final LocationID LIVERPOOL = new LocationID("Liverpool");

    private static final List<Product> ALL_PRODUCTS = new ArrayList<Product>() {{

        // National
        add(new Product("skyNews1", "Sky News", "News", NATIONAL));
        add(new Product("skySportsNews1", "Sky Sports News", "News", NATIONAL));

        // London
        add(new Product("arsenalTV", "Arsenal TV", "Sports", LONDON));
        add(new Product("chelseaTV", "Chelsea TV", "Sports", LONDON));

        // Liverpool
        add(new Product("liverpoolTV", "Liverpool TV", "Sports", LIVERPOOL));
    }};

    @Override
    public List<Product> productsForLocation(LocationID locationID) {
        Stream<Product> allProductsStream = ALL_PRODUCTS.stream();

        List<Product> productList =
                allProductsStream
                    .filter(filterForLocation(locationID))
                    .collect(Collectors.toList());

        return productList;
    }

    /**
     * The filter to use to figure out which products to return
     *
     * @return Predicate function to use for filtering
     */
    private Predicate<Product> filterForLocation(LocationID locationId)
    {
        return product ->
                NATIONAL.equals(product.location) || product.location.equals(locationId);
    }

}