text:
using System;
using System.Collections.Generic;

using NUnit.Framework;
using Shouldly;

using Mulder.Base.Extensions;

namespace Mulder.Tests.Base.Extensions
{
	public class YamlExtensionsTests
	{
		[TestFixture]
		public class when_serializing_dictionary_containing_only_strings_to_yaml
		{
			IDictionary<string, object> dictionary;
			string expectedYaml;

			[SetUp]
			public void Init()
			{
				dictionary = new Dictionary<string, object> {
					{ "Property1", "1" },
					{ "Property2", "2" },
					{ "Property3", "3" }
				};

				expectedYaml = string.Format("property1: 1{0}property2: 2{0}property3: 3{0}", Environment.NewLine);
			}

			[Test]
			public void should_create_yaml_string()
			{
				string yaml = dictionary.ToYaml();

				yaml.ShouldBe(expectedYaml);
			}
		}

		[TestFixture]
		public class when_serializing_dictionary_containing_only_strings_to_yaml_header
		{
			IDictionary<string, object> dictionary;
			string expectedHeader;

			[SetUp]
			public void Init()
			{
				dictionary = new Dictionary<string, object> {
					{ "Property1", "1" },
					{ "Property2", "2" },
					{ "Property3", "3" }
				};

				expectedHeader = string.Format("---{0}property1: 1{0}property2: 2{0}property3: 3{0}---{0}", Environment.NewLine);
			}

			[Test]
			public void should_create_a_yaml_header_string()
			{
				string yaml = dictionary.ToYamlHeader();

				yaml.ShouldBe(expectedHeader);
			}
		}

		[TestFixture]
		public class when_deserializing_an_empty_string
		{
			[Test]
			public void should_return_empty_dictionary()
			{
				"".DeserializeYaml().ShouldBeEmpty();
			}
		}

		[TestFixture]
		public class when_deserializing_yaml_text
		{
			string text = @"---
title: X-Files
cast:
  -
    name: David Duchovny
    role: Fox Mulder
  -
    name: Gillian Anderson
    role: Dana Scully
...";

			IDictionary<string, object> result;

			[SetUp]
			public void Init()
			{
				result = text.DeserializeYaml()[0] as IDictionary<string, object>;
			}

			[Test]
			public void should_return_populated_dictionary()
			{
				result.ShouldNotBeEmpty();
			}

			[Test]
			public void should_contain_title()
			{
				result.ShouldContainKeyAndValue("title", "X-Files");
			}

			[Test]
			public void should_contain_two_cast_members()
			{
				var cast = result["cast"] as List<object>;
				cast.Count.ShouldBe(2);
			}

			[Test]
			public void should_have_david_duchovny_as_first_cast_member()
			{
				var cast = result["cast"] as List<object>;
				var member = cast[0] as IDictionary<string, object>;
				member["name"].ShouldBe("David Duchovny");
				member["role"].ShouldBe("Fox Mulder");
			}

			[Test]
			public void should_have_gillian_anderson_as_second_cast_member()
			{
				var cast = result["cast"] as List<object>;
				var member = cast[1] as IDictionary<string, object>;
				member["name"].ShouldBe("Gillian Anderson");
				member["role"].ShouldBe("Dana Scully");
			}
		}

		[TestFixture]
		public class when_deserializing_a_yaml_header
		{
			string textWithoutHeader = @"Lorem ipsum dolor sit amet, consectetur adipiscing elit.";

			string textWithHeader = @"---
Property1: 1
Property2: 2
Property3: 3
---

Lorem ipsum dolor sit amet, consectetur adipiscing elit.";

			[Test]
			public void should_return_empty_dictionary_if_header_is_not_present()
			{
				textWithoutHeader.DeserializeYamlHeader().ShouldBeEmpty();
			}

			[Test]
			public void should_return_dictionary_of_items_if_header_is_present()
			{
				IDictionary<string, object> items = textWithHeader.DeserializeYamlHeader();

				items.Count.ShouldBe(3);
				items.ShouldContainKeyAndValue("Property1", "1");
				items.ShouldContainKeyAndValue("Property2", "2");
				items.ShouldContainKeyAndValue("Property3", "3");
			}
		}

		[TestFixture]
		public class when_excluding_the_yaml_header
		{
			string textWithoutHeader = @"Lorem ipsum dolor sit amet, consectetur adipiscing elit.";

			string textWithHeader = @"---
Property1: 1
Property2: 2
Property3: 3
---

Lorem ipsum dolor sit amet, consectetur adipiscing elit.";

			[Test]
			public void should_return_text_if_header_is_not_present()
			{
				textWithoutHeader.ExcludeYamlHeader().ShouldBe(textWithoutHeader);
			}

			[Test]
			public void should_return_text_witout_header_if_header_is_present()
			{
				textWithHeader.ExcludeYamlHeader().ShouldBe(textWithoutHeader);
			}
		}
	}
}


text:
SELECT projectId, datasetId, tableId, creationTime, lastModifiedTime, location, numBytes, numLongTermBytes, numRows, type FROM (
SELECT projectId, datasetId, tableId, creationTime, lastModifiedTime, location, numBytes, numLongTermBytes, numRows, type,
row_number() OVER (PARTITION BY projectId, datasetId, tableId ORDER BY snapshotTime DESC) AS rownum
FROM `$PROJECT_ID.bigquery.table_metadata_v1_0`
WHERE
_PARTITIONTIME BETWEEN TIMESTAMP(DATE_ADD(CURRENT_DATE(), INTERVAL -1 DAY))
  AND CURRENT_TIMESTAMP())
WHERE rownum = 1

redpajama_set_name: RedPajamaGithub


text:
"""PyQt v4 widget for VTK."""

__all__ = ['QVTKRenderWindowInteractor']


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.broad.igv.feature;

import java.text.NumberFormat;
import java.util.Locale;

/**
 * @author jrobinso
 */
public class Locus extends Range implements NamedFeature {

    private static NumberFormat NUMBER_FORMAT = NumberFormat.getInstance(Locale.US);

    public Locus(String chr, int start, int end) {
        super(chr, start, end);
    }

    /**
     * Generate Locus from locusString of form [chr]:[start]-[end]
     * Returns null if invalid string
     * @param locusString
     * @return
     */
    public static Locus fromString(String locusString) {
        Locus l = new Locus(locusString);
        return l.isValid() ? l : null;
    }

    public Locus(String locusString) {
        this(null, -1, -1);
        parseLocusString(locusString);

    }

    public boolean isValid() {
        return getChr() != null && getStart() >= 0 && getEnd() >= getStart();
    }

    // Only accept full locus strings,  i.e. must contain : and -
    private void parseLocusString(String locusString) {
        int colonIndex = locusString.indexOf(":");
        int dashIndex = locusString.indexOf("-");
        if (colonIndex > 0) {
            chr = locusString.substring(0, colonIndex);
            String posString = locusString.substring(colonIndex).replace(":", "");
            setStartEnd(posString);
        }
    }

    private void setStartEnd(String posString) {
        String[] posTokens = posString.split("-");
        String startString = posTokens[0].replaceAll(",", "");
        start = Math.max(0, Integer.parseInt(startString) - 1);
        end = start + 1;
        if (posTokens.length >= 2) {
            try {
                String endString = posTokens[1].replaceAll(",", "");
                end = Integer.parseInt(endString);
            } catch (NumberFormatException numberFormatException) {
                // This can happen, indicates an invalid or incomplete locus string
                // For now nothing to do here,
            }
        }
    }

    public String toString() {
        return chr + ":" + start + "-" + end;
    }

    @Override
    public String getName() {
        return toString();
    }

    public static String getFormattedLocusString(String chr, int start, int end) {
        String startStr = NUMBER_FORMAT.format(start + 1);
        String endStr = NUMBER_FORMAT.format(end);
        String position = chr + ":" + startStr + "-" + endStr;
        return position;
    }

}


text:
package com.hubspot.jinjava.tree.parse;

import static com.hubspot.jinjava.tree.parse.TokenScannerSymbols.TOKEN_TAG;

import com.hubspot.jinjava.interpret.TemplateSyntaxException;
import com.hubspot.jinjava.util.WhitespaceUtils;

public class TagToken extends Token {

  private static final long serialVersionUID = 2766011408032384360L;

  private String tagName;
  private String helpers;

  public TagToken(String image, int lineNumber) {
    super(image, lineNumber);
  }

  @Override
  public int getType() {
    return TOKEN_TAG;
  }

  /**
   * Get tag name
   */
  @Override
  protected void parse() {
    if (image.length() < 4) {
      throw new TemplateSyntaxException(image, "Malformed tag token", getLineNumber());
    }

    content = image.substring(2, image.length() - 2);

    if (WhitespaceUtils.startsWith(content, "-")) {
      setLeftTrim(true);
      content = WhitespaceUtils.unwrap(content, "-", "");
    }
    if (WhitespaceUtils.endsWith(content, "-")) {
      setRightTrim(true);
      content = WhitespaceUtils.unwrap(content, "", "-");
    }

    int nameStart = -1, pos = 0, len = content.length();

    for (; pos < len; pos++) {
      char c = content.charAt(pos);
      if (nameStart == -1 && Character.isJavaIdentifierStart(c)) {
        nameStart = pos;
      }
      else if (nameStart != -1 && !Character.isJavaIdentifierPart(c)) {
        break;
      }
    }

    if (pos < content.length()) {
      tagName = content.substring(nameStart, pos).toLowerCase();
      helpers = content.substring(pos);
    } else {
      tagName = content.toLowerCase().trim();
      helpers = "";
    }
  }

  public String getTagName() {
    return tagName;
  }

  public String getHelpers() {
    return helpers;
  }

  @Override
  public String toString() {
    if (helpers.length() == 0) {
      return "{% " + tagName + " %}";
    }
    return "{% " + tagName + " " + helpers + " %}";
  }

}


text:
from uliweb.orm import *
from uliweb.utils.common import get_var
from uliweb.utils.generic import GenericReference

def get_modified_user():
    from uliweb import request

    if request:
        return request.user.id

class DashBoardPanel(Model):
    __verbose_name__ = u'仪表盘内容面板'

    name = Field(str, max_length=50, verbose_name='名称', unique=True)
    title = Field(str, max_length=100, verbose_name='显示名称')
    description = Field(str, max_length=100, verbose_name='描述')
    num = Field(int, verbose_name='数量')
    unit = Field(str, max_length=10, verbose_name='单位')
    panel_type = Field(str, max_length=1, choices=get_var('DASHBOARD/PANEL_TYPE'), verbose_name='面板类型')
    content_type = Field(str, max_length=1, choices=get_var('DASHBOARD/CONTENT_TYPE'),
                         verbose_name='内容类型')
    URI = Field(str, max_length=255, verbose_name='访问URI')
    parameters = Field(str, max_length=255, verbose_name='参数')
    count_function = Field(str, max_length=255, verbose_name='数字函数')
    color = Field(str, max_length=20, verbose_name='颜色')
    height = Field(int, verbose_name='高度')
    icon = Field(CHAR, max_length=20, verbose_name='图标')
    closeable = Field(bool, verbose_name='关闭标识')

    panel_type = Field(str, max_length=1, choices=get_var('DASHBOARD/PANEL_TYPE'),
                       verbose_name='面板类型')

    created_time = Field(
        datetime.datetime, verbose_name='创建时间', auto_now_add=True)
    created_user = Reference(
        'user', verbose_name='创建人', default=get_modified_user, auto_add=True)

    modified_time = Field(
        datetime.datetime, verbose_name='修改时间', auto_now_add=True, auto_now=True)
    modified_user = Reference(
        'user', verbose_name='修改人', default=get_modified_user, auto=True, auto_add=True)

    def __unicode__(self):
        return self.title

class DashBoardPanelLayout(Model):
    __verbose_name__ = u'仪表盘面板布局'

    dashboard_type = GenericReference(table_fieldname='type_id', object_fieldname='owner_id')
    dashboard_name = Field(str, max_length=50, verbose_name='仪表盘')
    layout = Field(str, max_length=10, verbose_name='布局')

    panel = Reference('dashboardpanel', verbose_name='面板')
    title = Field(str, max_length=100, verbose_name='显示名称')
    color = Field(str, max_length=20, verbose_name='颜色')
    height = Field(int, verbose_name='高度')
    icon = Field(str, max_length=20, verbose_name='图标')
    row = Field(int, verbose_name='行位置')
    col = Field(int, verbose_name='列位置')

    created_time = Field(
        datetime.datetime, verbose_name='创建时间', auto_now_add=True)
    created_user = Reference(
        'user', verbose_name='创建人', default=get_modified_user, auto_add=True)

    modified_time = Field(
        datetime.datetime, verbose_name='修改时间', auto_now_add=True, auto_now=True)
    modified_user = Reference(
        'user', verbose_name='修改人', default=get_modified_user, auto=True, auto_add=True)


text:
struct PositiveBitField
{
  PositiveBitField() : i(6) {}
  // CHECK-FIXES: PositiveBitField()  {}
  int i : 5;
  // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use default member initializer for 'i' [modernize-use-default-member-init]
  // CHECK-FIXES: int i : 5{6};
};


text:
__author__ = 'facundo_nishiwaki'

import boto.ec2
from boto.ec2 import instance
import json
import os

from itertools import chain
import socket, sys
ACCOUNTS = {
    "HTCCSDEV" : {
        "ACCESS_KEY" : "DEV_ACCESS_KEY",
        "SECRET_KEY" : "DEV_SECRET_KEY"
    },
    "HTCCSCMS" : {
        "ACCESS_KEY" : "CMS_ACCESS_KEY",
        "SECRET_KEY" : "CMS_SECRET_KEY"
    },
    "HTCCSPROD" : {
        "ACCESS_KEY" : "PROD_ACCESS_KEY",
        "SECRET_KEY" : "PROD_SECRET_KEY"
    },
    "HTCCSMASTER" : {
        "ACCESS_KEY" : "MASTER_ACCESS_KEY",
        "SECRET_KEY" : "MASTER_SECRET_KEY"
    }
}

NORMALIZATION_FACTORS = {
    "small" : 1,
    "medium" : 2,
    "large" : 4,
    "xlarge" : 8,
    "2xlarge" : 16,
    "4xlarge" : 32,
    "8xlarge" : 64
}

class EC2Account:
    def __init__(self, name, access_key, secret_key):
        self.name = name
        self._access_key = access_key
        self._secret_key = secret_key
        self._instance_utilization = {}
        self._all_instance_types = []
        self._all_instances = {}
        self._all_reserved_instances = {}
        self._zones = {}

    def instances_in_region(self, region):
        region_info = boto.ec2.connect_to_region(region, aws_access_key_id=self._access_key, aws_secret_access_key=self._secret_key)
        self._zones[region] = region_info.get_all_zones()
        instances = region_info.get_only_instances()
        self._all_instances[region] = instances
        #all_instance_types = list(set([instance.instance_type for instance in instances]))
        #all_availability_zones = list(set([instance.placement for instance in instances]))
        #all_vpc_ids = list(set([instance.vpc_id for instance in instances]))
        return self._all_instances[region]

    def get_instance_counts_from_az(self, zone_name, instance_list):
        retVal = {}
        all_instance_types = list(set([i.instance_type for i in instance_list]))
        for type in all_instance_types:
            retVal[type] = len([i for i in instance_list if i.placement == zone_name and i.instance_type == type])
            if retVal[type] == 0:
                retVal.pop(type)
        return retVal

    def get_reserved_instance_counts(self, instance_list):
        all_availability_zones = list(set([i.availability_zone for i in instance_list]))
        retVal = {}

        for az in all_availability_zones:
            retVal[az] = self.get_reserved_instance_counts_from_az(az, instance_list)
        return retVal

    def get_reserved_instance_counts_from_az(self, zone_name, instance_list):
        all_instance_types = list(set([i.instance_type for i in instance_list]))
        ret_val = {}
        for instance_type in all_instance_types:
            ret_val[instance_type] = sum([r.instance_count for r in instance_list if
                                          r.instance_type == instance_type and
                                          r.availability_zone == zone_name])
        return ret_val

    def list_instances(self, region, **kwargs):
        retVal = {}
        region_info = boto.ec2.connect_to_region(region, aws_access_key_id=self._access_key, aws_secret_access_key=self._secret_key)
        self._zones[region] = region_info.get_all_zones()
        self._all_instances[region] = region_info.get_only_instances()

        if region not in self._all_instances.keys():
            return retVal
        if "vpc" in kwargs.keys():
            if kwargs["vpc"]:
                instances = [i for i in self._all_instances[region] if i.vpc_id is not None and i.state == "running"]
            elif not kwargs["vpc"]:
                instances = [i for i in self._all_instances[region] if i.vpc_id is None]
            kwargs.pop("vpc")
        else:
            instances = self._all_instances[region]
        args = dict([(k, kwargs[k]) for k in kwargs.keys() if hasattr(boto.ec2.instance.Instance, k) ])

        for zone in self._zones[region]:
            retVal[zone.name] = self.get_instance_counts_from_az(zone.name, instances)
        return retVal

    def list_reserved_instances(self, region, **kwargs):
        region_info = boto.ec2.connect_to_region(region, aws_access_key_id=self._access_key, aws_secret_access_key=self._secret_key)

        if "vpc" in kwargs.keys():
            if kwargs["vpc"]:
                kwargs["product_description"] = "Linux/UNIX (Amazon VPC)"
            else:
                kwargs["product_description"] = "Linux/UNIX"
            kwargs.pop("vpc")
        kwargs["state"] = "active"
        #zones = region_info.get_all_zones()

        reserved_instances = region_info.get_all_reserved_instances(filters=kwargs)
        self._all_reserved_instances[region] = [ri for ri in reserved_instances]
        return self.get_reserved_instance_counts(self._all_reserved_instances[region])

class ConsolidatedUtilization:
    def __init__(self):
        self.instance_types = []
        self.accounts_utilization = {}
        self.accounts_reserved_instance_utilization = {}
        self.total_running_instance_utilization = {}
        self.total_reserved_instance_utilization = {}
        self.actual_reserved_instance_usage = {}
        self.unused_reserved_instance_count = {}

    def add_account_running_instance_utilization(self, account_name, utilization):
        #self.total_running_instance_utilization[account_name] = utilization
        for region, region_utilization in utilization.iteritems():
            self.total_running_instance_utilization = \
                self.add_dictionaries(
                    self.total_running_instance_utilization,
                    region,
                    region_utilization)
            #self.add_region_running_instance_utilization(region, region_utilization)

    def add_account_reserved_instance_utilization(self, account_name, utilization):
        #self.accounts_reserved_instance_utilization[account_name] = utilization
        for region, region_utilization in utilization.iteritems():
            self.total_reserved_instance_utilization = \
                self.add_dictionaries(
                    self.total_reserved_instance_utilization,
                    region,
                    region_utilization)
        #for region, region_utilization in utilization.iteritems():
        #    self.add_region_reserved_instance_utilization(region, region_utilization)

    def get_reserved_instance_usage(self, region):
        self.actual_reserved_instance_usage[region] = self.subtract_dictionaries(
            self.total_reserved_instance_utilization[region],
            self.total_running_instance_utilization[region])
        return self.actual_reserved_instance_usage[region]

    def get_unused_reserved_instance_count(self, region):
        actual_usage = self.get_reserved_instance_usage(region)
        self.unused_reserved_instance_count[region] = {}
        for zone in actual_usage.keys():
            self.unused_reserved_instance_count[region][zone] = dict([(instance_type, -1* count)
                                                            if count > 0 else (instance_type, 0)
                                                            for (instance_type, count) in actual_usage[zone].iteritems()])
        return self.unused_reserved_instance_count[region]

    def get_instance_class_unit_usage(self, region):
        ret_val = {}
        reserved_instance_usage = self.get_reserved_instance_usage(region)
        instance_types = list(set([reserved_instance_usage[zone].keys() for zone in reserved_instance_usage.keys()]))
        classes = list(set([instance_type.split(".")[0] for instance_type in instance_types]))
        for c in classes:
            ret_val[c] = sum([self.get_instance_type_unit_count(region, instance_type) for instance_type in instance_types if instance_type.startswith(c)])
        return ret_val

    def get_instance_type_unit_count(self, region, instance_type):
        class_type, class_size = instance_type.split(".")
        counts = [self.get_reserved_instance_usage(region)[zone][instance_type] for zone in self.get_reserved_instance_usage(region).keys()]

        return NORMALIZATION_FACTORS[class_size] * sum(counts)

    def add_dictionaries(self, parent_dict, node_name, child):
        ret_val = parent_dict
        if node_name in parent_dict.keys():
            if type(parent_dict[node_name]).__name__ == "dict":
                for sub_node_name, grandchild in child.iteritems():
                    self.add_dictionaries(ret_val[node_name], sub_node_name, grandchild)
            else:
                ret_val[node_name] += child
        else:
            ret_val[node_name] = child
        return ret_val

    def subtract_dictionaries(self, d1, d2):
        ret_val = {}

        all_keys = list(set(d1.keys() + d2.keys()))

        for key in all_keys:
            if key in d1.keys():
                if type(d1[key]).__name__ == "dict":
                    if key in d2.keys():
                        ret_val[key] = self.subtract_dictionaries(d1[key], d2[key])
                    else:
                        ret_val[key] = d1[key]
                else:
                    if key in d2.keys():
                        ret_val[key] = d1[key] - d2[key]
                    else:
                        ret_val[key] = d1[key]
            else:
                if type(d2[key]).__name__ == "dict":
                    ret_val[key] = self.subtract_dictionaries({}, d2[key])
                else:
                    ret_val[key] = 0 - d2[key]

        return ret_val

    def get_reserved_instance_utilization_totals(self, region):
        return self.total_reserved_instance_utilization[region]

    def get_running_instance_utilization_totals(self, region):
        return self.total_running_instance_utilization[region]

if __name__ == "__main__":
    region = "ap-northeast-1"
    zone   = "ap-northeast-1a"
    instance_type = "m2.2xlarge"
    running_instances = {}
    reserved_instances = {}
    totals = ConsolidatedUtilization()
    actual = {}
    for name, account in ACCOUNTS.iteritems():
        running_instances[name] = {}
        reserved_instances[name] = {}
        account = EC2Account(name, account["ACCESS_KEY"], account["SECRET_KEY"])

        for region in [r.name for r in boto.ec2.regions() if r.name.find("gov") == -1 and r.name.find("cn") == -1]:
            running_instances[name][region] = account.list_instances(region, vpc=True)
            reserved_instances[name][region] = account.list_reserved_instances(region, vpc=True)

        totals.add_account_reserved_instance_utilization(name, reserved_instances[name])
        totals.add_account_running_instance_utilization(name, running_instances[name])

    #for region in [r.name for r in boto.ec2.regions() if r.name.find("gov") == -1]:
    #    print "reserved", totals.get_reserved_instance_utilization_totals(region)
    #    print "running", totals.get_running_instance_utilization_totals(region)
    for region in [r.name for r in boto.ec2.regions() if r.name.find("gov") == -1]:
        actual[region] = totals.get_reserved_instance_usage(region)
        print json.dumps(totals.get_unused_reserved_instance_count(region))

    print json.dumps(actual)


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title></title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link rel="stylesheet" href="css/normalize.css">
    <link rel="stylesheet" href="css/main.css">

Hello world! This is my portfolio page.


text:
layout: page
title: Where to sleep
excerpt: "Camping is best. But we know where you might find a bed around here too. "
tags: "accommodations"
comments: false
#image:
#  feature: sample-image-1.jpg
---

### Camping

We have tons of space for tents.  We'll have a simple outdoor kitchen set up and an outdoor toilet.

### Bed and Breakfasts

There are a lot of traditional B&B's and also a number of [Airbnb listings](https://www.airbnb.ca/s/duncan--on?checkin=29-07-2016&checkout=31-07-2016&guests=2&zoom=11&search_by_map=true&sw_lat=44.21212617906206&sw_lng=-80.63410933790158&ne_lat=44.514049781816155&ne_lng=-80.27018721876095&ss_id=ifmu1n5w&s_tag=bnalNWu4#).

### Hotels

Here's a link to some hotels.


text:
layout: page
title: Sobre
permalink: /about/
---

Mesmo sendo o menor estado do Brasil, Sergipe conta com um vasto número de programadores web,
e não é de se admirar que a grande massa desenvolva em PHP.

Temos que admitir que muitos não são capacitados, o que é péssimo para a linguagem.

Como defensores do PHP, nosso intuito é desmistificar a má fama do PHP. Uma linguagem tão poderosa,
deve ter o seu real valor reconhecido no mercado. Assim como já acontece em países vizinhos.

Além disso, também ansiamos que os desenvolvedores PHP se unam, troquem informações,
conversem, ajudem e certifiquem-se. Para tal, realizaremos ao decorrer do ano, eventos, encontros, palestras,
promoções e "n" outras coisas para incentivar a adoção do PHP no estado de Sergipe!

Para tanto precisamos também conscientizar os desenvolvedores PHP, para que deixem de ser sobrinhos, e comecem
a construir suas carreiras com conhecimento sólidos.

Entre nessa briga você também. Ajude o PHP a crescer ainda mais!


text:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >

    <solid android:color="#92e4e5" />

    <stroke
        android:width="2dp"
        android:color="#92e4e5" />

    <corners android:radius="2dp" />

</shape>


text:
' Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

Imports System.Composition
Imports Microsoft.CodeAnalysis.EmbeddedLanguages.LanguageServices
Imports Microsoft.CodeAnalysis.Host.Mef
Imports Microsoft.CodeAnalysis.VisualBasic.EmbeddedLanguages.VirtualChars

Namespace Microsoft.CodeAnalysis.VisualBasic.EmbeddedLanguages.LanguageServices
    <ExportLanguageService(GetType(IEmbeddedLanguagesProvider), LanguageNames.VisualBasic, ServiceLayer.Default), [Shared]>
    Friend Class VisualBasicEmbeddedLanguagesProvider
        Inherits AbstractEmbeddedLanguagesProvider

        Public Shared Info As New EmbeddedLanguageInfo(
            SyntaxKind.StringLiteralToken,
            SyntaxKind.InterpolatedStringTextToken,
            VisualBasicSyntaxFactsService.Instance,
            VisualBasicSemanticFactsService.Instance,
            VisualBasicVirtualCharService.Instance)

        <ImportingConstructor>
        <Obsolete(MefConstruction.ImportingConstructorMessage, True)>
        Public Sub New()
            MyBase.New(Info)
        End Sub
    End Class
End Namespace


text:
<?php

/**
 *
 * @package CRM
 * @copyright CiviCRM LLC (c) 2004-2015
 * $Id$
 *
 */

/**
 * This class generates form components for Label Format Settings
 *
 */
class CRM_Admin_Form_LabelFormats extends CRM_Admin_Form {

  /**
   * Label Format ID.
   */
  protected $_id = NULL;

  /**
   * Group name, label format or name badge
   */
  protected $_group = NULL;

  public function preProcess() {
    $this->_id = $this->get('id');
    $this->_group = CRM_Utils_Request::retrieve('group', 'String', $this, FALSE, 'label_format');
    $this->_values = array();
    if (isset($this->_id)) {
      $params = array('id' => $this->_id);
      CRM_Core_BAO_LabelFormat::retrieve($params, $this->_values, $this->_group);
    }
  }

  /**
   * Build the form object.
   *
   * @return void
   */
  public function buildQuickForm() {
    parent::buildQuickForm();

    if ($this->_action & (CRM_Core_Action::DELETE | CRM_Core_Action::COPY)) {
      $formatName = CRM_Core_BAO_LabelFormat::getFieldValue('CRM_Core_BAO_LabelFormat', $this->_id, 'label');
      $this->assign('formatName', $formatName);
      return;
    }

    $disabled = array();
    $required = TRUE;
    $is_reserved = $this->_id ? CRM_Core_BAO_LabelFormat::getFieldValue('CRM_Core_BAO_LabelFormat', $this->_id, 'is_reserved') : FALSE;
    if ($is_reserved) {
      $disabled['disabled'] = 'disabled';
      $required = FALSE;
    }

    $attributes = CRM_Core_DAO::getAttribute('CRM_Core_BAO_LabelFormat');
    $this->add('text', 'label', ts('Name'), $attributes['label'] + $disabled, $required);
    $this->add('text', 'description', ts('Description'), array('size' => CRM_Utils_Type::HUGE));
    $this->add('checkbox', 'is_default', ts('Is this Label Format the default?'));

    // currently we support only mailing label creation, hence comment below code
    /*
    $options = array(
    'label_format' => ts('Mailing Label'),
    'name_badge'   => ts('Name Badge'),
    );

    $labelType = $this->addRadio('label_type', ts('Used For'), $options, null, '  ');

    if ($this->_action != CRM_Core_Action::ADD) {
    $labelType->freeze();
    }
     */

    $this->add('select', 'paper_size', ts('Sheet Size'),
      array(
        0 => ts('- default -'),
      ) + CRM_Core_BAO_PaperSize::getList(TRUE), FALSE,
      array(
        'onChange' => "selectPaper( this.value );",
      ) + $disabled
    );
    $this->add('static', 'paper_dimensions', NULL, ts('Sheet Size (w x h)'));
    $this->add('select', 'orientation', ts('Orientation'), CRM_Core_BAO_LabelFormat::getPageOrientations(), FALSE,
      array(
        'onChange' => "updatePaperDimensions();",
      ) + $disabled
    );
    $this->add('select', 'font_name', ts('Font Name'), CRM_Core_BAO_LabelFormat::getFontNames($this->_group));
    $this->add('select', 'font_size', ts('Font Size'), CRM_Core_BAO_LabelFormat::getFontSizes());
    $this->add('static', 'font_style', ts('Font Style'));
    $this->add('checkbox', 'bold', ts('Bold'));
    $this->add('checkbox', 'italic', ts('Italic'));
    $this->add('select', 'metric', ts('Unit of Measure'), CRM_Core_BAO_LabelFormat::getUnits(), FALSE,
      array('onChange' => "selectMetric( this.value );")
    );
    $this->add('text', 'width', ts('Label Width'), array('size' => 8, 'maxlength' => 8) + $disabled, $required);
    $this->add('text', 'height', ts('Label Height'), array('size' => 8, 'maxlength' => 8) + $disabled, $required);
    $this->add('text', 'NX', ts('Labels Per Row'), array('size' => 3, 'maxlength' => 3) + $disabled, $required);
    $this->add('text', 'NY', ts('Labels Per Column'), array('size' => 3, 'maxlength' => 3) + $disabled, $required);
    $this->add('text', 'tMargin', ts('Top Margin'), array('size' => 8, 'maxlength' => 8) + $disabled, $required);
    $this->add('text', 'lMargin', ts('Left Margin'), array('size' => 8, 'maxlength' => 8) + $disabled, $required);
    $this->add('text', 'SpaceX', ts('Horizontal Spacing'), array('size' => 8, 'maxlength' => 8) + $disabled, $required);
    $this->add('text', 'SpaceY', ts('Vertical Spacing'), array('size' => 8, 'maxlength' => 8) + $disabled, $required);
    $this->add('text', 'lPadding', ts('Left Padding'), array('size' => 8, 'maxlength' => 8), $required);
    $this->add('text', 'tPadding', ts('Top Padding'), array('size' => 8, 'maxlength' => 8), $required);
    $this->add('text', 'weight', ts('Order'), CRM_Core_DAO::getAttribute('CRM_Core_BAO_LabelFormat', 'weight'), TRUE);

    $this->addRule('label', ts('Name already exists in Database.'), 'objectExists', array(
      'CRM_Core_BAO_LabelFormat',
      $this->_id,
    ));
    $this->addRule('NX', ts('Please enter a valid integer.'), 'integer');
    $this->addRule('NY', ts('Please enter a valid integer.'), 'integer');
    $this->addRule('tMargin', ts('Please enter a valid number.'), 'numeric');
    $this->addRule('lMargin', ts('Please enter a valid number.'), 'numeric');
    $this->addRule('SpaceX', ts('Please enter a valid number.'), 'numeric');
    $this->addRule('SpaceY', ts('Please enter a valid number.'), 'numeric');
    $this->addRule('lPadding', ts('Please enter a valid number.'), 'numeric');
    $this->addRule('tPadding', ts('Please enter a valid number.'), 'numeric');
    $this->addRule('width', ts('Please enter a valid number.'), 'numeric');
    $this->addRule('height', ts('Please enter a valid number.'), 'numeric');
    $this->addRule('weight', ts('Please enter a valid integer.'), 'integer');
  }

  /**
   * @return int
   */
  public function setDefaultValues() {
    if ($this->_action & CRM_Core_Action::ADD) {
      $defaults['weight'] = CRM_Utils_Array::value('weight', CRM_Core_BAO_LabelFormat::getDefaultValues($this->_group), 0);
    }
    else {
      $defaults = $this->_values;
      // Convert field names that are illegal PHP/SMARTY variable names
      $defaults['paper_size'] = $defaults['paper-size'];
      unset($defaults['paper-size']);
      $defaults['font_name'] = $defaults['font-name'];
      unset($defaults['font-name']);
      $defaults['font_size'] = $defaults['font-size'];
      unset($defaults['font-size']);

      $defaults['bold'] = (stripos($defaults['font-style'], 'B') !== FALSE);
      $defaults['italic'] = (stripos($defaults['font-style'], 'I') !== FALSE);
      unset($defaults['font-style']);
    }

    $defaults['label_type'] = $this->_group;
    return $defaults;
  }

  /**
   * Process the form submission.
   *
   *
   * @return void
   */
  public function postProcess() {
    if ($this->_action & CRM_Core_Action::DELETE) {
      // delete Label Format
      CRM_Core_BAO_LabelFormat::del($this->_id, $this->_group);
      CRM_Core_Session::setStatus(ts('Selected Label Format has been deleted.'), ts('Record Deleted'), 'success');
      return;
    }
    if ($this->_action & CRM_Core_Action::COPY) {
      // make a copy of the Label Format
      $labelFormat = CRM_Core_BAO_LabelFormat::getById($this->_id, $this->_group);
      $newlabel = ts('Copy of %1', array(1 => $labelFormat['label']));

      $list = CRM_Core_BAO_LabelFormat::getList(TRUE, $this->_group);
      $count = 1;

      while (in_array($newlabel, $list)) {
        $count++;
        $newlabel = ts('Copy %1 of %2', array(1 => $count, 2 => $labelFormat['label']));
      }

      $labelFormat['label'] = $newlabel;
      $labelFormat['grouping'] = CRM_Core_BAO_LabelFormat::customGroupName();
      $labelFormat['is_default'] = 0;
      $labelFormat['is_reserved'] = 0;

      $bao = new CRM_Core_BAO_LabelFormat();
      $bao->saveLabelFormat($labelFormat, NULL, $this->_group);
      CRM_Core_Session::setStatus(ts('%1 has been created.', array(1 => $labelFormat['label'])), ts('Saved'), 'success');
      return;
    }

    $values = $this->controller->exportValues($this->getName());

    // since we currently support only mailing label format
    $values['label_type'] = 'label_format';

    $values['is_default'] = isset($values['is_default']);

    // Restore field names that were converted because they are illegal PHP/SMARTY variable names
    if (isset($values['paper_size'])) {
      $values['paper-size'] = $values['paper_size'];
      unset($values['paper_size']);
    }
    if (isset($values['font_name'])) {
      $values['font-name'] = $values['font_name'];
      unset($values['font_name']);
    }
    if (isset($values['font_size'])) {
      $values['font-size'] = $values['font_size'];
      unset($values['font_size']);
    }

    $style = '';
    if (isset($values['bold'])) {
      $style .= 'B';
    }
    if (isset($values['italic'])) {
      $style .= 'I';
    }
    $values['font-style'] = $style;

    $bao = new CRM_Core_BAO_LabelFormat();
    $bao->saveLabelFormat($values, $this->_id, $values['label_type']);

    $status = ts('Your new Label Format titled %1 has been saved.', array(1 => $values['label']));
    if ($this->_action & CRM_Core_Action::UPDATE) {
      $status = ts('Your Label Format titled %1 has been updated.', array(1 => $values['label']));
    }
    CRM_Core_Session::setStatus($status, ts('Saved'), 'success');
  }

}


text:
<?php

/**
 * @see Zym_Paginate_Abstract
 */
require_once 'Zym/Paginate/Abstract.php';

/**
 * @author     Jurrien Stutterheim
 * @category   Zym
 * @package    Zym_Paginate
 * @copyright  Copyright (c) 2008 Zym. (http://www.zym-project.com/)
 * @license    http://www.zym-project.com/license    New BSD License
 */
class Zym_Paginate_DbTable extends Zym_Paginate_Abstract
{
    /**
     * The name for the rowcount column
     */
    const ROW_COUNT_COLUMN = 'zym_paginate_row_count';

    /**
     * @var Zend_Db_Table_Abstract
     */
    protected $_table = null;

    /**
     * @var Zend_Db_Table_Select
     */
    protected $_select = null;

    /**
     * Constructor
     *
     * @param Zend_Db_Table_Abstract $table
     * @param Zend_Db_Table_Select $select
     */
    public function __construct(Zend_Db_Table_Abstract $table, Zend_Db_Table_Select $select)
    {
        $this->_table = $table;
        $this->_select = $select;

        // @TODO: Check how well this works when you have a query with multiple joined tables
        $countSelect = clone $select;
        $countSelect->from($table, new Zend_Db_Expr('COUNT(*) AS ' . self::ROW_COUNT_COLUMN));
        $result = $table->fetchRow($countSelect);

        $this->_setRowCount($result->{self::ROW_COUNT_COLUMN});
    }

    /**
     * Get a page
     *
     * @var int $page
     * @return Zend_Db_Table_Rowset_Abstract
     */
    public function getPage($page)
    {
        $this->_select->limitPage((int) $page, $this->getRowLimit());

        return $this->_table->fetchAll($this->_select);
    }

    /**
     * Get the total amount of pages
     *
     * @return int
     */
    public function getPageCount()
    {
        if ($this->_pageCount === 0 && $this->_rowCount > 0) {
            $rowCount = $this->getRowCount();

            $floor = floor($rowCount / $this->_rowLimit);
            $rest = $rowCount % $this->_rowLimit;

            $this->_setPageCount($floor + ($rest > 0 ? 1 : 0));
        }

        return $this->_pageCount;
    }
}


text:
;(function ($, window, undefined) {
  'use strict';

  $(document).ready(function() {
    $(document).foundation();
  });

  // H5BP mobile helper
  MBP.scaleFix();
  MBP.hideUrlBarOnLoad();

})(jQuery, this);


text:
<!DOCTYPE html>

    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <meta charset="utf-8">
    <title>Intermark <?php echo isset($title) ? ' | ' . $title : null; ?></title>
    <meta name="generator" content="Bootply" />
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

    <link rel="icon" href="<?php echo base_url() ?>media/templates/intermark/images/ico/logo.png" type="icon">

    <link href="<?php echo base_url('/media/css/bootstrap.min.css'); ?>" rel="stylesheet">
    <link href="<?php echo base_url('/media/css/jquery-ui.min.css'); ?>" rel="stylesheet">
    <link href="<?php echo base_url('/media/css/jquery-ui.structure.min.css'); ?>" rel="stylesheet">
    <link href="<?php echo base_url('/media/css/jquery-ui.theme.min.css'); ?>" rel="stylesheet">
    <link href="<?php echo base_url('/media/css/ionicons.min.css'); ?>" type="text/css" rel="stylesheet">
    <link href="<?php echo base_url('media/css/jquery.Jcrop.min.css'); ?>" rel="stylesheet">
    <link href="<?php echo base_url('media/css/fullcalendar.min.css'); ?>" rel="stylesheet">
    <link href="<?php echo base_url('media/css/fullcalendar.print.min.css'); ?>" rel="stylesheet" media='print'>

    <link href="<?php echo base_url('/media/css/styles-beckend.css'); ?>" rel="stylesheet">

                            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse" style="background-color: white;">
                                Toggle navigation

                            </button>
                            <a class="navbar-brand" href="<?php echo site_url('gadmin/dashboard'); ?>" style="color:white;">Intermark - Control Panel

  <?php echo $text = ucfirst($this->session->userdata('user_name_admin')); ?>

                                                    <img src="<?php echo base_url('/media/image/profil.png'); ?>">

                                                    <?php echo $text = ucfirst($this->session->userdata('user_name_admin')); ?>

<?php echo $this->session->userdata('user_email_admin'); ?>

                                                    <a href="<?php echo site_url('gadmin/profile') ?>" class="btn btn-info btn-sm">Lihat Profil

<a style="margin-top: 15px" class="btn" href="<?php echo site_url('gadmin/profile/cpw/'); ?>"> Ubah Password [ <?php echo $this->session->userdata('user_name_admin') ?> ]

<a href="<?php echo site_url('user/auth/logout'); ?>" class="btn btn-sm btn-info"> Keluar

                    <?php
                    if ($this->session->flashdata('success')) {
                        $data['message'] = $this->session->flashdata('success');
                        $this->load->view('admin/notification_success', $data);
                    }
                    ?>

                        <?php $this->load->view('admin/list') ?>
                        <?php isset($main) ? $this->load->view($main) : null; ?>

© 2016-2017 Intermark - Supported by Rumah Cipta Generasi


text:
var Backbone = require('backbone');
var $ = require('jquery');
Backbone.$ = $;

var Handlebars = require('handlebars');

var OrderBookView = Backbone.View.extend({
	tagName: 'div',
	template: Handlebars.compile($('#orderbook-template').html()),

	render: function() {
		var viewData = {
			price: this.model.get('price'),
			quantity: this.model.get('quantity'),
			isBuy: this.model.get('isBuy')
		}
		return this.template(viewData);
	}

});

module.exports = OrderBookView;


text:
GCGen
=====

G-Code generator for 3D printer testing purpose

Simple Gcode generator to test the Strong Print Metal 3D Printer http://reprap.org/wiki/StrongPrint

V0.7 Jun 2014
Implemented primitives: Circle & Line
Implemented functions: Feed with retract

V0.10 August 2014
Implemented Test extrude function
Adapted to to automatic arc ignition with the M3 command


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>ListenerConfig</title>
<meta name="date" content="2015-03-27">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.webchecker.watcher

Class ListenerConfig

java.lang.Object

org.webchecker.watcher.ListenerConfig

public class ListenerConfig
extends java.lang.Object

Class represents a configuration of a listener. It contains only one parameter yet, but can be
 easily extend. There is no rule of number of listeners to one config, but one listener have to have
 exact one config.

Version:

1.0

Author:

Matěj Kripner <kripnermatej@gmail.com>

See Also:

Listener

Field Summary

Fields

Modifier and Type
Field and Description

static int
MIN_AUTO_CHECKING

Min value of auto checking delay.

Method Summary

All Methods Static Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

ListenerConfig
autoCheckingOff()

Turn the auto checking off.

ListenerConfig
autoCheckingOn(int delay)

Turn auto checking on with the given delay.

int
getAutoChecking()

Simply return value of auto checking attribute.

static ListenerConfig
getDefaults()

Returns new config in the default state.

boolean
isAutoCheckingOn()

Tests that auto checking is on.

void
setOnAutoCheckingChange(java.util.function.BiConsumer<java.lang.Integer,java.lang.Integer> onAutoCheckingChange)

Simple sets the value of auto checking change function attribute to given value.

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

MIN_AUTO_CHECKING

public static final int MIN_AUTO_CHECKING

Min value of auto checking delay. Has to be positive.

See Also:

Constant Field Values

Method Detail

getDefaults

public static ListenerConfig getDefaults()

Returns new config in the default state.

Returns:

new config in the default state

autoCheckingOn

public ListenerConfig autoCheckingOn(int delay)
                              throws java.lang.IllegalArgumentException

Turn auto checking on with the given delay.

 The given delay has to be valid. In fact, delay is valid when:
 delay >= {@link #MIN_AUTO_CHECKING}

Parameters:

delay - the new value of delay between two listening of a listener

Returns:

this

Throws:

java.lang.IllegalArgumentException - if validation of the given delay fails

See Also:

validateDelay(int)

autoCheckingOff

public ListenerConfig autoCheckingOff()

Turn the auto checking off.

Returns:

this

getAutoChecking

public int getAutoChecking()

Simply return value of auto checking attribute. If auto checking is off, return zero.

Returns:

value of auto checking attribute

isAutoCheckingOn

public boolean isAutoCheckingOn()

Tests that auto checking is on.

Returns:

auto checking is on

setOnAutoCheckingChange

public void setOnAutoCheckingChange(java.util.function.BiConsumer<java.lang.Integer,java.lang.Integer> onAutoCheckingChange)

Simple sets the value of auto checking change function attribute to given value.

Parameters:

onAutoCheckingChange - new value of auto checking change function attribute

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
using Newtonsoft.Json;
using Stripe.Client.Sdk.Attributes;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace Stripe.Client.Sdk.Models.Arguments
{
    public class AccountUpdateArguments
    {
        [JsonIgnore]
        [Required]
        public string AccountId { get; set; }

        public string BusinessLogo { get; set; }

        public string BusinessName { get; set; }

        public string BusinessPrimaryColor { get; set; }

        public string BusinessUrl { get; set; }

        public bool DebitNegativeBalances { get; set; }

        [ChildModel]
        public DeclineChargeOnArguments DeclineChargeOn { get; set; }

        public string DefaultCurrency { get; set; }

        public string Email { get; set; }

        [ChildModel]
        public LegalEntityArguments LegalEntity { get; set; }

        public Dictionary<string, string> Metadata { get; set; }

        public string ProductDescription { get; set; }

        public string StatementDescriptor { get; set; }

        public string SupportEmail { get; set; }

        public string SupportPhone { get; set; }

        public string SupportUrl { get; set; }

        [ChildModel]
        public TermsOfServiceAcceptanceArguments TosAcceptance { get; set; }

        [ChildModel]
        public TransferScheduleArguments TransferSchedule { get; set; }

        [ChildModel]
        public AccountVerification Verification { get; set; }
    }

    public class AccountUpdateArguments<T> : AccountUpdateArguments
        where T : IPaymentTypeArguments
    {
        [JsonIgnore]
        public string Token { get; set; }

        /// <summary>
        /// A card or bank account to attach to the account. You can provide either a token, like the ones returned by Stripe.js, or a dictionary as documented in the external_account parameter for either card or bank account creation
        /// </summary>
        [JsonIgnore]
        public T ExternalAccountCreateArguments { get; set; }

        [ChildModel]
        [Required]
        public object ExternalAccount => !string.IsNullOrWhiteSpace(Token) ? (object)Token : ExternalAccountCreateArguments;
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!--

-->

<g7.bluesky.launcher3.WallpaperRootView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/wallpaper_root"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <g7.bluesky.launcher3.CropView
        android:id="@+id/cropView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
    <ProgressBar
        android:id="@+id/loading"
        style="@android:style/Widget.Holo.ProgressBar.Large"
        android:visibility="invisible"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:indeterminate="true"
        android:indeterminateOnly="true"
        android:background="@android:color/transparent" />
    <LinearLayout
        android:id="@+id/wallpaper_strip"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:orientation="vertical" >
        <View
            android:layout_width="match_parent"
            android:layout_height="2dp"
            android:background="@drawable/tile_shadow_top" />
        <HorizontalScrollView
            android:id="@+id/wallpaper_scroll_container"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" >
            <LinearLayout android:id="@+id/master_wallpaper_list"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="horizontal" >
                <LinearLayout android:id="@+id/wallpaper_list"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:orientation="horizontal" />
                <LinearLayout android:id="@+id/live_wallpaper_list"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:orientation="horizontal" />
                <LinearLayout android:id="@+id/third_party_wallpaper_list"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:orientation="horizontal" />
            </LinearLayout>
        </HorizontalScrollView>
        <View
            android:layout_width="match_parent"
            android:layout_height="2dp"
            android:background="@drawable/tile_shadow_bottom" />
    </LinearLayout>
</g7.bluesky.launcher3.WallpaperRootView>


text:
#ifndef __NET_NFC_H
#define __NET_NFC_H

#include <linux/nfc.h>
#include <linux/device.h>
#include <linux/skbuff.h>

#define nfc_info(dev, fmt, ...) dev_info((dev), "NFC: " fmt, ##__VA_ARGS__)
#define nfc_err(dev, fmt, ...) dev_err((dev), "NFC: " fmt, ##__VA_ARGS__)

struct nfc_phy_ops {
	int (*write)(void *dev_id, struct sk_buff *skb);
	int (*enable)(void *dev_id);
	void (*disable)(void *dev_id);
};

struct nfc_dev;

/**
 * data_exchange_cb_t - Definition of nfc_data_exchange callback
 *
 * @context: nfc_data_exchange cb_context parameter
 * @skb: response data
 * @err: If an error has occurred during data exchange, it is the
 *	error number. Zero means no error.
 *
 * When a rx or tx package is lost or corrupted or the target gets out
 * of the operating field, err is -EIO.
 */
typedef void (*data_exchange_cb_t)(void *context, struct sk_buff *skb,
								int err);

typedef void (*se_io_cb_t)(void *context, u8 *apdu, size_t apdu_len, int err);

struct nfc_target;

struct nfc_ops {
	int (*dev_up)(struct nfc_dev *dev);
	int (*dev_down)(struct nfc_dev *dev);
	int (*start_poll)(struct nfc_dev *dev,
			  u32 im_protocols, u32 tm_protocols);
	void (*stop_poll)(struct nfc_dev *dev);
	int (*dep_link_up)(struct nfc_dev *dev, struct nfc_target *target,
			   u8 comm_mode, u8 *gb, size_t gb_len);
	int (*dep_link_down)(struct nfc_dev *dev);
	int (*activate_target)(struct nfc_dev *dev, struct nfc_target *target,
			       u32 protocol);
	void (*deactivate_target)(struct nfc_dev *dev,
				  struct nfc_target *target);
	int (*im_transceive)(struct nfc_dev *dev, struct nfc_target *target,
			     struct sk_buff *skb, data_exchange_cb_t cb,
			     void *cb_context);
	int (*tm_send)(struct nfc_dev *dev, struct sk_buff *skb);
	int (*check_presence)(struct nfc_dev *dev, struct nfc_target *target);
	int (*fw_download)(struct nfc_dev *dev, const char *firmware_name);

	/* Secure Element API */
	int (*discover_se)(struct nfc_dev *dev);
	int (*enable_se)(struct nfc_dev *dev, u32 se_idx);
	int (*disable_se)(struct nfc_dev *dev, u32 se_idx);
	int (*se_io) (struct nfc_dev *dev, u32 se_idx,
		      u8 *apdu, size_t apdu_length,
		      se_io_cb_t cb, void *cb_context);
};

#define NFC_TARGET_IDX_ANY -1
#define NFC_MAX_GT_LEN 48
#define NFC_ATR_RES_GT_OFFSET 15

/**
 * struct nfc_target - NFC target descriptiom
 *
 * @sens_res: 2 bytes describing the target SENS_RES response, if the target
 *	is a type A one. The %sens_res most significant byte must be byte 2
 *	as described by the NFC Forum digital specification (i.e. the platform
 *	configuration one) while %sens_res least significant byte is byte 1.
 */
struct nfc_target {
	u32 idx;
	u32 supported_protocols;
	u16 sens_res;
	u8 sel_res;
	u8 nfcid1_len;
	u8 nfcid1[NFC_NFCID1_MAXSIZE];
	u8 nfcid2_len;
	u8 nfcid2[NFC_NFCID2_MAXSIZE];
	u8 sensb_res_len;
	u8 sensb_res[NFC_SENSB_RES_MAXSIZE];
	u8 sensf_res_len;
	u8 sensf_res[NFC_SENSF_RES_MAXSIZE];
	u8 hci_reader_gate;
	u8 logical_idx;
};

/**
 * nfc_se - A structure for NFC accessible secure elements.
 *
 * @idx: The secure element index. User space will enable or
 *       disable a secure element by its index.
 * @type: The secure element type. It can be SE_UICC or
 *        SE_EMBEDDED.
 * @state: The secure element state, either enabled or disabled.
 *
 */
struct nfc_se {
	struct list_head list;
	u32 idx;
	u16 type;
	u16 state;
};

struct nfc_genl_data {
	u32 poll_req_portid;
	struct mutex genl_data_mutex;
};

struct nfc_dev {
	int idx;
	u32 target_next_idx;
	struct nfc_target *targets;
	int n_targets;
	int targets_generation;
	struct device dev;
	bool dev_up;
	bool fw_download_in_progress;
	u8 rf_mode;
	bool polling;
	struct nfc_target *active_target;
	bool dep_link_up;
	struct nfc_genl_data genl_data;
	u32 supported_protocols;

	struct list_head secure_elements;

	int tx_headroom;
	int tx_tailroom;

	struct timer_list check_pres_timer;
	struct work_struct check_pres_work;

	bool shutting_down;

	struct rfkill *rfkill;

	struct nfc_ops *ops;
};
#define to_nfc_dev(_dev) container_of(_dev, struct nfc_dev, dev)

extern struct class nfc_class;

struct nfc_dev *nfc_allocate_device(struct nfc_ops *ops,
				    u32 supported_protocols,
				    int tx_headroom,
				    int tx_tailroom);

/**
 * nfc_free_device - free nfc device
 *
 * @dev: The nfc device to free
 */
static inline void nfc_free_device(struct nfc_dev *dev)
{
	put_device(&dev->dev);
}

int nfc_register_device(struct nfc_dev *dev);

void nfc_unregister_device(struct nfc_dev *dev);

/**
 * nfc_set_parent_dev - set the parent device
 *
 * @nfc_dev: The nfc device whose parent is being set
 * @dev: The parent device
 */
static inline void nfc_set_parent_dev(struct nfc_dev *nfc_dev,
				      struct device *dev)
{
	nfc_dev->dev.parent = dev;
}

/**
 * nfc_set_drvdata - set driver specifc data
 *
 * @dev: The nfc device
 * @data: Pointer to driver specifc data
 */
static inline void nfc_set_drvdata(struct nfc_dev *dev, void *data)
{
	dev_set_drvdata(&dev->dev, data);
}

/**
 * nfc_get_drvdata - get driver specifc data
 *
 * @dev: The nfc device
 */
static inline void *nfc_get_drvdata(struct nfc_dev *dev)
{
	return dev_get_drvdata(&dev->dev);
}

/**
 * nfc_device_name - get the nfc device name
 *
 * @dev: The nfc device whose name to return
 */
static inline const char *nfc_device_name(struct nfc_dev *dev)
{
	return dev_name(&dev->dev);
}

struct sk_buff *nfc_alloc_send_skb(struct nfc_dev *dev, struct sock *sk,
				   unsigned int flags, unsigned int size,
				   unsigned int *err);
struct sk_buff *nfc_alloc_recv_skb(unsigned int size, gfp_t gfp);

int nfc_set_remote_general_bytes(struct nfc_dev *dev,
				 u8 *gt, u8 gt_len);
u8 *nfc_get_local_general_bytes(struct nfc_dev *dev, size_t *gb_len);

int nfc_fw_download_done(struct nfc_dev *dev, const char *firmware_name,
			 u32 result);

int nfc_targets_found(struct nfc_dev *dev,
		      struct nfc_target *targets, int ntargets);
int nfc_target_lost(struct nfc_dev *dev, u32 target_idx);

int nfc_dep_link_is_up(struct nfc_dev *dev, u32 target_idx,
		       u8 comm_mode, u8 rf_mode);

int nfc_tm_activated(struct nfc_dev *dev, u32 protocol, u8 comm_mode,
		     u8 *gb, size_t gb_len);
int nfc_tm_deactivated(struct nfc_dev *dev);
int nfc_tm_data_received(struct nfc_dev *dev, struct sk_buff *skb);

void nfc_driver_failure(struct nfc_dev *dev, int err);

int nfc_add_se(struct nfc_dev *dev, u32 se_idx, u16 type);
int nfc_remove_se(struct nfc_dev *dev, u32 se_idx);
struct nfc_se *nfc_find_se(struct nfc_dev *dev, u32 se_idx);

#endif /* __NET_NFC_H */


text:
Sequel.migration do
  up do
    run 'ALTER TABLE storage_apps CONVERT TO CHARACTER SET utf8mb4;'
  end

  down do
    run 'ALTER TABLE storage_apps CONVERT TO CHARACTER SET utf8;'
  end
end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LabProblems
{
    class _02SimpleCalculator
    {
        public static void Run()
        {
            var input = Console.ReadLine();
            var values = input.Split(' ');
            var stack = new Stack<string>(values.Reverse());
            while (stack.Count > 1)
            {
                int first = int.Parse(stack.Pop());
                String op = stack.Pop();
                int second = int.Parse(stack.Pop());
                switch (op)
                {
                    case "+":
                        stack.Push((first + second).ToString()); break;
                    case "-":
                        stack.Push((first - second).ToString()); break;
                }

            }
            Console.WriteLine(stack.Pop());
        }
    }
}


text:
/** @global container */
/** @var {Jymfony.Component.DependencyInjection.ContainerBuilder} container */

const Reference = Jymfony.Component.DependencyInjection.Reference;

container.register('security.command.user_password_encoder', Jymfony.Bundle.SecurityBundle.Command.UserPasswordEncoderCommand)
    .addArgument(new Reference(Jymfony.Component.Security.Encoder.EncoderFactoryInterface))
    .addArgument() // User classes
    .addTag('console.command')
;


text:
using System;
using System.Collections.Generic;

namespace ReactiveDomain.Testing
{
    public interface IScenarioWhenStateBuilder
    {
        IScenarioThenNoneStateBuilder ThenNone();
        IScenarioThenStateBuilder Then(IEnumerable<RecordedEvent> events);
        IScenarioThrowsStateBuilder Throws(Exception exception);
    }
}


text:
class PeriodicSamplingScheduler {
 public:
  PeriodicSamplingScheduler(base::TimeDelta sampling_duration,
                            double fraction_of_execution_time_to_sample,
                            base::TimeTicks start_time);
  virtual ~PeriodicSamplingScheduler();

  PeriodicSamplingScheduler(const PeriodicSamplingScheduler&) = delete;
  PeriodicSamplingScheduler& operator=(const PeriodicSamplingScheduler&) =
      delete;

  // Returns the amount of time between now and the next collection.
  base::TimeDelta GetTimeToNextCollection();

 protected:
  // Virtual to provide seams for test use.
  virtual double RandDouble() const;
  virtual base::TimeTicks Now() const;

 private:
  const base::TimeDelta period_duration_;
  const base::TimeDelta sampling_duration_;
  base::TimeTicks period_start_time_;
};

// IOSThreadProfiler performs startup and periodic profiling of Chrome
// threads.
class IOSThreadProfiler {
 public:
  ~IOSThreadProfiler();
  IOSThreadProfiler(const IOSThreadProfiler&) = delete;
  IOSThreadProfiler& operator=(const IOSThreadProfiler&) = delete;

  // Creates a profiler for a main thread and immediately starts it. This
  // function should only be used when profiling the main thread of a
  // process. The returned profiler must be destroyed prior to thread exit to
  // stop the profiling.
  //
  // SetMainThreadTaskRunner() should be called after the message loop has been
  // started on the thread. It is the caller's responsibility to ensure that
  // the instance returned by this function is still alive when the static API
  // SetMainThreadTaskRunner() is used. The latter is static to support Chrome's
  // set up where the IOSThreadProfiler is created in chrome/app which cannot be
  // easily accessed from chrome_browser_main.cc which sets the task runner.
  static std::unique_ptr<IOSThreadProfiler> CreateAndStartOnMainThread();

  // Sets the task runner when profiling on the main thread. This occurs in a
  // separate call from CreateAndStartOnMainThread so that startup profiling can
  // occur prior to message loop start. The task runner is associated with the
  // instance returned by CreateAndStartOnMainThread(), which must be alive when
  // this is called.
  static void SetMainThreadTaskRunner(
      scoped_refptr<base::SingleThreadTaskRunner> task_runner);

  // Get the stack sampling params to use.
  static base::StackSamplingProfiler::SamplingParams GetSamplingParams();

  // Creates a profiler for a child thread and immediately starts it. This
  // should be called from a task posted on the child thread immediately after
  // thread start. The thread will be profiled until exit.
  static void StartOnChildThread(
      metrics::CallStackProfileParams::Thread thread);

  // Sets the callback to use for reporting browser process profiles. This
  // indirection is required to avoid a dependency on unnecessary metrics code
  // in child processes.
  static void SetBrowserProcessReceiverCallback(
      const base::RepeatingCallback<void(base::TimeTicks,
                                         metrics::SampledProfile)>& callback);

  // This function must be called within child processes to supply the Service
  // Manager's connector, to bind the interface through which a profile is sent
  // back to the browser process.
  //
  // Note that the metrics::CallStackProfileCollector interface also must be
  // exposed to the child process, and metrics::mojom::CallStackProfileCollector
  // declared in chrome_content_browser_manifest_overlay.json, for the binding
  // to succeed.
  static void SetCollectorForChildProcess(
      mojo::PendingRemote<metrics::mojom::CallStackProfileCollector> collector);

 private:
  class WorkIdRecorder;

  // Creates the profiler. The task runner will be supplied for child threads
  // but not for main threads.
  IOSThreadProfiler(
      metrics::CallStackProfileParams::Thread thread,
      scoped_refptr<base::SingleThreadTaskRunner> owning_thread_task_runner =
          scoped_refptr<base::SingleThreadTaskRunner>());

  // Posts a task on `owning_thread_task_runner` to start the next periodic
  // sampling collection on the completion of the previous collection.
  static void OnPeriodicCollectionCompleted(
      scoped_refptr<base::SingleThreadTaskRunner> owning_thread_task_runner,
      base::WeakPtr<IOSThreadProfiler> thread_profiler);

  // Sets the task runner when profiling on the main thread. This occurs in a
  // separate call from CreateAndStartOnMainThread so that startup profiling can
  // occur prior to message loop start.
  void SetMainThreadTaskRunnerImpl(
      scoped_refptr<base::SingleThreadTaskRunner> task_runner);

  // Posts a delayed task to start the next periodic sampling collection.
  void ScheduleNextPeriodicCollection();

  // Creates a new periodic profiler and initiates a collection with it.
  void StartPeriodicSamplingCollection();

  const metrics::CallStackProfileParams::Process process_;
  const metrics::CallStackProfileParams::Thread thread_;

  scoped_refptr<base::SingleThreadTaskRunner> owning_thread_task_runner_;

  std::unique_ptr<WorkIdRecorder> work_id_recorder_;

  std::unique_ptr<base::StackSamplingProfiler> startup_profiler_;

  std::unique_ptr<base::StackSamplingProfiler> periodic_profiler_;
  std::unique_ptr<PeriodicSamplingScheduler> periodic_sampling_scheduler_;

  THREAD_CHECKER(thread_checker_);
  base::WeakPtrFactory<IOSThreadProfiler> weak_factory_{this};
};

#endif  // IOS_CHROME_BROWSER_IOS_THREAD_PROFILER_H_


text:
// Copyright 2022 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.skyframe.serialization;

import com.google.common.collect.ImmutableMap;
import com.google.devtools.build.lib.cmdline.Label;
import com.google.devtools.build.lib.skyframe.serialization.testutils.SerializationTester;
import com.google.devtools.build.lib.skyframe.serialization.testutils.TestUtils;
import net.starlark.java.eval.Module;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/** Tests for {@link ModuleCodec}. */
@RunWith(JUnit4.class)
public class ModuleCodecTest {
  @Test
  public void testCodec() throws Exception {
    Module subject1 = Module.create();

    Module subject2 = Module.create();
    subject2.setClientData(Label.parseAbsolute("//foo:bar", ImmutableMap.of()));
    subject2.setGlobal("x", 1);
    subject2.setGlobal("y", 2);

    new SerializationTester(subject1, subject2)
        .makeMemoizing()
        .setVerificationFunction(ModuleCodecTest::verifyDeserialization)
        .runTestsWithoutStableSerializationCheck();
  }

  private static void verifyDeserialization(Module subject, Module deserialized) {
    // Module doesn't implement proper equality.
    TestUtils.assertModulesEqual(subject, deserialized);
  }
}


text:
//#include <stdio.h>

#include "BulletCollision/CollisionShapes/btConvexShape.h"
#include "BulletCollision/CollisionShapes/btTriangleShape.h"
#include "BulletCollision/NarrowPhaseCollision/btSubSimplexConvexCast.h"
#include "BulletCollision/NarrowPhaseCollision/btGjkConvexCast.h"
#include "BulletCollision/NarrowPhaseCollision/btContinuousConvexCollision.h"
#include "BulletCollision/NarrowPhaseCollision/btGjkEpaPenetrationDepthSolver.h"
#include "btRaycastCallback.h"

btTriangleRaycastCallback::btTriangleRaycastCallback(const btVector3& from,const btVector3& to, unsigned int flags)
	:
	m_from(from),
	m_to(to),
   //@BP Mod
   m_flags(flags),
	m_hitFraction(btScalar(1.))
{

}

void btTriangleRaycastCallback::processTriangle(btVector3* triangle,int partId, int triangleIndex)
{
	const btVector3 &vert0=triangle[0];
	const btVector3 &vert1=triangle[1];
	const btVector3 &vert2=triangle[2];

	btVector3 v10; v10 = vert1 - vert0 ;
	btVector3 v20; v20 = vert2 - vert0 ;

	btVector3 triangleNormal; triangleNormal = v10.cross( v20 );

	const btScalar dist = vert0.dot(triangleNormal);
	btScalar dist_a = triangleNormal.dot(m_from) ;
	dist_a-= dist;
	btScalar dist_b = triangleNormal.dot(m_to);
	dist_b -= dist;

	if ( dist_a * dist_b >= btScalar(0.0) )
	{
		return ; // same sign
	}
   //@BP Mod - Backface filtering
   if (((m_flags & kF_FilterBackfaces) != 0) && (dist_a > btScalar(0.0)))
   {
      // Backface, skip check
      return;
   }

	const btScalar proj_length=dist_a-dist_b;
	const btScalar distance = (dist_a)/(proj_length);
	// Now we have the intersection point on the plane, we'll see if it's inside the triangle
	// Add an epsilon as a tolerance for the raycast,
	// in case the ray hits exacly on the edge of the triangle.
	// It must be scaled for the triangle size.

	if(distance < m_hitFraction)
	{

		btScalar edge_tolerance =triangleNormal.length2();
		edge_tolerance *= btScalar(-0.0001);
		btVector3 point; point.setInterpolate3( m_from, m_to, distance);
		{
			btVector3 v0p; v0p = vert0 - point;
			btVector3 v1p; v1p = vert1 - point;
			btVector3 cp0; cp0 = v0p.cross( v1p );

			if ( (btScalar)(cp0.dot(triangleNormal)) >=edge_tolerance)
			{

				btVector3 v2p; v2p = vert2 -  point;
				btVector3 cp1;
				cp1 = v1p.cross( v2p);
				if ( (btScalar)(cp1.dot(triangleNormal)) >=edge_tolerance)
				{
					btVector3 cp2;
					cp2 = v2p.cross(v0p);

					if ( (btScalar)(cp2.dot(triangleNormal)) >=edge_tolerance)
					{
                  //@BP Mod
                  // Triangle normal isn't normalized
				      triangleNormal.normalize();

                  //@BP Mod - Allow for unflipped normal when raycasting against backfaces
                  if (((m_flags & kF_KeepUnflippedNormal) != 0) || (dist_a <= btScalar(0.0)))
						{
							m_hitFraction = reportHit(-triangleNormal,distance,partId,triangleIndex);
						}
						else
						{
                     m_hitFraction = reportHit(triangleNormal,distance,partId,triangleIndex);
						}
					}
				}
			}
		}
	}
}

btTriangleConvexcastCallback::btTriangleConvexcastCallback (const btConvexShape* convexShape, const btTransform& convexShapeFrom, const btTransform& convexShapeTo, const btTransform& triangleToWorld, const btScalar triangleCollisionMargin)
{
	m_convexShape = convexShape;
	m_convexShapeFrom = convexShapeFrom;
	m_convexShapeTo = convexShapeTo;
	m_triangleToWorld = triangleToWorld;
	m_hitFraction = 1.0f;
	m_triangleCollisionMargin = triangleCollisionMargin;
	m_allowedPenetration = 0.f;
}

void
btTriangleConvexcastCallback::processTriangle (btVector3* triangle, int partId, int triangleIndex)
{
	btTriangleShape triangleShape (triangle[0], triangle[1], triangle[2]);
    triangleShape.setMargin(m_triangleCollisionMargin);

	btVoronoiSimplexSolver	simplexSolver;
	btGjkEpaPenetrationDepthSolver	gjkEpaPenetrationSolver;

//#define  USE_SUBSIMPLEX_CONVEX_CAST 1
//if you reenable USE_SUBSIMPLEX_CONVEX_CAST see commented out code below
#ifdef USE_SUBSIMPLEX_CONVEX_CAST
	btSubsimplexConvexCast convexCaster(m_convexShape, &triangleShape, &simplexSolver);
#else
	//btGjkConvexCast	convexCaster(m_convexShape,&triangleShape,&simplexSolver);
	btContinuousConvexCollision convexCaster(m_convexShape,&triangleShape,&simplexSolver,&gjkEpaPenetrationSolver);
#endif //#USE_SUBSIMPLEX_CONVEX_CAST

	btConvexCast::CastResult castResult;
	castResult.m_fraction = btScalar(1.);
	castResult.m_allowedPenetration = m_allowedPenetration;
	if (convexCaster.calcTimeOfImpact(m_convexShapeFrom,m_convexShapeTo,m_triangleToWorld, m_triangleToWorld, castResult))
	{
		//add hit
		if (castResult.m_normal.length2() > btScalar(0.0001))
		{
			if (castResult.m_fraction < m_hitFraction)
			{
/* btContinuousConvexCast's normal is already in world space */
/*
#ifdef USE_SUBSIMPLEX_CONVEX_CAST
				//rotate normal into worldspace
				castResult.m_normal = m_convexShapeFrom.getBasis() * castResult.m_normal;
#endif //USE_SUBSIMPLEX_CONVEX_CAST
*/
				castResult.m_normal.normalize();

				reportHit (castResult.m_normal,
							castResult.m_hitPoint,
							castResult.m_fraction,
							partId,
							triangleIndex);
			}
		}
	}
}


text:
$testDir = ".\bin\Debug\"
$tests = @("$testdir\UnitTests.dll")

# nuget install OpenCover
# nuget install NUnit.Runners

foreach ($elem in $tests) {
	..\packages\OpenCover.4.5.3723\OpenCover.Console.exe `
	-register:user `
	-target:..\packages\NUnit.Runners.2.6.4\tools\nunit-console.exe `
	"-targetargs: ""$elem"" /framework:net-4.5 /noshadow" `
	"-filter:+[HtmlKit]* -[UnitTests]* -[CodeGenerator]*" `
	-output:opencover.xml `
}


text:
package ch.uzh.ifi.attempto.acerules.help.page.ref;

import ch.uzh.ifi.attempto.acerules.help.HelpWindow;
import ch.uzh.ifi.attempto.acerules.help.page.Page;

public class Gelfond1988 extends Page {

	public Gelfond1988(HelpWindow helpWindow) {
		super(helpWindow, "Gelfond 1988", "References");
		addText("Michael Gelfond, Vladimir Lifschitz.");
		addItalicText("The Stable Model Semantics for Logic Programming.");
		addText("In proceedings of the Fifth International Conference on Logic Programming, 1070-1080, The MIT Press, 1988.");
		addGap();
	}

}


text:
layout: post
title: Note(6)--Uniform Laws or Uniform Tail Bounds
date: 2018-02-10
author: Gwan Siu
catalog: True
tags:
    - Statistics and Bayesian Analysis
---

> Previously, we discussed LLNs and tail bounds that apply to a collection of random variables taken together. In this blog, we mainly focus on uniform laws or uniform tail bounds.

#### 1. Uniform convergence of the CDF

*How can one estimate the CDF of an univariate random variable given a random sample?*

Suppose we have $X_{1},...,X_{n}\sim F_{X}$, so a little bit of thought might suggest a natural estimator is the `empirical CDF`, i.e.

$$
\begin{equation}
\widetilde{F}_{n}(x)=\frac{1}{n}\sum_{i=1}^{n}\mathbb{I}(X_{i}\leq x)
\end{equation}
$$

where $\mathbb{I}$ is an indicator function. Unlike in a classical statistics problem we are not estimating a simple parameter, rather we are estimating an entire function.

Suppose we fixed a value $x$ and we decide to try to estimate $F_{X}(x)$. We could use the empirical CDF at $x$, but this time it is a rather simple prpbelm. Thus, we have:

$$
\begin{equation}
\mathbb{E}[\widetilde{F}_{n}(x)]=\frac{1}{n}\sum_{i=1}^{n}\mathbb{E}[\mathbb{I}(X_{i}\leq x)]=\mathbb{P}(X\leq x)=F_{X}(x)
\end{equation}
$$

The indicator are bounded random random variables so we could just use Hoffding's bound to conclude that

$$
\begin{equation}
\mathbb{P}(\arrowvert \widetilde{F}_{n}(x)-F(x)\arrowvert\geq \epsilon)\leq 2\,\text{exp}(-2n\epsilon^{2})
\end{equation}
$$

This just show that for a single point $x$, we can use simple tail bounds to say that the empirical CDF is close to the true CDF. A more difficult question is to ask whether the empirical CDF and true CDF are close everywhere. In other words, we would like to know the behaviour of the worst case:

$$
\begin{equation}
\bigtriangleup=\sup_{x\in \mathbb{R}}\arrowvert \widetilde{F}_{n}(x)-F_{X}(x)\arrowvert
\end{equation}
$$

Reasoning about the $\bigtriangleup$ requires us to reason about the CDF everywhere, hence the name *uniform bounds* or *uniform LLNs*.

**Notes:**

1. The Glivenko-Cantelli theorem is like a WLLN but it is a uniform WLLN that ensures essentially that the WLLN is true at every point $x\in \mathbb{R}$.

2. There is a corresponidng strong GC theorem that guarantee convergence almost surely.

**Actually, we can estimate CDF of a random variable with no assumptions. This is constrast to estimating the density of a random variable which typically requires strong smoothness assumptions.**

#### 2. Equivalent forms, generalizations and empirical process theory

The empirical probability of a set $A$ is often denoted as:

$$
\begin{equation}
\mathbb{P}_{n}(A)=\frac{1}{n}\sum_{i=1}^{n}\mathbb{I}(X_{i}\in A)
\end{equation}
$$

The quantity $\bigtriangleup$ above can be equivalently written as,

$$
\begin{equation}
\bigtriangleup = \sup_{A\in\mathcal{A}}\arrowvert \mathbb{P}_{n}(A)-\mathbb{A}\arrowvert
\end{equation}
$$

where $\mathcal{A}$ is a collection of sets,

$$
\begin{equation}
\mathcal{A}={A(x):A(x)=(-\infty,x])}
\end{equation}
$$

since in this case, $\mathbb{P}(A(x))=F_{X}(x)$.

To generalize the CDF question to more generally about other interesting collections of sets $\mathcal{A}$, i.e. we are interested in collections of sets $\mathcal{A}$, for which we have uniform convergence, i.e:

$$
\begin{equation}
\bigtriangleup(\mathcal{A})=\sup_{A\in\mathcal{A}}\arrowvert \mathbb{P}_{n}(A)-\mathbb{P}(A)\arrowvert
\end{equation}
$$

converges in probability to 0. This is well known as *Vapnik-Cervonenkis* theory.

Even more generally, one can replace the indicators with general functions, i.e. let $\mathcal{F}$ be a class of integrable, real-valued functions, and suppose we have an i.i.d sample $X_{1},...,X_{n}\sim P$, then we could be intested in,

$$
\begin{equation}
\bigtriangleup(\mathcal{F})=\sup_{f\in\mathcal{F}}\arrowvert \frac{1}{n}\sum_{i=1}^{n}f(X_{i})-\mathbb{E}[f]\arrowvert
\end{equation}
$$

This quantity is known as an *empirical process* and empirical process theory is the area of statistics that asks questions about the convergence in probability, almost surely or in distribution for the quantity $\bigtriangleup(\mathcal{F})$ for interesting classes of functions of $\mathcal{F}$.

We refer to classes for which $\bigtriangleup(F)\overset{p}{\rightarrow}0,$ as *Glivenko-Cantelli* classes. The class of functions:

$$
\begin{equation}
\mathcal{F}={\mathbb{I}(-\infty,x]\arrowvert x\in \mathbb{R}}
\end{equation}
$$

which defines the uniform convergence of the CDF is an example of a *Glivenko-Cantelli* class.

#### 3. Failure of an uniform law

In generally, very complex classes of functions or sets will fail to be Glivenko-Cantelli. Thus, we need some methods to measure the complexity of functions or sets. A failure case is shown here.

Suppose we draw $X_{1},...,X_{n}\sim P$ where $P$ is some continuous distribution over $[0,1]$. Suppose further that $\mathcal{A}$ is all subsets of $[0,1]$ with finitely many elements.

Then observe that since the distribution is continuous we have that, $\mathbb{P}(A)=0$ for each $A\in \mathcal{A}$, however for the finite set${X_{1},...,X_{n}}$ we have that $\mathbb{P}_{n}(A)=1$, i.e.

$$
\begin{equation}
\bigtriangleup(\mathcal{A})=\sup_{A\in\mathcal{A}}\arrowvert \mathbb{P}_{n}(A)-\mathbb{P}(A)\arrowvert =1
\end{equation}
$$

no matter what how large $n$ is. So the collection of sets $\mathcal{A}$ is not Glivenko-Cantelli. Roughly, the collection of sets is "too large".

#### 4. Estimation of Statistical Functionals

Often we want to estimate some quantity which can be written as a simple functional of the CDF, and a natural estimate just replaces the true CDF with the empirical CDF(such estimators are known as plug-in esimators). *Functional is a function of a function*. Here are some classical examples:

1. **Expectation Functionals:** For a given function $g$, we can view the usual empirical estimator of its Expectation as a plug-in estimate where we replace the population CDF by the empirical CDF,

$$
\widetilde{\mathbb{E}}[g(X)]=\frac{1}{n}\sum_{i=1}^{n}g(X_{i})=\int_{x}g(x)f\widetilde{F}_{n}(x)
$$

2. **Quantile Functionals:** For an $\alpha\in[0,1]$, the $\alpha-th$ quantile of a distribution is given as:

$$
\begin{equation}
Q_{\alpha}(F)=\inf{\{t\in\mathbb{R}\arrowvert F(t)\geq \alpha}\}
\end{equation}
$$

Taking $\alpha=0.5$ gives the median. A natural plug-in estimator of $Q_{\alpha}(F)$ is to simply take $Q_{\alpha}(\widetilde{F}_{n})$.

3. **Goodness-of-fit Functionals:**

In data analysis, we want to test the hypothesis that we have are $i.i.d$ from some known distribution $F_{0}$. The rough idea is we form a statistic to test this hypothesis which(hopefully) takes large values when the distribution is not $F_{0}$ and takes small values otherwise. Typical tests of this form include the Kolmogorov-Smirnov test, where we compute the plug-in quantity:

$$
\begin{equation}
\widetilde{T}_{KS}=\sup_{x\in\mathbb{R}}\arrowvert \widetilde{F}_{n}(x)-F_{0}\arrowvert
\end{equation}
$$

which is natural because if the true distribution is $F_{0}$ we know by the Glivenko-Cantelli theorem that $T_{KS}$ is small. Similarly, one can use the Cramer-von Mises test which uses the plug-in statistic,

$$
\begin{equation}
\widetilde{T}_{CVM}=\int_{x}(\widetilde{F}_(x)-F_{0}(x))^{2}dF_{0}(x)
\end{equation}
$$

There are many other Statistical functionals for which the usual estimators can be thought of as plug-in estimators. For example: variance, correlation, and higher moments can all be expressed in this function.

In each of the above cases we are interested in estimating some functional $\gamma(F)$ and we use the plug-in estimator $\gamma(\widetilde{F}_{n})$. Analogous to the continuous mapping theorem, there is a Glivenko-Cantelli theorem that provides a WLLN for these estimators. We need to first defines a notion of continuity. Suppose $\gamma$ satisfies the property that for every $\epsilon >0$, there is a $\delta >0$ such that if

$$
\begin{equation}
\sup_{x}\arrowvert \widetilde{F}_{n}-F(x)\arrowvert \leq \delta
\end{equation}
$$

then

$$
\begin{equation}
\arrowvert \gamma(F)-\gamma(\widetilde{F}_{n})\arrowvert \leq \epsilon
\end{equation}
$$

for such functionals $\gamma$, it is a simple consequence of the Glivenko-Cantelli theorem that $\gamma(\widetilde{F}_{n})$ converges in probability to $\gamma(F)$.


text:
var _ = require("lodash");
var λ = require("contra");
var fs = require("fs");
var diff = require("diff-lines");
var path = require("path");
var test = require("tape");
var compiler = require("./");

var files_dir = path.resolve(__dirname, "../test-rulesets");

test("compiler", function(t){
    fs.readdir(files_dir, function(err, files){
        if(err) return t.end(err);

        var basenames = _.uniq(_.map(files, function(file){
            return path.basename(path.basename(file, ".krl"), ".js");
        }));

        λ.each(basenames, function(basename, next){
            var f_js = path.join(files_dir, basename) + ".js";
            var f_krl = path.join(files_dir, basename) + ".krl";
            λ.concurrent({
                js: λ.curry(fs.readFile, f_js, "utf-8"),
                krl: λ.curry(fs.readFile, f_krl, "utf-8")
            }, function(err, srcs){
                if(err) return t.end(err);

                var compiled;
                try{
                    compiled = compiler(srcs.krl).code;
                }catch(e){
                    console.log(f_krl);
                    console.log(e.stack);
                    process.exit(1);//end asap, so they can easily see the error
                }
                compiled = compiled.trim();
                var expected = srcs.js.trim();

                if(compiled === expected){
                    t.ok(true);
                    next();
                }else{
                    console.log("");
                    console.log(path.basename(f_krl) + " -> " + path.basename(f_js));
                    console.log("");
                    console.log(diff(expected, compiled, {
                        n_surrounding: 3
                    }));
                    console.log("");
                    console.log(path.basename(f_krl) + " -> " + path.basename(f_js));
                    process.exit(1);//end asap, so they can easily see the diff
                }

                next();
            });
        }, t.end);
    });
});

test("compiler errors", function(t){
    try{
        compiler("ruleset blah {global {ent:a = 1}}\n");
        t.fail("should have thrown up b/c ent:* = * not allowed in global scope");
    }catch(err){
        t.ok(true);
    }
    try{
        compiler("function(a, b = 1, c){a}");
        t.fail("once you have a default param, all following must have a default");
    }catch(err){
        t.equals(err + "", "Error: non-default argument follows default argument");
    }
    try{
        compiler("add(b = 1, 2)");
        t.fail("once you used a named arg, all following should be named");
    }catch(err){
        t.equals(err + "", "Error: non-named arg after named arg");
    }
    try{
        compiler("function(){a = 1}");
        t.fail("function must end with an expression");
    }catch(err){
        t.equals(err + "", "Error: function must end with an expression");
    }

    try{
        compiler("ruleset a{meta{keys b {\"one\":function(){}}}}");
        t.fail("meta key maps can only have strings");
    }catch(err){
        t.equals(err + "", "Error: A ruleset key that is Map, can only use Strings as values");
    }

    t.end();
});

test("special cases", function(t){
    //args shouldn't be dependent on each other and cause strange duplication
    var js = compiler("foo(1).bar(baz(2))").code;
    var expected = "";
    expected += "yield ctx.callKRLstdlib(\"bar\", [\n";
    expected += "  yield ctx.applyFn(ctx.scope.get(\"foo\"), ctx, [1]),\n";
    expected += "  yield ctx.applyFn(ctx.scope.get(\"baz\"), ctx, [2])\n";
    expected += "]);";
    t.equals(js, expected);
    t.end();
});


text:
@extends('admin.course.master')

@section('subsection_content')

  {{ Form::open( array('url' => '/admin/coursetimeslot/' . $timeslot->id, 'method' => 'PUT', 'class' => 'form-horizontal well') ) }}
    <fieldset>
      <legend>Editing timeslot “{{{ $timeslot->code }}}” for {{{ $course->description }}} – Section {{{ $section->code }}}...</legend>

has('section') ? ' error' : '' }}">
        Parent Section

          <select id="section" name="section" required>
            @foreach( $allSections as $s )
              <option value="{{ $s->id }}"{{ $s->id == Input::old('section', $section->id) ? ' selected' : '' }}>{{{ $s->code }}}</option>
            @endforeach
          </select>
          {{ $errors->first('section') }}

has('type') ? ' error' : '' }}">
        Timeslot Type

          <select id="type" name="type" required>
            <option value="LECTURE"{{ Input::old('type', $timeslot->type) == 'LECTURE' ? ' selected' : '' }}>Lecture</option>
            <option value="TUTORIAL"{{ Input::old('type', $timeslot->type) == 'TUTORIAL' ? ' selected' : '' }}>Tutorial</option>
            <option value="LAB"{{ Input::old('type', $timeslot->type) == 'LAB' ? ' selected' : '' }}>Lab</option>
          </select>
          {{ $errors->first('type') }}

has('code') ? ' error' : '' }}">
        Timeslot Code

          <input type="text" id="code" name="code" class="input-small" placeholder="e.g. CC" value="{{ Input::old('code', $timeslot->code) }}" required>
          {{ $errors->first('code') }}

has('date') ? ' error' : '' }}">
        Day

          <select id="date" name="date" required>
            <option value="0"{{ $timeslot->day == 0 ? ' selected' : '' }}>Sunday</option>
            <option value="1"{{ $timeslot->day == 1 ? ' selected' : '' }}>Monday</option>
            <option value="2"{{ $timeslot->day == 2 ? ' selected' : '' }}>Tuesday</option>
            <option value="3"{{ $timeslot->day == 3 ? ' selected' : '' }}>Wednesday</option>
            <option value="4"{{ $timeslot->day == 4 ? ' selected' : '' }}>Thursday</option>
            <option value="5"{{ $timeslot->day == 5 ? ' selected' : '' }}>Friday</option>
            <option value="6"{{ $timeslot->day == 6 ? ' selected' : '' }}>Saturaday</option>
          </select>
          {{ $errors->first('date') }}

has('startTime') ? 'error' : '' }}">
        Start Time

          <input type="time" id="startTime" name="startTime" class="input-small" value="{{ Input::old('startTime', $timeslot->start_time) }}" required>
          {{ $errors->first('startTime') }}

has('endTime') ? ' error' : '' }}">
        End Time

          <input type="time" id="endTime" name="endTime" class="input-small" value="{{ Input::old('endTime', $timeslot->end_time) }}" required>
          {{ $errors->first('endTime') }}

has('location') ? ' error' : '' }}">
        Location

          <input type="text" id="location" name="location" class="input-xlarge" value="{{ Input::old('location', $timeslot->location) }}" placeholder="Physical location where timeslot is held." required>
          {{ $errors->first('location') }}

has('instructor') ? ' error' : '' }}">
        Instructor

          <input type="text" id="instructor" name="instructor" class="input-xlarge" value="{{ Input::old('instructor', $timeslot->instructor) }}" placeholder="Name of the instructor that is teaching." required>
          {{ $errors->first('instructor') }}

          <button type="submit" class="btn btn-primary"> Save Changes</button>
          <button type="reset" class="btn"> Undo Changes</button>

    </fieldset>
    {{ Form::token() }}
  {{ Form::close() }}

@stop


text:
package com.cirrus.model.profile;

import com.cirrus.model.profile.impl.UserProfile;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;

import java.util.List;

@JsonDeserialize(as = UserProfile.class)
public interface IUserProfile {

    /**
     * Returns the email address of the user
     */
    String getEmailAddress();

    /**
     * Returns the password
     *
     * @return the password
     */
    String getPassword();

    /**
     * Adds a new storage service profile
     *
     * @param profile the storage service profile
     */
    void addStorageProfile(final IStorageServiceProfile profile);

    /**
     * Removes a storage service profile
     *
     * @param profile the storage service profile
     */
    void removeStorageProfile(final IStorageServiceProfile profile);

    /**
     * Returns all storage service profiles
     */
    List<IStorageServiceProfile> listStorageProfiles();
}


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.neu.nutrons.ultimateascent.commands;

/**
 *
 * @author NUTRONs
 * Raises elevator to target position.
 */
public class SetElevatorPositionCmd extends CommandBase{

    double pos;
    public SetElevatorPositionCmd(double pos) {
        this.pos = pos;
        requires(elevator);
    }
    protected void initialize() {
        elevator.enableControlLoop();

        elevator.setPosition(pos);
    }

    protected void execute() {
    }

    protected boolean isFinished() {
        return true;
    }

    protected void end() {
    }

    protected void interrupted() {
    }

}


text:
require 'simplecov'
SimpleCov.start

require 'mail'
Mail.defaults { delivery_method :test }

require 'sequel'
require 'feed2email'
Feed2Email.setup_database(connection: Sequel.sqlite)

require 'pry'
require 'webmock/rspec'

RSpec.configure do |config|
  config.run_all_when_everything_filtered = true
  config.filter_run :focus

  # Run specs in random order to surface order dependencies. If you find an
  # order dependency and want to debug it, you can fix the order by providing
  # the seed, which is printed after each run.
  #     --seed 1234
  config.order = 'random'

  config.before(:each) do
    Feed2Email.home_path = Dir.mktmpdir

    Mail::TestMailer.deliveries.clear
  end

  config.around(:each) do |example|
    Sequel::Model.db.transaction(rollback: :always, auto_savepoint: true) do
      example.run
    end
  end
end

def discard_output
  stdout, stderr = $stdout, $stderr # backup
  $stdout = $stderr = StringIO.new
  yield
  $stdout, $stdeer = stdout, stderr # restore
end

def discard_thor_error
  begin
    yield
  rescue Thor::Error
  end
end

def fixture_path(filename)
  File.join('spec', 'fixtures', filename)
end

def stub_redirects(urls, status = 301)
  urls.each_cons(2) do |url_from, url_to|
    stub_request(:head, url_from).to_return(
      status: status, headers: { location: url_to }
    )
  end
end


text:
class AddAlbumArtworkUrlToSongs < ActiveRecord::Migration
  def change
    add_column :songs, :album_artwork_url, :string
  end
end


text:
import sys
import os
import json
import getopt
import tempfile

def main(argv):
	DOCKER_ENV = os.environ.get('DOCKER_ENV_PROFILES')
	if DOCKER_ENV is None:
		print("DOCKER_ENV_PROFILES is not configured.", file=sys.stderr)
		return
	DOCKER_ENV = os.path.realpath(DOCKER_ENV)

	environment = os.environ.get('DOCKERENV_CURRENT_ENV')
	if environment is None:
		environment = 'develop'

	opts, args = getopt.gnu_getopt(argv, '', ["environment=", 'env='])
	for o, a in opts:
		if o in ("--environment", "--env"):
			environment = a

	env_dir = DOCKER_ENV + '/' + environment + '/';

	with open(env_dir + 'machines.json', 'r') as f:
		machine_data = json.load(f)

	print("export DOCKERENV_CURRENT_ENV=\"" + environment + '"')

	if len(args) == 0:
		currentenv = os.environ.get('DOCKERENV_CURRENT_MACHINE')
		sortedkeys = list(sorted(machine_data.keys()))
		for k in sortedkeys:
			if currentenv == k:
				print('*' + k, file=sys.stderr)
			else:
				print(k, file=sys.stderr)
	elif len(args) != 1:
		print("You must pass only one machine name.", file=sys.stderr)
	else:
		if args[0] in machine_data:
			data = machine_data[args[0]]
			socket = data.get('socket', 'false')
			hostname = data.get('host', '')
			port = data.get('port', '')

			if (socket == 'true'):
				print("export DOCKER_TLS_VERIFY=")
				print("export DOCKER_HOST=")
				print("export DOCKER_CERT_PATH=")
			else:
				tempdir = tempfile.mkdtemp(prefix='docker', suffix=environment)
				os.symlink(env_dir + 'ca.crt', tempdir + '/ca.pem')
				os.symlink(env_dir + 'personal.crt', tempdir + '/cert.pem')
				os.symlink(env_dir + 'personal.key', tempdir + '/key.pem')
				print("export DOCKER_TLS_VERIFY=\"1\"")
				print("export DOCKER_HOST=\"tcp://" + hostname + ":" + port + '"')
				print("export DOCKER_CERT_PATH=\"" + tempdir + '"')

			print("export DOCKERENV_CURRENT_MACHINE=\"" + args[0] + '"')
		else:
			print("Unknown machine name: " + args[0], file=sys.stderr)

if __name__ == '__main__':
    main(sys.argv[1:])


text:
<?xml version="1.0" encoding="UTF-8"?>

<!--
  ~ Copyright 1998-2012 Linux.org.ru
  ~    Licensed under the Apache License, Version 2.0 (the "License");
  ~    you may not use this file except in compliance with the License.
  ~    You may obtain a copy of the License at
  ~
  ~        http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~    Unless required by applicable law or agreed to in writing, software
  ~    distributed under the License is distributed on an "AS IS" BASIS,
  ~    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~    See the License for the specific language governing permissions and
  ~    limitations under the License.
  -->

<beans:beans xmlns="http://www.springframework.org/schema/security"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xmlns:beans="http://www.springframework.org/schema/beans"
             xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.1.xsd">

    <http pattern="/css/**" security="none"/>
    <http pattern="/img/**" security="none"/>
    <http pattern="/js/**" security="none"/>
    <http pattern="/photos/**" security="none"/>
    <http pattern="/tango/**" security="none"/>
    <http pattern="/white/**" security="none"/>
    <http pattern="/white2/**" security="none"/>
    <http pattern="/black/**" security="none"/>
    <http pattern="/adv/**" security="none"/>
    <http pattern="/fontello/**" security="none"/>
    <http pattern="*.css" security="none"/>
    <http pattern="/*.ico" security="none"/>

    <http use-expressions="true" auto-config="false" authentication-manager-ref="authenticationManager" create-session="stateless" entry-point-ref="authenticationEntryPoint">
        <intercept-url pattern="/**" access="permitAll"/>
        <remember-me key="${Secret}" services-ref="rememberMeServices"/>
        <!-- TODO: LoginController.ACEGI_COOKIE_NAME -->
        <logout logout-url="/logout" logout-success-url="/"
                delete-cookies="password,profile,JSESSIONID,SPRING_SECURITY_REMEMBER_ME_COOKIE"/>
        <anonymous username="anonymous" granted-authority="ROLE_SYSTEM_ANONYMOUS"/>
        <custom-filter after="ANONYMOUS_FILTER" ref="securityFilter"/>
    </http>
    <!-- <debug/> -->
    <authentication-manager alias="authenticationManager">
        <authentication-provider user-service-ref="userDetailsServiceImpl">
            <password-encoder ref="passwordEncoderImpl"/>
        </authentication-provider>
    </authentication-manager>

    <beans:bean id="rememberMeServices"
                class="org.springframework.security.web.authentication.rememberme.TokenBasedRememberMeServices">
        <beans:property name="userDetailsService" ref="userDetailsServiceImpl"/>
        <beans:property name="key" value="${Secret}"/>
        <beans:property name="cookieName" value="remember_me"/>
        <!-- 365 days -->
        <beans:property name="tokenValiditySeconds" value="31536000"/>
        <beans:property name="alwaysRemember" value="true" />
        <beans:property name="useSecureCookie" value="false"/>
    </beans:bean>

    <beans:bean id="securityFilter" class="ru.org.linux.auth.SecurityFilter"/>
    <beans:bean id="authenticationEntryPoint" class="ru.org.linux.auth.AuthenticationEntryPointImpl" />
</beans:beans>


text:
package ch.epfl.data.squall.expressions;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import ch.epfl.data.squall.types.DateType;
import ch.epfl.data.squall.types.Type;
import ch.epfl.data.squall.visitors.ValueExpressionVisitor;

public class DateSum implements ValueExpression<Date> {
    private static final long serialVersionUID = 1L;

    private final Type<Date> _dc = new DateType();

    private final ValueExpression<Date> _ve;
    private final int _interval, _unit;

    public DateSum(ValueExpression<Date> ve, int unit, int interval) {
	_ve = ve;
	_unit = unit;
	_interval = interval;
    }

    @Override
    public void accept(ValueExpressionVisitor vev) {
	vev.visit(this);
    }

    @Override
    public void changeValues(int i, ValueExpression<Date> newExpr) {
	// nothing
    }

    @Override
    public Date eval(List<String> tuple) {
	final Date base = _ve.eval(tuple);
	final Calendar c = Calendar.getInstance();
	c.setTime(base);
	c.add(_unit, _interval);
	return c.getTime();
    }

    @Override
    public String evalString(List<String> tuple) {
	return _dc.toString(eval(tuple));
    }

    @Override
    public List<ValueExpression> getInnerExpressions() {
	final List<ValueExpression> result = new ArrayList<ValueExpression>();
	result.add(_ve);
	return result;
    }

    @Override
    public Type getType() {
	return _dc;
    }

    @Override
    public void inverseNumber() {
	// nothing
    }

    @Override
    public boolean isNegative() {
	// nothing
	return false;
    }

    @Override
    public String toString() {
	final StringBuilder sb = new StringBuilder();
	sb.append("DateSum ").append(_ve.toString());
	sb.append(" interval ").append(_interval);
	sb.append(" unit ").append(_unit);
	return sb.toString();
    }

}