text:
from __future__ import absolute_import, division, print_function
__metaclass__ = type

ANSIBLE_METADATA = {'metadata_version': '1.1',
                    'status': ['stableinterface'],
                    'supported_by': 'core'}

DOCUMENTATION = '''
---
module: ec2_vpc_net
short_description: Configure AWS virtual private clouds
description:
    - Create, modify, and terminate AWS virtual private clouds.
version_added: "2.0"
author:
  - Jonathan Davila (@defionscode)
  - Sloane Hertel (@s-hertel)
options:
  name:
    description:
      - The name to give your VPC. This is used in combination with C(cidr_block) to determine if a VPC already exists.
    required: yes
  cidr_block:
    description:
      - The primary CIDR of the VPC. After 2.5 a list of CIDRs can be provided. The first in the list will be used as the primary CIDR
        and is used in conjunction with the C(name) to ensure idempotence.
    required: yes
  purge_cidrs:
    description:
      - Remove CIDRs that are associated with the VPC and are not specified in C(cidr_block).
    default: no
    type: bool
    version_added: '2.5'
  tenancy:
    description:
      - Whether to be default or dedicated tenancy. This cannot be changed after the VPC has been created.
    default: default
    choices: [ 'default', 'dedicated' ]
  dns_support:
    description:
      - Whether to enable AWS DNS support.
    default: yes
    type: bool
  dns_hostnames:
    description:
      - Whether to enable AWS hostname support.
    default: yes
    type: bool
  dhcp_opts_id:
    description:
      - the id of the DHCP options to use for this vpc
  tags:
    description:
      - The tags you want attached to the VPC. This is independent of the name value, note if you pass a 'Name' key it would override the Name of
        the VPC if it's different.
    aliases: [ 'resource_tags' ]
  state:
    description:
      - The state of the VPC. Either absent or present.
    default: present
    choices: [ 'present', 'absent' ]
  multi_ok:
    description:
      - By default the module will not create another VPC if there is another VPC with the same name and CIDR block. Specify this as true if you want
        duplicate VPCs created.
    type: bool
    default: false
requirements:
    - boto3
    - botocore
extends_documentation_fragment:
    - aws
    - ec2
'''

EXAMPLES = '''
# Note: These examples do not set authentication details, see the AWS Guide for details.

- name: create a VPC with dedicated tenancy and a couple of tags
  ec2_vpc_net:
    name: Module_dev2
    cidr_block: 10.10.0.0/16
    region: us-east-1
    tags:
      module: ec2_vpc_net
      this: works
    tenancy: dedicated
'''

RETURN = '''
vpc:
  description: info about the VPC that was created or deleted
  returned: always
  type: complex
  contains:
    cidr_block:
      description: The CIDR of the VPC
      returned: always
      type: str
      sample: 10.0.0.0/16
    cidr_block_association_set:
      description: IPv4 CIDR blocks associated with the VPC
      returned: success
      type: list
      sample:
        "cidr_block_association_set": [
            {
                "association_id": "vpc-cidr-assoc-97aeeefd",
                "cidr_block": "20.0.0.0/24",
                "cidr_block_state": {
                    "state": "associated"
                }
            }
        ]
    classic_link_enabled:
      description: indicates whether ClassicLink is enabled
      returned: always
      type: NoneType
      sample: null
    dhcp_options_id:
      description: the id of the DHCP options assocaited with this VPC
      returned: always
      type: str
      sample: dopt-0fb8bd6b
    id:
      description: VPC resource id
      returned: always
      type: str
      sample: vpc-c2e00da5
    instance_tenancy:
      description: indicates whether VPC uses default or dedicated tenancy
      returned: always
      type: str
      sample: default
    is_default:
      description: indicates whether this is the default VPC
      returned: always
      type: bool
      sample: false
    state:
      description: state of the VPC
      returned: always
      type: str
      sample: available
    tags:
      description: tags attached to the VPC, includes name
      returned: always
      type: complex
      contains:
        Name:
          description: name tag for the VPC
          returned: always
          type: str
          sample: pk_vpc4
'''

try:
    import botocore
except ImportError:
    pass  # Handled by AnsibleAWSModule

from time import sleep, time
from ansible.module_utils.aws.core import AnsibleAWSModule
from ansible.module_utils.ec2 import (AWSRetry, camel_dict_to_snake_dict, compare_aws_tags,
                                      ansible_dict_to_boto3_tag_list, boto3_tag_list_to_ansible_dict)
from ansible.module_utils.six import string_types
from ansible.module_utils._text import to_native
from ansible.module_utils.network.common.utils import to_subnet

def vpc_exists(module, vpc, name, cidr_block, multi):
    """Returns None or a vpc object depending on the existence of a VPC. When supplied
    with a CIDR, it will check for matching tags to determine if it is a match
    otherwise it will assume the VPC does not exist and thus return None.
    """
    try:
        matching_vpcs = vpc.describe_vpcs(Filters=[{'Name': 'tag:Name', 'Values': [name]}, {'Name': 'cidr-block', 'Values': cidr_block}])['Vpcs']
        # If an exact matching using a list of CIDRs isn't found, check for a match with the first CIDR as is documented for C(cidr_block)
        if not matching_vpcs:
            matching_vpcs = vpc.describe_vpcs(Filters=[{'Name': 'tag:Name', 'Values': [name]}, {'Name': 'cidr-block', 'Values': [cidr_block[0]]}])['Vpcs']
    except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
        module.fail_json_aws(e, msg="Failed to describe VPCs")

    if multi:
        return None
    elif len(matching_vpcs) == 1:
        return matching_vpcs[0]['VpcId']
    elif len(matching_vpcs) > 1:
        module.fail_json(msg='Currently there are %d VPCs that have the same name and '
                             'CIDR block you specified. If you would like to create '
                             'the VPC anyway please pass True to the multi_ok param.' % len(matching_vpcs))
    return None

@AWSRetry.backoff(delay=3, tries=8, catch_extra_error_codes=['InvalidVpcID.NotFound'])
def get_classic_link_with_backoff(connection, vpc_id):
    try:
        return connection.describe_vpc_classic_link(VpcIds=[vpc_id])['Vpcs'][0].get('ClassicLinkEnabled')
    except botocore.exceptions.ClientError as e:
        if e.response["Error"]["Message"] == "The functionality you requested is not available in this region.":
            return False
        else:
            raise

def get_vpc(module, connection, vpc_id):
    # wait for vpc to be available
    try:
        connection.get_waiter('vpc_available').wait(VpcIds=[vpc_id])
    except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
        module.fail_json_aws(e, msg="Unable to wait for VPC {0} to be available.".format(vpc_id))

    try:
        vpc_obj = AWSRetry.backoff(
            delay=3, tries=8,
            catch_extra_error_codes=['InvalidVpcID.NotFound'],
        )(connection.describe_vpcs)(VpcIds=[vpc_id])['Vpcs'][0]
    except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
        module.fail_json_aws(e, msg="Failed to describe VPCs")
    try:
        vpc_obj['ClassicLinkEnabled'] = get_classic_link_with_backoff(connection, vpc_id)
    except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
        module.fail_json_aws(e, msg="Failed to describe VPCs")

    return vpc_obj

def update_vpc_tags(connection, module, vpc_id, tags, name):
    if tags is None:
        tags = dict()

    tags.update({'Name': name})
    tags = dict((k, to_native(v)) for k, v in tags.items())
    try:
        current_tags = dict((t['Key'], t['Value']) for t in connection.describe_tags(Filters=[{'Name': 'resource-id', 'Values': [vpc_id]}])['Tags'])
        tags_to_update, dummy = compare_aws_tags(current_tags, tags, False)
        if tags_to_update:
            if not module.check_mode:
                tags = ansible_dict_to_boto3_tag_list(tags_to_update)
                vpc_obj = AWSRetry.backoff(
                    delay=1, tries=5,
                    catch_extra_error_codes=['InvalidVpcID.NotFound'],
                )(connection.create_tags)(Resources=[vpc_id], Tags=tags)

                # Wait for tags to be updated
                expected_tags = boto3_tag_list_to_ansible_dict(tags)
                filters = [{'Name': 'tag:{0}'.format(key), 'Values': [value]} for key, value in expected_tags.items()]
                connection.get_waiter('vpc_available').wait(VpcIds=[vpc_id], Filters=filters)

            return True
        else:
            return False
    except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
        module.fail_json_aws(e, msg="Failed to update tags")

def update_dhcp_opts(connection, module, vpc_obj, dhcp_id):
    if vpc_obj['DhcpOptionsId'] != dhcp_id:
        if not module.check_mode:
            try:
                connection.associate_dhcp_options(DhcpOptionsId=dhcp_id, VpcId=vpc_obj['VpcId'])
            except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
                module.fail_json_aws(e, msg="Failed to associate DhcpOptionsId {0}".format(dhcp_id))

            try:
                # Wait for DhcpOptionsId to be updated
                filters = [{'Name': 'dhcp-options-id', 'Values': [dhcp_id]}]
                connection.get_waiter('vpc_available').wait(VpcIds=[vpc_obj['VpcId']], Filters=filters)
            except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
                module.fail_json(msg="Failed to wait for DhcpOptionsId to be updated")

        return True
    else:
        return False

def create_vpc(connection, module, cidr_block, tenancy):
    try:
        if not module.check_mode:
            vpc_obj = connection.create_vpc(CidrBlock=cidr_block, InstanceTenancy=tenancy)
        else:
            module.exit_json(changed=True)
    except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
        module.fail_json_aws(e, "Failed to create the VPC")

    # wait for vpc to exist
    try:
        connection.get_waiter('vpc_exists').wait(VpcIds=[vpc_obj['Vpc']['VpcId']])
    except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
        module.fail_json_aws(e, msg="Unable to wait for VPC {0} to be created.".format(vpc_obj['Vpc']['VpcId']))

    return vpc_obj['Vpc']['VpcId']

def wait_for_vpc_attribute(connection, module, vpc_id, attribute, expected_value):
    start_time = time()
    updated = False
    while time() < start_time + 300:
        current_value = connection.describe_vpc_attribute(
            Attribute=attribute,
            VpcId=vpc_id
        )['{0}{1}'.format(attribute[0].upper(), attribute[1:])]['Value']
        if current_value != expected_value:
            sleep(3)
        else:
            updated = True
            break
    if not updated:
        module.fail_json(msg="Failed to wait for {0} to be updated".format(attribute))

def get_cidr_network_bits(module, cidr_block):
    fixed_cidrs = []
    for cidr in cidr_block:
        split_addr = cidr.split('/')
        if len(split_addr) == 2:
            # this_ip is a IPv4 CIDR that may or may not have host bits set
            # Get the network bits.
            valid_cidr = to_subnet(split_addr[0], split_addr[1])
            if cidr != valid_cidr:
                module.warn("One of your CIDR addresses ({0}) has host bits set. To get rid of this warning, "
                            "check the network mask and make sure that only network bits are set: {1}.".format(cidr, valid_cidr))
            fixed_cidrs.append(valid_cidr)
        else:
            # let AWS handle invalid CIDRs
            fixed_cidrs.append(cidr)
    return fixed_cidrs

def main():
    argument_spec = dict(
        name=dict(required=True),
        cidr_block=dict(type='list', required=True),
        tenancy=dict(choices=['default', 'dedicated'], default='default'),
        dns_support=dict(type='bool', default=True),
        dns_hostnames=dict(type='bool', default=True),
        dhcp_opts_id=dict(),
        tags=dict(type='dict', aliases=['resource_tags']),
        state=dict(choices=['present', 'absent'], default='present'),
        multi_ok=dict(type='bool', default=False),
        purge_cidrs=dict(type='bool', default=False),
    )

    module = AnsibleAWSModule(
        argument_spec=argument_spec,
        supports_check_mode=True
    )

    name = module.params.get('name')
    cidr_block = get_cidr_network_bits(module, module.params.get('cidr_block'))
    purge_cidrs = module.params.get('purge_cidrs')
    tenancy = module.params.get('tenancy')
    dns_support = module.params.get('dns_support')
    dns_hostnames = module.params.get('dns_hostnames')
    dhcp_id = module.params.get('dhcp_opts_id')
    tags = module.params.get('tags')
    state = module.params.get('state')
    multi = module.params.get('multi_ok')

    changed = False

    connection = module.client(
        'ec2',
        retry_decorator=AWSRetry.jittered_backoff(
            retries=8, delay=3, catch_extra_error_codes=['InvalidVpcID.NotFound']
        )
    )

    if dns_hostnames and not dns_support:
        module.fail_json(msg='In order to enable DNS Hostnames you must also enable DNS support')

    if state == 'present':

        # Check if VPC exists
        vpc_id = vpc_exists(module, connection, name, cidr_block, multi)

        if vpc_id is None:
            vpc_id = create_vpc(connection, module, cidr_block[0], tenancy)
            changed = True

        vpc_obj = get_vpc(module, connection, vpc_id)

        associated_cidrs = dict((cidr['CidrBlock'], cidr['AssociationId']) for cidr in vpc_obj.get('CidrBlockAssociationSet', [])
                                if cidr['CidrBlockState']['State'] != 'disassociated')
        to_add = [cidr for cidr in cidr_block if cidr not in associated_cidrs]
        to_remove = [associated_cidrs[cidr] for cidr in associated_cidrs if cidr not in cidr_block]
        expected_cidrs = [cidr for cidr in associated_cidrs if associated_cidrs[cidr] not in to_remove] + to_add

        if len(cidr_block) > 1:
            for cidr in to_add:
                changed = True
                connection.associate_vpc_cidr_block(CidrBlock=cidr, VpcId=vpc_id)

        if purge_cidrs:
            for association_id in to_remove:
                changed = True
                try:
                    connection.disassociate_vpc_cidr_block(AssociationId=association_id)
                except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
                    module.fail_json_aws(e, "Unable to disassociate {0}. You must detach or delete all gateways and resources that "
                                         "are associated with the CIDR block before you can disassociate it.".format(association_id))

        if dhcp_id is not None:
            try:
                if update_dhcp_opts(connection, module, vpc_obj, dhcp_id):
                    changed = True
            except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
                module.fail_json_aws(e, "Failed to update DHCP options")

        if tags is not None or name is not None:
            try:
                if update_vpc_tags(connection, module, vpc_id, tags, name):
                    changed = True
            except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
                module.fail_json_aws(e, msg="Failed to update tags")

        current_dns_enabled = connection.describe_vpc_attribute(Attribute='enableDnsSupport', VpcId=vpc_id, aws_retry=True)['EnableDnsSupport']['Value']
        current_dns_hostnames = connection.describe_vpc_attribute(Attribute='enableDnsHostnames', VpcId=vpc_id, aws_retry=True)['EnableDnsHostnames']['Value']
        if current_dns_enabled != dns_support:
            changed = True
            if not module.check_mode:
                try:
                    connection.modify_vpc_attribute(VpcId=vpc_id, EnableDnsSupport={'Value': dns_support})
                except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
                    module.fail_json_aws(e, "Failed to update enabled dns support attribute")
        if current_dns_hostnames != dns_hostnames:
            changed = True
            if not module.check_mode:
                try:
                    connection.modify_vpc_attribute(VpcId=vpc_id, EnableDnsHostnames={'Value': dns_hostnames})
                except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
                    module.fail_json_aws(e, "Failed to update enabled dns hostnames attribute")

        # wait for associated cidrs to match
        if to_add or to_remove:
            try:
                connection.get_waiter('vpc_available').wait(
                    VpcIds=[vpc_id],
                    Filters=[{'Name': 'cidr-block-association.cidr-block', 'Values': expected_cidrs}]
                )
            except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
                module.fail_json_aws(e, "Failed to wait for CIDRs to update")

        # try to wait for enableDnsSupport and enableDnsHostnames to match
        wait_for_vpc_attribute(connection, module, vpc_id, 'enableDnsSupport', dns_support)
        wait_for_vpc_attribute(connection, module, vpc_id, 'enableDnsHostnames', dns_hostnames)

        final_state = camel_dict_to_snake_dict(get_vpc(module, connection, vpc_id))
        final_state['tags'] = boto3_tag_list_to_ansible_dict(final_state.get('tags', []))
        final_state['id'] = final_state.pop('vpc_id')

        module.exit_json(changed=changed, vpc=final_state)

    elif state == 'absent':

        # Check if VPC exists
        vpc_id = vpc_exists(module, connection, name, cidr_block, multi)

        if vpc_id is not None:
            try:
                if not module.check_mode:
                    connection.delete_vpc(VpcId=vpc_id)
                changed = True
            except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
                module.fail_json_aws(e, msg="Failed to delete VPC {0} You may want to use the ec2_vpc_subnet, ec2_vpc_igw, "
                                     "and/or ec2_vpc_route_table modules to ensure the other components are absent.".format(vpc_id))

        module.exit_json(changed=changed, vpc={})

if __name__ == '__main__':
    main()


text:
module Mongoid
  module Paranoia
    VERSION = '0.1.2'
  end
end

redpajama_set_name: RedPajamaGithub


text:
```csharp
public static class GTKExtensions {
	// methods
	public static Gdk.Color ToColor (this SkiaSharp.SKColor color);
	public static Gdk.Pixbuf ToPixbuf (this SkiaSharp.SKBitmap skiaBitmap);
	public static Gdk.Pixbuf ToPixbuf (this SkiaSharp.SKImage skiaImage);
	public static Gdk.Pixbuf ToPixbuf (this SkiaSharp.SKPixmap pixmap);
	public static Gdk.Pixbuf ToPixbuf (this SkiaSharp.SKPicture picture, SkiaSharp.SKSizeI dimensions);
	public static Gdk.Point ToPoint (this SkiaSharp.SKPointI point);
	public static Gdk.Rectangle ToRect (this SkiaSharp.SKRectI rect);
	public static SkiaSharp.SKBitmap ToSKBitmap (this Gdk.Pixbuf pixbuf);
	public static SkiaSharp.SKColor ToSKColor (this Gdk.Color color);
	public static SkiaSharp.SKImage ToSKImage (this Gdk.Pixbuf pixbuf);
	public static void ToSKPixmap (this Gdk.Pixbuf pixbuf, SkiaSharp.SKPixmap pixmap);
	public static SkiaSharp.SKPointI ToSKPointI (this Gdk.Point point);
	public static SkiaSharp.SKRectI ToSKRectI (this Gdk.Rectangle rect);
	public static SkiaSharp.SKSizeI ToSKSizeI (this Gdk.Size size);
	public static Gdk.Size ToSize (this SkiaSharp.SKSizeI size);
}
```


text:
/*
 * Author: Minho Kim (ISKU)
 * Date: 2017.06.30
 * E-mail: minho1a@hanmail.net
 *
 * https://github.com/ISKU/Algorithm
 * https://www.codeground.org/
 */

import java.util.*;
import java.io.*;

public class Solution {
	public static void main(String... args) throws IOException {
		BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
		BufferedWriter output = new BufferedWriter(new OutputStreamWriter(System.out));
		int testCase = Integer.parseInt(input.readLine());

		for (int tCase = 1; tCase <= testCase; tCase++) {
			Integer.parseInt(input.readLine());
			StringTokenizer parser = new StringTokenizer(input.readLine());
			int prev = Integer.parseInt(parser.nextToken());
			int answer = 0, asc = 0;

			while (parser.hasMoreTokens()) {
				int cur = Integer.parseInt(parser.nextToken());

				if (prev < cur)
					asc++;
				else {
					answer = (asc > 0) ? answer + 1 : answer;
					asc = 0;
				}

				prev = cur;
			}

			output.write(String.format("Case #%d\n%d\n", tCase, ((asc > 0) ? answer + 1 : answer) * 2));
		}

		output.close();
	}
}


text:
package com.division.jsonrpc.api;

/**
 * The basis of all JSON-RPC requests and responses. All
 * transactions must contain these elements. This class
 * should only be changed if the JSON-RPC spec is modified.
 */
public class RPCTransport {

    public static String jsonrpc = "2.0";
}


text:
package com.learnNcode.gmaillikeloading;

import android.app.ActionBar;
import android.graphics.ColorFilter;
import android.widget.LinearLayout;
import android.widget.ProgressBar;

public class CustomComponent {

	protected ActionBar actionBarView = null;
	protected LinearLayout loadingBars;
	protected ProgressBar loadingBarLeft;
	protected ProgressBar loadingBarRight;
	protected ProgressBar loadingBarIndeterminate;
	protected int actionBarDisplayOptions = 0;
	protected boolean isRefreshStarted = false;
	protected IRefreshListner refreshListnerInstance;
	protected ColorFilter colorFilter;

	protected static CustomComponent component = new CustomComponent();

	private CustomComponent(){}

	protected static CustomComponent CustomComponentInstance() {
		if(component == null){
			component = new CustomComponent();
		}
		return component;
	}

	protected void setActionBarDisplayOptions() {
		if(actionBarView != null){
			actionBarView.setDisplayOptions(actionBarDisplayOptions);
		}
	}

}


text:
package com.nunogoncalves.httpclientwithjsoup.parsers;

/**
 * Created by nuno on 11-05-2015.
 */
public class HtmlParserFactory {

    public HtmlParserFactory() {
        super();
    }

    public HtmlParser createParser(String html, String cssQuery) {
        return new CustomParser(html, cssQuery);
    }

}


text:
Polygon::Polygon(int sideCount) : pArray(new Point [sideCount]), length(sideCount)
{
}

Polygon::~Polygon()
{
	delete[] pArray;
}

double Polygon::getPerim()
{
	double perimSum = 0;

	for (int i = 1; i < length; i++)
		perimSum += distance(pArray[i - 1], pArray[i]); // Assuming the points are orderd.
	perimSum += distance(pArray[0], pArray[length - 1]);

 	return perimSum;
}

double Polygon::getArea()
{
	return 0.0;
}


text:
<!DOCTYPE html>

Lorem ipsum dolor sit amet, consectetur adipisicing elit,
    sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim
    ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip
    ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate
    velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat
    cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est
    laborum.

Lorem ipsum dolor sit amet, consectetur adipisicing elit,
    sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim
    ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip
    ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate
    velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat
    cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est
    laborum.


text:
ActiveRecord::Schema.define(version: 20140911080841) do

  create_table "comments", force: true do |t|
    t.integer  "user_id"
    t.integer  "gameuser_id"
    t.text     "comment_text"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  create_table "friendships", force: true do |t|
    t.integer  "user_id"
    t.integer  "friend_id"
    t.boolean  "blocked"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  add_index "friendships", ["friend_id"], name: "index_friendships_on_friend_id"
  add_index "friendships", ["user_id"], name: "index_friendships_on_user_id"

  create_table "game_users", force: true do |t|
    t.integer  "user_id"
    t.integer  "game_id"
    t.integer  "rating_id"
    t.integer  "average",    default: 0,     null: false
    t.datetime "created_at"
    t.datetime "updated_at"
    t.boolean  "deleted",    default: false
  end

  create_table "games", force: true do |t|
    t.string   "name"
    t.string   "icon"
    t.text     "description"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  create_table "ratings", force: true do |t|
    t.integer  "game_user_id"
    t.integer  "score",        default: 0, null: false
    t.integer  "user_id"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  add_index "ratings", ["game_user_id"], name: "index_ratings_on_game_user_id"

  create_table "users", force: true do |t|
    t.string   "email",                  default: "", null: false
    t.string   "encrypted_password",     default: "", null: false
    t.string   "name",                   default: "", null: false
    t.integer  "age",                                 null: false
    t.text     "description"
    t.string   "avatar"
    t.string   "reset_password_token"
    t.datetime "reset_password_sent_at"
    t.datetime "remember_created_at"
    t.integer  "sign_in_count",          default: 0,  null: false
    t.datetime "current_sign_in_at"
    t.datetime "last_sign_in_at"
    t.string   "current_sign_in_ip"
    t.string   "last_sign_in_ip"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.boolean  "admin"
  end

  add_index "users", ["email"], name: "index_users_on_email", unique: true
  add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true

end


text:
<!DOCTYPE html>

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

		<meta name="description" content="">
		<meta name="author" content="">
		<link rel="icon" href="../../favicon.ico">

		<title>QUAY- concepts</title>

		<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
				integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"
				crossorigin="anonymous"/>

		<link href="https://fonts.googleapis.com/css?family=Exo" rel="stylesheet">
		<link href="https://fonts.googleapis.com/css?family=Rajdhani" rel="stylesheet">

		<link rel="stylesheet" href="css/quay.css" type="text/css">

			<button type="button" class="btn btn-default btn-md">

Design

Development

Contact Form

Resume

			</button>

Development

Design

Branding

Concept

Design. Cross- platform.

A la carte offerings to meet your business needs in web, digital, product, and graphic design.
					With years of experience working as a designer for small and large brands in New York, I've worked on magazine layouts (print & digital), business cards & logos, textile prints, line sheets, apparel hang tag and labels, and retail packaging to name a few.

I specialize in working with artists, entrepreneurs, or small businesses looking for custom design work to bring more exposure to their products and projects.

Development. Full stack web development.

Custom, responsive, and mobile-first websites. As a junior web developer armed with the LAMP stack, I am looking forward to creating design- minded dynamic sites for portfolios that need more exposure. Hosting, maintenance, and ecommerce packages offered.

The project to the left is ABQuery, a non- profit web resource that visualized open city data on a map. This was built using the google map api plugin and angular 2 framework.

					<address>
						Contact:
					</address>

				<form id="contact-form" action="php/mailer.php" method="post">

						<input class="form-control" id="name" name="name" placeholder="Name" type="text"/>

						<input class="form-control" id="email" name="email" placeholder="Email" type="email" required/>

						<textarea class="form-control" id="message" name="message" placeholder="Message"
									 rows="5"></textarea>

						<button class="btn btn-primary pull-right" type="submit">Submit</button>

				</form>

Resume ·  Back to top

© 2017 QUAY-concepts ·


text:
$(".js-offcanvas").hiraku({
  btn: ".js-offcanvas-btn",
  fixedHeader: ".js-fixed-header",
  direction: "left",
  breakpoint: 767
});


text:
import osgtest.library.core as core
import osgtest.library.files as files
import osgtest.library.service as service
import osgtest.library.osgunittest as osgunittest

class TestStopXrootd(osgunittest.OSGTestCase):
    def setUp(self):
        if core.rpm_is_installed("xcache"):
            self.skip_ok_if(core.PackageVersion("xcache") >= "1.0.2",
                            "xcache 1.0.2+ configs conflict with xrootd tests")

    def test_01_stop_xrootd(self):
        if core.state['xrootd.backups-exist']:
            files.restore(core.config['xrootd.config'], "xrootd")
            files.restore('/etc/xrootd/auth_file', "xrootd")
            if not core.rpm_is_installed('xrootd-lcmaps'):
                files.restore('/etc/grid-security/xrd/xrdmapfile', "xrootd")
            if core.el_release() < 7:
                files.restore(core.config['xrootd.service-defaults'], "xrootd")
        core.skip_ok_unless_installed('xrootd', 'globus-proxy-utils', by_dependency=True)
        self.skip_ok_if(core.state['xrootd.started-server'], 'did not start server')
        service.check_stop(core.config['xrootd_service'])
        files.remove(core.config['xrootd.tmp-dir'], force=True)


text:
Aplicacion web para manejar las horas de trabajo social de los alumnos de UNITEC.

## Getting Started

### Build and Run (Port 3000)

```
$ npm install
$ npm start
```

### Generators

```
$ npm install -g plop
$ plop
```

### Tests

```
$ npm install -g karma
$ npm test
```


text:
package com.esri.geoevent.solutions.transport.irc.jerklib.events.impl;

import com.esri.geoevent.solutions.transport.irc.jerklib.Session;
import com.esri.geoevent.solutions.transport.irc.jerklib.events.ConnectionCompleteEvent;
import com.esri.geoevent.solutions.transport.irc.jerklib.events.IRCEvent;

/**
 * @author mohadib
 * @see ConnectionCompleteEvent
 *
 */
public class ConnectionCompleteEventImpl implements ConnectionCompleteEvent
{

	private final String rawEventData, hostName, oldHostName;
	private final Session session;

	public ConnectionCompleteEventImpl(String rawEventData, String hostName, Session session, String oldHostName)
	{

		this.rawEventData = rawEventData;
		this.hostName = hostName;
		this.session = session;
		this.oldHostName = oldHostName;

	}

	/* (non-Javadoc)
	 * @see com.esri.ges.transport.Irc.jerklib.events.ConnectionCompleteEvent#getOldHostName()
	 */
	public String getOldHostName()
	{
		return oldHostName;
	}

	/* (non-Javadoc)
	 * @see com.esri.ges.transport.Irc.jerklib.events.IRCEvent#getType()
	 */
	public Type getType()
	{
		return IRCEvent.Type.CONNECT_COMPLETE;
	}

	/* (non-Javadoc)
	 * @see com.esri.ges.transport.Irc.jerklib.events.IRCEvent#getRawEventData()
	 */
	public String getRawEventData()
	{
		return rawEventData;
	}

	/* (non-Javadoc)
	 * @see com.esri.ges.transport.Irc.jerklib.events.ConnectionCompleteEvent#getActualHostName()
	 */
	public String getActualHostName()
	{
		return hostName;
	}

	/* (non-Javadoc)
	 * @see com.esri.ges.transport.Irc.jerklib.events.IRCEvent#getSession()
	 */
	public Session getSession()
	{
		return session;
	}

	/* (non-Javadoc)
	 * @see java.lang.Object#toString()
	 */
	public String toString()
	{
		return rawEventData;
	}

}


text:
Irregular Verb
==============

.. slug: irregular-verb
.. date: 2015-09-13 23:02:37 UTC-07:00
.. tags:
.. category:
.. link:
.. description:
.. type: text

Swahili has Zero irregular verbs and English has about 200 irregular verbs.


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>com.google.protobuf.compatibility</groupId>
    <artifactId>compatibility-test-suite</artifactId>
    <version>2.5.0</version>
    <relativePath>..</relativePath>
  </parent>

  <groupId>com.google.protobuf.compatibility</groupId>
  <artifactId>compatibility-tests</artifactId>
  <version>2.5.0</version>

  <name>Compatibility Tests</name>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.4</version>
    </dependency>
    <dependency>
      <groupId>org.easymock</groupId>
      <artifactId>easymock</artifactId>
      <version>2.2</version>
    </dependency>
    <dependency>
      <groupId>org.easymock</groupId>
      <artifactId>easymockclassextension</artifactId>
      <version>2.2.1</version>
    </dependency>
    <dependency>
      <groupId>com.google.protobuf</groupId>
      <artifactId>protobuf-java</artifactId>
      <version>${tests.protobuf.version}</version>
    </dependency>
    <dependency>
      <groupId>com.google.protobuf.compatibility</groupId>
      <artifactId>compatibility-protos</artifactId>
      <version>2.5.0</version>
    </dependency>
    <dependency>
      <groupId>com.google.protobuf.compatibility</groupId>
      <artifactId>compatibility-more-protos</artifactId>
      <version>2.5.0</version>
    </dependency>
  </dependencies>
  <build>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
          <source>1.6</source>
          <target>1.6</target>
        </configuration>
      </plugin>
      <plugin>
        <artifactId>maven-surefire-plugin</artifactId>
        <configuration>
          <testSourceDirectory>${basedir}/src/main/java/</testSourceDirectory>
          <testClassesDirectory>${project.build.directory}/classes/</testClassesDirectory>
          <includes>
            <include>**/*Test.java</include>
          </includes>
          <workingDirectory>${protobuf.test.source.path}</workingDirectory>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>


text:
if (test_config[:database] == :postgres)
  puppetdb_query_url = "http://localhost:8080/pdb/query"
  test_name "test postgresql database restart handling to ensure we recover from a restart" do
    step "clear puppetdb database" do
      clear_and_restart_puppetdb(database)
    end

    with_puppet_running_on master, {
      'master' => {
        'autosign' => 'true'
      }} do
      step "Run agents once to activate nodes" do
        run_agent_on agents, "--test --server #{master}"
      end
    end

    step "Verify that the number of active nodes is what we expect" do
      result = on database, %Q|curl -G #{puppetdb_query_url}/v4/nodes|
      result_node_statuses = JSON.parse(result.stdout)
      assert_equal(agents.length, result_node_statuses.length, "Expected query to return '#{agents.length}' active nodes; returned '#{result_node_statuses.length}'")
    end

    restart_postgres(database)

    step "Verify that the number of active nodes is what we expect" do
      result = on database, %Q|curl -G #{puppetdb_query_url}/v4/nodes|
      result_node_statuses = JSON.parse(result.stdout)
      assert_equal(agents.length, result_node_statuses.length, "Expected query to return '#{agents.length}' active nodes; returned '#{result_node_statuses.length}'")
    end
  end
end


text:
package com.otus.alexeenko.database.services;

import com.otus.alexeenko.database.services.datasets.BaseDataSet;

/**
 * Created by Vsevolod on 11/06/2017.
 */
public interface DataBaseService {
    void start();

    <T extends BaseDataSet> void save(T dataSet);

    <T extends BaseDataSet> T load(long id, Class<T> clazz);

    void dispose();
}


text:
RSpec.describe Enumerize::Integrations::RSpec::Matcher do

  let(:model) do
    Class.new do
      extend Enumerize

      def self.name
        'Model'
      end
    end
  end

  subject do
    model.new
  end

  describe '#in' do

    context 'defined as array' do

      before do
        model.enumerize(:sex, :in => [:male, :female])
      end

      it 'accepts the right params as a array' do
        expect(subject).to enumerize(:sex).in(:male, :female)
      end

      it 'accepts the the right params in a different order' do
        expect(subject).to enumerize(:sex).in(:female, :male)
      end

      it 'rejects wrong params' do
        message = 'Expected Model to define enumerize :sex in: "boy", "girl"'
        expect do
          expect(subject).to enumerize(:sex).in(:boy, :girl)
        end.to fail_with(message)
      end
    end

    context 'defined as hash' do

      before do
        model.enumerize(:sex, :in => { male: 0, female: 1 })
      end

      it 'accepts the right params as a array' do
        expect(subject).to enumerize(:sex).in(:male, :female)
      end

      it 'accepts the right params as a hash' do
        expect(subject).to enumerize(:sex).in(male: 0, female: 1)
      end

      it 'accepts the right params as a hash in a different order' do
        expect(subject).to enumerize(:sex).in(female: 1, male: 0)
      end

      it 'rejects wrong keys' do
        message = 'Expected Model to define enumerize :sex in: "{:boy=>0, :girl=>1}"'
        expect do
          expect(subject).to enumerize(:sex).in(boy: 0, girl: 1)
        end.to fail_with(message)
      end

      it 'rejects wrong values' do
        message = 'Expected Model to define enumerize :sex in: "{:male=>2, :female=>3}"'
        expect do
        expect(subject).to enumerize(:sex).in(male: 2, female: 3)
        end.to fail_with(message)
      end
    end

    it 'has the right description' do
      matcher = enumerize(:sex).in(:male, :female)
      expect(matcher.description).to eq('define enumerize :sex in: "female", "male"')
    end
  end

  describe '#with_default' do

    before do
      model.enumerize(:sex, :in => [:male, :female], default: :female)
    end

    it 'accepts the right default value' do
      expect(subject).to enumerize(:sex).in(:male, :female).with_default(:female)
    end

    it 'rejects the wrong default value' do
      message = 'Expected Model to define enumerize :sex in: "female", "male" with "male" as default value'
      expect do
        expect(subject).to enumerize(:sex).in(:male, :female).with_default(:male)
      end.to fail_with(message)
    end

    it 'rejects if the `in` is wrong with a correct default value' do
      message = 'Expected Model to define enumerize :sex in: "boy", "girl" with "female" as default value'
      expect do
        expect(subject).to enumerize(:sex).in(:boy, :girl).with_default(:female)
      end.to fail_with(message)
    end

    it 'has the right description' do
      matcher = enumerize(:sex).in(:male, :female).with_default(:female)
      message = 'define enumerize :sex in: "female", "male" with "female" as default value'
      expect(matcher.description).to eq(message)
    end
  end
end


text:
package org.apache.geode.distributed.internal;

import java.io.IOException;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

import org.apache.logging.log4j.Logger;

import org.apache.geode.distributed.internal.membership.InternalDistributedMember;
import org.apache.geode.internal.admin.remote.RemoteTransportConfig;
import org.apache.geode.internal.i18n.LocalizedStrings;
import org.apache.geode.internal.logging.LogService;
import org.apache.geode.internal.logging.log4j.LocalizedMessage;

public class StartupOperation {
  private static final Logger logger = LogService.getLogger();

  DistributionManager dm;
  RemoteTransportConfig transport;
  Set newlyDeparted;

  StartupOperation(DistributionManager dm, RemoteTransportConfig transport) {
    this.dm = dm;
    this.transport = transport;
  }

  /**
   * send the startup message and wait for responses. If timeout is zero, this waits forever for all
   * responses to come back. This method may throw jgroups and other io exceptions since it
   * interacts with the distribution manager at a low level to send the startup messages. It does
   * this to ensure it knows which recipients didn't receive the message.
   *
   * @return whether all recipients could be contacted. The failure set can be fetched with
   *         getFailureSet??
   */
  boolean sendStartupMessage(Set recipients, long timeout, Set interfaces, String redundancyZone,
      boolean enforceUniqueZone)
      throws InterruptedException, ReplyException, java.net.UnknownHostException, IOException {
    if (Thread.interrupted())
      throw new InterruptedException();
    StartupMessageReplyProcessor proc = new StartupMessageReplyProcessor(dm, recipients);
    boolean isSharedConfigurationEnabled = false;
    if (InternalLocator.hasLocator()) {
      isSharedConfigurationEnabled = InternalLocator.getLocator().isSharedConfigurationEnabled();
    }
    StartupMessage msg =
        new StartupMessage(InternalLocator.getLocatorStrings(), isSharedConfigurationEnabled);

    msg.setInterfaces(interfaces);
    msg.setDistributedSystemId(dm.getConfig().getDistributedSystemId());
    msg.setRedundancyZone(redundancyZone);
    msg.setEnforceUniqueZone(enforceUniqueZone);
    msg.setMcastEnabled(transport.isMcastEnabled());
    msg.setMcastPort(dm.getSystem().getOriginalConfig().getMcastPort());
    msg.setMcastHostAddress(dm.getSystem().getOriginalConfig().getMcastAddress());
    msg.setTcpDisabled(transport.isTcpDisabled());
    msg.setRecipients(recipients);
    msg.setReplyProcessorId(proc.getProcessorId());

    this.newlyDeparted = dm.sendOutgoing(msg); // set of departed jgroups ids
    if (this.newlyDeparted != null && !this.newlyDeparted.isEmpty()) {
      // tell the reply processor not to wait for the recipients that didn't
      // get the message
      // Vector viewMembers = dm.getViewMembers();
      for (Iterator it = this.newlyDeparted.iterator(); it.hasNext();) {
        InternalDistributedMember id = (InternalDistributedMember) it.next();
        this.dm.handleManagerDeparture(id, false,
            LocalizedStrings.StartupOperation_LEFT_THE_MEMBERSHIP_VIEW.toLocalizedString());
        proc.memberDeparted(id, true);
      }
    }

    if (proc.stillWaiting() && logger.isDebugEnabled()) {
      logger.debug("Waiting {} milliseconds to receive startup responses", timeout);
    }
    boolean timedOut = true;
    Set unresponsive = null;
    try {
      timedOut = !proc.waitForReplies(timeout);
    } finally {
      if (timedOut) {
        unresponsive = new HashSet();
        proc.collectUnresponsiveMembers(unresponsive);
        if (!unresponsive.isEmpty()) {
          for (Iterator it = unresponsive.iterator(); it.hasNext();) {
            InternalDistributedMember um = (InternalDistributedMember) it.next();
            if (!dm.getViewMembers().contains(um)) {
              // Member slipped away and we didn't notice.
              it.remove();
              dm.handleManagerDeparture(um, true,
                  LocalizedStrings.StartupOperation_DISAPPEARED_DURING_STARTUP_HANDSHAKE
                      .toLocalizedString());
            } else if (dm.isCurrentMember(um)) {
              // he must have connected back to us and now we just
              // need to get his startup response
              logger.warn(LocalizedMessage.create(
                  LocalizedStrings.StartupOperation_MEMBERSHIP_RECEIVED_CONNECTION_FROM_0_BUT_RECEIVED_NO_STARTUP_RESPONSE_AFTER_1_MS,
                  new Object[] {um, Long.valueOf(timeout)}));
            }
          } // for

          // Tell the dm who we expect to be waiting for...
          this.dm.setUnfinishedStartups(unresponsive);

          // Re-examine list now that we have elided the startup problems....
          if (!unresponsive.isEmpty()) {
            logger.warn(LocalizedMessage.create(
                LocalizedStrings.StartupOperation_MEMBERSHIP_STARTUP_TIMED_OUT_AFTER_WAITING_0_MILLISECONDS_FOR_RESPONSES_FROM_1,
                new Object[] {Long.valueOf(timeout), unresponsive}));
          }
        } // !isEmpty
      } // timedOut
    } // finally

    boolean problems;
    problems = this.newlyDeparted != null && this.newlyDeparted.size() > 0;
    // problems = problems ||
    // (unresponsive != null && unresponsive.size() > 0);
    return !problems;
  }
}


text:
import os
from tempfile import mkdtemp
from shutil import rmtree

import numpy as np

import nibabel as nif
from nipype.testing import (assert_equal, assert_not_equal,
                            assert_raises, skipif)
from nipype.interfaces.base import TraitError

import nipype.interfaces.freesurfer as fs

def create_files_in_directory():
    outdir = os.path.realpath(mkdtemp())
    cwd = os.getcwd()
    os.chdir(outdir)
    filelist = ['a.nii', 'b.nii']
    for f in filelist:
        hdr = nif.Nifti1Header()
        shape = (3, 3, 3, 4)
        hdr.set_data_shape(shape)
        img = np.random.random(shape)
        nif.save(nif.Nifti1Image(img, np.eye(4), hdr),
                 os.path.join(outdir, f))
    with open(os.path.join(outdir, 'reg.dat'), 'wt') as fp:
        fp.write('dummy file')
    filelist.append('reg.dat')
    return filelist, outdir, cwd

def create_surf_file():
    outdir = os.path.realpath(mkdtemp())
    cwd = os.getcwd()
    os.chdir(outdir)
    surf = 'lh.a.nii'
    hdr = nif.Nifti1Header()
    shape = (1, 100, 1)
    hdr.set_data_shape(shape)
    img = np.random.random(shape)
    nif.save(nif.Nifti1Image(img, np.eye(4), hdr),
             os.path.join(outdir, surf))
    return surf, outdir, cwd

def clean_directory(outdir, old_wd):
    if os.path.exists(outdir):
        rmtree(outdir)
    os.chdir(old_wd)

@skipif(fs.no_freesurfer)
def test_sample2surf():

    s2s = fs.SampleToSurface()
    # Test underlying command
    yield assert_equal, s2s.cmd, 'mri_vol2surf'

    # Test mandatory args exception
    yield assert_raises, ValueError, s2s.run

    # Create testing files
    files, cwd, oldwd = create_files_in_directory()

    # Test input settings
    s2s.inputs.source_file = files[0]
    s2s.inputs.reference_file = files[1]
    s2s.inputs.hemi = "lh"
    s2s.inputs.reg_file = files[2]
    s2s.inputs.sampling_range = .5
    s2s.inputs.sampling_units = "frac"
    s2s.inputs.sampling_method = "point"

    # Test a basic command line
    yield assert_equal, s2s.cmdline, ("mri_vol2surf "
                                      "--hemi lh --o %s --ref %s --reg reg.dat --projfrac 0.500 --mov %s"
                                      % (os.path.join(cwd, "lh.a.mgz"), files[1], files[0]))

    # Test identity
    s2sish = fs.SampleToSurface(source_file=files[1], reference_file=files[0], hemi="rh")
    yield assert_not_equal, s2s, s2sish

    # Test hits file name creation
    s2s.inputs.hits_file = True
    yield assert_equal, s2s._get_outfilename("hits_file"), os.path.join(cwd, "lh.a_hits.mgz")

    # Test that a 2-tuple range raises an error
    def set_illegal_range():
        s2s.inputs.sampling_range = (.2, .5)
    yield assert_raises, TraitError, set_illegal_range

    # Clean up our mess
    clean_directory(cwd, oldwd)

@skipif(fs.no_freesurfer)
def test_surfsmooth():

    smooth = fs.SurfaceSmooth()

    # Test underlying command
    yield assert_equal, smooth.cmd, "mri_surf2surf"

    # Test mandatory args exception
    yield assert_raises, ValueError, smooth.run

    # Create testing files
    surf, cwd, oldwd = create_surf_file()

    # Test input settings
    smooth.inputs.in_file = surf
    smooth.inputs.subject_id = "fsaverage"
    fwhm = 5
    smooth.inputs.fwhm = fwhm
    smooth.inputs.hemi = "lh"

    # Test the command line
    yield assert_equal, smooth.cmdline, \
        ("mri_surf2surf --cortex --fwhm 5.0000 --hemi lh --sval %s --tval %s/lh.a_smooth%d.nii --s fsaverage" %
         (surf, cwd, fwhm))

    # Test identity
    shmooth = fs.SurfaceSmooth(
        subject_id="fsaverage", fwhm=6, in_file=surf, hemi="lh", out_file="lh.a_smooth.nii")
    yield assert_not_equal, smooth, shmooth

    # Clean up
    clean_directory(cwd, oldwd)

@skipif(fs.no_freesurfer)
def test_surfxfm():

    xfm = fs.SurfaceTransform()

    # Test underlying command
    yield assert_equal, xfm.cmd, "mri_surf2surf"

    # Test mandatory args exception
    yield assert_raises, ValueError, xfm.run

    # Create testing files
    surf, cwd, oldwd = create_surf_file()

    # Test input settings
    xfm.inputs.source_file = surf
    xfm.inputs.source_subject = "my_subject"
    xfm.inputs.target_subject = "fsaverage"
    xfm.inputs.hemi = "lh"

    # Test the command line
    yield assert_equal, xfm.cmdline, \
        ("mri_surf2surf --hemi lh --tval %s/lh.a.fsaverage.nii --sval %s --srcsubject my_subject --trgsubject fsaverage" %
         (cwd, surf))

    # Test identity
    xfmish = fs.SurfaceTransform(
        source_subject="fsaverage", target_subject="my_subject", source_file=surf, hemi="lh")
    yield assert_not_equal, xfm, xfmish

    # Clean up
    clean_directory(cwd, oldwd)

@skipif(fs.no_freesurfer)
def test_surfshots():

    fotos = fs.SurfaceSnapshots()

    # Test underlying command
    yield assert_equal, fotos.cmd, "tksurfer"

    # Test mandatory args exception
    yield assert_raises, ValueError, fotos.run

    # Create testing files
    files, cwd, oldwd = create_files_in_directory()

    # Test input settins
    fotos.inputs.subject_id = "fsaverage"
    fotos.inputs.hemi = "lh"
    fotos.inputs.surface = "pial"

    # Test a basic command line
    yield assert_equal, fotos.cmdline, "tksurfer fsaverage lh pial -tcl snapshots.tcl"

    # Test identity
    schmotos = fs.SurfaceSnapshots(subject_id="mysubject", hemi="rh", surface="white")
    yield assert_not_equal, fotos, schmotos

    # Test that the tcl script gets written
    fotos._write_tcl_script()
    yield assert_equal, True, os.path.exists("snapshots.tcl")

    # Test that we can use a different tcl script
    foo = open("other.tcl", "w").close()
    fotos.inputs.tcl_script = "other.tcl"
    yield assert_equal, fotos.cmdline, "tksurfer fsaverage lh pial -tcl other.tcl"

    # Test that the interface crashes politely if graphics aren't enabled
    try:
        hold_display = os.environ["DISPLAY"]
        del os.environ["DISPLAY"]
        yield assert_raises, RuntimeError, fotos.run
        os.environ["DISPLAY"] = hold_display
    except KeyError:
        pass

    # Clean up our mess
    clean_directory(cwd, oldwd)


text:
import React from 'react';
import ReactDOM from 'react-dom';
import renderer from 'react-test-renderer';
import { mount } from 'enzyme';

import { Notifications } from '../Notifications';
import { notification } from './fixtures';

describe('Containers::Notification', () => {
  it('renders without crashing', () => {
    const div = document.createElement('div');
    ReactDOM.render(<Notifications notification={notification} />, div);
  });

  it('renders correctly', () => {
    const tree = renderer
      .create(<Notifications notification={notification} />)
      .toJSON();
    expect(tree).toMatchSnapshot();
  });

  it('renders correctly after props change', () => {
    const notif = mount(<Notifications notification={notification} />);
    const newNotification = {
      title: 'Test Again',
      message: 'Testing notifications change',
      level: 'success',
    };
    notif.setProps({ notification: newNotification });
    expect(notif.find('.notification-message').text()).toBe(
      'Testing notifications change'
    );
  });
});


text:
var Promise = require('promise');

var UserProvider = require('user_provider_mongodb').UserProvider;
Users = new UserProvider();

var UsersController = function() {
  this.app = module.parent.exports.app;
  this.init();
}

UsersController.prototype.init = function() {

  this.app.helpers({app: this.app});

  var xMessageErrorHandler = function(response, code) {
    return function(err) {
      response.headers['X-Message'] = err;
      response.send(code);
    }
  }

  this.app.get('/users', function(req, res) {
    //TODO
  });

  this.app.post('/users', function(req, res) {
    // TODO
  });

  this.app.del('/users/:id', function(req, res) {
    // TODO
  });

  this.app.put('/users/:id', function(req, res) {
    // TODO
  });
}

exports = module.exports = UsersController;


text:
<?php

namespace Pheasant\Tests;

use Pheasant;
use Pheasant\DomainObject;
use Pheasant\Events;
use Pheasant\Tests\Examples\EventTestObject;
use Pheasant\Types;

class EventsTest extends \Pheasant\Tests\MysqlTestCase
{
    public function setUp()
    {
        parent::setUp();
        $this->mapper = \Mockery::mock('\Pheasant\Mapper\Mapper');
    }

    public function tearDown()
    {
        parent::tearDown();
        \Mockery::close();
    }

    /**
     * Initialize DomainObject.
     */
    public function initialize($class, $callback = null)
    {
        Pheasant::instance()
            ->register($class, $this->mapper)
            ->initialize($class, $callback)
            ;
    }

    public function testEventsBoundToSchema()
    {
        $this->mapper->shouldReceive('save')->times(1);

        $events = [];
        $callback = function ($e) use (&$events) { $events[] = $e; };

        $this->initialize('Pheasant\DomainObject', function ($builder) use ($callback) {
            $builder->properties([
                'test' => new Types\StringType(),
                ]);
            $builder->events([
                'afterCreate' => $callback,
                ]);
        });

        $do = new DomainObject();
        $do->test = 'blargh';
        $do->save();

        $this->assertEquals($do->test, 'blargh');
        $this->assertEquals($events, ['afterCreate']);
    }

    public function testEventsBoundToObject()
    {
        $this->mapper->shouldReceive('save')->times(2);
        $events = [];

        $this->initialize('Pheasant\DomainObject', function ($builder) {
            $builder->properties([
                'test' => new Types\StringType(),
                ]);
        });

        $do1 = new DomainObject();
        $do2 = new DomainObject();

        $do1->events([
            'afterSave' => function ($e) use (&$events) { $events[] = "do1.$e"; },
            ]);

        $do2->events([
            'afterSave' => function ($e) use (&$events) { $events[] = "do2.$e"; },
            ]);

        $do1->save();
        $do2->save();

        $this->assertEquals($events, ['do1.afterSave', 'do2.afterSave']);
    }

    public function testBuiltInEventMethods()
    {
        $this->mapper->shouldReceive('save')->times(1);

        $this->initialize('Pheasant\Tests\Examples\EventTestObject', function ($builder) {
            $builder->properties([
                'test' => new Types\StringType(),
                ]);
        });

        $do = EventTestObject::create(['test' => 'llamas']);
        $this->assertEquals(['beforeSave', 'afterSave'], $do->events);
    }

    /**
     * Events on objects returned by finder do not fire.
     */
    public function testIssue30()
    {
        $this->mapper->shouldReceive('save')->times(1);

        $this->initialize('Pheasant\Tests\Examples\EventTestObject', function ($builder) {
            $builder->properties([
                'test' => new Types\StringType(),
                ]);
        });

        $do = EventTestObject::fromArray(['test' => 'llamas'], false);
        $do->save();

        $this->assertEquals($do->events, ['beforeSave', 'afterSave']);
    }

    public function testSystemWideInitializeEvent()
    {
        $events = [];
        $ph = $this->pheasant;

        $this->pheasant->events()->register('afterInitialize', function ($e, $schema) use (&$events, $ph) {
            // Issue #49
            // make sure this doesn't trigger recursion
            $mapper = $ph->mapperFor($schema->className());

            $events[] = func_get_args();
        });

        $this->initialize('Pheasant\Tests\Examples\EventTestObject', function ($builder) {
            $builder->properties([
                'test' => new Types\StringType(),
                ]);
        });

        $this->assertCount(1, $events);
        $this->assertEquals('Pheasant\Tests\Examples\EventTestObject', $events[0][1]->className());
        $this->assertEquals('afterInitialize', $events[0][0]);
    }

    public function testEventCorking()
    {
        $fired = [];

        $events = new Events();
        $events->register('*', function () use (&$fired) {
            $fired[] = func_get_args();
        });

        $events->cork();
        $events->trigger('beholdLlamas', new \stdClass());
        $this->assertCount(0, $fired);

        $events->uncork();
        $this->assertCount(1, $fired);
    }

    public function testChainingEventObjects()
    {
        $events1 = new Events();
        $events2 = new Events();

        $fired1 = [];
        $fired2 = [];

        $events1->register('*', function () use (&$fired1) {
            $fired1[] = func_get_args();
        });
        $events2->register('*', function () use (&$fired2) {
            $fired2[] = func_get_args();
        });

        $events1->register('*', $events2);
        $events1->trigger('beholdLlamas', new \stdClass());

        $this->assertCount(1, $fired1);
        $this->assertCount(1, $fired2);
        $this->assertEquals('beholdLlamas', $fired2[0][0]);
    }

    public function testSaveInAfterCreateDoesntLoop()
    {
        $this->mapper->shouldReceive('save')->times(2);

        $this->initialize('Pheasant\Tests\Examples\EventTestObject', function ($builder) {
            $builder->properties([
                'test' => new Types\StringType(),
            ]);
            $builder->events([
                'afterCreate' => function ($event, $obj) {
                    $obj->save();
                },
            ]);
        });

        $do = new EventTestObject();
        $do->test = 'blargh';
        $do->save();

        $this->assertTrue(true);
    }
}


text:
var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
import { SlideGesture } from './slide-gesture';
import { defaults } from '../util/util';
import { pointerCoord, windowDimensions } from '../util/dom';
/**
 * @private
 */
export var SlideEdgeGesture = (function (_super) {
    __extends(SlideEdgeGesture, _super);
    function SlideEdgeGesture(element, opts) {
        if (opts === void 0) { opts = {}; }
        defaults(opts, {
            edge: 'left',
            maxEdgeStart: 50
        });
        _super.call(this, element, opts);
        // Can check corners through use of eg 'left top'
        this.edges = opts.edge.split(' ');
        this.maxEdgeStart = opts.maxEdgeStart;
    }
    SlideEdgeGesture.prototype.canStart = function (ev) {
        var _this = this;
        var coord = pointerCoord(ev);
        this._d = this.getContainerDimensions();
        return this.edges.every(function (edge) { return _this._checkEdge(edge, coord); });
    };
    SlideEdgeGesture.prototype.getContainerDimensions = function () {
        return {
            left: 0,
            top: 0,
            width: windowDimensions().width,
            height: windowDimensions().height
        };
    };
    SlideEdgeGesture.prototype._checkEdge = function (edge, pos) {
        switch (edge) {
            case 'left': return pos.x <= this._d.left + this.maxEdgeStart;
            case 'right': return pos.x >= this._d.width - this.maxEdgeStart;
            case 'top': return pos.y <= this._d.top + this.maxEdgeStart;
            case 'bottom': return pos.y >= this._d.height - this.maxEdgeStart;
        }
    };
    return SlideEdgeGesture;
}(SlideGesture));
//# sourceMappingURL=slide-edge-gesture.js.map


text:
package management

import (
	"context"

	"github.com/rancher/rancher/pkg/auth/data"
	"github.com/rancher/rancher/pkg/chart"
	"github.com/rancher/rancher/pkg/features"
	"github.com/rancher/rancher/pkg/types/config"
	"github.com/rancher/rancher/pkg/wrangler"
)

func Add(ctx context.Context, wrangler *wrangler.Context, management *config.ManagementContext) error {
	_, err := addRoles(wrangler, management)
	if err != nil {
		return err
	}
	if err := addClusterRoleForNamespacedCRDs(management); err != nil {
		return err
	}

	if err := data.AuthConfigs(management); err != nil {
		return err
	}

	if features.Legacy.Enabled() {
		if err := syncCatalogs(management); err != nil {
			return err
		}
	}

	if err := addDefaultPodSecurityPolicyTemplates(management); err != nil {
		return err
	}

	if err := addKontainerDrivers(management); err != nil {
		return err
	}

	if err := addCattleGlobalNamespaces(management); err != nil {
		return err
	}

	if err := addMachineDrivers(management); err != nil {
		return err
	}

	return chart.Populate(ctx, wrangler.Core.ConfigMap())
}


text:
package com.test;

public class TestInnerClass {
	private int a;
	private String b;

	public int getA() {
		return a;
	}

	public void setA(int a) {
		this.a = a;
	}

	public String getB() {
		return b;
	}

	public void setB(String b) {
		this.b = b;
	}

	public static void main(String[] args) {
		@SuppressWarnings("unused")
		Inner inner = new TestInnerClass.Inner();
	}

	public static class Inner{
		private String name;

		public String getName() {
			return name;
		}

		public void setName(String name) {
			this.name = name;
		}

	}
}


text:
Monitoring Record

             Back

Monitoring

Update

<form id="regForm" action="" method="post">

    Year:

      <select ng-model="records.year">
        <option ng-repeat="year in years" value="{{year}}">{{year}}</option>
      </select>

    COC date:

<input ng-model="records.coc_date" type="date" />

    COC #:

<input value="{{records.coc_no}}" ng-model="records.coc_no" />

    Date monitored:

       <input type="date" id="exampleInput" name="input" ng-model="records.date_monitored" ng-change="workingdays_()"
       placeholder="yyyy-MM-dd"/>

    Inspectors:

<textarea ng-model="records.inspectors">{{records.inspectors}}</textarea>

    Deficiency
  <input type="radio" name="deficiency" ng-model="records.deficiency" ng-value="1">has deficiency
    <input ng-value="0" type="radio" ng-model="records.deficiency" name="deficiency" >no deficiency

    Status:
    <input type="radio" name="status" ng-model="records.status" ng-value="1">Monitor <input ng-value="0" type="radio"  ng-model="records.status" name="status" >not Monitor

    Due date:

<input ng-model="records.due_date" type="date" placeholder="yyyy-MM-dd" />

    First Comply:

<input ng-model="records.first_comply" type="date" placeholder="yyyy-MM-dd" />

    Second Comply:

<input ng-model="records.second_comply" type="date" placeholder="yyyy-MM-dd" />

    Third Comply:

<input ng-model="records.third_comply" type="date" placeholder="yyyy-MM-dd" />

    Full Comply :

<input ng-model="records.full_comply" type="date" placeholder="yyyy-MM-dd" />

    Compliance Status:
    <input type="radio" name="compliance_status" ng-model="records.compliance_status" ng-value="1">complied <input ng-value="0" type="radio"  ng-model="records.compliance_status" name="compliance_status" >not complied

    LTO issued:

<input ng-model="records.license_validity_start" type="date" placeholder="yyyy-MM-dd" />

    LTO validity:

<input ng-model="records.license_validity_end" type="date" placeholder="yyyy-MM-dd" />

    NOV #:

<input ng-model="records.nov" value="{{records.nov}}" />

    NOV issued:

<input ng-model="records.nov_date" type="date" placeholder="yyyy-MM-dd"/>

    NOV Remarks:

<textarea ng-model="records.nov_remarks">{{records.nov_remarks}}</textarea>

    Remarks:

<textarea ng-model="records.remarks">{{records.remarks}}</textarea>

  <input type="button" class="greenButton" ng-click="Click(records)" value="Submit" />
    <input type="button" class="blueButton" ng-click="reseter()" value="Reset" />

</form>


text:
namespace gazebo_msgs
{

  class ContactState : public ros::Msg
  {
    public:
      const char* info;
      const char* collision1_name;
      const char* collision2_name;
      uint8_t wrenches_length;
      geometry_msgs::Wrench st_wrenches;
      geometry_msgs::Wrench * wrenches;
      geometry_msgs::Wrench total_wrench;
      uint8_t contact_positions_length;
      geometry_msgs::Vector3 st_contact_positions;
      geometry_msgs::Vector3 * contact_positions;
      uint8_t contact_normals_length;
      geometry_msgs::Vector3 st_contact_normals;
      geometry_msgs::Vector3 * contact_normals;
      uint8_t depths_length;
      float st_depths;
      float * depths;

    ContactState():
      info(""),
      collision1_name(""),
      collision2_name(""),
      wrenches_length(0), wrenches(NULL),
      total_wrench(),
      contact_positions_length(0), contact_positions(NULL),
      contact_normals_length(0), contact_normals(NULL),
      depths_length(0), depths(NULL)
    {
    }

    virtual int serialize(unsigned char *outbuffer) const
    {
      int offset = 0;
      uint32_t length_info = strlen(this->info);
      memcpy(outbuffer + offset, &length_info, sizeof(uint32_t));
      offset += 4;
      memcpy(outbuffer + offset, this->info, length_info);
      offset += length_info;
      uint32_t length_collision1_name = strlen(this->collision1_name);
      memcpy(outbuffer + offset, &length_collision1_name, sizeof(uint32_t));
      offset += 4;
      memcpy(outbuffer + offset, this->collision1_name, length_collision1_name);
      offset += length_collision1_name;
      uint32_t length_collision2_name = strlen(this->collision2_name);
      memcpy(outbuffer + offset, &length_collision2_name, sizeof(uint32_t));
      offset += 4;
      memcpy(outbuffer + offset, this->collision2_name, length_collision2_name);
      offset += length_collision2_name;
      *(outbuffer + offset++) = wrenches_length;
      *(outbuffer + offset++) = 0;
      *(outbuffer + offset++) = 0;
      *(outbuffer + offset++) = 0;
      for( uint8_t i = 0; i < wrenches_length; i++){
      offset += this->wrenches[i].serialize(outbuffer + offset);
      }
      offset += this->total_wrench.serialize(outbuffer + offset);
      *(outbuffer + offset++) = contact_positions_length;
      *(outbuffer + offset++) = 0;
      *(outbuffer + offset++) = 0;
      *(outbuffer + offset++) = 0;
      for( uint8_t i = 0; i < contact_positions_length; i++){
      offset += this->contact_positions[i].serialize(outbuffer + offset);
      }
      *(outbuffer + offset++) = contact_normals_length;
      *(outbuffer + offset++) = 0;
      *(outbuffer + offset++) = 0;
      *(outbuffer + offset++) = 0;
      for( uint8_t i = 0; i < contact_normals_length; i++){
      offset += this->contact_normals[i].serialize(outbuffer + offset);
      }
      *(outbuffer + offset++) = depths_length;
      *(outbuffer + offset++) = 0;
      *(outbuffer + offset++) = 0;
      *(outbuffer + offset++) = 0;
      for( uint8_t i = 0; i < depths_length; i++){
      offset += serializeAvrFloat64(outbuffer + offset, this->depths[i]);
      }
      return offset;
    }

    virtual int deserialize(unsigned char *inbuffer)
    {
      int offset = 0;
      uint32_t length_info;
      memcpy(&length_info, (inbuffer + offset), sizeof(uint32_t));
      offset += 4;
      for(unsigned int k= offset; k< offset+length_info; ++k){
          inbuffer[k-1]=inbuffer[k];
      }
      inbuffer[offset+length_info-1]=0;
      this->info = (char *)(inbuffer + offset-1);
      offset += length_info;
      uint32_t length_collision1_name;
      memcpy(&length_collision1_name, (inbuffer + offset), sizeof(uint32_t));
      offset += 4;
      for(unsigned int k= offset; k< offset+length_collision1_name; ++k){
          inbuffer[k-1]=inbuffer[k];
      }
      inbuffer[offset+length_collision1_name-1]=0;
      this->collision1_name = (char *)(inbuffer + offset-1);
      offset += length_collision1_name;
      uint32_t length_collision2_name;
      memcpy(&length_collision2_name, (inbuffer + offset), sizeof(uint32_t));
      offset += 4;
      for(unsigned int k= offset; k< offset+length_collision2_name; ++k){
          inbuffer[k-1]=inbuffer[k];
      }
      inbuffer[offset+length_collision2_name-1]=0;
      this->collision2_name = (char *)(inbuffer + offset-1);
      offset += length_collision2_name;
      uint8_t wrenches_lengthT = *(inbuffer + offset++);
      if(wrenches_lengthT > wrenches_length)
        this->wrenches = (geometry_msgs::Wrench*)realloc(this->wrenches, wrenches_lengthT * sizeof(geometry_msgs::Wrench));
      offset += 3;
      wrenches_length = wrenches_lengthT;
      for( uint8_t i = 0; i < wrenches_length; i++){
      offset += this->st_wrenches.deserialize(inbuffer + offset);
        memcpy( &(this->wrenches[i]), &(this->st_wrenches), sizeof(geometry_msgs::Wrench));
      }
      offset += this->total_wrench.deserialize(inbuffer + offset);
      uint8_t contact_positions_lengthT = *(inbuffer + offset++);
      if(contact_positions_lengthT > contact_positions_length)
        this->contact_positions = (geometry_msgs::Vector3*)realloc(this->contact_positions, contact_positions_lengthT * sizeof(geometry_msgs::Vector3));
      offset += 3;
      contact_positions_length = contact_positions_lengthT;
      for( uint8_t i = 0; i < contact_positions_length; i++){
      offset += this->st_contact_positions.deserialize(inbuffer + offset);
        memcpy( &(this->contact_positions[i]), &(this->st_contact_positions), sizeof(geometry_msgs::Vector3));
      }
      uint8_t contact_normals_lengthT = *(inbuffer + offset++);
      if(contact_normals_lengthT > contact_normals_length)
        this->contact_normals = (geometry_msgs::Vector3*)realloc(this->contact_normals, contact_normals_lengthT * sizeof(geometry_msgs::Vector3));
      offset += 3;
      contact_normals_length = contact_normals_lengthT;
      for( uint8_t i = 0; i < contact_normals_length; i++){
      offset += this->st_contact_normals.deserialize(inbuffer + offset);
        memcpy( &(this->contact_normals[i]), &(this->st_contact_normals), sizeof(geometry_msgs::Vector3));
      }
      uint8_t depths_lengthT = *(inbuffer + offset++);
      if(depths_lengthT > depths_length)
        this->depths = (float*)realloc(this->depths, depths_lengthT * sizeof(float));
      offset += 3;
      depths_length = depths_lengthT;
      for( uint8_t i = 0; i < depths_length; i++){
      offset += deserializeAvrFloat64(inbuffer + offset, &(this->st_depths));
        memcpy( &(this->depths[i]), &(this->st_depths), sizeof(float));
      }
     return offset;
    }

    const char * getType(){ return "gazebo_msgs/ContactState"; };
    const char * getMD5(){ return "48c0ffb054b8c444f870cecea1ee50d9"; };

  };

}
#endif


text:
package ovfexporter

import (
	"fmt"
	"strings"

	daisy "github.com/GoogleCloudPlatform/compute-daisy"
	"google.golang.org/api/compute/v1"

	"github.com/GoogleCloudPlatform/compute-image-import/cli_tools/common/utils/daisyutils"
	"github.com/GoogleCloudPlatform/compute-image-import/cli_tools/common/utils/logging"
	ovfexportdomain "github.com/GoogleCloudPlatform/compute-image-import/cli_tools/gce_ovf_export/domain"
)

type instanceExportCleanerImpl struct {
	wf               *daisy.Workflow
	attachDiskWfs    []*daisy.Workflow
	startInstanceWf  *daisy.Workflow
	logger           logging.Logger
	wfPreRunCallback wfCallback
}

// NewInstanceExportCleaner creates a new instance export cleaner which is
// responsible for bringing the exported VM back to its pre-export state
func NewInstanceExportCleaner(logger logging.Logger) ovfexportdomain.InstanceExportCleaner {
	return &instanceExportCleanerImpl{logger: logger}
}

func (iec *instanceExportCleanerImpl) init(instance *compute.Instance, params *ovfexportdomain.OVFExportArgs) error {
	// don't use default timeout as it might not be long enough for cleanup,
	// e.g. if it's very short (e.g. 10s)
	wfTimeout := "10m"
	attachedDisks := instance.Disks

	for _, attachedDisk := range attachedDisks {
		attachDiskWf, err := generateWorkflowWithSteps(fmt.Sprintf("ovf-export-clean-attach-disk-%v", attachedDisk.DeviceName),
			wfTimeout,
			func(w *daisy.Workflow) error {
				iec.addAttachDiskStepStep(w, instance, params, attachedDisk)
				return nil
			})
		if err != nil {
			return err
		}
		iec.attachDiskWfs = append(iec.attachDiskWfs, attachDiskWf)

	}

	wasInstanceRunningBeforeExport := isInstanceRunning(instance)
	if wasInstanceRunningBeforeExport {
		var err error
		iec.startInstanceWf, err = generateWorkflowWithSteps("ovf-export-clean-start-instance", wfTimeout,
			func(w *daisy.Workflow) error {
				if wasInstanceRunningBeforeExport {
					iec.addStartInstanceStep(w, instance, params)
				}
				return nil
			})
		if err != nil {
			return err
		}
	}

	return nil
}

func (iec *instanceExportCleanerImpl) addStartInstanceStep(w *daisy.Workflow,
	instance *compute.Instance, params *ovfexportdomain.OVFExportArgs) {
	stepName := "start-instance"
	startInstanceStep := daisy.NewStepDefaultTimeout(stepName, w)
	startInstanceStep.StartInstances = &daisy.StartInstances{Instances: []string{getInstancePath(instance, params.Project)}}
	w.Steps[stepName] = startInstanceStep
}

func (iec *instanceExportCleanerImpl) addAttachDiskStepStep(w *daisy.Workflow,
	instance *compute.Instance, params *ovfexportdomain.OVFExportArgs, attachedDisk *compute.AttachedDisk) {
	diskPath := attachedDisk.Source[strings.Index(attachedDisk.Source, "projects/"):]
	attachDiskStepName := "attach-disk"
	attachDiskStep := daisy.NewStepDefaultTimeout(attachDiskStepName, w)
	attachDiskStep.AttachDisks = &daisy.AttachDisks{
		{
			Instance: getInstancePath(instance, params.Project),
			AttachedDisk: compute.AttachedDisk{
				Mode:       attachedDisk.Mode,
				Source:     diskPath,
				Boot:       attachedDisk.Boot,
				DeviceName: attachedDisk.DeviceName,
			},
		},
	}
	w.Steps[attachDiskStepName] = attachDiskStep
}

func (iec *instanceExportCleanerImpl) Clean(instance *compute.Instance, params *ovfexportdomain.OVFExportArgs) error {
	err := iec.init(instance, params)
	if err != nil {
		return err
	}
	for _, attachDiskWf := range iec.attachDiskWfs {
		if iec.wfPreRunCallback != nil {
			iec.wfPreRunCallback(attachDiskWf)
		}
		// ignore errors as these will be due to instance being already started or disks already attached
		_ = daisyutils.NewDaisyWorker(func() (*daisy.Workflow, error) {
			return attachDiskWf, nil
		}, params.EnvironmentSettings(attachDiskWf.Name), iec.logger).Run(map[string]string{})
	}
	if iec.startInstanceWf != nil {
		if iec.wfPreRunCallback != nil {
			iec.wfPreRunCallback(iec.startInstanceWf)
		}
		_ = daisyutils.NewDaisyWorker(func() (*daisy.Workflow, error) {
			return iec.startInstanceWf, nil
		}, params.EnvironmentSettings(iec.startInstanceWf.Name), iec.logger).Run(map[string]string{})
	}
	return err
}

func (iec *instanceExportCleanerImpl) Cancel(reason string) bool {
	// cleaner is not cancelable
	return false
}


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

namespace OctoAwesome.Basics
{
    /// <summary>
    /// Basisschnittstelle für Baumdefinitionen, die vom TreePopulator verarbeitet werden sollen.
    /// </summary>
    public interface ITreeDefinition : IDefinition
    {
        /// <summary>
        /// Gibt die Reihenfolge dieser ITreeDefinition in der Abarbeitung beim bepflanzen der Chunks an.
        /// </summary>
        int Order { get; }

        /// <summary>
        /// Maximaltemperatur für diese Art von Bäumen.
        /// </summary>
        float MaxTemperature { get; }

        /// <summary>
        /// Minimaltemperatur für diese Art von Bäumen.
        /// </summary>
        float MinTemperature { get; }

        /// <summary>
        /// Initialisiert die Treedefinition.
        /// </summary>
        /// <param name="definitionManager">Der verwendete <see cref="IDefinitionManager"/>.</param>
        void Init(IDefinitionManager definitionManager);

        /// <summary>
        /// Gibt die Anzahl der Bäume zurück, die in einem Chunk gepflanzt werden sollen.
        /// </summary>
        /// <param name="planet">Der aktuelle Planet</param>
        /// <param name="index">Der Index des Chunks in absoluten Blockkoordinaten.</param>
        /// <returns></returns>
        int GetDensity(IPlanet planet, Index3 index);

        /// <summary>
        /// Pflanzt einen Baum.
        /// </summary>
        /// <param name="definitionManager">Der verwendete <see cref="IDefinitionManager"/>.</param>
        /// <param name="planet">Der aktuelle Planet.</param>
        /// <param name="index">Die Position des Baums. X, Y in lokalen Chunk-Koordinaten, Z in absoluten Koordinaten.</param>
        /// <param name="builder">Der <see cref="LocalBuilder"/> zum Setzen des Baums.</param>
        /// <param name="seed">Seed für das zufälligere Pflanzen.</param>
        void PlantTree(IDefinitionManager definitionManager, IPlanet planet, Index3 index, LocalBuilder builder, int seed);
    }
}


text:
package org.springframework.samples.jpetstore.dao.ibatis;

import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

import org.springframework.dao.DataAccessException;
import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;
import org.springframework.samples.jpetstore.dao.ProductDao;
import org.springframework.samples.jpetstore.domain.Product;

public class SqlMapProductDao extends SqlMapClientDaoSupport implements ProductDao {

  public List getProductListByCategory(String categoryId) throws DataAccessException {
    return getSqlMapClientTemplate().queryForList("getProductListByCategory", categoryId);
  }

  public Product getProduct(String productId) throws DataAccessException {
    return (Product) getSqlMapClientTemplate().queryForObject("getProduct", productId);
  }

  public List searchProductList(String keywords) throws DataAccessException {
    Object parameterObject = new ProductSearch(keywords);
    return getSqlMapClientTemplate().queryForList("searchProductList", parameterObject);
  }

  /* Inner Classes */

  public static class ProductSearch {

    private List keywordList = new ArrayList();

    public ProductSearch(String keywords) {
      StringTokenizer splitter = new StringTokenizer(keywords, " ", false);
      while (splitter.hasMoreTokens()) {
        this.keywordList.add("%" + splitter.nextToken() + "%");
      }
    }

    public List getKeywordList() {
      return keywordList;
    }
  }

}


text:
using System.Text.Json;
using Azure.Core;

namespace Azure.ResourceManager.HybridContainerService.Models
{
    public partial class ProvisionedClustersExtendedLocation : IUtf8JsonSerializable
    {
        void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
        {
            writer.WriteStartObject();
            if (Optional.IsDefined(ProvisionedClustersExtendedLocationType))
            {
                writer.WritePropertyName("type");
                writer.WriteStringValue(ProvisionedClustersExtendedLocationType);
            }
            if (Optional.IsDefined(Name))
            {
                writer.WritePropertyName("name");
                writer.WriteStringValue(Name);
            }
            writer.WriteEndObject();
        }

        internal static ProvisionedClustersExtendedLocation DeserializeProvisionedClustersExtendedLocation(JsonElement element)
        {
            Optional<string> type = default;
            Optional<string> name = default;
            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("type"))
                {
                    type = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("name"))
                {
                    name = property.Value.GetString();
                    continue;
                }
            }
            return new ProvisionedClustersExtendedLocation(type.Value, name.Value);
        }
    }
}


text:
iconic_taxa_by_name = Taxon.iconic_taxa.index_by(&:name)
mapnik_xml_path = File.join(Rails.root, 'config/observations.mapnik.xml')
icon_path = File.join(Rails.root, 'public/images/mapMarkers')
vrt_xml_path = File.join(Rails.root, "config/observations_#{Rails.env}.ogr.vrt")
db_config = YAML.load(File.open("#{Rails.root}/config/database.yml"))[Rails.env]
db_connection_string = "#{ActiveRecord::Base.connection.adapter_name.upcase}:"
# db_connection_string += db_config[Rails.env].map{|k,v| "#{k}=#{v}"}.join(',')
db_connection_string += "#{db_config['database']}"
db_connection_string += ",user=#{db_config['username']}" if db_config['username']
db_connection_string += ",host=#{db_config['host']}" if db_config['host']
db_connection_string += ",password=#{db_config['password']}" if db_config['password']
db_connection_string += ",port=#{db_config['port']}" if db_config['port']
db_connection_string += ",tables=#{Observation.table_name}"

mapnik_xml = <<XML
<Map srs="+proj=latlong +datum=WGS84">
  <Style name="observationsStyle">
    <Rule>
      <Filter>[iconic_taxon_id] = #{iconic_taxa_by_name['Plantae'].id}</Filter>
      <PointSymbolizer file="#{File.join(icon_path, 'mm_8_stemless_iNatGreen.png')}" type="png" width="8" height="8" />
    </Rule>
    <Rule>
      <Filter>#{%w"Animalia Aves Mammalia Actinopterygii Amphibia Reptilia".map {|name| "[iconic_taxon_id] = #{iconic_taxa_by_name[name].id}"}.join(' or ')}</Filter>
      <PointSymbolizer file="#{File.join(icon_path, 'mm_8_stemless_DodgerBlue.png')}" type="png" width="8" height="8" />
    </Rule>
    <Rule>
      <Filter>#{%w"Insecta Arachnida Mollusca".map {|name| "[iconic_taxon_id] = #{iconic_taxa_by_name[name].id}"}.join(' or ')}</Filter>
      <PointSymbolizer file="#{File.join(icon_path, 'mm_8_stemless_OrangeRed.png')}" type="png" width="8" height="8" />
    </Rule>
    <Rule>
      <Filter>[iconic_taxon_id] = #{iconic_taxa_by_name['Fungi'].id}</Filter>
      <PointSymbolizer file="#{File.join(icon_path, 'mm_8_stemless_DeepPink.png')}" type="png" width="8" height="8" />
    </Rule>
    <Rule>
      <ElseFilter/>
      <PointSymbolizer file="#{File.join(icon_path, 'mm_8_stemless_unknown.png')}" type="png" width="8" height="8" />
    </Rule>
  </Style>

  <Layer name="observationsLayer" srs="+proj=latlong +datum=WGS84">
    <StyleName>observationsStyle</StyleName>
    <Datasource>
      <Parameter name="type">ogr</Parameter>
      <Parameter name="file">#{vrt_xml_path}</Parameter>
      <Parameter name="layer">observations</Parameter>
    </Datasource>
  </Layer>
</Map>
XML

file = File.new(mapnik_xml_path, 'w+')
file.write(mapnik_xml)
file.close

vrt_xml = <<XML
<OGRVRTDataSource>
    <OGRVRTLayer name="observations">
        <SrcDataSource>#{db_connection_string}</SrcDataSource>
        <SrcSQL>SELECT id, latitude, longitude, iconic_taxon_id FROM #{Observation.table_name} ORDER BY id DESC</SrcSQL>
        <GeometryType>wkbPoint</GeometryType>
        <GeometryField encoding="PointFromColumns" x="longitude" y="latitude"/>
    </OGRVRTLayer>
</OGRVRTDataSource>
XML

file = File.new(vrt_xml_path, 'w+')
file.write(vrt_xml)
file.close

puts "Created #{mapnik_xml_path}"
puts "Created #{vrt_xml_path}"
puts "You can move these files to wherever your tile server is expecting "
puts "them, but make sure to change the path to the VRT within the Mapnik "
puts "XML."


text:
module Facts
  module Freebsd
    module Memory
      module System
        class Available
          FACT_NAME = 'memory.system.available'
          ALIASES = 'memoryfree'

          def call_the_resolver
            fact_value = Facter::Resolvers::Freebsd::SystemMemory.resolve(:available_bytes)
            fact_value = Facter::Util::Facts::UnitConverter.bytes_to_human_readable(fact_value)

            [Facter::ResolvedFact.new(FACT_NAME, fact_value), Facter::ResolvedFact.new(ALIASES, fact_value, :legacy)]
          end
        end
      end
    end
  end
end


text:
// Author: Charles Weld
// Date: 14/03/2010 7:38 AM

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Threading;
using Airion.Parallels.Internal;

namespace Airion.Parallels
{
	public static class TaskHandle
	{
		/// <summary>
		/// Waits until one of the tasks represented by <see cref="taskHandles"/> is finished, all remaining task will be aborted.
		/// </summary>
		/// <param name="taskHandles">The task handles to wait on.</param>
		/// <returns></returns>
		public static int WaitAny(params ITaskHandle[] taskHandles)
		{
			//FIXME: The is broken, we should return if a scheduled task is finished not ignore it.
			// create wait handle array
			int maxLength = taskHandles.Length;
			var scheduledTasks = new IScheduledTask[maxLength];
			int index = 0;
			for (int i = 0; i < maxLength; i++) {
				var scheduledTask = taskHandles[i] as IScheduledTask;
				if(scheduledTask != null) {
					if(!scheduledTask.IsFinished) {
						scheduledTasks[index] = scheduledTask;
						index++;
					}
				} else {
					throw new InvalidOperationException(String.Format("Couldn't convert task handle \"{0}\" to a IScheduledTask.", taskHandles[i]));
				}
			}

			int length = index;
			var waitHandles = new WaitHandle[index];
			for (int i = 0; i < length; i++) {
				waitHandles[i] = scheduledTasks[i].FinishedHandle;
			}
			int releasedIndex = WaitHandle.WaitAny(waitHandles);
			// release resources
			for (int i = 0; i < index; i++) {
				scheduledTasks[i].Close();
			}
			return releasedIndex;
		}

		public static void WaitAll(params ITaskHandle[] taskHandles)
		{
			for (int i = 0; i < taskHandles.Length; i++) {
				taskHandles[i].Wait();
			}
		}
	}
}


text:
package ru.taximaxim.dbreplicator2.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;

/**
 * Класс инкапсулирующий задачу менеджера записей.
 *
 * @author ags
 *
 */
@Entity
@Table( name = "cron" )
public class CronSettingsModel implements CronSettings{

    /**
     * Идентификатор задачи
     */
    @Id
    @Column(name = "id_task")
    private int taskId;

    /**
     * Флаг доступности задачи
     */
    @Column(name = "enabled")
    private boolean enabled;

    /**
     * Cron строка, описывающая периодичность запуска задачи.
     * (В случае использования simple триггера будет равно null)
     */
    @Column(name = "cron_string")
    private String cronString;

    /**
     * Интервал после ошибочного выполнения задачи
     */
    @Column(name = "description")
    private String description;

    /**
     * Обработчик реплики
     */
    @ManyToOne
    @JoinColumn(name = "id_runner")
    @Fetch(FetchMode.SELECT)
    private RunnerModel runner;

    /**
     * Для использования выполнения задачи будем использовать поток реплику, как
     * подготовленное рабочее решение.
     *
     */

    @Override
    public int getTaskId() {
        return taskId;
    }

    @Override
    public void setTaskId(int taskId) {
        this.taskId = taskId;
    }

    @Override
    public boolean getEnabled() {
        return enabled;
    }

    @Override
    public void setEnabled(boolean enabled) {
        this.enabled = enabled;
    }

     @Override
    public String getCronString() {
        return cronString;
    }

    @Override
    public void setCronString(String cronString) {
        this.cronString = cronString;
    }

    @Override
    public String getDescription() {
        return description;
    }

    @Override
    public void setDescription(String description) {
        this.description = description;
    }

    @Override
    public RunnerModel getRunner() {
        return runner;
    }

    @Override
    public void setRunner(RunnerModel runner) {
        this.runner = runner;
    }
}


text:
namespace {

ui::DeskExtension* GetDeskExtension(aura::Window* window) {
  return views::DesktopWindowTreeHostLacros::From(window->GetHost())
      ->GetDeskExtension();
}

//////////////////////////////////////////////////////////////////////
// DesksHelperLacros implementation:

class DesksHelperLacros : public chromeos::DesksHelper {
 public:
  explicit DesksHelperLacros(aura::Window* window) : window_(window) {}
  DesksHelperLacros(const DesksHelperLacros&) = delete;
  DesksHelperLacros& operator=(const DesksHelperLacros&) = delete;
  ~DesksHelperLacros() override = default;

  // chromeos::DesksHelper:
  bool BelongsToActiveDesk(aura::Window* window) override {
    views::Widget* widget = views::Widget::GetWidgetForNativeWindow(window);
    DCHECK(widget);
    // If the window is on all workspaces or unassigned, we should consider that
    // the window belongs to active desk.
    if (widget->IsVisibleOnAllWorkspaces())
      return true;
    const std::string& workspace = widget->GetWorkspace();
    if (workspace.empty())
      return true;

    int desk_index;
    if (!base::StringToInt(workspace, &desk_index))
      return false;
    return GetActiveDeskIndex() == desk_index;
  }
  int GetActiveDeskIndex() const override {
    return GetDeskExtension(window_)->GetActiveDeskIndex();
  }
  std::u16string GetDeskName(int index) const override {
    return GetDeskExtension(window_)->GetDeskName(index);
  }
  int GetNumberOfDesks() const override {
    return GetDeskExtension(window_)->GetNumberOfDesks();
  }
  void SendToDeskAtIndex(aura::Window* window, int desk_index) override {
    GetDeskExtension(window)->SendToDeskAtIndex(desk_index);
  }

 private:
  raw_ptr<aura::Window> window_;
};

DEFINE_OWNED_UI_CLASS_PROPERTY_KEY(DesksHelperLacros,
                                   kDesksHelperLacrosKey,
                                   nullptr)

}  // namespace

DEFINE_UI_CLASS_PROPERTY_TYPE(DesksHelperLacros*)

//////////////////////////////////////////////////////////////////////
// DesksHelper implementation:
namespace chromeos {

// static
DesksHelper* DesksHelper::Get(aura::Window* window) {
  DCHECK(window);
  if (auto* desks_helper = window->GetProperty(kDesksHelperLacrosKey))
    return desks_helper;
  return window->SetProperty(kDesksHelperLacrosKey,
                             std::make_unique<DesksHelperLacros>(window));
}

DesksHelper::DesksHelper() = default;

DesksHelper::~DesksHelper() = default;

}  // namespace chromeos


text:
import { GraphQLScalarType } from 'graphql';
import { GraphQLError } from 'graphql/error';
import { Kind } from 'graphql/language';

export default new GraphQLScalarType({
  name: 'Date',
  serialize(value) {
    if (!(value instanceof Date)) {
      throw new TypeError('Field error: value is not an instance of Date');
    }

    if (isNaN(value.getTime())) {
      throw new TypeError('Field error: value is an invalid Date');
    }

    return value.toJSON();
  },
  parseValue(value) {
    const date = new Date(value);

    if (isNaN(date.getTime())) {
      throw new TypeError('Field error: value is an invalid Date');
    }

    return date;
  },
  parseLiteral(ast) {
    if (ast.kind !== Kind.STRING) {
      throw new GraphQLError(`Query error: Can only parse strings to buffers but got a: ${ast.kind}`, [ast]);
    }

    const result = new Date(ast.value);
    if (isNaN(result.getTime())) {
      throw new GraphQLError('Query error: Invalid date', [ast]);
    }

    if (ast.value !== result.toJSON()) {
      throw new GraphQLError('Query error: Invalid date format, only accepts: YYYY-MM-DDTHH:MM:SS.SSSZ', [ast]);
    }

    return result;
  }
});


text:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:orientation="vertical"
        android:layout_height="wrap_content">

        <TextView
            android:id="@+id/tv_html"
            android:padding="20dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </LinearLayout>

</ScrollView>


text:
  ## tries to interpret the uri as a local path and replaces it
  ## with a normalized local path (ie file:// ...)
  ## returns a new uri
  function(uri_qualify_local_path uri)
    uri("${uri}")
    ans(uri)

    map_tryget(${uri} input)
    ans(uri_string)

    map_tryget(${uri} normalized_host)
    ans(normalized_host)

    map_tryget("${uri}" scheme)
    ans(scheme)

    ## check if path path is going to be local
    eval_truth(
       "${scheme}_" MATCHES "(^_$)|(^file_$)" # scheme is file
       AND normalized_host STREQUAL "localhost" # and host is localhost
       AND NOT "${uri_string}" MATCHES "^[^/]+:" # and input uri is not scp like ssh syntax
     )
    ans(is_local)

    ## special handling of local path
    if(is_local)
      ## use the locally qualfied full path
      map_get("${uri}" path)
      ans(local_path)
      path_qualify(local_path)
      map_tryget(${uri} params)
      ans(params)
      uri("${local_path}")
      ans(uri)
      map_set("${uri}" params "${params}")
    endif()
    return_ref(uri)
  endfunction()


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Caliburn.Micro;
using EauxDeBaignade.HauteAutriche.Model;
using Newtonsoft.Json;

namespace EauxDeBaignade.HauteAutriche.ViewModels
{
    public class BadestelleDetailsPageViewModel : Screen
    {
        protected override void OnActivate()
        {
            base.OnActivate();

            this.Badestelle = JsonConvert.DeserializeObject<Badestelle>(NavigationBadestelleJson);
        }

        public string NavigationBadestelleJson { get; set; }

        private Badestelle _badestelle;

        public Badestelle Badestelle
        {
            get
            {
                return _badestelle;
            }
            set
            {
                _badestelle = value;
                NotifyOfPropertyChange(() => Badestelle);
            }
        }
    }
}


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>类 com.asteroid.model.User的使用</title>
<meta name="date" content="2014-06-21">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

您的浏览器已禁用 JavaScript。

概览

程序包

类

使用

树

已过时

索引

帮助

上一个

下一个

框架

无框架

所有类

类 com.asteroid.model.User
的使用

使用User的程序包

程序包
说明

com.asteroid.action

com.asteroid.controller.daoVO

com.asteroid.controller.user

com.asteroid.service

com.asteroid.util

com.asteroid.action中User的使用

返回User的com.asteroid.action中的方法

限定符和类型
方法和说明

User
LoginAction.getUser()

参数类型为User的com.asteroid.action中的方法

限定符和类型
方法和说明

void
LoginAction.setUser(User user)

com.asteroid.controller.daoVO中User的使用

返回User的com.asteroid.controller.daoVO中的方法

限定符和类型
方法和说明

User
ReleaseVO.getUser()

User
CommentVO.getUser()

参数类型为User的com.asteroid.controller.daoVO中的方法

限定符和类型
方法和说明

void
CommentVO.setUser(User user)

com.asteroid.controller.user中User的使用

返回User的com.asteroid.controller.user中的方法

限定符和类型
方法和说明

User
UserDao.findById(int id)

查找个人信息

返回变量类型为User的类型的com.asteroid.controller.user中的方法

限定符和类型
方法和说明

java.util.List<User>
UserDao.findAll()

返回所有用户

参数类型为User的com.asteroid.controller.user中的方法

限定符和类型
方法和说明

boolean
UserDao.save(User user)

添加用户

boolean
UserDao.update(User user)

修改个人信息

com.asteroid.service中User的使用

返回User的com.asteroid.service中的方法

限定符和类型
方法和说明

User
UserService.getUserInfo()

User
UserService.setUserInfo(int id)

com.asteroid.util中User的使用

返回User的com.asteroid.util中的方法

限定符和类型
方法和说明

static User
SessionManage.getUser()

概览

程序包

类

使用

树

已过时

索引

帮助

上一个

下一个

框架

无框架

所有类


text:
cask 'waltr1' do
  version '1.7.4,1538043028'
  sha256 '2195386c41b511201be8796f58c726ead0b9b28880a87b0aae1054351b88b198'

  # devmate.com/com.softorino.Waltr was verified as official when first introduced to the cask
  url "https://dl.devmate.com/com.softorino.Waltr/#{version.before_comma}/#{version.after_comma}/WALTR-#{version.before_comma}.zip"
  appcast 'https://updates.devmate.com/com.softorino.Waltr.xml'
  name 'WALTR'
  homepage 'https://softorino.com/waltr/'

  app 'Waltr.app'
end