text:
package oneil.marcel;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

public class SortDriver {
	public enum SortType {
		SELECTION, INSERTION, MERGE, QUICK
	}

	public enum TimeType {
		MILLI, NANO
	}

	public static void main(String[] args) {
		Scanner s = new Scanner(System.in);
		boolean quit = false;
		do {
			int selection = menu(s);
			if (selection <= 4) {
				int listLength = readInt(s, "How many integer values would you like to sort? ");
				int[] list = createList(listLength);
				switch (selection) {
				case 1:
					printInfo(list, timeSort(list, SortType.SELECTION, TimeType.MILLI));
					break;
				case 2:
					printInfo(list, timeSort(list, SortType.INSERTION, TimeType.MILLI));
					break;
				case 3:
					printInfo(list, timeSort(list, SortType.MERGE, TimeType.MILLI));
					break;
				case 4:
					printInfo(list, timeSort(list, SortType.QUICK, TimeType.MILLI));
					break;
				}
			} else if (selection == 5) {
				try {
					File file = new File("sortdata.csv");
					FileWriter out = new FileWriter(file);
					int[] listLengths = { 5000, 10000, 20000, 40000, 80000, 100000 };
					SortType[] sortTypes = { SortType.SELECTION, SortType.INSERTION, SortType.MERGE, SortType.QUICK };
					out.write("# of Items,Selection,Insertion,Merge,Quick\n");
					for (int length : listLengths) {
						out.write(length + "");
						for (SortType sort : sortTypes) {
							int[] list = createList(length);
							long totalTime = timeSort(list, sort, TimeType.NANO);
							out.write("," + totalTime);
						}
						out.write("\n");
					}
					out.close();
					System.out.println("Data was generated in file sortdata.csv");
					System.out.println();
				} catch (IOException e) {
					System.out.println(e.getMessage());
				}
			} else {
				quit = true;
			}
		} while (!quit);
		s.close();
	}

	/*
	 * 	*****Selection Sort Data*****
	 *
	 * 	sortdata.csv
	 *
	 * 	+------------+--------------+
	 * 	| # of Items | Milliseconds |
	 * 	+------------+--------------+
	 * 	|       5000 |           26 |
	 * 	|      10000 |           38 |
	 * 	|      20000 |          141 |
	 * 	|      40000 |          537 |
	 * 	|      80000 |         2094 |
	 * 	|     100000 |         3221 |
	 * 	+------------+--------------+
	 *
	 *
	 * 	Trendline (using gnuplot)
	 * 	For f(x) = a*x**2 + b*x + c
	 *
	 * 	Final set of parameters            Asymptotic Standard Error
	 * 	=======================            ==========================
	 * 	a               = 3.13281e-07      +/- 5.94e-09     (1.896%)
	 * 	b               = 0.000919426      +/- 0.00063      (68.52%)
	 * 	c               = 3.16963          +/- 10.68        (337.1%)
	 *
	 *
	 * 	For x = 150000
	 *
	 * 	Theoretical value: 7190
	 * 	Experimental value: 7236
	 *
	 * 	Error: ~0.64%
	 */

	public static int menu(Scanner s) {
		System.out.println("*******MENU*******");
		System.out.println("1: Selection Sort");
		System.out.println("2: Insertion Sort");
		System.out.println("3: Merge Sort");
		System.out.println("4: Quick Sort");
		System.out.println("5: Compare Sorts");
		System.out.println("6: Quit");

		int input = 6;
		boolean invalid = false;

		do {
			System.out.print(invalid ? "Please input a valid command: " : "Please select a command: ");
			if (s.hasNextInt()) {
				input = s.nextInt();
				if (input < 1 || input > 6) {
					invalid = true;
					s.nextLine();
				} else {
					invalid = false;
					s.nextLine();
				}
			} else {
				invalid = true;
				s.nextLine();
			}
		} while (invalid);
		System.out.println();
		return input;
	}

	private static int[] createList(int listLength) {
		int[] list = new int[listLength];
		for (int i = 0; i < listLength; i++) {
			list[i] = (int) (Math.random() * Integer.MAX_VALUE + 1);
		}
		return list;
	}

	private static long timeSort(int[] list, SortType sort, TimeType time) {
		long startTime;
		long endTime;
		if (time == TimeType.MILLI)
			startTime = System.currentTimeMillis();
		else
			startTime = System.nanoTime();
		switch (sort) {
		case SELECTION:
			Sorts.selectionSort(list);
			break;
		case INSERTION:
			Sorts.insertionSort(list);
			break;
		case MERGE:
			Sorts.mergeSort(list, new int[list.length], 0, list.length - 1);
			break;
		case QUICK:
			Sorts.quicksort(list, 0, list.length);
			break;
		}
		if (time == TimeType.MILLI)
			endTime = System.currentTimeMillis();
		else
			endTime = System.nanoTime();
		return endTime - startTime;
	}

	private static void printInfo(int[] list, long time) {
		System.out.println("Smallest Value: " + list[0]);
		System.out.println("Largest Value: " + list[list.length - 1]);
		System.out.println("Total Sorting Time (ms): " + time);
		System.out.println();
	}

	private static int readInt(Scanner s, String prompt) {
		int input = 0;
		boolean invalid = false;

		do {
			System.out.print(invalid ? "Please input a valid positive integer: " : prompt);
			if (s.hasNextLine()) {
				if (s.hasNextInt()) {
					input = s.nextInt();
					if (input > 0 || input == -1)
						invalid = false;
					else
						invalid = true;
				} else {
					invalid = true;
				}
			} else {
				invalid = true;
			}
			s.nextLine(); // consume remaining tokens
		} while (invalid);
		return input;

	}

}


text:
import datetime
import json

from babel.dates import format_datetime
from google.appengine.ext.deferred import deferred

from rogerthat.bizz.gcs import get_serving_url
from rogerthat.bizz.import_export import export_service_data, import_service_data, validate_export_service_data
from rogerthat.consts import EXPORTS_BUCKET
from rogerthat.models import ServiceIdentity
from rogerthat.rpc import users
import webapp2 as webapp2

class ExportServiceDataHandler(webapp2.RequestHandler):
    def get(self):
        from rogerthat.bizz.service import ExportBrandingsException
        current_user = users.get_current_user()
        service_identity = self.request.GET.get('service_identity') or ServiceIdentity.DEFAULT
        date = format_datetime(datetime.datetime.now(), locale='en_GB', format='medium')
        result_path = '/%s/services/%s/%s/export %s.zip' % (EXPORTS_BUCKET, current_user.email(), service_identity, date)
        self.response.headers['Content-Type'] = 'application/json'
        try:
            validate_export_service_data(current_user, service_identity)
        except ExportBrandingsException as e:
            self.response.set_status(400)
            self.response.out.write(json.dumps({'message': e.message}))
            return
        deferred.defer(export_service_data, current_user, service_identity, result_path)
        self.response.out.write(json.dumps({'download_url': get_serving_url(result_path)}))

class ImportServiceDataHandler(webapp2.RequestHandler):
    def post(self):
        current_user = users.get_current_user()
        uploaded_file = self.request.POST.get('file', None)
        if uploaded_file is None:
            self.abort(400)
        if not uploaded_file.type.startswith('application/zip'):
            self.abort(400)
        file_content = uploaded_file.value
        import_service_data(current_user, file_content)
        self.redirect('/?sp=1')

redpajama_set_name: RedPajamaGithub


text:
layout: post
title:  "DevoWeek - 2017/12/10"
date:   2017-12-10
categories: [DevoWeek]
tags: [ .NET, F#, Angular, Spotify, Testing]
---

This week:

## News:

* **[dotnet-script 0.16 is out](https://www.strathweb.com/2017/12/c-repl-for-net-core-2-0-and-load-support-from-nuget-0-16-dotnet-script-is-out/)** - I haven't written in DevoWeek about scripted C# on .NET Core, so here it is. Also check out [project site](https://github.com/filipw/dotnet-script).
* **[Stubbing your way to automated end to end testing in an API first world](https://alastaircrabtree.com/stubbing-your-way-to-automated-e2e-testing-api-first-with-wiremock/)** - A blog post about stubbing your 3rd party systems in E2E tests with [WireMock.NET](https://github.com/WireMock-Net/WireMock.Net). Good read.
* **[Over 5 Years of F#](http://jnyman.com/2017/12/04/five_years_of_fsharp/)** - Story of some developer from Arizona that started with Excel addons and ended up as F#(+C#) developer. He wrote about his history and what are his thoughts. Really cool post.
* **[11 Angular Component Libraries You Should Know In 2018](https://blog.bitsrc.io/11-angular-component-libraries-you-should-know-in-2018-e9f9c9d544ff)**
* **[My 2017 year on Spotify](https://2017wrapped.com/share/en/-L-lFh9YDjd3HLfdb7_f)** - You can get yours [here](https://2017wrapped.com/).

![My 2017 year on Spotify](https://i.imgur.com/m872HtW.png)

## DevoWeek
Works on *continous post deployment* are still going. As I mentioned in the last post, I dropped idea of manualy creating HTTP requests for using [octokit.NET](https://github.com/octokit/octokit.net). The choice turned out to be great. Development speeded up dramaticly as octokit.net is well documented and I can fully focus on learning F#, not worring about some GitHub API limitations.

Work goes well, but there is much *unknown* yet to be found.


text:
from thorpy.miscgui.title import Title
from thorpy.painting.painters.painter import Painter
from thorpy.painting.fusionner import _Fusionner

def get_void_state():
##    from thorpy.miscgui.title import Title
##    from thorpy.painting.painter import Painter
##    from thorpy.miscgui.fusionner import _Fusionner
    title = Title("")
    painter = Painter(None)
    fusionner = _Fusionner(painter, title)
    return State(fusionner)


text:
namespace MvcProject.Web.Routes.Tests
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Web.Routing;

    using Areas.Common.Controllers;
    using MvcRouteTester;
    using NUnit.Framework;

    [TestFixture]
    public class ProductsRouteTests
    {
        [Test]
        public void TestRouteById()
        {
            var routeCollection = new RouteCollection();
            const string Url = "/Product/M2toaGR3NldEbW4tc2sha2o4bQ==";
            RouteConfig.RegisterRoutes(routeCollection);
            routeCollection
                .ShouldMap(Url)
                .To<ProductsController>(ctr => ctr.ById("M2toaGR3NldEbW4tc2sha2o4bQ=="));

            // Structure of the above test
            // => ProductsController
            // => ById
            // => Id = M2toaGR3NldEbW4tc2sha2o4bQ==
        }
    }
}


text:
"""Utility functions for the autoimport code."""
import pathlib
import sys
from collections import OrderedDict
from typing import Generator, List, Optional, Tuple

from rope.base.project import Project

from .defs import ModuleCompiled, ModuleFile, ModuleInfo, Package, PackageType, Source

def get_package_tuple(
    package_path: pathlib.Path, project: Optional[Project] = None
) -> Optional[Package]:
    """
    Get package name and type from a path.

    Checks for common issues, such as not being a viable python module
    Returns None if not a viable package.
    """
    package_name = package_path.name
    package_type: PackageType
    if package_name.startswith(".") or package_name == "__pycache__":
        return None
    if package_name.endswith((".egg-info", ".dist-info")):
        return None
    if package_path.is_file():
        if package_name.endswith(".so"):
            package_name = package_name.split(".")[0]
            package_type = PackageType.COMPILED
        elif package_name.endswith(".pyd"):
            package_name = package_name.split(".")[0]
            package_type = PackageType.COMPILED
        elif package_name.endswith(".py"):
            package_name = package_path.stem
            package_type = PackageType.SINGLE_FILE
        else:
            return None
    else:
        package_type = PackageType.STANDARD
    package_source: Source = get_package_source(package_path, project, package_name)
    return Package(package_name, package_source, package_path, package_type)

def get_package_source(
    package: pathlib.Path, project: Optional[Project], name: str
) -> Source:
    """Detect the source of a given package. Rudimentary implementation."""
    if name in sys.builtin_module_names:
        return Source.BUILTIN
    if project is not None and project.address in str(package):
        return Source.PROJECT
    if "site-packages" in package.parts:
        return Source.SITE_PACKAGE
    if sys.version_info < (3, 10, 0):
        if str(package).startswith(sys.prefix):
            return Source.STANDARD
    else:
        if name in sys.stdlib_module_names:
            return Source.STANDARD
    return Source.UNKNOWN

def get_modname_from_path(
    modpath: pathlib.Path, package_path: pathlib.Path, add_package_name: bool = True
) -> str:
    """Get module name from a path in respect to package."""
    package_name: str = package_path.stem
    rel_path_parts = modpath.relative_to(package_path).parts
    modname = ""
    if len(rel_path_parts) > 0:
        for part in rel_path_parts[:-1]:
            modname += part
            modname += "."
        if rel_path_parts[-1] == "__init__":
            modname = modname[:-1]
        else:
            modname = modname + modpath.stem
    if add_package_name:
        modname = package_name if modname == "" else package_name + "." + modname
    else:
        assert modname != "."
    return modname

def sort_and_deduplicate(results: List[Tuple[str, int]]) -> List[str]:
    """Sort and deduplicate a list of name, source entries."""
    results = sorted(results, key=lambda y: y[-1])
    results_sorted = [name for name, source in results]
    return list(OrderedDict.fromkeys(results_sorted))

def sort_and_deduplicate_tuple(
    results: List[Tuple[str, str, int]]
) -> List[Tuple[str, str]]:
    """Sort and deduplicate a list of name, module, source entries."""
    results = sorted(results, key=lambda y: y[-1])
    results_sorted = [result[:-1] for result in results]
    return list(OrderedDict.fromkeys(results_sorted))

def should_parse(path: pathlib.Path, underlined: bool) -> bool:
    if underlined:
        return True
    for part in path.parts:
        if part.startswith("_"):
            return False
    return True

def get_files(
    package: Package, underlined: bool = False
) -> Generator[ModuleInfo, None, None]:
    """Find all files to parse in a given path using __init__.py."""
    if package.type in (PackageType.COMPILED, PackageType.BUILTIN):
        if package.source in (Source.STANDARD, Source.BUILTIN):
            yield ModuleCompiled(None, package.name, underlined, True)
    elif package.type == PackageType.SINGLE_FILE:
        assert package.path
        assert package.path.suffix == ".py"
        yield ModuleFile(package.path, package.path.stem, underlined, False)
    else:
        assert package.path
        for file in package.path.glob("*.py"):
            if file.name == "__init__.py":
                yield ModuleFile(
                    file,
                    get_modname_from_path(file.parent, package.path),
                    underlined,
                    True,
                )
            elif should_parse(file, underlined):
                yield ModuleFile(
                    file, get_modname_from_path(file, package.path), underlined, False
                )


text:
package com.amazonaws.services.apigatewayv2.model.transform;

import java.math.*;

import javax.annotation.Generated;

import com.amazonaws.services.apigatewayv2.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;

import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;

/**
 * UpdateDomainNameResult JSON Unmarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class UpdateDomainNameResultJsonUnmarshaller implements Unmarshaller<UpdateDomainNameResult, JsonUnmarshallerContext> {

    public UpdateDomainNameResult unmarshall(JsonUnmarshallerContext context) throws Exception {
        UpdateDomainNameResult updateDomainNameResult = new UpdateDomainNameResult();

        int originalDepth = context.getCurrentDepth();
        String currentParentElement = context.getCurrentParentElement();
        int targetDepth = originalDepth + 1;

        JsonToken token = context.getCurrentToken();
        if (token == null)
            token = context.nextToken();
        if (token == VALUE_NULL) {
            return updateDomainNameResult;
        }

        while (true) {
            if (token == null)
                break;

            if (token == FIELD_NAME || token == START_OBJECT) {
                if (context.testExpression("apiMappingSelectionExpression", targetDepth)) {
                    context.nextToken();
                    updateDomainNameResult.setApiMappingSelectionExpression(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("domainName", targetDepth)) {
                    context.nextToken();
                    updateDomainNameResult.setDomainName(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("domainNameConfigurations", targetDepth)) {
                    context.nextToken();
                    updateDomainNameResult.setDomainNameConfigurations(new ListUnmarshaller<DomainNameConfiguration>(DomainNameConfigurationJsonUnmarshaller
                            .getInstance()).unmarshall(context));
                }
                if (context.testExpression("tags", targetDepth)) {
                    context.nextToken();
                    updateDomainNameResult.setTags(new MapUnmarshaller<String, String>(context.getUnmarshaller(String.class), context
                            .getUnmarshaller(String.class)).unmarshall(context));
                }
            } else if (token == END_ARRAY || token == END_OBJECT) {
                if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
                    if (context.getCurrentDepth() <= originalDepth)
                        break;
                }
            }
            token = context.nextToken();
        }

        return updateDomainNameResult;
    }

    private static UpdateDomainNameResultJsonUnmarshaller instance;

    public static UpdateDomainNameResultJsonUnmarshaller getInstance() {
        if (instance == null)
            instance = new UpdateDomainNameResultJsonUnmarshaller();
        return instance;
    }
}


text:
from oslo_db.sqlalchemy import models as oslo_models
from sqlalchemy.ext import declarative
from sqlalchemy.orm import attributes

class _SaharaBase(oslo_models.ModelBase, oslo_models.TimestampMixin):
    """Base class for all SQLAlchemy DB Models."""

    def to_dict(self):
        """sqlalchemy based automatic to_dict method."""
        d = {}

        # if a column is unloaded at this point, it is
        # probably deferred. We do not want to access it
        # here and thereby cause it to load...
        unloaded = attributes.instance_state(self).unloaded

        for col in self.__table__.columns:
            if col.name not in unloaded:
                d[col.name] = getattr(self, col.name)

        datetime_to_str(d, 'created_at')
        datetime_to_str(d, 'updated_at')

        return d

def datetime_to_str(dct, attr_name):
    if dct.get(attr_name) is not None:
        value = dct[attr_name].isoformat('T')
        ms_delimiter = value.find(".")
        if ms_delimiter != -1:
            # Removing ms from time
            value = value[:ms_delimiter]
        dct[attr_name] = value

SaharaBase = declarative.declarative_base(cls=_SaharaBase)


text:
//
// Copyright (c) Microsoft Corporation.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//

using System;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation.Language;

namespace Microsoft.Windows.PowerShell.ScriptAnalyzer.Generic
{
    /// <summary>
    /// Represents an abstract class for rule that checks whether the script
    /// uses certain cmdlet.
    /// </summary>
    public abstract class AvoidCmdletGeneric : IScriptRule
    {
        /// <summary>
        /// AnalyzeScript: Analyzes the given Ast and returns DiagnosticRecords based on the analysis.
        /// </summary>
        /// <param name="ast">The script's ast</param>
        /// <param name="fileName">The name of the script file being analyzed</param>
        /// <returns>The results of the analysis</returns>
        public IEnumerable<DiagnosticRecord> AnalyzeScript(Ast ast, string fileName)
        {
            if (ast == null) throw new ArgumentNullException("ast");

            // Finds all CommandAsts.
            IEnumerable<Ast> commandAsts = ast.FindAll(testAst => testAst is CommandAst, true);

            List<String> cmdletNameAndAliases = Microsoft.Windows.PowerShell.ScriptAnalyzer.Helper.Instance.CmdletNameAndAliases(GetCmdletName());

            // Iterates all CommandAsts and check the command name.
            foreach (CommandAst cmdAst in commandAsts)
            {
                if (cmdAst.GetCommandName() == null) continue;

                if (cmdletNameAndAliases.Contains(cmdAst.GetCommandName(), StringComparer.OrdinalIgnoreCase))
                {
                    yield return new DiagnosticRecord(GetError(fileName), cmdAst.Extent, GetName(), DiagnosticSeverity.Warning, fileName);
                }
            }
        }

        /// <summary>
        /// Retrieves the name of the cmdlet to avoid
        /// </summary>
        /// <returns></returns>
        public abstract string GetCmdletName();

        /// <summary>
        /// GetError: Retrieves the error message.
        /// </summary>
        /// <returns></returns>
        public abstract string GetError(string FileName);

        /// <summary>
        /// GetName: Retrieves the name of the rule.
        /// </summary>
        /// <returns>The name of the rule.</returns>
        public abstract string GetName();

        /// <summary>
        /// GetCommonName: Retrieves the common name of this rule.
        /// </summary>
        /// <returns>The common name of this rule</returns>
        public abstract string GetCommonName();

        /// <summary>
        /// GetDescription: Retrieves the description of the rule.
        /// </summary>
        /// <returns>The description of the rule.</returns>
        public abstract string GetDescription();

        /// <summary>
        /// GetSourceName: Retrieves the source name of the rule.
        /// </summary>
        /// <returns>The source name of the rule.</returns>
        public abstract string GetSourceName();

        /// <summary>
        /// GetSourceType: Retrieves the source type of the rule.
        /// </summary>
        /// <returns>The source type of the rule.</returns>
        public abstract  SourceType GetSourceType();

        /// <summary>
        /// GetSeverity: Retrieves the severity of the rule: error, warning of information.
        /// </summary>
        /// <returns></returns>
        public abstract RuleSeverity GetSeverity();
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
      <title>All Classes - BlackBerry® 10 BBM AIR Native Extension</title>
      <base target="classFrame">
      <link rel="stylesheet" href="style.css" type="text/css" media="screen">
      <link rel="stylesheet" href="print.css" type="text/css" media="print">
      <link rel="stylesheet" href="override.css" type="text/css">

All Classes

            BBMContact

            BBMContactEvent

            BBMContactStatus

            BBMContactUpdateTypes

            BBMManager

            BBMProfileBoxItem

            BBMRegisterEvent

            BBMResult

            BBMUserProfile

            BBMUserProfileEvent


text:
/**
 * Shared code for interacting with the GitHub API.
 *
 * Exposes two magic-named hooks:
 *
 * - process(searchValue, username): Execute a search.
 * - setup(): Optional. Execute code when the page loads.
 */

// Get the client ID and secret from the URL if they're not provided in config.
// This lets people try the demo.
(function() {
    var matches;
    if (!window.CLIENT_ID) {
        matches = /[?&]client_id=([^&#]+)/.exec(location.search);
        if (matches && matches[1]) {
            window.CLIENT_ID = matches[1];
        }
        else {
            window.CLIENT_ID = '';
        }
    }
    if (!window.CLIENT_SECRET) {
        matches = /[?&]client_secret=([^&#]+)/.exec(location.search);
        if (matches && matches[1]) {
            window.CLIENT_SECRET = matches[1];
        }
        else {
            window.CLIENT_SECRET = '';
        }
    }
})();

var last403 = 0;

/**
 * Request an API resource from GitHub.
 *
 * @param {String} url
 *   The URL to request. The client ID and secret will be appended.
 * @param {Function} callback
 *   A function to execute after the resource is loaded.
 *
 * @return {XMLHttpRequest}
 *   The request object.
 */
function loadAjax(url, callback, complete) {
    url = url + (/\?/g.test(url) ? '&' : '?') + 'client_id=' + CLIENT_ID + '&client_secret=' + CLIENT_SECRET;
    var xhr = new XMLHttpRequest(), success = false;
    xhr.onreadystatechange = function () {
        if (xhr.readyState === xhr.DONE) {
            // Request completed successfully
            if (xhr.status === 200 || xhr.status === 0) {
                try {
                    var json = JSON.parse(xhr.responseText);
                    callback(json);
                }
                catch (e) {
                    callback(xhr.responseText);
                }
                success = true;
            }
            // Request was well-formed but couldn't be completed in time
            else if (xhr.status === 202) {
                console.info('Request to ' + url + ' returned 202 Accepted, indicating that GitHub is processing the request asynchronously and could not return immediately. This usually happens for long-running actions like forking a repo or calculating statistics.');
            }
            // Requested repo is empty (204) or still being created (409); ignore
            else if (xhr.status === 204 || xhr.status === 409) {
                console.info('Request to ' + url + ' returned 204 No Content. This usually means the requested repo is empty.');
            }
            // For our uses, 403 usually indicates a rate limiting error
            else if (xhr.status === 403) {
                try {
                    var response = JSON.parse(xhr.responseText);
                    console.error('Request to ' + url + ' denied: ' + response.message);
                    var now = Date.now();
                    if (now - last403 > 3000) {
                        last403 = now;
                        alert(response.message);
                    }
                }
                catch (e) {
                    console.error('Request to ' + url + ' denied: ' + xhr.responseText);
                }
            }
            else if (xhr.status > 499) {
                console.error('Request to ' + url + ' failed with code ' + xhr.status + ' because of a server error.');
            }
            // Browsers seem to handle 304 as serving a 200 from the cache.
            // 301, 302, and 307 will automatically be followed.
            // Other known possible status codes:
            // 201 (resource created; we're not doing that here)
            // 205 (notifications marked as read; we're not doing that here)
            // 401 (invalid login)
            // 400 or 422 (invalid request parameters)
            // 404 (hidden data or endpoint does not exist)
            // 405 (merge cannot be performed; we're not doing that here)
            else {
                console.error('Unable to load [' + url + '] [' + xhr.status + ']');
            }
            if (typeof complete === 'function') complete(xhr, success, url);
        }
    };

    xhr.open('GET', url, true);
    xhr.send(null);
    return xhr;
}

/**
 * HTML-escape a string.
 */
function sanitize(s) {
    var d = document.createElement('div');
    d.textContent = s;
    return d.innerHTML.replace(/"/g, '"');
}

/**
 * Get the top and left coordinates of a DOM element.
 *
 * Copied from http://stackoverflow.com/a/16752864/843621
 * This is slightly wrong -- see http://stackoverflow.com/q/442404/843621 for
 * correct versions -- but it does the job.
 *
 * @param {HTMLElement} ele
 *   The element for which to get coordinates.
 *
 * @return {Number[]}
 *   A two-element array containing the left and top pixel coordinates of the
 *   relevant element, respectively.
 */
function getPos(ele) {
    var x = 0;
    var y = 0;
    while (true) {
        x += ele.offsetLeft;
        y += ele.offsetTop;
        if (ele.offsetParent === null) {
            break;
        }
        ele = ele.offsetParent;
    }
    return [x, y];
}

/**
 * Execute a search.
 */
function submitSearch(event) {
    if (event) event.preventDefault();
    document.getElementById('search-results').style.display = 'none';
    var searchValue = document.getElementById('username-field').value;
    // Run the process hook.
    process(searchValue, encodeURIComponent(searchValue));
}

window.onload = function() {
    // Insert the correct URL for the current page into the help text.
    document.getElementById('here').textContent = location.href + (/\?/g.test(location.href) ? '&' : '?') + 'client_id=CLIENT_ID&client_secret=CLIENT_SECRET';
    // Hide the help text if we already have the keys.
    if (window.CLIENT_ID && window.CLIENT_SECRET) {
        document.getElementById('info').style.display = 'none';
    }

    // Move the autocomplete results below the search field.
    var elem = document.getElementById('username-field'),
        move = document.getElementById('search-results');
    var o = getPos(elem);
    move.style.position = 'absolute';
    move.style.left = o[0] + 'px';
    move.style.top = (o[1] + elem.offsetHeight) + 'px';

    // If the ?user parameter is in the URL, automatically execute the search.
    var matches = /[?&]user=([^&#]+)/.exec(location.search);
    if (matches && matches[1]) {
        document.getElementById('username-field').value = matches[1];
        submitSearch();
    }

    // Submit the search form.
    document.getElementById('search-form').addEventListener('submit', submitSearch);

    // Get autocomplete results when searching for users.
    var lastTimeout = null,
        lastXHR = null,
        lastInput = '';
    document.getElementById('search-form').addEventListener('keyup', function(event) {
        event.preventDefault();
        var div = document.getElementById('search-results');
        var searchValue = document.getElementById('username-field').value;
        if (searchValue.length < 2) {
            if (lastTimeout) clearTimeout(lastTimeout);
            if (lastXHR && lastXHR.readyState !== lastXHR.DONE) lastXHR.abort();
            div.style.display = 'none';
            return;
        }
        if (searchValue === lastInput) {
            return;
        }
        lastInput = searchValue;
        var username = encodeURIComponent(searchValue);

        if (lastTimeout) clearTimeout(lastTimeout);
        lastTimeout = setTimeout(function() {
            if (lastXHR && lastXHR.readyState !== lastXHR.DONE) lastXHR.abort();
            lastXHR = loadAjax('https://api.github.com/search/users?per_page=10&q=' + username, function(results) {
                var users = [];
                for (var i = 0, l = results.items.length; i < l; i++) {
                    var u = results.items[i], n = sanitize(u.login);
                    users.push('
' + n + '
');
                }
                if (users.length) {
                    div.innerHTML = users.join('');
                    div.style.display = 'block';
                }
                else {
                    div.style.display = 'none';
                }
            });
        }, 250);
    });

    // Execute a search when an autocomplete result is clicked.
    document.getElementById('search-results').addEventListener('click', function(event) {
        event.preventDefault();
        var elem = event.target;
        if (elem && elem.nodeName.toLowerCase() != 'div') {
            elem = elem.parentNode;
        }
        if (elem.nodeName.toLowerCase() == 'div' && ~elem.className.indexOf('suggestion')) {
            document.getElementById('username-field').value = decodeURIComponent(elem.getAttribute('data-name'));
            this.style.display = 'none';
            submitSearch();
        }
    });

    // Run the setup hook if it's available.
    if (typeof setup === 'function') setup();
};


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <title>Statistics of list in UD_Serbian-SET</title>
    <link rel="root" href=""/>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
    <link rel="stylesheet" type="text/css" href="../../css/jquery-ui-redmond.css"/>
    <link rel="stylesheet" type="text/css" href="../../css/style.css"/>
    <link rel="stylesheet" type="text/css" href="../../css/style-vis.css"/>
    <link rel="stylesheet" type="text/css" href="../../css/hint.css"/>

          home

          edit page
          issue tracker

          <gcse:search></gcse:search>

        This page pertains to UD version 2.

            It appears that you have Javascript disabled.
            Please consider enabling Javascript for this page to see the visualizations.

Treebank Statistics: UD_Serbian-SET: Relations: list

This relation is universal.

11 nodes (0%) are attached to their parents as list.

11 instances of list (100%) are left-to-right (parent precedes child).
Average distance between parent and child is 5.72727272727273.

The following 2 pairs of parts of speech are connected with list: <tt>NOUN</tt>-<tt>NOUN</tt> (6; 55% instances), <tt>PROPN</tt>-<tt>PROPN</tt> (5; 45% instances).

# visual-style 16	bgColor:blue
# visual-style 16	fgColor:white
# visual-style 10	bgColor:blue
# visual-style 10	fgColor:white
# visual-style 10 16 list	color:blue
1	Za	za	ADP	Sa	Case=Acc	2	case	_	_
2	mene	ja	PRON	Pp1-sa	Case=Acc|Number=Sing|Person=1|PronType=Prs	5	obl	_	_
3	grad	grad	NOUN	Ncmsn	Case=Nom|Gender=Masc|Number=Sing	5	nsubj	_	_
4	Madrid	Madrid	PROPN	Npmsn	Case=Nom|Gender=Masc|Number=Sing	3	flat	_	_
5	predstavlja	predstavljati	VERB	Vmr3s	Mood=Ind|Number=Sing|Person=3|Tense=Pres|VerbForm=Fin	0	root	_	_
6	simbol	simbol	NOUN	Ncmsan	Animacy=Inan|Case=Acc|Gender=Masc|Number=Sing	5	obj	_	_
7	mnogih	mnogi	ADJ	Agpfpgy	Case=Gen|Definite=Def|Degree=Pos|Gender=Fem|Number=Plur	8	amod	_	_
8	stvari	stvar	NOUN	Ncfpg	Case=Gen|Gender=Fem|Number=Plur	6	nmod	_	_
9	--	--	PUNCT	Z	_	10	punct	_	_
10	mladosti	mladost	NOUN	Ncfsg	Case=Gen|Gender=Fem|Number=Sing	8	appos	_	SpaceAfter=No
11	,	,	PUNCT	Z	_	10	punct	_	_
12	doma	dom	NOUN	Ncmsg	Case=Gen|Gender=Masc|Number=Sing	10	list	_	SpaceAfter=No
13	,	,	PUNCT	Z	_	10	punct	_	_
14	porodice	porodica	NOUN	Ncfsg	Case=Gen|Gender=Fem|Number=Sing	10	list	_	_
15	i	i	CCONJ	Cc	_	10	cc	_	_
16	prijateljstva	prijateljstvo	NOUN	Ncnsg	Case=Gen|Gender=Neut|Number=Sing	10	list	_	SpaceAfter=No
17	"	"	PUNCT	Z	_	5	punct	_	SpaceAfter=No
18	,	,	PUNCT	Z	_	19	punct	_	_
19	rekao	reći	VERB	Vmp-sm	Gender=Masc|Number=Sing|Tense=Past|VerbForm=Part|Voice=Act	5	parataxis	_	_
20	je	biti	AUX	Var3s	Mood=Ind|Number=Sing|Person=3|Tense=Pres|VerbForm=Fin	19	aux	_	_
21	bugarski	bugarski	ADJ	Agpmsny	Case=Nom|Definite=Def|Degree=Pos|Gender=Masc|Number=Sing	22	amod	_	_
22	lider	lider	NOUN	Ncmsn	Case=Nom|Gender=Masc|Number=Sing	19	nsubj	_	_
23	primajući	primati	ADV	Rr	Tense=Pres|VerbForm=Conv	19	xcomp	_	_
24	nagradu	nagrada	NOUN	Ncfsa	Case=Acc|Gender=Fem|Number=Sing	23	obj	_	SpaceAfter=No
25	.	.	PUNCT	Z	_	5	punct	_	_

# visual-style 17	bgColor:blue
# visual-style 17	fgColor:white
# visual-style 5	bgColor:blue
# visual-style 5	fgColor:white
# visual-style 5 17 list	color:blue
1	Zaustavlja	zaustavljati	VERB	Vmr3s	Mood=Ind|Number=Sing|Person=3|Tense=Pres|VerbForm=Fin	0	root	_	_
2	se	sebe	PRON	Px--sa	Case=Acc|PronType=Prs|Reflex=Yes	1	expl	_	_
3	u	u	ADP	Sl	Case=Loc	4	case	_	_
4	stanicama	stanica	NOUN	Ncfpl	Case=Loc|Gender=Fem|Number=Plur	1	obl	_	_
5	Skoplje	Skoplje	PROPN	Npnsn	Case=Nom|Gender=Neut|Number=Sing	4	appos	_	_
6	Sever	sever	NOUN	Ncmsn	Case=Nom|Gender=Masc|Number=Sing	5	flat	_	SpaceAfter=No
7	,	,	PUNCT	Z	_	5	punct	_	_
8	Gorce	Gorce	PROPN	Npmsn	Case=Nom|Gender=Masc|Number=Sing	5	list	_	_
9	Petrov	Petrov	PROPN	Npmsn	Case=Nom|Gender=Masc|Number=Sing	8	flat	_	SpaceAfter=No
10	,	,	PUNCT	Z	_	5	punct	_	_
11	Volkovo	Volkovo	PROPN	Npmsn	Case=Nom|Gender=Masc|Number=Sing	5	list	_	SpaceAfter=No
12	,	,	PUNCT	Z	_	5	punct	_	_
13	Jankovik	Jankovik	PROPN	Npmsn	Case=Nom|Gender=Masc|Number=Sing	5	list	_	SpaceAfter=No
14	,	,	PUNCT	Z	_	5	punct	_	_
15	Uroševac	Uroševac	PROPN	Npmsn	Case=Nom|Gender=Masc|Number=Sing	5	list	_	_
16	i	i	CCONJ	Cc	_	5	cc	_	_
17	Kosovo	Kosovo	PROPN	Npnsn	Case=Nom|Gender=Neut|Number=Sing	5	list	_	_
18	Polje	polje	NOUN	Ncnsn	Case=Nom|Gender=Neut|Number=Sing	17	flat	_	SpaceAfter=No
19	,	,	PUNCT	Z	_	20	punct	_	_
20	završavajući	završavati	ADV	Rr	Tense=Pres|VerbForm=Conv	1	xcomp	_	_
21	svoj	svoj	DET	Px-msan	Animacy=Inan|Case=Acc|Gender=Masc|Number=Sing|Poss=Yes|PronType=Prs|Reflex=Yes	22	det	_	_
22	put	put	NOUN	Ncmsan	Animacy=Inan|Case=Acc|Gender=Masc|Number=Sing	20	obj	_	_
23	u	u	ADP	Sl	Case=Loc	24	case	_	_
24	Prištini	Priština	PROPN	Npfsl	Case=Loc|Gender=Fem|Number=Sing	20	obl	_	SpaceAfter=No
25	.	.	PUNCT	Z	_	1	punct	_	_

© 2014–2021
            Universal Dependencies contributors.
            Site powered by Annodoc and brat
.


text:
<?php
  require 'vendor/autoload.php';
  require_once 'Constants.php';

  use net\authorize\api\contract\v1 as AnetAPI;
  use net\authorize\api\controller as AnetController;

  define("AUTHORIZENET_LOG_FILE", "phplog");

  function chargeCreditCard($amount){
      // Common setup for API credentials
      $merchantAuthentication = new AnetAPI\MerchantAuthenticationType();
      $merchantAuthentication->setName(Constants::MERCHANT_LOGIN_ID);
      $merchantAuthentication->setTransactionKey(Constants::MERCHANT_TRANSACTION_KEY);
      $refId = 'ref' . time();

      // Create the payment data for a credit card
      $creditCard = new AnetAPI\CreditCardType();
      $creditCard->setCardNumber("4111111111111111");
      $creditCard->setExpirationDate("1226");
      $creditCard->setCardCode("123");
      $paymentOne = new AnetAPI\PaymentType();
      $paymentOne->setCreditCard($creditCard);

      $order = new AnetAPI\OrderType();
      $order->setDescription("New Item");

      //create a transaction
      $transactionRequestType = new AnetAPI\TransactionRequestType();
      $transactionRequestType->setTransactionType( "authCaptureTransaction");
      $transactionRequestType->setAmount($amount);
      $transactionRequestType->setOrder($order);
      $transactionRequestType->setPayment($paymentOne);

      $request = new AnetAPI\CreateTransactionRequest();
      $request->setMerchantAuthentication($merchantAuthentication);
      $request->setRefId( $refId);
      $request->setTransactionRequest( $transactionRequestType);
      $controller = new AnetController\CreateTransactionController($request);
      $response = $controller->executeWithApiResponse( \net\authorize\api\constants\ANetEnvironment::SANDBOX);

      if ($response != null)
      {
        if($response->getMessages()->getResultCode() == Constants::RESPONSE_OK)
        {
          $tresponse = $response->getTransactionResponse();

	        if ($tresponse != null && $tresponse->getMessages() != null)
          {
            echo " Transaction Response code : " . $tresponse->getResponseCode() . "\n";
            echo "Charge Credit Card AUTH CODE : " . $tresponse->getAuthCode() . "\n";
            echo "Charge Credit Card TRANS ID  : " . $tresponse->getTransId() . "\n";
            echo " Code : " . $tresponse->getMessages()[0]->getCode() . "\n";
	          echo " Description : " . $tresponse->getMessages()[0]->getDescription() . "\n";
          }
          else
          {
            echo "Transaction Failed \n";
            if($tresponse->getErrors() != null)
            {
              echo " Error code  : " . $tresponse->getErrors()[0]->getErrorCode() . "\n";
              echo " Error message : " . $tresponse->getErrors()[0]->getErrorText() . "\n";
            }
          }
        }
        else
        {
          echo "Transaction Failed \n";
          $tresponse = $response->getTransactionResponse();
          if($tresponse != null && $tresponse->getErrors() != null)
          {
            echo " Error code  : " . $tresponse->getErrors()[0]->getErrorCode() . "\n";
            echo " Error message : " . $tresponse->getErrors()[0]->getErrorText() . "\n";
          }
          else
          {
            echo " Error code  : " . $response->getMessages()->getMessage()[0]->getCode() . "\n";
            echo " Error message : " . $response->getMessages()->getMessage()[0]->getText() . "\n";
          }
        }
      }
      else
      {
        echo  "No response returned \n";
      }

      return $response;
  }
  if(!defined('DONT_RUN_SAMPLES'))
      chargeCreditCard(Constants::SAMPLE_AMOUNT);
?>