text:
using System.Security.Claims;
using Microsoft.AspNetCore.Http.Features.Authentication;

namespace Microsoft.AspNetCore.Authentication;

/// <summary>
/// Keeps the User and AuthenticationResult consistent with each other
/// </summary>
internal sealed class AuthenticationFeatures : IAuthenticateResultFeature, IHttpAuthenticationFeature
{
    private ClaimsPrincipal? _user;
    private AuthenticateResult? _result;

    public AuthenticationFeatures(AuthenticateResult result)
    {
        AuthenticateResult = result;
    }

    public AuthenticateResult? AuthenticateResult
    {
        get => _result;
        set
        {
            _result = value;
            _user = _result?.Principal;
        }
    }

    public ClaimsPrincipal? User
    {
        get => _user;
        set
        {
            _user = value;
            _result = null;
        }
    }
}


text:
using PHP.Core.Reflection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PHP.Core;
using System.Runtime.InteropServices;
namespace PHP.Library.Soap
{
	[Serializable()]
	public partial class SoapClient
	{
        ///
		protected SoapClient(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context)
		{
		}
        ///
		[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
		public SoapClient(ScriptContext context, bool newInstance) : base(context, newInstance)
		{
		}
        ///
		[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
		public SoapClient(ScriptContext context, DTypeDesc caller) : this(context, true)
		{
			this.InvokeConstructor(context, caller);
		}
        ///
		[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
		public object __call(ScriptContext __context, object function_name, object arguments)
		{

			string tmp1 = PhpVariable.AsString(function_name);
			if (tmp1 == null)

				{
					PhpException.InvalidImplicitCast(function_name, "string", "__call");
					return null;
				}

			PhpArray tmp2 = arguments as PhpArray;
			if (tmp2 == null)

				{
					PhpException.InvalidImplicitCast(arguments, "PhpArray", "__call");
					return null;
				}
			return __call(tmp1, tmp2);
		}
        ///
		[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
		public static object __call(object instance, PhpStack stack)
		{
			stack.CalleeName = "__call";

			object arg1 = stack.PeekValue(1);

			object arg2 = stack.PeekValue(2);
			stack.RemoveFrame();
			return ((SoapClient)instance).__call(stack.Context, arg1, arg2);
		}
        ///
		[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
		public object __doRequest(ScriptContext __context)
		{
			return __doRequest();
		}
        ///
		[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
		public static object __doRequest(object instance, PhpStack stack)
		{
			stack.CalleeName = "__doRequest";
			stack.RemoveFrame();
			return ((SoapClient)instance).__doRequest(stack.Context);
		}
        ///
		[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
		public object __getFunctions(ScriptContext __context)
		{
			return __getFunctions();
		}
        ///
		[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
		public static object __getFunctions(object instance, PhpStack stack)
		{
			stack.CalleeName = "__getFunctions";
			stack.RemoveFrame();
			return ((SoapClient)instance).__getFunctions(stack.Context);
		}
        ///
		[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
		public object __getLastRequest(ScriptContext __context)
		{
			return __getLastRequest();
		}
        ///
		[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
		public static object __getLastRequest(object instance, PhpStack stack)
		{
			stack.CalleeName = "__getLastRequest";
			stack.RemoveFrame();
			return ((SoapClient)instance).__getLastRequest(stack.Context);
		}
        ///
		[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
		public object __getLastRequestHeaders(ScriptContext __context)
		{
			return __getLastRequestHeaders();
		}
        ///
		[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
		public static object __getLastRequestHeaders(object instance, PhpStack stack)
		{
			stack.CalleeName = "__getLastRequestHeaders";
			stack.RemoveFrame();
			return ((SoapClient)instance).__getLastRequestHeaders(stack.Context);
		}
        ///
		[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
		public object __getLastResponse(ScriptContext __context)
		{
			return __getLastResponse();
		}
        ///
		[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
		public static object __getLastResponse(object instance, PhpStack stack)
		{
			stack.CalleeName = "__getLastResponse";
			stack.RemoveFrame();
			return ((SoapClient)instance).__getLastResponse(stack.Context);
		}
        ///
		[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
		public object __getLastResponseHeaders(ScriptContext __context)
		{
			return __getLastResponseHeaders();
		}
        ///
		[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
		public static object __getLastResponseHeaders(object instance, PhpStack stack)
		{
			stack.CalleeName = "__getLastResponseHeaders";
			stack.RemoveFrame();
			return ((SoapClient)instance).__getLastResponseHeaders(stack.Context);
		}
        ///
		[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
		public object __getTypes(ScriptContext __context)
		{
			return __getTypes();
		}
        ///
		[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
		public static object __getTypes(object instance, PhpStack stack)
		{
			stack.CalleeName = "__getTypes";
			stack.RemoveFrame();
			return ((SoapClient)instance).__getTypes(stack.Context);
		}
        ///
		[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
		public object __setCookie(ScriptContext __context, object name, object value)
		{

			string tmp1 = PhpVariable.AsString(name);
			if (tmp1 == null)

				{
					PhpException.InvalidImplicitCast(name, "string", "__setCookie");
					return null;
				}

			string tmp2 = PhpVariable.AsString(value);
			if (tmp2 == null)

				{
					PhpException.InvalidImplicitCast(value, "string", "__setCookie");
					return null;
				}
			__setCookie(tmp1, tmp2);
			return null;
		}
        ///
		[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
		public static object __setCookie(object instance, PhpStack stack)
		{
			stack.CalleeName = "__setCookie";

			object arg1 = stack.PeekValue(1);

			object arg2 = stack.PeekValue(2);
			stack.RemoveFrame();
			return ((SoapClient)instance).__setCookie(stack.Context, arg1, arg2);
		}
        ///
		[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
		public object __setLocation(ScriptContext __context, object new_location)
		{

			string tmp1 = PhpVariable.AsString(new_location);
			if (tmp1 == null)

				{
					PhpException.InvalidImplicitCast(new_location, "string", "__setLocation");
					return null;
				}
			return __setLocation(tmp1);
		}
        ///
		[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
		public static object __setLocation(object instance, PhpStack stack)
		{
			stack.CalleeName = "__setLocation";

			object arg1 = stack.PeekValue(1);
			stack.RemoveFrame();
			return ((SoapClient)instance).__setLocation(stack.Context, arg1);
		}
        ///
		[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
		public object __setSoapHeaders(ScriptContext __context, object SoapHeaders)
		{

			PhpArray tmp1 = SoapHeaders as PhpArray;
			if (tmp1 == null)

				{
					PhpException.InvalidImplicitCast(SoapHeaders, "PhpArray", "__setSoapHeaders");
					return null;
				}
			__setSoapHeaders(tmp1);
			return null;
		}
        ///
		[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
		public static object __setSoapHeaders(object instance, PhpStack stack)
		{
			stack.CalleeName = "__setSoapHeaders";

			object arg1 = stack.PeekValue(1);
			stack.RemoveFrame();
			return ((SoapClient)instance).__setSoapHeaders(stack.Context, arg1);
		}
        ///
		[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
		public object __construct(ScriptContext __context, object wsdl, 		[System.Runtime.InteropServices.OptionalAttribute()]
object options)
		{

			string tmp1 = PhpVariable.AsString(wsdl);
			if (tmp1 == null)

				{
					PhpException.InvalidImplicitCast(wsdl, "string", "__construct");
					return null;
				}

			PhpArray tmp2 = null;
			if (options != Arg.Default)

				{
					tmp2 = options as PhpArray;
					if (tmp2 == null)

						{
							PhpException.InvalidImplicitCast(options, "PhpArray", "__construct");
							return null;
						}
				}
			__construct(tmp1, tmp2);
			return null;
		}
        ///
		[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
		public static object __construct(object instance, PhpStack stack)
		{
			stack.CalleeName = "__construct";

			object arg1 = stack.PeekValue(1);

			object arg2 = stack.PeekValueOptional(2);
			stack.RemoveFrame();
			return ((SoapClient)instance).__construct(stack.Context, arg1, arg2);
		}
        ///
		private static void __PopulateTypeDesc(PhpTypeDesc desc)
		{
			desc.AddMethod("__call", PhpMemberAttributes.Public, new RoutineDelegate(SoapClient.__call));
			desc.AddMethod("__doRequest", PhpMemberAttributes.Public, new RoutineDelegate(SoapClient.__doRequest));
			desc.AddMethod("__getFunctions", PhpMemberAttributes.Public, new RoutineDelegate(SoapClient.__getFunctions));
			desc.AddMethod("__getLastRequest", PhpMemberAttributes.Public, new RoutineDelegate(SoapClient.__getLastRequest));
			desc.AddMethod("__getLastRequestHeaders", PhpMemberAttributes.Public, new RoutineDelegate(SoapClient.__getLastRequestHeaders));
			desc.AddMethod("__getLastResponse", PhpMemberAttributes.Public, new RoutineDelegate(SoapClient.__getLastResponse));
			desc.AddMethod("__getLastResponseHeaders", PhpMemberAttributes.Public, new RoutineDelegate(SoapClient.__getLastResponseHeaders));
			desc.AddMethod("__getTypes", PhpMemberAttributes.Public, new RoutineDelegate(SoapClient.__getTypes));
			desc.AddMethod("__setCookie", PhpMemberAttributes.Public, new RoutineDelegate(SoapClient.__setCookie));
			desc.AddMethod("__setLocation", PhpMemberAttributes.Public, new RoutineDelegate(SoapClient.__setLocation));
			desc.AddMethod("__setSoapHeaders", PhpMemberAttributes.Public, new RoutineDelegate(SoapClient.__setSoapHeaders));
			desc.AddMethod("__construct", PhpMemberAttributes.Public, new RoutineDelegate(SoapClient.__construct));
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
namespace shared.validations {
    const dateAfterDirectiveName: string = `${sharedComponentPrefix}DateAfter`;
    const dateAfterErrorKey: string = 'dateAfter';

    sharedModule.directive(dateAfterDirectiveName, ['$parse', 'dateTimeValidationService',
        ($parse: angular.IParseService, dateTimeValidationService: DateTimeValidationService) => ({
            require: 'ngModel',
            restrict: 'A',
            link: (scope: angular.IScope, element: angular.IAugmentedJQuery, attrs: angular.IAttributes, controller: angular.INgModelController): void => {
                function validate(value: any, otherValue: any): boolean {
                    if (!value || !otherValue) {
                        return true;
                    }
                    let date: moment.Moment = moment(value);
                    let otherDate: moment.Moment = moment(otherValue);
                    return dateTimeValidationService.compareDates(date, otherDate) > 0;
                }
                scope.$watch(attrs[dateAfterDirectiveName], (newValue: any) => {
                    controller.$setValidity(dateAfterErrorKey, validate(controller.$viewValue, newValue));
                });
                controller.$validators[dateAfterErrorKey] = (value: string) => {
                    let otherDate: any = $parse(attrs[dateAfterDirectiveName])(scope);
                    return validate(value, otherDate);
                };
            }
        })
    ]);

    const dateBeforeDirectiveName: string = `${sharedComponentPrefix}DateBefore`;
    const dateBeforeErrorKey: string = 'dateBefore';

    sharedModule.directive(dateBeforeDirectiveName, ['$parse', 'dateTimeValidationService',
        ($parse: angular.IParseService, dateTimeValidationService: DateTimeValidationService) => ({
            require: 'ngModel',
            restrict: 'A',
            link: (scope: angular.IScope, element: angular.IAugmentedJQuery, attrs: angular.IAttributes, controller: angular.INgModelController): void => {
                function validate(value: any, otherValue: any): boolean {
                    if (!value || !otherValue) {
                        return true;
                    }
                    let date: moment.Moment = moment(value);
                    let otherDate: moment.Moment = moment(otherValue);
                    return dateTimeValidationService.compareDates(date, otherDate) < 0;
                }
                scope.$watch(attrs[dateBeforeDirectiveName], (newValue: any) => {
                    controller.$setValidity(dateBeforeErrorKey, validate(controller.$viewValue, newValue));
                });
                controller.$validators[dateBeforeErrorKey] = (value: string) => {
                    let otherDate: any = $parse(attrs[dateBeforeDirectiveName])(scope);
                    return validate(value, otherDate);
                };
            }
        })
    ]);

    const datePresentOrFutureDirectiveName: string = `${sharedComponentPrefix}DatePresentOrFuture`;
    const datePresentOrFutureErrorKey: string = 'datePresentOrFuture';

    sharedModule.directive(datePresentOrFutureDirectiveName, ['dateTimeValidationService',
        (dateTimeValidationService: DateTimeValidationService) => ({
            require: 'ngModel',
            restrict: 'A',
            link: (scope: angular.IScope, element: angular.IAugmentedJQuery, attrs: angular.IAttributes, controller: angular.INgModelController): void => {
                controller.$validators[datePresentOrFutureErrorKey] = (value: string) => {
                    let date: moment.Moment = moment(value);
                    return dateTimeValidationService.isDatePresentOrFuture(date);
                };
            }
        })
    ]);

    const datePresentOrPastDirectiveName: string = `${sharedComponentPrefix}DatePresentOrPast`;
    const datePresentOrPastErrorKey: string = 'datePresentOrPast';

    sharedModule.directive(datePresentOrPastDirectiveName, ['dateTimeValidationService',
        (dateTimeValidationService: DateTimeValidationService) => ({
            require: 'ngModel',
            restrict: 'A',
            link: (scope: angular.IScope, element: angular.IAugmentedJQuery, attrs: angular.IAttributes, controller: angular.INgModelController): void => {
                controller.$validators[datePresentOrPastErrorKey] = (value: string) => {
                    let date: moment.Moment = moment(value);
                    return dateTimeValidationService.isDatePresentOrPast(date);
                };
            }
        })
    ]);

    const dateWithinPastPeriodDirectiveName: string = `${sharedComponentPrefix}DateWithinPastPeriod`;
    const dateWithinPastPeriodErrorKey: string = 'dateWithinPastPeriod';

    sharedModule.directive(dateWithinPastPeriodDirectiveName, ['dateTimeValidationService',
        (dateTimeValidationService: DateTimeValidationService) => ({
            require: 'ngModel',
            restrict: 'A',
            link: (scope: angular.IScope, element: angular.IAugmentedJQuery, attrs: angular.IAttributes, controller: angular.INgModelController): void => {
                let period: number = parseInt(attrs[dateWithinPastPeriodDirectiveName]);
                if (isNaN(period)) {
                    console.error(`Period specified for ${dateWithinPastPeriodDirectiveName} directive is not a valid integer.`);
                    return;
                }
                controller.$validators[dateWithinPastPeriodErrorKey] = (value: string)  => {
                    let date: moment.Moment = moment(value);
                    return dateTimeValidationService.isDateWithinPastPeriod(date, period);
                };
            }
        })
    ]);
}


text:
"""
helper functions for extracting necessary parameters for different types of markings
also for dimensionality reduction
"""
from __future__ import print_function
import math
import random
import unicodedata
import re
import sys

class InvalidMarking(Exception):
    def __init__(self,pt):
        self.pt = pt
    def __str__(self):
        return "invalid marking: " + str(self.pt)

class EmptyPolygon(Exception):
    def __init__(self):
        pass
    def __str__(self):
        return "empty polygon"

# extract the relevant params for different shapes from the json blob
# todo - do a better job of checking to make sure that the marking lies within the image dimension
# todo - also generalize to ROI
def relevant_line_params(marking,image_dimensions):
    # want to extract the params x1,x2,y1,y2 but
    # ALSO make sure that x1 <= x2 and flip if necessary
    x1 = marking["x1"]
    x2 = marking["x2"]
    y1 = marking["y1"]
    y2 = marking["y2"]

    if min(x1,x2,y1,y2) < 0:
        raise InvalidMarking(marking)

    # only do this part if we have been provided dimensions
    if image_dimensions is not None:
        if (max(x1,x2) >= image_dimensions[0]) or (max(y1,y2) >= image_dimensions[1]):
            raise InvalidMarking(marking)

    if x1 <= x2:
        return x1,y1,x2,y2
    else:
        return x2,y2,x1,y1

# the following convert json blobs into sets of values we can actually cluster on
# todo - do a better job with checking whether the markings fall within the image_dimensions
def relevant_point_params(marking,image_dimensions):
    # todo - this has to be changed
    image_dimensions = 100000,100000
    if (marking["x"] == "") or (marking["y"] == ""):
        raise InvalidMarking(marking)

    try:
        x = float(marking["x"])
        y = float(marking["y"])
    except ValueError:
        warning(marking)
        raise

    if (x<0)or(y<0)or(x > image_dimensions[0]) or(y>image_dimensions[1]):
        # warning( "marking probably outside of image")
        # warning( marking)
        raise InvalidMarking(marking)

    return x,y

def relevant_rectangle_params(marking,image_dimensions):
    x = float(marking["x"])
    y = float(marking["y"])
    x2 = x + float(marking["width"])
    y2 = y + float(marking["height"])

    # not sure how nan can happen but apparently it can
    if math.isnan(x) or math.isnan(y) or math.isnan(x2) or math.isnan(y2):
        raise InvalidMarking(marking)
    if min(x,y,x2,y2) < 0:
        raise InvalidMarking(marking)

    if (float(marking["width"]) == 0) or (float(marking["height"]) == 0):
        raise EmptyPolygon()

    if (image_dimensions is not None) and (image_dimensions != (None,None)):
        if(x2 > image_dimensions[1]) or(y2>image_dimensions[0]):
            raise InvalidMarking(marking)

    return (x,y),(x,y2),(x2,y2),(x2,y)

def relevant_circle_params(marking,image_dimensions):
    return marking["x"],marking["y"],marking["r"]

def relevant_ellipse_params(marking,image_dimensions):
    return marking["x"],marking["y"],marking["rx"],marking["ry"],marking["angle"]

def relevant_polygon_params(marking,image_dimensions):
    points = marking["points"]
    return tuple([(p["x"],p["y"]) for p in points])

def relevant_bezier_params(marking,image_dimensions):
    points = marking["points"]
    output = [(points[0]["x"], points[0]["y"])]
    def get_points_along_curve(pStart, pControl, pEnd, output):
        # t is position along curve, add more to get better approximation
        # this splits each segment into 5 straight lines
        for t in [0.2, 0.4, 0.6, 0.8, 1]:
            x = (1 - t) * (1 - t) * pStart["x"] + 2 * (1 - t) * t * pControl["x"] + t * t * pEnd["x"]
            y = (1 - t) * (1 - t) * pStart["y"] + 2 * (1 - t) * t * pControl["y"] + t * t * pEnd["y"]
            output.append((x, y))
    N = len(points)
    for idx in range(0, N, 2):
        # check if closed automatically (odd length to points) and add in the final point
        if idx+1 == N:
            output.append((points[idx + 1]["x"], points[idx + 1]["y"]))
        # check if this is the last segment and close with the first point
        elif idx+2 == N:
            get_points_along_curve(points[idx], points[idx + 1], points[0], output)
            # don't duplicate the inital point
            output = output[:-1]
        else:
            get_points_along_curve(points[idx], points[idx + 1], points[idx + 2], output)
    return output

def hesse_line_reduction(line_segments):
    """
    use if we want to cluster based on Hesse normal form - but want to retain the original values
    :param line_segment:
    :return:
    """

    reduced_markings = []

    for line_seg in line_segments:
        x1,y1,x2,y2 = line_seg[:4]

        x2 += random.uniform(-0.0001,0.0001)
        x1 += random.uniform(-0.0001,0.0001)

        dist = (x2*y1-y2*x1)/math.sqrt((y2-y1)**2+(x2-x1)**2)

        try:
            tan_theta = math.fabs(y1-y2)/math.fabs(x1-x2)
            theta = math.atan(tan_theta)
        except ZeroDivisionError:
            theta = math.pi/2.

        reduced_markings.append([dist,theta])

        # for cases where we have lines of text, don't want to ignore those
        if len(line_seg) > 4:
            reduced_markings[-1].append(line_seg[4])

    return reduced_markings

def rectangle_reduction(list_of_rectangles):
    """
    reduce rectangles to a 2-d marking,ie. their center
    :param list_of_rectangles:
    :return:
    """

    reduced_rectangles = []
    for (a,b),(_,c),(d,_),_ in list_of_rectangles:
        x_center = (a+d)/2.
        y_center = (b+c)/2.

        reduced_rectangles.append((x_center,y_center))

    return reduced_rectangles

def relevant_text_params(marking,image_dimensions):
    """
    extract the relevant params from the the transcription marking
    note that the text is the last item - which means we can treat the results
    pretty much like a line segment - which it mostly is
    :param marking:
    :param image_dimensions:
    :return:
    """
    if ("startPoint" not in marking) or ("endPoint" not in marking):
        raise InvalidMarking(marking)
    x1 = marking["startPoint"]["x"]
    y1 = marking["startPoint"]["y"]
    x2 = marking["endPoint"]["x"]
    y2 = marking["endPoint"]["y"]

    if min(x1,x2,y1,y2) < 0:
        raise InvalidMarking(marking)

    if "text" not in marking:
        raise InvalidMarking(marking)

    text = marking["text"]

    if "variants" in marking:
        variants = [v for v in marking["variants"] if v != ""]
    else:
        variants = []

    if x1 <= x2:
        return x1,x2,y1,y2,text,variants
    else:
        return x2,x2,y2,y1,text,variants

def text_line_reduction(line_segments):
    """
    use if we want to cluster based on Hesse normal form - but want to retain the original values
    :param line_segment:
    :return:
    """
    reduced_markings = []

    for line_seg in line_segments:
        # last value is variants which is only relevant to Folger
        x1,y1,x2,y2,text,_ = line_seg

        x2 += random.uniform(-0.0001,0.0001)
        x1 += random.uniform(-0.0001,0.0001)

        dist = (x2*y1-y2*x1)/math.sqrt((y2-y1)**2+(x2-x1)**2)

        try:
            tan_theta = math.fabs(y1-y2)/math.fabs(x1-x2)
            theta = math.atan(tan_theta)
        except ZeroDivisionError:
            theta = math.pi/2.

        reduced_markings.append((dist,theta,text))

    return reduced_markings

def csv_string(string):
    """
    remove or replace all characters which might cause problems in a csv template
    :param str:
    :return:
    """
    if type(string) == unicode:
        string = unicodedata.normalize('NFKD', string).encode('ascii','ignore')
    string = re.sub(' ', '_', string)
    string = re.sub(r'\W+', '', string)

    return string

def warning(*objs):
    print("WARNING: ", *objs, file=sys.stderr)


text:
<!DOCTYPE HTML>

		<title>Opdracht 27</title>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
		<link rel="shortcut icon" href="favicon.ico" />
		<link rel="stylesheet" href="style.css" />

Opdracht 27

booklist 2

booklist 3


text:
alias docker-rm-exited="docker ps -aq --no-trunc | xargs docker rm"
alias docker-rm-dangle="docker images -q --filter dangling=true | xargs docker rmi"
#alias docker-stop-all="docker stop `docker ps -aq`"
docker-stop-all() {
    docker stop $(docker ps -aq)
}
#alias docker-rm-all-containers="docker rm $(docker ps -aq)"
docker-rm-all-containers() {
    docker rm $(docker ps -aq)
}
#alias docker-rm-all-images="docker rmi $(docker images -q)"
docker-rm-all-images() {
    docker rmi $(docker images -q)
}


text:
package io.netty.channel;

import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

import io.netty.bootstrap.Bootstrap;

public class DefaultChannelPipelineTailTest {

    private static EventLoopGroup GROUP;

    @BeforeClass
    public static void init() {
        GROUP = new DefaultEventLoopGroup(1);
    }

    @AfterClass
    public static void destroy() {
        GROUP.shutdownGracefully();
    }

    @Test
    public void testOnUnhandledInboundChannelActive() throws Exception {
        final CountDownLatch latch = new CountDownLatch(1);
        MyChannel myChannel = new MyChannel() {
            @Override
            protected void onUnhandledInboundChannelActive() {
                latch.countDown();
            }
        };

        Bootstrap bootstrap = new Bootstrap()
                .channelFactory(new MyChannelFactory(myChannel))
                .group(GROUP)
                .handler(new ChannelInboundHandlerAdapter())
                .remoteAddress(new InetSocketAddress(0));

        Channel channel = bootstrap.connect()
                .sync().channel();

        try {
            assertTrue(latch.await(1L, TimeUnit.SECONDS));
        } finally {
            channel.close();
        }
    }

    @Test
    public void testOnUnhandledInboundChannelInactive() throws Exception {
        final CountDownLatch latch = new CountDownLatch(1);
        MyChannel myChannel = new MyChannel() {
            @Override
            protected void onUnhandledInboundChannelInactive() {
                latch.countDown();
            }
        };

        Bootstrap bootstrap = new Bootstrap()
                .channelFactory(new MyChannelFactory(myChannel))
                .group(GROUP)
                .handler(new ChannelInboundHandlerAdapter())
                .remoteAddress(new InetSocketAddress(0));

        Channel channel = bootstrap.connect()
                .sync().channel();

        channel.close().syncUninterruptibly();

        assertTrue(latch.await(1L, TimeUnit.SECONDS));
    }

    @Test
    public void testOnUnhandledInboundException() throws Exception {
        final AtomicReference<Throwable> causeRef = new AtomicReference<Throwable>();
        final CountDownLatch latch = new CountDownLatch(1);
        MyChannel myChannel = new MyChannel() {
            @Override
            protected void onUnhandledInboundException(Throwable cause) {
                causeRef.set(cause);
                latch.countDown();
            }
        };

        Bootstrap bootstrap = new Bootstrap()
                .channelFactory(new MyChannelFactory(myChannel))
                .group(GROUP)
                .handler(new ChannelInboundHandlerAdapter())
                .remoteAddress(new InetSocketAddress(0));

        Channel channel = bootstrap.connect()
                .sync().channel();

        try {
            IOException ex = new IOException("testOnUnhandledInboundException");
            channel.pipeline().fireExceptionCaught(ex);
            assertTrue(latch.await(1L, TimeUnit.SECONDS));
            assertSame(ex, causeRef.get());
        } finally {
            channel.close();
        }
    }

    @Test
    public void testOnUnhandledInboundMessage() throws Exception {
        final CountDownLatch latch = new CountDownLatch(1);
        MyChannel myChannel = new MyChannel() {
            @Override
            protected void onUnhandledInboundMessage(Object msg) {
                latch.countDown();
            }
        };

        Bootstrap bootstrap = new Bootstrap()
                .channelFactory(new MyChannelFactory(myChannel))
                .group(GROUP)
                .handler(new ChannelInboundHandlerAdapter())
                .remoteAddress(new InetSocketAddress(0));

        Channel channel = bootstrap.connect()
                .sync().channel();

        try {
            channel.pipeline().fireChannelRead("testOnUnhandledInboundMessage");
            assertTrue(latch.await(1L, TimeUnit.SECONDS));
        } finally {
            channel.close();
        }
    }

    @Test
    public void testOnUnhandledInboundReadComplete() throws Exception {
        final CountDownLatch latch = new CountDownLatch(1);
        MyChannel myChannel = new MyChannel() {
            @Override
            protected void onUnhandledInboundReadComplete() {
                latch.countDown();
            }
        };

        Bootstrap bootstrap = new Bootstrap()
                .channelFactory(new MyChannelFactory(myChannel))
                .group(GROUP)
                .handler(new ChannelInboundHandlerAdapter())
                .remoteAddress(new InetSocketAddress(0));

        Channel channel = bootstrap.connect()
                .sync().channel();

        try {
            channel.pipeline().fireChannelReadComplete();
            assertTrue(latch.await(1L, TimeUnit.SECONDS));
        } finally {
            channel.close();
        }
    }

    @Test
    public void testOnUnhandledInboundUserEventTriggered() throws Exception {
        final CountDownLatch latch = new CountDownLatch(1);
        MyChannel myChannel = new MyChannel() {
            @Override
            protected void onUnhandledInboundUserEventTriggered(Object evt) {
                latch.countDown();
            }
        };

        Bootstrap bootstrap = new Bootstrap()
                .channelFactory(new MyChannelFactory(myChannel))
                .group(GROUP)
                .handler(new ChannelInboundHandlerAdapter())
                .remoteAddress(new InetSocketAddress(0));

        Channel channel = bootstrap.connect()
                .sync().channel();

        try {
            channel.pipeline().fireUserEventTriggered("testOnUnhandledInboundUserEventTriggered");
            assertTrue(latch.await(1L, TimeUnit.SECONDS));
        } finally {
            channel.close();
        }
    }

    @Test
    public void testOnUnhandledInboundWritabilityChanged() throws Exception {
        final CountDownLatch latch = new CountDownLatch(1);
        MyChannel myChannel = new MyChannel() {
            @Override
            protected void onUnhandledInboundWritabilityChanged() {
                latch.countDown();
            }
        };

        Bootstrap bootstrap = new Bootstrap()
                .channelFactory(new MyChannelFactory(myChannel))
                .group(GROUP)
                .handler(new ChannelInboundHandlerAdapter())
                .remoteAddress(new InetSocketAddress(0));

        Channel channel = bootstrap.connect()
                .sync().channel();

        try {
            channel.pipeline().fireChannelWritabilityChanged();
            assertTrue(latch.await(1L, TimeUnit.SECONDS));
        } finally {
            channel.close();
        }
    }

    private static class MyChannelFactory implements ChannelFactory<MyChannel> {
        private final MyChannel channel;

        MyChannelFactory(MyChannel channel) {
            this.channel = channel;
        }

        @Override
        public MyChannel newChannel() {
            return channel;
        }
    }

    private abstract static class MyChannel extends AbstractChannel {
        private static final ChannelMetadata METADATA = new ChannelMetadata(false);

        private final ChannelConfig config = new DefaultChannelConfig(this);

        private boolean active;
        private boolean closed;

        protected MyChannel() {
            super(null);
        }

        @Override
        protected DefaultChannelPipeline newChannelPipeline() {
            return new MyChannelPipeline(this);
        }

        @Override
        public ChannelConfig config() {
            return config;
        }

        @Override
        public boolean isOpen() {
            return !closed;
        }

        @Override
        public boolean isActive() {
            return isOpen() && active;
        }

        @Override
        public ChannelMetadata metadata() {
            return METADATA;
        }

        @Override
        protected AbstractUnsafe newUnsafe() {
            return new MyUnsafe();
        }

        @Override
        protected boolean isCompatible(EventLoop loop) {
            return true;
        }

        @Override
        protected SocketAddress localAddress0() {
            return null;
        }

        @Override
        protected SocketAddress remoteAddress0() {
            return null;
        }

        @Override
        protected void doBind(SocketAddress localAddress) throws Exception {
        }

        @Override
        protected void doDisconnect() throws Exception {
        }

        @Override
        protected void doClose() throws Exception {
            closed = true;
        }

        @Override
        protected void doBeginRead() throws Exception {
        }

        @Override
        protected void doWrite(ChannelOutboundBuffer in) throws Exception {
            throw new IOException();
        }

        protected void onUnhandledInboundChannelActive() {
        }

        protected void onUnhandledInboundChannelInactive() {
        }

        protected void onUnhandledInboundException(Throwable cause) {
        }

        protected void onUnhandledInboundMessage(Object msg) {
        }

        protected void onUnhandledInboundReadComplete() {
        }

        protected void onUnhandledInboundUserEventTriggered(Object evt) {
        }

        protected void onUnhandledInboundWritabilityChanged() {
        }

        private class MyUnsafe extends AbstractUnsafe {
            @Override
            public void connect(SocketAddress remoteAddress, SocketAddress localAddress, ChannelPromise promise) {
                if (!ensureOpen(promise)) {
                    return;
                }

                if (!active) {
                    active = true;
                    pipeline().fireChannelActive();
                }

                promise.setSuccess();
            }
        }

        private class MyChannelPipeline extends DefaultChannelPipeline {

            MyChannelPipeline(Channel channel) {
                super(channel);
            }

            @Override
            protected void onUnhandledInboundChannelActive() {
                MyChannel.this.onUnhandledInboundChannelActive();
            }

            @Override
            protected void onUnhandledInboundChannelInactive() {
                MyChannel.this.onUnhandledInboundChannelInactive();
            }

            @Override
            protected void onUnhandledInboundException(Throwable cause) {
                MyChannel.this.onUnhandledInboundException(cause);
            }

            @Override
            protected void onUnhandledInboundMessage(Object msg) {
                MyChannel.this.onUnhandledInboundMessage(msg);
            }

            @Override
            protected void onUnhandledInboundChannelReadComplete() {
                MyChannel.this.onUnhandledInboundReadComplete();
            }

            @Override
            protected void onUnhandledInboundUserEventTriggered(Object evt) {
                MyChannel.this.onUnhandledInboundUserEventTriggered(evt);
            }

            @Override
            protected void onUnhandledChannelWritabilityChanged() {
                MyChannel.this.onUnhandledInboundWritabilityChanged();
            }
        }
    }
}


text:
Chloe - Personal Assistant
Facebook App Api: https://developers.facebook.com/apps/1683077831978416/dashboard/
- App ID: 1683077831978416
- API Version: v2.5
- App Secret: a0fdb850bb9df2c587695e670b0dbf30
- App Token: 1683077831978416|04RDW2VFVfZof8LoSvBqeWbPezg
- Client Token: 69796d59f05500fb19457b844fd26b61
- http://facebook4j.org/en/index.html#how_to_install
- http://mrbool.com/how-to-integrate-facebook-api-in-java/29175
- https://developers.facebook.com/tools/access_token/

https://graph.facebook.com/oauth/access_token?client_id=1683077831978416&client_secret=3e64df46c06d9641900ac72a11e9f14d&grant_type=fb_exchange_token

https://graph.facebook.com/oauth/authorize?client_id=1683077831978416&display=page&redirect_uri=http://www.onmydoorstep.com.au/fbauth&scope=public_profile,email,user_about_me,user_actions.books,user_actions.fitness,user_actions.music,user_actions.news,user_actions.video

http://www.onmydoorstep.com.au/fbauth

To understand what each Facebook Token does: https://developers.facebook.com/docs/facebook-login/access-tokens
To Get a token start here: https://developers.facebook.com/tools/accesstoken/


text:
12 Practices every Android Development Beginner should know — Part 1
============================================================

### One practice at a time to become a better Android beginner

![](https://cdn-images-1.medium.com/max/800/1*RwCbsNdykQYr6vDa6aCGKQ.jpeg)

It's been more than 12 years since Andy Rubin and team started working on the idea of a mobile operating system that would change the way mobile phones, rather smartphones were seen by consumers as well as the people who developed software for it. Smartphones back then were limited to texting and checking emails (and of course, making phone calls), giving users and developers a boundary to work within.

Android, the breaker of chains, with its excellent framework design gave both the parties the freedom to explore more than just a limited set of functionalities. One would argue that the iPhone brought the revolution in the mobile industry, but the thing is no matter how cool (and pricey, eh?) an iPhone is, it again brings that boundary, that limitation we never wanted.

However, as Uncle Ben said — with great power comes great responsibility — we also need to be extra careful with our Android application design approach. I have often seen, in many courses offered, the negligence to teach beginners that value, the value to understand the architecture well enough before starting. We just throw things at people without correctly explaining what the upsides and downsides are, how they impact design or what to use, what not to.

In this post, we will see some of the practices that a beginner or an intermediate (if missed any) level developer should know in order to get better out of the Android framework. This post will be followed by more in this series of posts where we will talk about more such useful practices. Let's begin.

* * *

### 1\. Difference between @+id and @id

In order to access a widget (or component) in Java or to make others dependent on it, we need a unique value to represent it. That unique value is provided by android:id attribute which essentially adds id provided as a suffix to @+id/ to the  _id resource file_  for others to query. An id for Toolbar can be defined like this,

```
android:id="@+id/toolbar
```

The following id can now be tracked by  _findViewById(…)_  which looks for it in the res file for id, or simply R.id directory and returns the type of View in question.

The other one, @id, behaves the same as findViewById(…) — looks for the component by the id provided but is reserved for layouts only. The most general use of it is to place a component relative to the component it returns.

```
android:layout_below="@id/toolbar"
```

### 2\. Using @string res for providing Strings in XML

In simpler words, don't use hard coded strings in XML. The reason behind it is fairly simple. When we use hard coded string in XML, we often use the same word over and over again. Just imagine the nightmare of changing the same word at multiple places which could have been just one had it been a string resource. The other benefit it provides is multi-language support as different string resource files can be created for different languages.

```
android:text="My Awesome Application"
```

When using hard coded strings, you will often see a warning over the use of such strings in Android Studio, offering to change that hard coded string into a string resource. Try clicking on them and then hitting ALT + ENTER to get the resource extractor. You can also go to strings.xml located in values folder under res and declare a string resource like this,

```
<string name="app_name">My Awesome Application</string>
```

and then use it in place of the hard coded string,

```
android:text="@string/app_name"
```

### 3\. Using @android and ?attr constants

This is a fairly effective practice to use predefined constants instead of declaring new ones. Take an example of #ffffff or white color which is used several times in a layout. Now instead of writing #ffffff every single time, or declaring a color resource for white, we could directly use this,

```
@android:color/white
```

Android has several color constants declared mainly for general colors like white, black or pink. It's best use case is setting transparent color with,

```
@android:color/transparent
```

Another constant holder is ?attr which is used for setting predefined attribute values to different attributes. Just take an example of a custom Toolbar. This Toolbar needs a defined width and height. The width can be normally set to MATCH_PARENT, but what about height? Most of us aren't aware of the guidelines, and we simply set the desired height that seems fitting. That's wrong practice. Instead of setting our own height, we should rather be using,

```
android:layout_height="?attr/actionBarSize"
```

Another use of ?attr is to draw ripples on views when clicked. SelectableItemBackground is a predefined drawable that can be set as background to any view which needs ripple effect,

```
android:background="?attr/selectableItemBackground"
```

or we can use

```
android:background="?attr/selectableItemBackgroundBorderless"
```

to enable borderless ripple.

### 4\. Difference between SP and DP

While there's no real difference between these two, it's important to know what these two are, and where to use them to best results.

SP or Scale-independent pixels are recommended for use with TextViews which require the font size to not change with display (density). Instead, the content of a TextView needs to scale as per the needs of a user, or simply the font size preferred by the user.

With anything else that needs dimension or position, DP or Density-independent pixels can be used. As mentioned earlier, DP and SP are same things, it's just that DP scales well with changing densities as the Android System dynamically calculates the pixels from it making it suitable for use on components that need to look and feel the same on different devices with different display densities.

### 5\. Use of Drawables and Mipmaps

This is the most confusing of them all — How are drawable and mipmap different?

While it may seem that both serve the same purpose, they are inherentaly different. Mipmaps are meant to be used for storing icons, where as drawables are for any other format. Let's see how they are used by the system internally and why not to use one in place of the other.

You'll notice that your application has several mipmap and drawable folders, each representing a different display resolution. When it comes to choosing from Drawable folder, the system chooses from the folder that belongs to current device density. However, with Mipmap, the system can choose an icon from any folder that fits the need mainly because some launchers display larger icons than intended, so system chooses the next size up.

In short, use mipmaps for icons or markers that see a change in resolution when used on different device densities and use drawable for other resource types that can be stripped out when required.

For example, a Nexus 5 is xxhdpi. Now when we put icons in mipmap folders, all the folders of mipmap will be retained. But when it comes to drawable, only drawable-xxhdpi will be retained, terming any other folder useless.

### 6\. Using Vector Drawables

It's a very common practice to add multiple versions (sizes) of the same asset in order to support different screen densities. While this approach may work, it also adds certain performance overheads like larger apk size and extra development effort. To eliminate these overheads, Android team at Google announced the addition of Vector Drawables.

Vector Drawables are SVGs (scaled vector graphics) but in XML representing an image drawn using a set of dots, lines and curves with fill colors. The very fact that Vector Drawables are made of lines and dots, gives them the ability to scale at different densities without losing resolution. The other associated benefit with Vector Drawables is the ease of animation. Add multiple vector drawables in a single AnimatedVectorDrawable file and we're good to go instead of adding multiple images and handling them separately.

```
<vector xmlns:android="http://schemas.android.com/apk/res/android"
 android:width="24dp"
 android:height="24dp"
 android:viewportWidth="24.0"
 android:viewportHeight="24.0">
```

```
    <path android:fillColor="#69cdff" android:pathData="M3,18h18v-2L3,16v2zM3,13h18v-2L3,11v2zM3,6v2h18L21,6L3,6z"/>
```

```
</vector>
```

The above vector definition will result in the following drawable,

![](https://cdn-images-1.medium.com/max/600/1*KGmMIhrQR0UyrpIP_niEZw.png)

To Add a vector drawable to your android project, right click on app module of your project, then New >> Vector Assets.This will get you Asset Studio which gives you two options to configure vector drawable. First, picking from Material Icons and second, choosing a local SVG or PSD file.

Google recommends using Material Icons for anything app related to maintain continuity and feel of Android. Be sure to check out all of the icons [here][1].

### 7\. Setting End/Start Margin

This is one of the easiest things people miss out on. Margin! Sure adding margin is easy but what about supporting older platforms?

Start and End are supersets of Left and Right respectively, so if the application has minSdkVersion 17 or less, start or end margin/padding is required with older left/right. On platforms where start and end are missing, these two can be safely ignored for left/right. Sample declaration looks like this,

```
android:layout_marginEnd="20dp"
android:paddingStart="20dp"
```

### 8\. Using Getter/Setter Generator

One of the most frustrating things to do while creating a holder class (which simply holds variable data) is creating multiple getters and setters — Copy/paste method body and rename them for each variable.

Luckily, Android Studio has a solution for it. It goes like this — declare all the variables you need inside the class, and go to Toolbar >> Code. The Shortcut for it is ALT + Insert. Clicking Code will get you Generate, tap on it and among many other options, there will be Getter and Setter option. Tapping on it while maintaining focus on your class page will add all the getters and setters to the class (handle the previous window on your own). Neat, isn't it?

### 9\. Using Override/Implement Generator

Another helpful generator. Writing custom classes and extending them is easy but what about classes you have little idea about. Take PagerAdapter for example. You want a ViewPager to show a few pages and for that, you will need a custom PagerAdapter that will work as you define inside its overridden methods. But where are those methods? Android Studio may be gracious enough to force you to add a constructor to your custom class or even to give a short cut for (that's you ALT + Enter), but the rest of the (abstract) methods from parent PagerAdapter need to be added manually which I am sure is tiring for most of us.

To get a list of all the overridden methods available, go to Code >> Generate and Override method or Implement methods, which ever is your need. You can even choose to add multiple methods to your class, just hold Ctrl and select methods and hit OK.

### 10\. Understanding Contexts Properly

Context is scary and I believe a lot of beginners never care to understand the architecture of Context class — what it is, and why is it needed everywhere.

In simpler terms, it is the one that binds all that you see on the screen together. All the views (or their extensions) are tied to the current environment using Context. Context is responsible for allowing access to application level resources such as density or current activity associated with it. Activities, Services, and Application all implement Context interface to provide other to-be-associated components in-house resources. Take an example of a TextView which has to be added to MainActivity. You would notice while creating an object that the TextView constructor needs Context. This is to resolve any resources needed within TextView definition. Say TextView needs to internally load the Roboto font. For doing this, TextView needs Context. Also when we are providing context (or this) to TextView, we're telling it to bind with the current activity's lifecycle.

Another key use of Context is to initiate application level operations such as initiating a library. A library lives through out the application lifecycle and thus it needs to be initiated with getApplicationContext() instead of  _getContext_  or  _this_ or  _getActivity()_ . It's important to know the correct use of different Context types to avoid a memory leak. Other uses of Context includes starting an Activity or Service. Remember startActivity(…)? When you need to change Activity from a non-activity class, you will need a context object to access startActivity method since it belongs to the Context class, not Activity class.

```
getContext().startActivity(getContext(), SecondActivity.class);
```

If you want to know more about the behavior of Context, go [here][2] or [here][3]. The first one is a nice article on Contexts and where to use them while the latter is Android documentation for Context which has elaborately explained all of its available features — methods, static flags and more.

### Bonus #1: Formatting Code

Who doesn't like clean, properly formatted code? Well, almost every one of us working on classes that tend to go up to 1000 lines in size want our code to stay structured. And it's not that only larger classes need formatting, even smaller modular classes need to make sure code remains readable.

With Android Studio, or any of the JetBrains IDEs you don't even need to care about manually structuring your code like adding indentation or space before =. Write code the way you want and when you feel like formatting it, just hit ALT + CTRL + L on Windows or ALT + CTRL + SHIFT + L on Linux. *Code Auto-Formatted*

### Bonus #2: Using Libraries

One of the key principles of Object Oriented Programming is to increase reuse of code or rather decrease the habit of reinventing the wheel. It's a very common approach that a lot of beginners follow wrongly. The approach has two ends,

- Don't use libraries, write every code on your own.

- Use a library for everything.

Going completely to either of the ends is wrong practice. If you go to the first end, you're going to eat up a lot of resources just to live up to your pride to own everything. Plus chances are there that your code will be less tested than that library you should have gone with, increasing the chances of a buggy module. Don't reinvent the wheel when there is a limited resource. Go with a tested library and when you've got the complete idea and resources, replace the library with your own reliable code.

With the second end, there is an even bigger issue — reliance on foreign code. Don't get used to the idea of relying on others code for everything. Write your own code for things that need lesser resources or things that are within your reach. You don't need a library that sets up custom TypeFaces (fonts) for you, that you can do on your own.

So remember, stay in the middle of the two ends — don't reinvent everything but also don't over-rely on foreign code. Stay neutral and code to your abilities.

* * *

This article was first published on [What's That Lambda][4]. Be sure to visit for more articles like this one on Android, Node.js, Angular.js and more.

--------------------------------------------------------------------------------

via: https://android.jlelse.eu/12-practices-every-android-beginner-should-know-cd43c3710027

作者:[ Nilesh Singh][a]
译者:[译者ID](https://github.com/译者ID)
校对:[校对者ID](https://github.com/校对者ID)

本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出

[a]:https://android.jlelse.eu/@nileshsingh?source=post_header_lockup
[1]:https://material.io/icons/
[2]:https://blog.mindorks.com/understanding-context-in-android-application-330913e32514
[3]:https://developer.android.com/reference/android/content/Context.html
[4]:https://www.whatsthatlambda.com/android/android-dev-101-things-every-beginner-must-know


text:
package no.uib.cipr.matrix;

import no.uib.cipr.matrix.Matrix.Norm;

import com.github.fommil.netlib.LAPACK;
import org.netlib.util.doubleW;
import org.netlib.util.intW;

/**
 * Dense Cholesky decomposition
 */
public class DenseCholesky {

    /**
     * Matrix dimension
     */
    private final int n;

    /**
     * Cholesky decomposition of a lower matrix
     */
    private LowerTriangDenseMatrix Cl;

    /**
     * Cholesky decomposition of an upper matrix
     */
    private UpperTriangDenseMatrix Cu;

    /**
     * If the matrix is SPD or not
     */
    private boolean notspd;

    /**
     * True for upper part, else false
     */
    private final boolean upper;

    /**
     * Constructor for DenseCholesky
     *
     * @param n
     *            Matrix size
     * @param upper
     *            True for decomposing an upper symmetrical matrix, false for a
     *            lower symmetrical matrix
     */
    public DenseCholesky(int n, boolean upper) {
        this.n = n;
        this.upper = upper;

        if (upper)
            Cu = new UpperTriangDenseMatrix(n);
        else
            Cl = new LowerTriangDenseMatrix(n);
    }

    /**
     * Calculates a Cholesky decomposition
     *
     * @param A
     *            Matrix to decompose. Not modified
     * @return The current decomposition
     */
    public static DenseCholesky factorize(Matrix A) {
        return new DenseCholesky(A.numRows(), true)
                .factor(new UpperSPDDenseMatrix(A));
    }

    /**
     * Calculates a Cholesky decomposition
     *
     * @param A
     *            Matrix to decompose. Overwritten on return
     * @return The current decomposition
     */
    public DenseCholesky factor(LowerSPDDenseMatrix A) {
        if (upper)
            throw new IllegalArgumentException(
                    "Cholesky decomposition constructed for upper matrices");

        return decompose(A);
    }

    /**
     * Calculates a Cholesky decomposition
     *
     * @param A
     *            Matrix to decompose. Overwritten on return
     * @return The current decomposition
     */
    public DenseCholesky factor(UpperSPDDenseMatrix A) {
        if (!upper)
            throw new IllegalArgumentException(
                    "Cholesky decomposition constructed for lower matrices");

        return decompose(A);
    }

    private DenseCholesky decompose(AbstractDenseMatrix A) {
        if (n != A.numRows())
            throw new IllegalArgumentException("n != A.numRows()");

        notspd = false;

        intW info = new intW(0);
        if (upper)
            LAPACK.getInstance().dpotrf(UpLo.Upper.netlib(), A.numRows(),
                    A.getData(), Matrices.ld(A.numRows()), info);
        else
            LAPACK.getInstance().dpotrf(UpLo.Lower.netlib(), A.numRows(),
                    A.getData(), Matrices.ld(A.numRows()), info);

        if (info.val > 0)
            notspd = true;
        else if (info.val < 0)
            throw new IllegalArgumentException();

        if (upper)
            Cu.set(A);
        else
            Cl.set(A);

        return this;
    }

    /**
     * Returns true if the matrix decomposed is symmetrical, positive definite
     */
    public boolean isSPD() {
        return !notspd;
    }

    /**
     * Returns the decomposition matrix. Only valid for decomposition of a lower
     * SPD matrix
     */
    public LowerTriangDenseMatrix getL() {
        if (!upper)
            return Cl;
        else
            throw new UnsupportedOperationException();
    }

    /**
     * Returns the decomposition matrix. Only valid for decomposition of a upper
     * SPD matrix
     */
    public UpperTriangDenseMatrix getU() {
        if (upper)
            return Cu;
        else
            throw new UnsupportedOperationException();
    }

    /**
     * Solves for B, overwriting it on return
     */
    public DenseMatrix solve(DenseMatrix B) throws MatrixNotSPDException {
        if (notspd)
            throw new MatrixNotSPDException();
        if (n != B.numRows())
            throw new IllegalArgumentException("n != B.numRows()");

        intW info = new intW(0);
        if (upper)
            LAPACK.getInstance().dpotrs(UpLo.Upper.netlib(), Cu.numRows(),
                    B.numColumns(), Cu.getData(), Matrices.ld(Cu.numRows()),
                    B.getData(), Matrices.ld(Cu.numRows()), info);
        else
            LAPACK.getInstance().dpotrs(UpLo.Lower.netlib(), Cl.numRows(),
                    B.numColumns(), Cl.getData(), Matrices.ld(Cl.numRows()),
                    B.getData(), Matrices.ld(Cl.numRows()), info);

        if (info.val < 0)
            throw new IllegalArgumentException();

        return B;
    }

    /**
     * Computes the reciprocal condition number
     *
     * @param A
     *            The matrix this is a decomposition of
     * @return The reciprocal condition number. Values close to unity indicate a
     *         well-conditioned system, while numbers close to zero do not.
     */
    public double rcond(Matrix A) {
        if (n != A.numRows())
            throw new IllegalArgumentException("n != A.numRows()");
        if (!A.isSquare())
            throw new IllegalArgumentException("!A.isSquare()");

        double anorm = A.norm(Norm.One);

        double[] work = new double[3 * n];
        int[] iwork = new int[n];

        intW info = new intW(0);
        doubleW rcond = new doubleW(0);
        if (upper)
            LAPACK.getInstance().dpocon(UpLo.Upper.netlib(), n, Cu.getData(),
            	Matrices.ld(n), anorm, rcond, work, iwork, info);
        else
            LAPACK.getInstance().dpocon(UpLo.Lower.netlib(), n, Cl.getData(),
            	Matrices.ld(n), anorm, rcond, work, iwork, info);

        if (info.val < 0)
            throw new IllegalArgumentException();

        return rcond.val;
    }

}


text:
/**
 * Created by Sabine on 05.04.2016.
 */

angular.module('citizen-engagement.issue', [])

    .controller('IssueListCtrl',
        function ($scope, $http, apiUrl, $state) {

            /* scroll*/
            $scope.noMoreItemsAvailable = false;
            var i = 0;
            var currentPage = 0

            $scope.loadMore = function () {

                i++;
                $http({
                    method: 'GET',
                    url: apiUrl + '/issues',
                    headers: {
                        'x-pagination': currentPage + ";4",
                        'x-sort': '-createdOn'
                    }
                }).success(function (issues) {
                    $scope.issues = $scope.issues.concat(issues);

                    if (issues.length == 0) {
                        $scope.noMoreItemsAvailable = true;
                    }
                });

                currentPage++;

                $scope.$broadcast('scroll.infiniteScrollComplete');
            };
            /* End scroll*/
            $scope.loadIssues = function () {
                console.log("ok");
                $http.get(apiUrl + '/issues', {headers: {'x-sort': '-createdOn'}}).success(function (issues) {

                    $scope.issues = issues;

                    console.log("j'ai la première issue du tableau" + issues[0]);

                });
            };
            $scope.loadIssues();

            /* $scope.loadIssueType = function () {
             $http.get(apiUrl + '/issues').success(function (issues) {
             $scope.issues = issues;
             console.log(issueTypes[0].name);

             index = 0;

             while (index < issues.length)
             {
             console.log(issues[index].name);
             index++;
             }

             });
             };*/
        })

    .controller("issueDetailCtrl", function ($scope, $http, apiUrl, $stateParams) {
        console.log("j'arrive à récupe le paramètre" + $stateParams);
        var id = $stateParams.issueId;
        console.log('id ' + id);
        $http({
            method: 'GET',
            url: apiUrl + '/issues/' + id
        }).success(function (issue) {
            console.log("okbla");

            $scope.issue = issue;
            console.log("j'ai mon issue" + issue);

        });

    })

    .controller('NewCommentCtrl',
        function ($scope, $http, apiUrl, $stateParams, $state, $window) {
            console.log("j'arrive à récupe le paramètre" + $stateParams);
            var id = $stateParams.issueId;
            console.log('id ' + id);

            $scope.comment = {};

            $scope.submit = function () {
                console.log("je test")
                var link = apiUrl + '/issues/' + id + '/actions/'
                $http.post(link, {
                    type: "comment",
                    payload: {
                        text: $scope.action.payload.text
                    }

                }).then(function (res) {
                    console.log("0 " + $scope.action.payload.text);

                    $scope.response = res.comment;
                    $window.location.reload(true);

                    console.log('voilà la réponse: ' + $scope.reponse);

                });

            };

        }
    )

    .controller('NewIssueCtrl',
        function ($scope, $http, apiUrl, GeolocServiceFla, CameraService, qimgUrl, qimgToken) {
            $scope.loadIssueTypes = function () {
                console.log("ok");
                $http.get(apiUrl + '/issueTypes').success(function (issueTypes) {

                    $scope.issueTypes = issueTypes;

                    console.log(issueTypes[0]);

                });
            };
            $scope.loadIssueTypes();
            GeolocServiceFla.locateUser().then(function (coords) {
                console.log("lat 1:" + coords.latitude);
            });

            $scope.issue = {};

            $scope.submit = function () {

                console.log("je test")
                $http({
                    method: "POST",
                    url: qimgUrl + "/images",
                    headers: {
                        Authorization: "Bearer " + qimgToken
                    },
                    data: {
                        data: $scope.imageData
                    }
                }).success(function (data) {
                    var imageUrl = data.url;
                    $scope.issue.imageUrl = imageUrl;
                    console.log($scope.issue.imageUrl);

                    var link = apiUrl + '/issues'
                    $http.post(link, {
                        description: $scope.issue.description,
                        lng: $scope.issue.lng,
                        lat: $scope.issue.lat,
                        //imageUrl: $scope.issue.imageUrl,
                        imageUrl: $scope.issue.imageUrl,
                        issueTypeId: $scope.issue.issueTypeId,

                    }).then(function (res) {
                        console.log("0 " + $scope.issue.issueTypeId);
                        console.log("1 " + $scope.issue.description);
                        $scope.response = res.issue;
                        console.log('voilà la réponse: ' + $scope.response);

                        // redirect

                        $state.go('home');
                    });

                }).error(function (error) {
                    console.log("error: " + JSON.stringify(arguments));
                });

            };
            $scope.takePicture = function () {
                console.log("picture");
                CameraService.getPicture({
                    quality: 75,
                    targetWidth: 400,
                    targetHeight: 300,
                    destinationType: Camera.DestinationType.DATA_URL
                }).then(function (imageData) {
                    $scope.imageData = imageData;
                    console.log($scope.imageData);

                });

            };

        }
    )


text:
package com.fulcrumgenomics.umi

import com.fulcrumgenomics.testing.{SamBuilder, UnitSpec}
import org.scalatest.OptionValues

class CopyUmiFromReadNameTest extends UnitSpec with OptionValues {

  private case class Result(name: String, umi: String)

  /** Runs CopyUmiFromReadName using the given read names returning the output read names and UMIs. */
  private def run(names: Iterable[String], removeUmi: Boolean): IndexedSeq[Result] = {
    // build the reads
    val builder = new SamBuilder()
    names.foreach { name => builder.addFrag(name=name, unmapped=true) }

    // run the tool
    val out  = makeTempFile("test.", ".bam")
    val tool = new CopyUmiFromReadName(input=builder.toTempFile(), output=out, removeUmi=removeUmi)
    executeFgbioTool(tool)

    // slurp the results
    val recs = readBamRecs(out)
    recs.length shouldBe builder.size
    recs.map { rec => Result(name=rec.name, umi=rec[String](ConsensusTags.UmiBases)) }
  }

  "CopyUmiFromReadName" should "copy the UMI from a read name" in {
    val names   = Seq("1:AAAA", "1:2:CCCC", "1:2:3:GGGG", "blah:AAAA-CCCC")
    val results = run(names=names, removeUmi=false)
    results.map(_.name) should contain theSameElementsInOrderAs names
    results.map(_.umi) should contain theSameElementsInOrderAs Seq("AAAA", "CCCC", "GGGG", "AAAA-CCCC")
  }

  it should "remove the UMI from the read name when --remove-umi=true" in {
    val names   = Seq("1:AAAA", "1:2:CCCC", "1:2:3:GGGG", "blah:AAAA-CCCC")
    val results = run(names=names, removeUmi=true)
    results.map(_.name) should contain theSameElementsInOrderAs Seq("1", "1:2", "1:2:3", "blah")
    results.map(_.umi) should contain theSameElementsInOrderAs Seq("AAAA", "CCCC", "GGGG", "AAAA-CCCC")
  }

  it should "update the UMI delimiter in the read name when --umi-delimiter=+" in {
    val names   = Seq("1:AAAA", "1:2:CCCC", "1:2:3:GGGG", "blah:AAAA+CCCC")
    val results = run(names=names, removeUmi=true)
    results.map(_.name) should contain theSameElementsInOrderAs Seq("1", "1:2", "1:2:3", "blah")
    results.map(_.umi) should contain theSameElementsInOrderAs Seq("AAAA", "CCCC", "GGGG", "AAAA-CCCC")
  }
}


text:
itk_fetch_module(MultipleImageIterator
"Several applications such as multi-atlas segmentation
require frequent iteration over multiple image volumes at the same time.
Doing so with the regular ITK iterators is tedious and error prone
as it requires updating each iterator at end of each iteration.
Failing to do so results in hard to debug errors and crashes.
The MultipleImageIterator is a simple wrapper class that tries to make this more convenient.

A more detailed description can be found in the Insight Journal article::
Schaerer J. \"A MultipleImageIterator for iterating over multiple images simultaneously\".
  https://www.insight-journal.org/browse/publication/915
  December, 2014.
"
  MODULE_COMPLIANCE_LEVEL 2
  GIT_REPOSITORY ${git_protocol}://github.com/KitwareMedical/MultipleImageIterator.git
  GIT_TAG 046e70f43f56ac1a0e32e083fb1fe1d1379a1f73
  )


text:
using Common;
using Microsoft.Practices.Unity;

namespace DataLoader
{
    class Program
    {
        static void Main(string[] args)
        {
            var container = new UnityContainer();
            container.RegisterType<ILoggerFactory, LogManagerFacade>()
                .RegisterType<IGraphDataCommandClientFactory, GraphDataCommandClientFactory>()
                .RegisterType<IInputFilenameProvider, InputFilenameProvider>()
                .RegisterInstance<string[]>(args);
            var log = container.Resolve<ILoggerFactory>().GetLogger(typeof(Program));
            log.Info("Program started, resolving parser.");
            var parser = container.Resolve<DataParser>();
            log.Info("Running parser.");
            parser.Parse();
            log.Info("Finished.");
        }
    }
}


text:
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class Test {
  public static final List<Number> EVEN = Collections.unmodi<caret>fiableList(Arrays.asList(2,4,6,8,10,2));
}


text:
<?php namespace VilniusTechnology\SymfonysFacade;

/*
 * Created by PhpStorm.
 * User: lukasm - vilnius.technology
 * Date: 15.5.1
 * Time: 18.55
 */

use Illuminate\Filesystem\Filesystem;
use Illuminate\Routing\Router;
use Illuminate\Support\Facades\App;
use Illuminate\Support\ServiceProvider;
use Symfony\Component\Finder\Finder;
use VilniusTechnology\SymfonysFacade\Facades\Commands\SymfonyCommandsFacade;
use VilniusTechnology\SymfonysFacade\Facades\Routes\LaraverRouteBuilder;
use VilniusTechnology\SymfonysFacade\Facades\Routes\SymfonyRoutesManager;
use VilniusTechnology\SymfonysFacade\Services\Symfony\SymfonyContainer;

class SymfonysFacadeServiceProvider extends ServiceProvider
{
    private $symfonyContainer;

    private $routebuilder;

    private $symfonyCommandsFacade;

    /** @var SymfonyRoutesManager $routeManager */
    public $routeManager;

    /**
     * Boot package.
     */
    public function boot()
    {
        $this->symfonyContainer = new SymfonyContainer(App::environment(), false);
        $this->routebuilder = new LaraverRouteBuilder();
        $this->routeManager = new SymfonyRoutesManager($this->symfonyContainer, $this->routebuilder);
        $this->symfonyCommandsFacade = new SymfonyCommandsFacade($this->symfonyContainer);

        $this->loadAutoloader(base_path('packages'));
        $this->setupRoutes($this->app->router);
        $this->loadViewsFrom(realpath(__DIR__ . '/../views'), 'SymfonysFacade');
        $this->registerCommands();

        $this->publishes([__DIR__.'/config/symfo.php' => config_path('symfo.php')]);
    }

    /**
     * Register services.
     */
    public function register()
    {
        $this->app->bind('VilniusTechnology\SymfonysFacade\Services\Symfony\SymfonyContainer', function () {
            return $this->symfonyContainer;
        });

        $this->app->bind('VilniusTechnology\SymfonysFacade\Facades\Routes\SymfonyRoutesManager', function () {
            return $this->routeManager;
        });

        $this->app->bind('VilniusTechnology\SymfonysFacade\Facades\Routes\LaraverRouteBuilder', function () {
            return $this->routebuilder;
        });

        $this->app->bind('VilniusTechnology\SymfonysFacade\Facades\Commands\SymfonyCommandsFacade', function () {
            return $this->symfonyCommandsFacade;
        });
    }

    /**
     * Define the routes for the application.
     *
     * @param Router $router
     */
    public function setupRoutes(Router $router)
    {
        $router->group(['namespace' => 'VilniusTechnology\SymfonysFacade\Controllers'], function () {
            require __DIR__ . '/Http/routes.php';
        });

       $this->routeManager->addSymfonyRoutes($router);

    }

    /**
     * Require composer's autoload file the packages.
     **/
    protected function loadAutoloader($path)
    {
        $finder = new Finder;
        $files = new Filesystem;

        $autoloads = $finder->in($path)->files()->name('autoload.php')->depth('<= 3')->followLinks();

        foreach ($autoloads as $file) {
            $files->requireOnce($file->getRealPath());
        }
    }

    /**
     * Registers commands facade.
     */
    public function registerCommands() {
        $this->commands(['VilniusTechnology\SymfonysFacade\Commands\SymfonyCommand']);
    }
}


text:
            Alphabetically

            By location


text:
from setuptools import (
    find_packages,
    setup,
)

with open('README.rst', 'rb') as stream:
    readme = stream.read()
    if hasattr(readme, 'decode'):
        readme = readme.decode('utf-8')

with open('c4cast/version.txt', 'r') as stream:
    version = stream.read()
    if hasattr(version, 'decode'):
        version = version.decode('utf-8')
    version = version.strip()

setup(
    name='c4cast',
    url='https://github.com/AndreLouisCaron/c4cast',
    description='Simple cash flow forecast app.',
    long_description=readme,
    keywords='cashflow forecast',
    license='MIT',
    maintainer='Andre Caron',
    maintainer_email='ac@smartmob.org',
    version=version,
    classifiers=[
        'Development Status :: 1 - Planning',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Operating System :: MacOS :: MacOS X',
        'Programming Language :: Python',
        'Programming Language :: Python :: 3.5',
        'Topic :: Software Development :: Libraries',
    ],
    packages=find_packages(),
    package_data={
        'c4cast': [
            'version.txt',
        ],
    },
    entry_points={
        'console_scripts': [
            'c4cast = c4cast:main',
         ],
    },
    install_requires=[
    ],
)


text:
Many Unix-based systems support the concept of a **symbolic link**. This is where one directory name is transparently mapped to another. Before we look further at symbolic links, here's a brief primer on Unix paths.

* The root directory on a file-system is `/`. Everything is contained with in `/`. This is like `C:\` on Windows, but contains everything rather than just the system drive. Thus, all absolute paths begin with a `/` - if it doesn't, the path is assumed to be relative to the current location.

* Successive nested directorys are joined with slashes, so a directory `a` in a directory `b` in a directory `c` in root is denoted `/c/b/a`.

* To distinguish a directory from a file, a trailing slash can be added, so `/c/b/a` and `/c/b/a/` are equivalent assuming `a` is a directory and not a file.

* Path names are case sensitive. `/bin/thing` is different from `/bin/Thing`.

Now, symbolic links are the more general equivalent of Windows shortcuts. They can be used to 'redirect' one directory to another. For example, if I have a version of a program `thing` located at `/bin/thing-2`, then when thing upgrades to thing 3 then any programs referring to `/bin/thing-2` will break once it changes to `/bin/thing-3`. Thus, I might make a symbolic link `/bin/thing` which refers to `/bin/thing-2`. This means any attempt to visit a path beginning with `/bin/thing` will be silently redirected to `/bin/thing-2`. Hence, once the program updates, just change the symbolic link and everything is working still.

Symbolic links can have more to them, and you can in fact make them on Windows with some NTFS trickery, but this challenge focuses just on Unix style directories.

Our challenge is to resolve a given path name into its actual location given a number of symbolic links. Assume that symbolic links can point to other links.

## Input Description

You will accept a number **N**. You will then accept **N** lines in the format:

    /path/of/link:/path/of/destination

Then you will accept a path of a directory to be fully expanded.

For example:

    4
    /bin/thing:/bin/thing-3
    /bin/thing-3:/bin/thing-3.2
    /bin/thing-3.2/include:/usr/include
    /usr/include/SDL:/usr/local/include/SDL
    /bin/thing/include/SDL/stan

## Output Description

Expand it into its true form, for example:

   /usr/local/include/SDL/stan

# Sample Inputs and Outputs

## Sample Input

    1
    /home/elite/documents:/media/mmcstick/docs
    /home/elite/documents/office

## Sample Output

    /media/mmcstick/docs/office

## Sample Input

    3
    /bin:/usr/bin
    /usr/bin:/usr/local/bin/
    /usr/local/bin/log:/var/log-2014
    /bin/log/rc

## Sample Output

    /var/log-2014/rc

## Sample Input

    2
    /etc:/tmp/etc
    /tmp/etc/:/etc/
    /etc/modprobe.d/config/

## Sample Output

Program should hang - recursive loop.

(I know nested symlinks are restricted in practice, but we're livin' life on the edge in this subreddit.)

# Extension

Extend your solution to resolve existing symlinks in the definition of successive symlinks. For example:

    4
    /bin/thing:/bin/thing-3
    /bin/thing-3:/bin/thing-3.2
    /bin/thing/include:/usr/include
    /bin/thing-3.2/include/SDL:/usr/local/include/SDL
    /bin/thing/include/SDL/stan

Notice how the 3rd link relies on the first and second symlinks, and the 4th link relies on the 3rd link working.

This should resolve correctly into `/usr/local/include/SDL/stan`.


text:
#ifndef BX_COMMANDLINE_H_HEADER_GUARD
#define BX_COMMANDLINE_H_HEADER_GUARD

#include "string.h"

namespace bx
{
	///
	StringView tokenizeCommandLine(const StringView& _commandLine, char* _buffer, uint32_t& _bufferSize, int32_t& _argc, char* _argv[], int32_t _maxArgvs, char _term = '\0');

	///
	class CommandLine
	{
	public:
		///
		CommandLine(int32_t _argc, char const* const* _argv);

		///
		const char* findOption(const char* _long, const char* _default) const;

		///
		const char* findOption(const char _short, const char* _long, const char* _default) const;

		///
		const char* findOption(const char* _long, int32_t _numParams = 1) const;

		///
		const char* findOption(const char _short, const char* _long = NULL, int32_t _numParams = 1) const;

		///
		const char* findOption(int32_t _skip, const char _short, const char* _long = NULL, int32_t _numParams = 1) const;

		///
		bool hasArg(const char _short, const char* _long = NULL) const;

		///
		bool hasArg(const char* _long) const;

		///
		bool hasArg(const char*& _value, const char _short, const char* _long = NULL) const;

		///
		bool hasArg(int32_t& _value, const char _short, const char* _long = NULL) const;

		///
		bool hasArg(uint32_t& _value, const char _short, const char* _long = NULL) const;

		///
		bool hasArg(float& _value, const char _short, const char* _long = NULL) const;

		///
		bool hasArg(double& _value, const char _short, const char* _long = NULL) const;

		///
		bool hasArg(bool& _value, const char _short, const char* _long = NULL) const;

		///
		int32_t getNum() const;

		///
		char const* get(int32_t _idx) const;

	private:
		///
		const char* find(int32_t _skip, const char _short, const char* _long, int32_t _numParams) const;

		int32_t m_argc;
		char const* const* m_argv;
	};

} // namespace bx

#endif /// BX_COMMANDLINE_H_HEADER_GUARD


text:
package com.elasticm2m.frameworks.core;

import com.elasticm2m.frameworks.common.base.ElasticBaseResource;
import com.google.inject.Inject;
import com.google.inject.name.Named;
import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;

public class ConfigurationResource extends ElasticBaseResource {

    private String configData = "";

    @Inject(optional = true)
    public void setConfigData(@Named("config-data") String configData) {
        this.configData = configData;
    }

    @Override
    public void configure() {
        Config config = ConfigFactory.parseString(configData);
        bind(Config.class).toInstance(config);
    }
}


text:
// Copyright 2009 the Sputnik authors.  All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.

/*---
info: The length property of the Math.min method is 2
es5id: 15.8.2.12_A4
description: Checking if Math.min.length property is defined and equals to 2
---*/

// CHECK#1
if (typeof Math.min !== "function") {
	$ERROR('#1: Math.min method is not defined');
}

// CHECK#2
if (typeof Math.min.length === "undefined") {
	$ERROR('#2: length property of Math.min method is undefined');
}

// CHECK#3
if (Math.min.length !== 2) {
	$ERROR('#3: The length property of the Math.min method is not 2');
}


text:
package io.rsocket.transport.local;

import io.rsocket.Closeable;
import io.rsocket.transport.ClientTransport;
import io.rsocket.transport.ServerTransport;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import reactor.core.Scannable;
import reactor.core.publisher.Mono;
import reactor.core.publisher.Sinks;
import reactor.util.annotation.Nullable;

/**
 * An implementation of {@link ServerTransport} that connects to a {@link ClientTransport} in the
 * same JVM.
 */
public final class LocalServerTransport implements ServerTransport<Closeable> {

  private static final ConcurrentMap<String, ConnectionAcceptor> registry =
      new ConcurrentHashMap<>();

  private final String name;

  private LocalServerTransport(String name) {
    this.name = name;
  }

  /**
   * Creates an instance.
   *
   * @param name the name of this {@link ServerTransport} that clients will connect to
   * @return a new instance
   * @throws NullPointerException if {@code name} is {@code null}
   */
  public static LocalServerTransport create(String name) {
    Objects.requireNonNull(name, "name must not be null");
    return new LocalServerTransport(name);
  }

  /**
   * Creates an instance with a random name.
   *
   * @return a new instance with a random name
   */
  public static LocalServerTransport createEphemeral() {
    return create(UUID.randomUUID().toString());
  }

  /**
   * Remove an instance from the JVM registry.
   *
   * @param name the local transport instance to free
   * @throws NullPointerException if {@code name} is {@code null}
   */
  public static void dispose(String name) {
    Objects.requireNonNull(name, "name must not be null");
    registry.remove(name);
  }

  /**
   * Retrieves an instance of {@link ConnectionAcceptor} based on the name of its {@code
   * LocalServerTransport}. Returns {@code null} if that server is not registered.
   *
   * @param name the name of the server to retrieve
   * @return the server if it has been registered, {@code null} otherwise
   * @throws NullPointerException if {@code name} is {@code null}
   */
  static @Nullable ConnectionAcceptor findServer(String name) {
    Objects.requireNonNull(name, "name must not be null");

    return registry.get(name);
  }

  /** Return the name associated with this local server instance. */
  String getName() {
    return name;
  }

  /**
   * Return a new {@link LocalClientTransport} connected to this {@code LocalServerTransport}
   * through its {@link #getName()}.
   */
  public LocalClientTransport clientTransport() {
    return LocalClientTransport.create(name);
  }

  @Override
  public Mono<Closeable> start(ConnectionAcceptor acceptor) {
    Objects.requireNonNull(acceptor, "acceptor must not be null");
    return Mono.create(
        sink -> {
          ServerCloseable closeable = new ServerCloseable(name, acceptor);
          if (registry.putIfAbsent(name, acceptor) != null) {
            throw new IllegalStateException("name already registered: " + name);
          }
          sink.success(closeable);
        });
  }

  static class ServerCloseable implements Closeable {

    private final LocalSocketAddress address;

    private final ConnectionAcceptor acceptor;

    private final Sinks.Empty<Void> onClose = Sinks.empty();

    ServerCloseable(String name, ConnectionAcceptor acceptor) {
      Objects.requireNonNull(name, "name must not be null");
      this.address = new LocalSocketAddress(name);
      this.acceptor = acceptor;
    }

    @Override
    public void dispose() {
      if (!registry.remove(address.getName(), acceptor)) {
        throw new AssertionError();
      }
      onClose.tryEmitEmpty();
    }

    @Override
    @SuppressWarnings("ConstantConditions")
    public boolean isDisposed() {
      return onClose.scan(Scannable.Attr.TERMINATED) || onClose.scan(Scannable.Attr.CANCELLED);
    }

    @Override
    public Mono<Void> onClose() {
      return onClose.asMono();
    }
  }
}


text:
import csv

class DataBus(object):
    def __init__(self, filename):
        """
        :param filename: *string*
        """
        self.filename = filename

    def write_header(self, sensors):
        """

        :param sensors: *list* with sensornames
        :return: *None*
        """
        with open(self.filename, mode='wb') as csv_file:
            csv_writer = csv.writer(csv_file, delimiter=';')
            csv_writer.writerow(['timestamp'] + sensors)

    def write_content_row(self, content):
        """

        :param content: *list* with timestamp an sensorvalues
        :return: *None*
        """
        with open(self.filename, mode='ab') as csv_file:
            csv_writer = csv.writer(csv_file, delimiter=';')
            csv_writer.writerow(content)


text:
<?php namespace BattleAPI\Game;

use BattleAPI\Response\Response;

interface Soldier
{
    /**
     * @param string $soldierId
     * @param Platform $platform
     */
    public function __construct($soldierId, Platform $platform);

    /**
     * @return string
     */
    public function getId();

    /**
     * @return Platform
     */
    public function getPlatform();

    /**
     * @return Response
     */
    public function getOverview();
}


text:
A simple ***push & pull MVC framework*** heavly inspired to different PHP microframeworks and
PHP MVC framework like ZF1.

## Why?

I want to try out the test-driven development [at least write some tests ;)].

Just for my pleasure.

## Goals

 * PHPUnit
 * Very simple implementation (***only 8 classes*** + autoloader)
 * PHP 5.3+ implementation

## Features

 * 100% MVC implementation [66% no model support] ;)
 * Useful hooks (Fixed events)
  * Loop Startup
  * Pre Dispatch
  * Init Hook
  * Post Dispatch
  * Loop Shutdown
 * View Renderer Switch
 * View Helpers
 * Partial views
 * Two step view (Layout support)
 * Controllers stack
 * Headers handler
 * Event manager (Self designed hooks)
 * Router
  * Only controller/action names
  * Dash URLs support (/a-dash/the-name-of-content)
 * Pull Driven requests
  * View request data to a controller-action
 * Rewritable views
  * Different views mount points for rewrite views

## Install with Composer

If you want you can use Composer for install simple-mvc.
Create the `composer.json`

```json
{
    "require": {
        "wdalmut/simple-mvc": "*"
    }
}
```

Now you can install the framework

```shell
$ curl -s http://getcomposer.org/installer | php
$ php composer.phar install
```

You can use the Composer autoloader

```php
<?php
require_once 'vendor/autoloader.php';

$app = new Application();
//...
```

## Examples and docs

 * [Documentation](http://simple-mvc.readthedocs.org/en/latest/index.html)
 * [Real Example](master/examples)

## Build Status

 * Master branch
   * [![Build Status](https://secure.travis-ci.org/wdalmut/simple-mvc.png?branch=master)](http://travis-ci.org/wdalmut/simple-mvc?branch=master)
 * Development branch
   * [![Build Status](https://secure.travis-ci.org/wdalmut/simple-mvc.png?branch=development)](http://travis-ci.org/wdalmut/simple-mvc?branch=development)

The end.


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- $Revision: 334762 $ -->
<refentry xml:id="function.pg-parameter-status" xmlns="http://docbook.org/ns/docbook">
 <refnamediv>
  <refname>pg_parameter_status</refname>
  <refpurpose>Looks up a current parameter setting of the server.</refpurpose>
 </refnamediv>

 <refsect1 role="description">
  &reftitle.description;
  <methodsynopsis>
   <type>string</type><methodname>pg_parameter_status</methodname>
   <methodparam choice="opt"><type>resource</type><parameter>connection</parameter></methodparam>
   <methodparam><type>string</type><parameter>param_name</parameter></methodparam>
  </methodsynopsis>
  <para>
    Looks up a current parameter setting of the server.
  </para>
  <para>
    Certain parameter values are reported by the server automatically at
    connection startup or whenever their values change. <function>pg_parameter_status</function> can be
    used to interrogate these settings. It returns the current value of a
    parameter if known, or &false; if the parameter is not known.
  </para>
  <para>
    Parameters reported as of PostgreSQL 8.0 include <literal>server_version</literal>,
    <literal>server_encoding</literal>, <literal>client_encoding</literal>,
    <literal>is_superuser</literal>, <literal>session_authorization</literal>,
    <literal>DateStyle</literal>, <literal>TimeZone</literal>, and <literal>integer_datetimes</literal>.
    (<literal>server_encoding</literal>, <literal>TimeZone</literal>, and
    <literal>integer_datetimes</literal> were not reported by releases before 8.0.) Note that
    <literal>server_version</literal>, <literal>server_encoding</literal> and <literal>integer_datetimes</literal>
    cannot change after PostgreSQL startup.
  </para>
  <para>
    PostgreSQL 7.3 or lower servers do not report parameter settings,
    <function>pg_parameter_status</function>
    includes logic to obtain values for <literal>server_version</literal> and
    <literal>client_encoding</literal>
    anyway. Applications are encouraged to use <function>pg_parameter_status</function> rather than ad
    hoc code to determine these values.
  </para>
  <caution>
    <para>
      On a pre-7.4
      PostgreSQL server, changing <literal>client_encoding</literal> via <literal>SET</literal> after connection startup will
      not be reflected by <function>pg_parameter_status</function>.
     </para>
  </caution>
 </refsect1>

 <refsect1 role="parameters">
  &reftitle.parameters;
  <para>
   <variablelist>
    <varlistentry>
     <term><parameter>connection</parameter></term>
     <listitem>
      <para>
       PostgreSQL database connection resource.  When
       <parameter>connection</parameter> is not present, the default connection
       is used. The default connection is the last connection made by
       <function>pg_connect</function> or <function>pg_pconnect</function>.
      </para>
     </listitem>
    </varlistentry>
    <varlistentry>
     <term><parameter>param_name</parameter></term>
     <listitem>
        <para>
         Possible <parameter>param_name</parameter> values include <literal>server_version</literal>,
        <literal>server_encoding</literal>, <literal>client_encoding</literal>,
        <literal>is_superuser</literal>, <literal>session_authorization</literal>,
        <literal>DateStyle</literal>, <literal>TimeZone</literal>, and
        <literal>integer_datetimes</literal>.
        </para>
     </listitem>
    </varlistentry>
   </variablelist>
  </para>
 </refsect1>

 <refsect1 role="returnvalues">
  &reftitle.returnvalues;
  <para>A <type>string</type> containing the value of the parameter, &false; on failure or invalid
  <parameter>param_name</parameter>.</para>
 </refsect1>

 <refsect1 role="examples">
  &reftitle.examples;
  <para>
   <example>
    <title><function>pg_parameter_status</function> example</title>
    <programlisting role="php">
<![CDATA[
<?php
  $dbconn = pg_connect("dbname=publisher") or die("Could not connect");

  echo "Server encoding: ", pg_parameter_status($dbconn, "server_encoding");
?>
]]>
    </programlisting>
    &example.outputs;
    <screen>
<![CDATA[
Server encoding: SQL_ASCII
]]>
    </screen>
   </example>
  </para>
 </refsect1>
</refentry>

<!-- Keep this comment at the end of the file
Local variables:
mode: sgml
sgml-omittag:t
sgml-shorttag:t
sgml-minimize-attributes:nil
sgml-always-quote-attributes:t
sgml-indent-step:1
sgml-indent-data:t
indent-tabs-mode:nil
sgml-parent-document:nil
sgml-default-dtd-file:"~/.phpdoc/manual.ced"
sgml-exposed-tags:nil
sgml-local-catalogs:nil
sgml-local-ecat-files:nil
End:
vim600: syn=xml fen fdm=syntax fdl=2 si
vim: et tw=78 syn=sgml
vi: ts=1 sw=1
-->


text:
layout: page
title: Portfolio
permalink: /portfolio/
---

### Twitter Clone (RailsTutorial)

The classic rite-of-passage for aspiring Rails Developers, I approached Hartl's Rails Tutorial as a crash course overview before diving deep into the various topics using The Odin Project. You'll notice a branch in my git repo where I've decided to translate the MiniTest suite to RSpec, not out of any sort of preference but just to enhance my understanding of both tools.

[See it deployed on Heroku](http://serene-lake-1633.herokuapp.com)

[Check the GitHub Repo](http://github.com/ashleymichal/sample_app)

[Link to Rails Tutorial](http://www.railstutorial.org)

<!-- ### Computer Science Fundamentals

Some valuable computer science exercises from The Odin Project.

[Check the GitHub Repo](https://github.com/ashleymichal/ruby-comp-sci)

[The Odin Project](http://www.theodinproject.com) -->

<!-- ### Ruby-Connect

Collaborative project building an SMS game of Connect Four using Sinatra and Twilio. Part of Ruby Monday, an ongoing group-project through CodeNewbie.org.

My first contribution is to pair with another member to build out the game interface.

[See it deployed on Heroku](#)

[Check the GitHub Repo](#)

[Learn more about Ruby Monday @CodeNewbie]() -->

<!-- ### Rummikub

First collaborative project undertaken with a friend from CodeNewbie-ATX. -->

### Typo (Working with 'Legacy' Code) *In Progress!*

The over-arching project from UC Berkeley's MOOC 'Engineering Software as a Service, pt 2' teaches the Agile workflow by requiring students to iterate over the TDD workflow with an existing web application, in this case [Typo](#), a weblog CMS built in Rails. The project builds over several weeks, focusing on refactoring, project management, and maintenance.

[See it deployed on Heroku](#)

[Check the Github Repo (assignment details in ReadMe)](#)

### RottenPotatoes

The over-arching project from UC Berkeley's MOOC 'Engineering Software as a Service pt 1' teaches the Agile workflow by requiring students to build a restful social network application for movie reviews reminiscent of RottenTomatoes.com. The project builds over several weeks, with most of the front end being supplied in the boilerplate code.

[See it deployed on Heroku](#)

[Check the Github Repo (assignment details in ReadMe)](#)

<!-- [LINK_TEXT](LINK_URL) -->